scDEF tutorial — 3k PBMCs¶
The 3k PBMC data set from 10x Genomics (one healthy donor, well-annotated cell types with known markers) is the reference example for the unsupervised scDEF workflow: fit, filter, re-fit and filter again into a hierarchy of cell states with sparse gene signatures, then validate those signatures against known markers.
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 markers (for later signature validation)¶
markers = {
'Memory CD4 T': ['IL7R', 'CD3D', 'CD3E', 'IL32', 'CD2'],
'Naive CD4 T': ['IL7R', 'CCR7', 'TCF7', 'LEF1', 'SELL'],
'CD14+ Mono': ['CD14', 'LYZ', 'S100A8', 'S100A9', 'FCN1'],
'FCGR3A+ Mono': ['FCGR3A', 'MS4A7', 'LST1', 'AIF1', 'CDKN1C'],
'B': ['CD79A', 'MS4A1', 'CD79B', 'IGHM', 'BANK1'],
'CD8 T': ['CD8A', 'CD8B', 'GZMK', 'CCL5', 'NKG7'],
'NK': ['GNLY', 'NKG7', 'KLRD1', 'KLRF1', 'PRF1'],
'DC': ['FCER1A', 'CST3', 'HLA-DRA', 'CD74', 'CLEC10A'],
'Platelet': ['PPBP', 'PF4', 'GNG11', 'TUBB1', 'NRGN'],
}
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
sc.settings.verbosity = 1
adata = sc.read_10x_mtx(
'../scdef_data/pbmcs_data/pbmcs3k/data/filtered_gene_bc_matrices/hg19/',
var_names='gene_symbols', cache=True)
adata.obs.index = adata.obs.index.str.replace('-1', '') # match the annotation barcodes
# QC + raw counts in a layer (scDEF models counts).
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=3)
adata.var['mt'] = adata.var_names.str.startswith('MT-')
adata.var['rb'] = adata.var_names.str.startswith('RPS') | adata.var_names.str.startswith('RPL')
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt', 'rb'], percent_top=None, log1p=False, inplace=True)
adata = adata[adata.obs.n_genes_by_counts < 2500, :]
adata = adata[adata.obs.pct_counts_mt < 5, :]
adata.layers['counts'] = adata.X.toarray()
/tmp/ipykernel_752856/2585033778.py:9: ImplicitModificationWarning: Setting element `.layers['counts']` of view, initializing view as actual. adata.layers['counts'] = adata.X.toarray()
# HVG on the counts; keep marker genes; then a scanpy embedding for the colors.
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
sc.pp.highly_variable_genes(adata, flavor='seurat_v3', layer='counts', n_top_genes=4000)
for g in {x for gs in markers.values() for x in gs}:
if g in adata.var_names:
adata.var.loc[g, 'highly_variable'] = True
adata = adata[:, adata.var.highly_variable].copy()
sc.pp.regress_out(adata, ['total_counts', 'pct_counts_mt'])
sc.pp.scale(adata, max_value=10)
sc.tl.pca(adata, svd_solver='arpack')
sc.pp.neighbors(adata, n_neighbors=10, n_pcs=40)
sc.tl.umap(adata)
# Cell-type labels from the reference annotations (fine 'Cell types' + 'Coarse').
annotations = pd.read_csv('../scdef_data/pbmcs_data/pbmcs3k/annotations.csv', index_col=0)
map_coarse = {c: ('T' if c.endswith(' T') else 'Mono' if (c.endswith('Mono') or c == 'DC') else c)
for c in annotations['seurat_annotations'].astype('category').cat.categories}
adata.obs['Cell types'] = annotations['seurat_annotations']
adata.obs['Coarse'] = adata.obs['Cell types'].map(map_coarse).astype('category')
sc.pl.umap(adata, color=['Coarse', 'Cell types'], frameon=False) # also writes *_colors
Fit scDEF¶
model = scd.scDEF(adata, counts_layer='counts')
print(model)
model.fit(hierarchical_init=True)
scDEF object with 6 layers
Layer names: L0, L1, L2, L3, L4, L5
Layer sizes: 100, 40, 16, 6, 3, 1
alpha parameter: 7.94
Using BRD
Number of batches: 1
Contains AnnData object with n_obs × n_vars = 2638 × 4005
obs: 'n_genes', 'n_genes_by_counts', 'total_counts', 'total_counts_mt', 'pct_counts_mt', 'total_counts_rb', 'pct_counts_rb', 'Cell types', 'Coarse'
var: 'gene_ids', 'n_cells', 'mt', 'rb', 'n_cells_by_counts', 'mean_counts', 'pct_dropout_by_counts', 'total_counts', 'highly_variable', 'highly_variable_rank', 'means', 'variances', 'variances_norm', 'mean', 'std'
uns: 'log1p', 'hvg', 'pca', 'neighbors', 'umap', 'Coarse_colors', 'Cell types_colors'
obsm: 'X_pca', 'X_umap'
varm: 'PCs'
layers: 'counts'
obsp: 'distances', 'connectivities'
INFO:scDEF:Built hierarchical z/W init from KMeans (100 L0 clusters) using 'X_pca'. INFO:scDEF:Each epoch contains 11 batches of size 256 26%|██▌ | 259/1000 [01:17<03:43, 3.32it/s, Loss=2.95e+6, Rel. impr.=-0.00439] INFO:scDEF:Converged at epoch 260.
Check the fit¶
qc is the composite panel: loss curve, BRD vs Gini, learned-vs-observed scales, relevance distributions. The loss should have plateaued and the scales should track the observed library sizes / gene totals.
scd.pl.qc(model)
Diagnose, filter, re-fit, filter again¶
fit() only prunes the upper layers. Pruning layer 0, the layer you interpret, is a separate step after looking at the diagnostics. The recommended workflow, used for every data set in the scDEF paper, filters twice: a lenient filter after the first fit, which keeps every layer-0 factor with a BRD of at least 1 unless it has very many effective parents, then a second fit from the kept factors, which re-learns the hierarchy, and a second filter, which keeps the factors with at most 1.5 effective parents (or a BRD of at least 4). scd.tl.filter filters and refreshes the diagnostics and the gene signatures.
Here we run the steps one by one to look at the diagnostics in between. model.learn() runs the same four steps in one call; the other tutorials use it.
scd.tl.factor_diagnostics(model)
scd.pl.factor_diagnostics(model, annotate_factors=True)
scd.tl.filter(model, **scd.scDEF.LEARN_FIRST_FILTER) # lenient: the re-fit re-learns the hierarchy
model.fit() # re-fit the reduced hierarchy, warm-started from the first fit
scd.tl.filter(model, **scd.scDEF.LEARN_SECOND_FILTER) # keep the factors that sit in the hierarchy
scd.pl.qc(model)
print([len(fl) for fl in model.factor_lists]) # factors kept per layer
INFO:scDEF:Refit: dropped 1 layer(s) with duplicate adjacent widths; warm-start via composed W (old_keep=[0, 1, 2, 3, 4]). INFO:scDEF:Continuing scDEF from previous fit with layer sizes [21, 9, 6, 4, 1]. INFO:scDEF:Refit: rescaled BRD warm start to geometric mean 1 (range 1.04–4.78 -> 0.572–2.63). INFO:scDEF:Refit: rescaled ARD warm start to geometric mean 1 (range 0.623–12.1 -> 0.209–4.05). INFO:scDEF:Each epoch contains 11 batches of size 256 26%|██▌ | 259/1000 [00:52<02:29, 4.94it/s, Loss=2.93e+6, Rel. impr.=-0.00477] INFO:scDEF:Converged at epoch 260.
[18, 9, 6, 4, 1]
Best of several initialisations. A fit depends on its random initialisation. The paper fits each data set from five seeds and keeps the model with the lowest final loss, which does not use any annotation:
models = [scd.scDEF(adata, counts_layer='counts', seed=s).learn() for s in range(5)] model = min(models, key=lambda m: m.final_loss())
Gene signatures¶
Signature membership is a per-gene posterior call, not a top-N cut. scd.tl.filter has already computed the confident signatures and cached them for every layer, so the graph can print them and the boxplot can show why a gene is in (or out of) one.
Inspect the full hierarchy¶
Before refining anything, see what the model actually found — the full tree, wedged by cell type, with each node's top signature genes.
scd.pl.make_graph(model, show_signatures=True, wedged='Cell types',
color_edges=True, n_cells_label=True)
# Zoom into one node's signature: quartiles/whiskers of each gene's loading, coloured by
# P(in signature). Swap in any layer-0 node from the graph above.
scd.pl.factor_gene_uncertainty_boxplot(
model, factor=model.factor_names[0][0], layer_idx=0,
color_by_confidence=True, confidence_tau_quantile=0.99,
)
Marker genes¶
The signatures above describe each factor's programme. Because each cell combines several factors, the genes with the largest loadings are not always the ones that distinguish a factor's cells: a programme shared with the parent factor can rank high. The marker genes rank the genes by how much more they are expressed where a factor is used than where the other factors of its layer are (the gene spectra scores of cNMF; see the analysis workflow). The paper scores signatures against known markers with them.
marker_genes, marker_scores = scd.tl.marker_genes(model, top_genes=10)
pd.DataFrame({f: marker_genes[f] for f in model.factor_names[0]})
| L0_0 | L0_1 | L0_2 | L0_3 | L0_4 | L0_5 | L0_6 | L0_7 | L0_8 | L0_9 | L0_10 | L0_11 | L0_12 | L0_13 | L0_14 | L0_15 | L0_16 | L0_17 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | LIMD2 | GNLY | FCGR3A | B2M | ARL6IP5 | IGJ | CCL5 | LYZ | LTB | RPL34 | S100A8 | PF4 | CD74 | FUS | RPS2 | FTL | ACTG1 | FCER1A |
| 1 | UCK1 | GZMB | IFITM2 | IFI6 | POLR3K | TNFRSF17 | GZMK | LGALS2 | IL7R | RPS27A | S100A9 | PPBP | HLA-DRA | SH3KBP1 | RPL13 | LST1 | ACTB | CLEC10A |
| 2 | NDUFA4 | NKG7 | CNIH4 | ISG15 | CDC123 | HAGH | GZMH | CD14 | JUN | MT-CO2 | RBP7 | SDPR | CD79B | VPS28 | RPL19 | IFITM3 | PFN1 | HLA-DRB1 |
| 3 | TASP1 | PRF1 | MS4A7 | IFI44L | PCSK7 | MZB1 | CD8A | FCN1 | JUNB | JUNB | S100A12 | GNG11 | MS4A1 | NOC4L | RPS6 | FTH1 | RRM2 | HLA-DPB1 |
| 4 | C17orf62 | FGFBP2 | CTD-2006K23.1 | MT2A | VAMP8 | STAU1 | GZMA | GSTP1 | ZFP36 | CCR7 | G0S2 | GP9 | HLA-DQB1 | HDAC1 | RPS5 | CDKN1C | BIRC5 | HLA-DPA1 |
| 5 | DHX9 | SPON2 | VMO1 | MX1 | CDC40 | PRPS2 | LAG3 | LGALS3 | IER2 | SMDT1 | C19orf59 | SPARC | HLA-DRB1 | FBXO25 | RPL10A | AIF1 | CCNB2 | CST3 |
| 6 | SURF1 | KLRD1 | MS4A4A | IFIT1 | ARL2 | HRASLS2 | CD8B | CTSS | TMSB4X | LEF1 | FTL | CLU | HLA-DPB1 | LYRM2 | TPT1 | HES4 | KIFC1 | HLA-DRB5 |
| 7 | HDDC3 | GZMA | LYPD2 | OAS1 | ARVCF | NR3C1 | CTSW | AP1S2 | TRADD | CTB-113I20.2 | RETN | AP001189.4 | HLA-DQA1 | PTGES2 | NACA | FCER1G | TYMS | HLA-DRA |
| 8 | NFE2L2 | CLIC3 | EIF1AY | OASL | AAGAB | LRRIQ3 | NKG7 | CCL3 | FXYD5 | TRAF3IP3 | IL8 | NRGN | HLA-DQA2 | ARHGDIA | NT5C3A | SAT1 | SH3BGRL3 | CLIC2 |
| 9 | NIFK | AKR1C3 | RP11-1008C21.1 | RFC5 | RAD51B | EARS2 | LYAR | TMEM176B | IL32 | IQCE | S100A6 | TUBB1 | HLA-DPA1 | PARP1 | REG4 | COTL1 | KIAA0101 | SERPINF1 |
Separate technical from biological factors¶
set_technical_factors flags dense, high-entropy factors — typically ambient / mito-ribo or MALAT1-driven programs that don't sit under any one lineage; make_hierarchies then stores biological / technical / global views of the tree.
scd.tl.set_technical_factors(model)
scd.tl.make_hierarchies(model)
scd.pl.biological_hierarchy(model, show_signatures=True, wedged='Cell types')
scd.pl.technical_hierarchy(model, wedged='Cell types')
scd.tl.get_technical_signature(model, top_genes=10)
['RPL13', 'RPS5', 'RPL19', 'RPS6', 'TPT1', 'RPL10A', 'C6orf48', 'NACA', 'CD48', 'MYCBP2']
Confident per-cell assignment¶
Assign each cell at the finest layer it is confident at; ambiguous cells fall back toward the root, and confident_depth_score ranks how undifferentiated a cell is.
scd.tl.assign_confident(model, exclude_technical=True)
sc.pl.umap(model.adata, color=['confident_best_layer', 'confident_depth_score'])
Multi-layer UMAP embeddings¶
scd.tl.umap(model)
scd.pl.umap(model, color='Cell types')
Association of factors with annotations¶
obs_scores links factors to annotations; continuous_obs_scores correlates factors with continuous covariates; signatures_scores measures how well the learned signatures recover the known markers.
scd.pl.obs_scores(model, ['Cell types', 'Coarse'], mode='weights')
scd.pl.continuous_obs_scores(model, ['total_counts', 'pct_counts_mt'], figsize=(16, 2))
scd.pl.signatures_scores(model, 'Cell types', markers, top_genes=20)
Annotate the hierarchy¶
assign_obs_to_factors matches factors to annotation values, giving labels usable as factor_annotations in make_graph.
# Restrict to nodes drawn in the biological hierarchy; `matches` is keyed
# factor -> label, which is what make_graph looks up.
nodes = scd.utils.hierarchy_utils.get_nodes_from_hierarchy(model.adata.uns['biological_hierarchy'])
assignments, matches = scd.utils.factor_utils.assign_obs_to_factors(
model, ['Cell types', 'Coarse'], factor_names=nodes)
scd.pl.make_graph(model, hierarchy=model.adata.uns['biological_hierarchy'],
factor_annotations=matches, show_signatures=True, wedged='Cell types')
A transition across the hierarchy¶
A transition path starts at one layer-0 factor, rises to the ancestor it shares with another layer-0 factor, and descends to that factor. Classical (CD14+) monocytes give rise to non-classical (FCGR3A+) monocytes (Patel et al., 2017), so we take the layer-0 factor with the most CD14+ monocytes as the source and the factor with the most FCGR3A+ monocytes as the target. build_transition_paths returns the paths between them, shortest first, and make_graph draws a path on the hierarchy with path=. score_paths gives every cell a position along each path, from 0 at the source to 1 at the target, and an affinity: the share of the cell's layer-0 weight that falls below the shared ancestor in the tree. A position is meaningful only for cells with a high affinity.
# Factor numbers change between fits, so the endpoints are picked by their cells.
l0 = model.adata.obs['L0'].astype(str)
cell_types = model.adata.obs['Cell types'].astype(str)
source = l0[cell_types == 'CD14+ Mono'].value_counts().index[0]
target = l0[cell_types == 'FCGR3A+ Mono'].value_counts().index[0]
paths = scd.tl.build_transition_paths(model, sources=[source], targets=[target], max_path_len=9)
scd.tl.score_paths(model, paths_key='transition_paths')
paths[0]
['L0_10', 'L1_1', 'L2_1', 'L3_0', 'L2_0', 'L1_0', 'L0_15']
# The path on the hierarchy: its nodes and edges in black.
scd.pl.make_graph(model, path=paths[0], path_color='black', path_node_penwidth=4,
show_signatures=True, wedged='Cell types')
# Cells with an affinity of at least 0.5, ordered by position; one block per node of the path,
# with the factor score and the top genes of the node.
scd.pl.path_trajectory_heatmap(model, path_id=0, paths_key='transition_paths', min_sort_affinity=0.5,
annotation_obs_key='Cell types', heatmap_cmap='viridis')
The CD14+ monocytes come first and the FCGR3A+ monocytes last. The genes of the source factor fall along the path and those of the target factor rise, and the nodes above them show the programme the two monocyte types share. A path between two factors does not by itself show that one state gives rise to the other, because the tree groups factors by expression, not by lineage; here the transition is known.
Save the fitted model¶
model.save('scdef-pbmcs3k', overwrite=True)
# reload later with: model = scd.scDEF.load('scdef-pbmcs3k')