scDEF tutorial — whole adult planarian¶
21,612 cells from the flatworm Schmidtea mediterranea (Plass et al.), annotated at two resolutions (clusters_coarse, tissues; clusters_neoblasts, subtypes). A large, richly hierarchical data set: scDEF recovers a cell-type hierarchy and, on top of it, differentiation trajectories from the neoblast progenitors.
Running this notebook. Fitting is the slow step — run top-to-bottom once; the fitted model is saved at the end, so you can re-open it with
scd.scDEF.load(...)instead of re-fitting. The steps follow the reference analysis workflow.
Known genes and ground-truth hierarchy (reference)¶
known_genes = {
'dd_Smed_v6_659_0': 'piwi', 'dd_Smed_v6_332_0': 'prog-1', 'dd_Smed_v6_363_0': 'prog-2-2',
'dd_Smed_v6_920_0': 'agat1', 'dd_Smed_v6_432_0': 'mhc', 'dd_Smed_v6_12634_0': 'myoD',
'dd_Smed_v6_6208_0': 'chat', 'dd_Smed_v6_3977_0': 'snap25', 'dd_Smed_v6_1117_0': 'npp-18',
'dd_Smed_v6_8548_0': 'ncam-2', 'dd_Smed_v6_19336_0': 'gbrb-1', 'dd_Smed_v6_9893_0': 'smed-coe',
'dd_Smed_v6_8494_0': 'roboA', 'dd_Smed_v6_14852_0': 'netrin', 'dd_Smed_v6_13817_0': 'musashi',
'dd_Smed_v6_1013_0': 'pmp-7', 'dd_Smed_v6_364_0': 'vim-1', 'dd_Smed_v6_11310_0': 'egfr',
}
true_hierarchy = {
'stem cells': ['neoblast'],
'neurons': ['ChAT neurons 1', 'ChAT neurons 2', 'GABA neurons', 'spp-11+ neurons',
'npp-18+ neurons', 'cav-1+ neurons', 'neural progenitors'],
'epidermis': ['early epidermal progenitors', 'activated early epidermal progenitors',
'epidermal neoblasts', 'epidermis', 'epidermis DVb', 'epidermis DVb neoblast',
'late epidermal progenitors 1', 'late epidermal progenitors 2'],
'muscle': ['muscle body', 'muscle pharynx', 'muscle progenitors'],
'parenchyma': ['pgrn+ parenchymal cells', 'ldlrr-1+ parenchymal cells',
'psap+ parenchymal cells', 'aqp+ parenchymal cells', 'parenchymal progenitors'],
'secretory': ['secretory 1', 'secretory 2', 'secretory 3', 'secretory 4'],
'pharynx': ['pharynx cell type progenitors', 'pharynx cell type'],
'gut': ['gut progenitors', 'phagocytes', 'goblet cells'],
'protonephridia': ['protonephridia'], 'pigment': ['pigment'],
'otf+ cells 1': ['otf+ cells 1'], 'otf+ cells 2': ['otf+ cells 2'],
'psd+ cells': ['psd+ cells'], 'glia': ['glia'],
}
Load packages and data¶
import numpy as np
import pandas as pd
import scanpy as sc
import scdef as scd
import matplotlib.pyplot as plt
adata = sc.read_h5ad('../scdef_data/planaria/planaria_pp.h5ad')
# Already QC'd + HVG-filtered; raw counts are in the 'counts' layer, and the data ships a
# t-SNE + annotation colors. Rename transcript ids to gene symbols where known (so signatures
# and gene_score are readable).
adata.var['transcript_id'] = adata.var_names.astype(str)
adata.var_names = [known_genes.get(g, g) for g in adata.var_names]
adata.var_names_make_unique()
adata.obs['clusters_coarse'].value_counts()
clusters_coarse stem cells 8075 epidermis 4391 neurons 2358 muscle 2351 parenchyma 2042 gut 745 secretory 466 pigment 321 pharynx 292 psd+ cells 174 otf+ cells 1 166 otf+ cells 2 127 protonephridia 80 glia 24 Name: count, dtype: int64
sc.pl.tsne(adata, color=['clusters_coarse', 'clusters_neoblasts'], frameon=False)
Fit scDEF¶
learn runs the recommended workflow, the one the scDEF paper uses for every data set: fit, filter, fit again from the kept factors, and filter again (see Getting started with 3k PBMCs for the steps one by one). The paper also keeps the best of five initialisations; one is enough to follow the tutorial. This is a larger data set, so the fits take longer.
model = scd.scDEF(adata, counts_layer='counts')
print(model)
model.learn()
scDEF object with 6 layers
Layer names: L0, L1, L2, L3, L4, L5
Layer sizes: 100, 40, 16, 6, 3, 1
alpha parameter: 0.58
Using BRD
Number of batches: 1
Contains AnnData object with n_obs × n_vars = 21612 × 4900
obs: 'n_genes', 'n_counts', 'clusters', 'clusters_neoblasts', 'clusters_coarse'
var: 'n_cells', 'mean', 'std', 'transcript_id'
uns: 'clusters_coarse_colors', 'clusters_colors', 'clusters_neoblasts_colors', 'clusters_sizes', 'log1p', 'neighbors', 'paga', 'pca', 'tsne'
obsm: 'X_pca', 'X_tsne'
varm: 'PCs'
layers: 'counts'
obsp: 'connectivities', 'distances'
INFO:scDEF:Built hierarchical z/W init from KMeans (100 L0 clusters) using 'X_pca'. INFO:scDEF:Each epoch contains 85 batches of size 256 12%|█▏ | 123/1000 [03:32<25:16, 1.73s/it, Loss=7.57e+6, Rel. impr.=-0.00105] INFO:scDEF:Converged at epoch 124. INFO:scDEF:Continuing scDEF from previous fit with layer sizes [51, 24, 13, 5, 3, 1]. INFO:scDEF:Refit: rescaled BRD warm start to geometric mean 1 (range 1.1–16.2 -> 0.342–5.02). INFO:scDEF:Refit: rescaled ARD warm start to geometric mean 1 (range 0.0242–20.8 -> 0.141–7.07). INFO:scDEF:Each epoch contains 85 batches of size 256 17%|█▋ | 172/1000 [04:34<22:01, 1.60s/it, Loss=7.21e+6, Rel. impr.=-0.00146] INFO:scDEF:Converged at epoch 173.
scDEF object with 6 layers
Layer names: L0, L1, L2, L3, L4, L5
Layer sizes: 31, 17, 11, 4, 3, 1
alpha parameter: 0.58
Using BRD
Number of batches: 1
Contains AnnData object with n_obs × n_vars = 21612 × 4900
obs: 'n_genes', 'n_counts', 'clusters', 'clusters_neoblasts', 'clusters_coarse', 'cell_scale', 'L0', 'L1', 'L2', 'L3', 'L4', 'L5', 'L0_0_score', 'L0_1_score', 'L0_2_score', 'L0_3_score', 'L0_4_score', 'L0_5_score', 'L0_6_score', 'L0_7_score', 'L0_8_score', 'L0_9_score', 'L0_10_score', 'L0_11_score', 'L0_12_score', 'L0_13_score', 'L0_14_score', 'L0_15_score', 'L0_16_score', 'L0_17_score', 'L0_18_score', 'L0_19_score', 'L0_20_score', 'L0_21_score', 'L0_22_score', 'L0_23_score', 'L0_24_score', 'L0_25_score', 'L0_26_score', 'L0_27_score', 'L0_28_score', 'L0_29_score', 'L0_30_score', 'L1_0_score', 'L1_1_score', 'L1_2_score', 'L1_3_score', 'L1_4_score', 'L1_5_score', 'L1_6_score', 'L1_7_score', 'L1_8_score', 'L1_9_score', 'L1_10_score', 'L1_11_score', 'L1_12_score', 'L1_13_score', 'L1_14_score', 'L1_15_score', 'L1_16_score', 'L2_0_score', 'L2_1_score', 'L2_2_score', 'L2_3_score', 'L2_4_score', 'L2_5_score', 'L2_6_score', 'L2_7_score', 'L2_8_score', 'L2_9_score', 'L2_10_score', 'L3_0_score', 'L3_1_score', 'L3_2_score', 'L3_3_score', 'L4_0_score', 'L4_1_score', 'L4_2_score', 'L5_0_score', 'L0_0_prob', 'L0_1_prob', 'L0_2_prob', 'L0_3_prob', 'L0_4_prob', 'L0_5_prob', 'L0_6_prob', 'L0_7_prob', 'L0_8_prob', 'L0_9_prob', 'L0_10_prob', 'L0_11_prob', 'L0_12_prob', 'L0_13_prob', 'L0_14_prob', 'L0_15_prob', 'L0_16_prob', 'L0_17_prob', 'L0_18_prob', 'L0_19_prob', 'L0_20_prob', 'L0_21_prob', 'L0_22_prob', 'L0_23_prob', 'L0_24_prob', 'L0_25_prob', 'L0_26_prob', 'L0_27_prob', 'L0_28_prob', 'L0_29_prob', 'L0_30_prob', 'L1_0_prob', 'L1_1_prob', 'L1_2_prob', 'L1_3_prob', 'L1_4_prob', 'L1_5_prob', 'L1_6_prob', 'L1_7_prob', 'L1_8_prob', 'L1_9_prob', 'L1_10_prob', 'L1_11_prob', 'L1_12_prob', 'L1_13_prob', 'L1_14_prob', 'L1_15_prob', 'L1_16_prob', 'L2_0_prob', 'L2_1_prob', 'L2_2_prob', 'L2_3_prob', 'L2_4_prob', 'L2_5_prob', 'L2_6_prob', 'L2_7_prob', 'L2_8_prob', 'L2_9_prob', 'L2_10_prob', 'L3_0_prob', 'L3_1_prob', 'L3_2_prob', 'L3_3_prob', 'L4_0_prob', 'L4_1_prob', 'L4_2_prob', 'L5_0_prob'
var: 'n_cells', 'mean', 'std', 'transcript_id', 'gene_scale'
uns: 'clusters_coarse_colors', 'clusters_colors', 'clusters_neoblasts_colors', 'clusters_sizes', 'log1p', 'neighbors', 'paga', 'pca', 'tsne', 'entropy_annealing_trace', 'entropy_annealing_trace_epochs', 'L0_colors', 'L1_colors', 'L2_colors', 'L3_colors', 'L4_colors', 'L5_colors', 'factor_diagnostics', 'factor_obs', 'factor_obs_full', 'L0_signatures', 'L1_signatures', 'L2_signatures', 'L3_signatures', 'L4_signatures', 'L5_signatures', '_factor_obs_upper_lists_fixed', '_factor_obs_fit_revision', 'confident_signatures', 'factor_signatures'
obsm: 'X_pca', 'X_tsne', 'X_L0', 'X_L1', 'X_L2', 'X_L3', 'X_L4', 'X_L5', 'X_L0_probs', 'X_L1_probs', 'X_L2_probs', 'X_L3_probs', 'X_L4_probs', 'X_L5_probs'
varm: 'PCs'
layers: 'counts'
obsp: 'connectivities', 'distances'
Check the fit¶
scd.pl.qc(model)
The learned cell size follows the observed library size above about 60 counts. The planaria cells have few counts (a median of 58 over the 4,900 genes), and for those with fewer than about 30, mostly neoblasts, the weights take up part of the depth and the learned cell size falls below the diagonal. The rest of the tutorial uses the proportions of the weights, which do not depend on that scale.
scd.pl.factor_diagnostics(model, annotate_factors=True)
print([len(fl) for fl in model.factor_lists]) # factors kept per layer
[31, 17, 11, 4, 3, 1]
Hierarchy of cell states¶
Leaves are specific cell types; nodes near the root aggregate a tissue. show_signatures prints the top genes driving each lineage — compare the recovered tree against the known true_hierarchy defined at the top.
scd.pl.make_graph(model, wedged='clusters_coarse', show_signatures=True, n_cells_label=True)
Colour the tree by a single gene instead. With gene_score_scale='layer', each node shows the score of the gene relative to its largest score among the factors of the same layer, so the factors that use the gene most are brightest: mhc (muscle) lights up the muscle branch and chat (neurons) the neural branch. The default, gene_score_scale='factor', shows the score relative to the top gene of each factor instead, and so highlights a gene only where it leads the programme.
scd.pl.make_graph(model, gene_score='mhc', gene_score_scale='layer', show_signatures=False)
scd.pl.make_graph(model, gene_score='chat', gene_score_scale='layer', show_signatures=False)
Multi-layer UMAP by cell type¶
Layer 0 separates the differentiated cell types with neoblasts at the centre; upper layers progressively merge cell types within a tissue.
scd.tl.umap(model)
scd.pl.umap(model, color='clusters_coarse')
Association of factors with cell types across layers¶
Several layer-0 factors map to neuronal subtypes, and the layers above group them by tissue: the hierarchy captures cell types finely and aggregates them.
scd.pl.obs_scores(model, ['clusters_coarse', 'clusters_neoblasts'], mode='weights',
figsize=(14, 12), fontsize=8) # about 50 annotation rows
Differentiation paths¶
A differentiation path runs from the root of the hierarchy to a layer-0 factor. score_paths gives every cell a position along each path, from 0 at the root to 1 at the leaf. As in the paper, we take for the muscle lineage the path to the layer-0 factor that holds most muscle body cells, draw it on the hierarchy, and compare the positions of the neoblasts, the muscle progenitors and the differentiated muscle cells.
scd.tl.build_differentiation_paths(model)
scd.tl.score_paths(model, paths_key='differentiation_paths')
paths = model.adata.uns['differentiation_paths']['paths']
# the layer-0 factor with the most muscle body cells, and the strongest path to it
obs = model.adata.obs
leaf = obs.loc[obs['clusters'] == 'muscle body', 'L0'].astype(str).value_counts().index[0]
muscle = max((p for p in paths if p['nodes'][-1] == leaf), key=lambda p: p['path_weight_product'])
' -> '.join(muscle['nodes'])
'L5_0 -> L4_1 -> L3_1 -> L2_4 -> L1_4 -> L0_7'
scd.pl.make_graph(model, path=muscle['nodes'], path_color='black', path_node_penwidth=4,
wedged='clusters_coarse', show_signatures=False)
stage = pd.Series(np.select([obs['clusters_coarse'] == 'stem cells', obs['clusters'] == 'muscle progenitors',
obs['clusters_coarse'] == 'muscle'],
['neoblasts', 'muscle progenitors', 'muscle cells'], default=''), index=obs.index)
position = model.adata.obsm['differentiation_paths_positions'][:, muscle['path_id']]
order = ['neoblasts', 'muscle progenitors', 'muscle cells']
fig, ax = plt.subplots(figsize=(5, 3))
ax.boxplot([position[(stage == s).to_numpy()] for s in order], showfliers=False)
ax.set_xticks([1, 2, 3], order)
ax.set_ylabel('Position on the muscle path\n(0 at the root, 1 at the leaf)')
plt.show()
The neoblasts sit near the root of the muscle path, the differentiated muscle cells furthest along it, and the progenitors between them. A position along a path follows the hierarchy, which groups factors by expression; here it agrees with the known order of muscle differentiation.
Save the fitted model¶
model.save('scdef-planaria', overwrite=True)