scDEF tutorial — two batches of PBMCs¶
Two batches of healthy PBMCs (donors pbmc1 / pbmc2, one Drop-seq run each). They share the same cell types, so almost all between-batch variation is technical. This notebook shows scDEF's batch integration and the standard batch-interpretation procedure: fit a reference with batch_key, then decompose_batch_effects and inspect layer 0 to decide what is technical vs biological. The interferon notebook runs the same procedure and reaches the opposite conclusion.
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 signature validation)¶
markers = {
'CD4+ T cell': ['CD3D', 'CD3E', 'CD3G', 'TRAC', 'CD4', 'TCF7', 'CD27', 'IL7R'],
'Cytotoxic T cell': ['CD3D', 'CD3E', 'CD3G', 'TRAC', 'CD8A', 'CD8B', 'GZMK', 'CCL5', 'NKG7'],
'CD14+ monocyte': ['VCAN', 'FCN1', 'S100A8', 'S100A9', 'CD14', 'ITGAL', 'ITGAM', 'CSF3R',
'CSF1R', 'CX3CR1', 'TYROBP', 'LYZ', 'S100A12'],
'CD16+ monocyte': ['FCN1', 'FCGR3A', 'FCGR3B', 'ITGAL', 'ITGAM', 'CSF3R', 'CSF1R', 'CX3CR1',
'CDKN1C', 'MS4A7'],
'Dendritic cell': ['HLA-DPB1', 'HLA-DPA1', 'HLA-DQA1', 'ITGAX', 'CD1C', 'FCER1A', 'CLEC10A',
'FCGR2B', 'MS4A1', 'CD79A', 'CD79B'],
'Plasmacytoid dendritic cell': ['IL3RA', 'GZMB', 'JCHAIN', 'IRF7', 'TCF4', 'LILRA4', 'CLEC4C'],
'B cell': ['CD19', 'MS4A1', 'CD79A', 'CD79B', 'MZB1', 'IGHD', 'IGHM'],
'Natural killer cell': ['NCAM1', 'NKG7', 'KLRB1', 'KLRD1', 'KLRF1', 'KLRC1', 'KLRC2', 'KLRC3',
'KLRC4', 'FCGR3A', 'FCGR3B', 'ITGAL', 'ITGAM', 'FCER1G'],
'Megakaryocyte': ['PF4', 'PPBP', 'ITGA2B', 'NRGN', 'TUBB1', 'SPARC', 'RGS18', 'GNG11'],
}
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/pbmcs_data/pbmcsca.h5ad')
# One technology (Drop-seq); the two donors pbmc1/pbmc2 are the two batches.
adata = adata[adata.obs['Method'] == 'Drop-seq'].copy()
adata.obs['Experiment'].value_counts()
Experiment pbmc2 3362 pbmc1 3222 Name: count, dtype: int64
# QC + counts layer (following the paper preprocessing).
sc.pp.filter_cells(adata, min_genes=200)
sc.pp.filter_genes(adata, min_cells=10)
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 < 2000, :]
adata = adata[adata.obs.pct_counts_mt < 8, :]
adata.layers['counts'] = adata.X.toarray()
/tmp/ipykernel_768540/1256034521.py:9: ImplicitModificationWarning: Setting element `.layers['counts']` of view, initializing view as actual. adata.layers['counts'] = adata.X.toarray()
# HVG on the counts, per batch; 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', n_top_genes=4000, layer='counts',
batch_key='Experiment')
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)
# Coarse cell type (CellType) and fine subtype (SubType).
stypes = {'CD4+ T cell': 'T cell', 'Cytotoxic T cell': 'T cell',
'CD14+ monocyte': 'Monocyte', 'CD16+ monocyte': 'Monocyte', 'Dendritic cell': 'Monocyte'}
adata.obs['SubType'] = adata.obs['CellType']
adata.obs['CellType'] = adata.obs['CellType'].replace(stypes)
sc.pl.umap(adata, color=['CellType', 'SubType', 'Experiment'], frameon=False)
/tmp/ipykernel_768540/488915410.py:5: FutureWarning: The behavior of Series.replace (and DataFrame.replace) with CategoricalDtype is deprecated. In a future version, replace will only be used for cases that preserve the categories. To change the categories, use ser.cat.rename_categories instead. adata.obs['CellType'] = adata.obs['CellType'].replace(stypes)
Fit scDEF with batch annotations¶
batch_key lets scDEF model per-batch library sizes and gene detection rates — the one direct batch correction it applies; sparsity and the hierarchy do the rest.
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.
ref = scd.scDEF(adata, counts_layer='counts', batch_key='Experiment')
print(ref)
ref.learn()
INFO:scDEF:Found 2 values for `Experiment` in data: ['pbmc1' 'pbmc2']
scDEF object with 6 layers
Layer names: L0, L1, L2, L3, L4, L5
Layer sizes: 100, 40, 16, 6, 3, 1
alpha parameter: 3.52
Using BRD
Number of batches: 2
Contains AnnData object with n_obs × n_vars = 6412 × 4009
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'nGene', 'nUMI', 'percent.mito', 'Cluster', 'CellType', 'Experiment', 'Method', 'n_genes', 'n_genes_by_counts', 'total_counts', 'total_counts_mt', 'pct_counts_mt', 'total_counts_rb', 'pct_counts_rb', 'SubType'
var: 'features', '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', 'highly_variable_nbatches', 'mean', 'std'
uns: 'log1p', 'hvg', 'pca', 'neighbors', 'umap', 'CellType_colors', 'SubType_colors', 'Experiment_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 26 batches of size 256 24%|██▍ | 245/1000 [02:40<08:15, 1.52it/s, Loss=4.54e+6, Rel. impr.=-0.00384] INFO:scDEF:Converged at epoch 246. INFO:scDEF:Refit: dropped 1 layer(s) with duplicate adjacent widths; warm-start via composed W (old_keep=[0, 1, 2, 3, 5]). INFO:scDEF:Continuing scDEF from previous fit with layer sizes [15, 11, 6, 3, 1]. INFO:scDEF:Refit: rescaled BRD warm start to geometric mean 1 (range 1–4.29 -> 0.532–2.28). INFO:scDEF:Refit: rescaled ARD warm start to geometric mean 1 (range 0.0345–2.16 -> 0.141–6.66). INFO:scDEF:Each epoch contains 26 batches of size 256 14%|█▍ | 142/1000 [01:06<06:44, 2.12it/s, Loss=4.49e+6, Rel. impr.=-0.00923] INFO:scDEF:Converged at epoch 143.
scDEF object with 5 layers
Layer names: L0, L1, L2, L3, L4
Layer sizes: 11, 6, 4, 3, 1
alpha parameter: 3.52
Using BRD
Number of batches: 2
Contains AnnData object with n_obs × n_vars = 6412 × 4009
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'nGene', 'nUMI', 'percent.mito', 'Cluster', 'CellType', 'Experiment', 'Method', 'n_genes', 'n_genes_by_counts', 'total_counts', 'total_counts_mt', 'pct_counts_mt', 'total_counts_rb', 'pct_counts_rb', 'SubType', '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', 'L1_0_score', 'L1_1_score', 'L1_2_score', 'L1_3_score', 'L1_4_score', 'L1_5_score', 'L2_0_score', 'L2_1_score', 'L2_2_score', 'L2_3_score', 'L3_0_score', 'L3_1_score', 'L3_2_score', 'L4_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', 'L1_0_prob', 'L1_1_prob', 'L1_2_prob', 'L1_3_prob', 'L1_4_prob', 'L1_5_prob', 'L2_0_prob', 'L2_1_prob', 'L2_2_prob', 'L2_3_prob', 'L3_0_prob', 'L3_1_prob', 'L3_2_prob', 'L4_0_prob'
var: 'features', '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', 'highly_variable_nbatches', 'mean', 'std', 'gene_scale_0', 'gene_scale_1'
uns: 'log1p', 'hvg', 'pca', 'neighbors', 'umap', 'CellType_colors', 'SubType_colors', 'Experiment_colors', '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', '_factor_obs_upper_lists_fixed', '_factor_obs_fit_revision', 'confident_signatures', 'factor_signatures'
obsm: 'X_pca', 'X_umap', '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: 'distances', 'connectivities'
Check the fit¶
scd.pl.qc(ref)
scd.pl.factor_diagnostics(ref, annotate_factors=True)
print([len(fl) for fl in ref.factor_lists]) # factors kept per layer
[11, 6, 4, 3, 1]
Batches are integrated¶
Across layers, cell types separate while the two batches stay mixed — integration without over-correction.
scd.tl.umap(ref)
scd.pl.umap(ref, color=['SubType', 'Experiment'])
Factors track cell type, not batch¶
Factors associate with SubType far more than with Experiment, and no layer-0 factor is specific to one donor.
scd.pl.obs_scores(ref, ['SubType', 'Experiment'], mode='weights')
scd.pl.make_graph(ref, wedged='Experiment', n_cells_label=True) # no batch-dominated node
scd.pl.signatures_scores(ref, 'SubType', markers, top_genes=20)
Same factors used across batches, within a cell type¶
A per-cell factor heatmap restricted to one cell type and grouped by batch confirms integration at the single-cell level. We look at monocytes — the cell type that responds in the interferon notebook — and here both batches use the same factors, with no batch-specific program. That is the direct contrast: the analogous heatmap in the interferon notebook shows a condition-specific split.
scd.pl.obs_cell_factor_heatmap(ref, subset_obs_key='CellType',
subset_obs='Monocyte', group_obs_key='Experiment', values='score')
Standard batch interpretation: decompose and inspect layer 0¶
Fitting with batch_key corrects a per-gene batch scale. To see what that term absorbed and decide whether any residual per-batch structure is technical or biological, re-learn the lower layers without the batch term (decompose_batch_effects) and inspect its factors. This is the standard step for any multi-batch data set: ref stays the representation you use downstream, dec is the diagnostic.
The decomposition keeps the cell weights of one layer, the anchor (top_layer), and the layers above it fixed, and re-learns the layers below without the batch term, so whatever that term absorbed reappears as factors under the fixed groups of the anchor. The anchor should mix the batches and still resolve the groups under which batch-specific programmes are expected. As in the paper, we use layer 2: in the graph above, its factors contain cells of both batches and still separate the main cell types, so a batch effect can appear at layers 0 and 1.
dec = scd.scDEF.decompose_batch_effects(ref, top_layer=2)
scd.tl.factor_diagnostics(dec, batch_key='Experiment') # batch structure + gene signatures for decomposed L0
INFO:scDEF:batch_cell_scale=True: keeping the per-batch cell_scale prior from `Experiment` (2 batches) while gene_scale stays a single shared row. INFO:scDEF:Found 2 values for `Experiment` in data: ['pbmc1' 'pbmc2'] INFO:scDEF:batch_gene_scale=False: keeping a single shared `gene_scale` row while fitting the per-batch `cell_scale` prior. INFO:scDEF:Each epoch contains 26 batches of size 256 61%|██████▏ | 245/400 [02:01<01:17, 2.01it/s, Loss=4.53e+6, Rel. impr.=-0.00483] INFO:scDEF:Converged at epoch 246.
rep = scd.tl.batch_structure_report(dec, batch_key='Experiment')
rep # `shape` describes each L0 factor's batch structure
| n_cells | dom_batch | frac_dom_batch | batch_purity_soft | loading_ratio | eff_parents | parent | opp_batch_sibling | branch_auc | shape | gene_scale_affinity_pbmc1 | gene_scale_affinity_pbmc2 | gene_scale_affinity_max | gene_scale_affinity_batch | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| L0 | ||||||||||||||
| L0_1 | 935 | pbmc1 | 0.992513 | 0.782453 | 4.206728 | 1.062636 | L1_5 | False | 0.993430 | branch_skewed | 0.536406 | -0.536406 | 0.536406 | pbmc1 |
| L0_7 | 962 | pbmc2 | 0.984407 | 0.760603 | 4.952753 | 1.003802 | L1_2 | False | 0.996568 | branch_skewed | -0.468938 | 0.468938 | 0.468938 | pbmc2 |
| L0_9 | 389 | pbmc1 | 0.812339 | 0.692730 | 1.093131 | 1.159727 | L1_0 | False | 0.967348 | branch_skewed | 0.105144 | -0.105144 | 0.105144 | pbmc1 |
| L0_2 | 37 | pbmc1 | 0.810811 | 0.525912 | 1.055968 | 2.360935 | L1_1 | True | 0.993918 | overlaid | -0.053899 | 0.053899 | 0.053899 | pbmc2 |
| L0_3 | 1173 | pbmc2 | 0.713555 | 0.716546 | 1.342819 | 1.000475 | L1_1 | True | 0.993918 | branch_split | -0.296013 | 0.296013 | 0.296013 | pbmc2 |
| L0_6 | 186 | pbmc2 | 0.709677 | 0.610896 | 1.634865 | 2.117012 | L1_2 | False | 0.996568 | overlaid | -0.133957 | 0.133957 | 0.133957 | pbmc2 |
| L0_4 | 1132 | pbmc1 | 0.704064 | 0.655233 | 3.591813 | 1.396716 | L1_4 | False | 0.998293 | branch_skewed | 0.239299 | -0.239299 | 0.239299 | pbmc1 |
| L0_10 | 297 | pbmc2 | 0.659933 | 0.611839 | 1.681098 | 2.240925 | L1_2 | False | 0.996568 | balanced | -0.051306 | 0.051306 | 0.051306 | pbmc2 |
| L0_0 | 406 | pbmc2 | 0.652709 | 0.580778 | 1.267313 | 3.275811 | L1_1 | True | 0.993918 | balanced | -0.073366 | 0.073366 | 0.073366 | pbmc2 |
| L0_8 | 701 | pbmc2 | 0.556348 | 0.513470 | 0.581671 | 1.165960 | L1_3 | False | 0.996064 | balanced | -0.097412 | 0.097412 | 0.097412 | pbmc2 |
| L0_5 | 194 | pbmc1 | 0.520619 | 0.548076 | 1.099895 | 1.209169 | L1_0 | False | 0.967348 | balanced | -0.009349 | 0.009349 | 0.009349 | pbmc2 |
The report describes geometry, not cause. For these healthy batches the per-batch structure is technical — per-batch views of a shared cell type (branch_split / branch_skewed). See the split first, then fold it back into the batch-corrected parent. (In the interferon notebook the analogous split is a genuine biological response and is kept — same procedure, different decision from the experimental design.)
# The per-batch splits: same cell type appearing as two L0 factors under one parent.
scd.pl.make_graph(dec, wedged='Experiment', show_signatures=True, n_cells_label=True)
flagged = rep.index[rep['shape'].isin(['branch_split', 'branch_skewed'])]
print('flagged as batch-technical:', list(flagged))
scd.tl.set_batch_technical_factors(dec, flagged)
scd.tl.factor_batch_correction(dec)
flagged as batch-technical: ['L0_1', 'L0_7', 'L0_9', 'L0_3', 'L0_4']
factor_batch_correction folds each flagged split back into its shared parent, writing obsm['X_L0_batch_corrected'] and two label columns: L0_batch_corrected (the merged-sibling name, such as L0_1+L0_7) and batch_corrected (each cell's roll-up). Colouring by Experiment as well shows what the folding does: layer 0 of the decomposition separates the two donors, and each folded label covers the cells of both.
scd.tl.umap(dec)
scd.pl.umap(dec, color=['Experiment', 'L0_batch_corrected', 'batch_corrected'])
Save the fitted models¶
ref.save('scdef-pbmcs2b-ref', overwrite=True) # the representation to use downstream
dec.save('scdef-pbmcs2b-dec', overwrite=True) # the batch-structure diagnostic