scDEF tutorial — interferon-stimulated PBMCs¶
Two batches of PBMCs, one stimulated with interferon-beta and one control (stim = STIM / CTRL). Batch is confounded with condition, so correction must not erase the real signal. This notebook runs the same reference → decompose → inspect-L0 procedure as the two-batch notebook, but the per-batch monocyte split turns out to be the genuine interferon response (CCL8, CXCL10, ISG15) — biological, and kept.
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.
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/ifnb/ifnb.h5ad')
# Cell-type labels and condition live in the metadata csv.
adata.obs = pd.read_csv('../scdef_data/pbmcs_data/ifnb/ifnb_metadata.csv', index_col=0)
adata.raw = None
adata.layers['counts'] = adata.X.copy() # X holds raw counts
adata.obs['stim'].value_counts()
stim STIM 7451 CTRL 6548 Name: count, dtype: int64
# QC (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-')
sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], percent_top=None, log1p=False, inplace=True)
adata = adata[adata.obs.n_genes_by_counts < 5000, :]
adata = adata[adata.obs.pct_counts_mt < 5, :]
# HVG on counts, per batch; then a scanpy embedding for the colors.
sc.pp.highly_variable_genes(adata, flavor='seurat_v3', n_top_genes=4000, layer='counts',
batch_key='stim')
adata = adata[:, adata.var.highly_variable].copy()
sc.pp.normalize_total(adata, target_sum=1e4)
sc.pp.log1p(adata)
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)
/home/pedro/.local/lib/python3.10/site-packages/scanpy/preprocessing/_highly_variable_genes.py:172: ImplicitModificationWarning: Trying to modify attribute `._uns` of view, initializing view as actual.
adata.uns["hvg"] = {"flavor": flavor}
# A cell-state label that splits monocytes by condition (the effect of interest).
adata.obs['cell_state'] = adata.obs.apply(
lambda r: f"{r['seurat_annotations']}_{r['stim']}" if 'Mono' in str(r['seurat_annotations'])
else r['seurat_annotations'], axis=1).astype('category')
sc.pl.umap(adata, color=['seurat_annotations', 'stim'], frameon=False)
Fit reference scDEF with batch annotations¶
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='stim')
print(ref)
ref.learn()
INFO:scDEF:Found 2 values for `stim` in data: ['CTRL' 'STIM']
scDEF object with 6 layers
Layer names: L0, L1, L2, L3, L4, L5
Layer sizes: 100, 40, 16, 6, 3, 1
alpha parameter: 4.44
Using BRD
Number of batches: 2
Contains AnnData object with n_obs × n_vars = 13999 × 4000
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'stim', 'seurat_annotations', 'n_genes', 'n_genes_by_counts', 'total_counts', 'total_counts_mt', 'pct_counts_mt', 'cell_state'
var: 'features', 'n_cells', 'mt', '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: 'hvg', 'log1p', 'pca', 'neighbors', 'umap', 'seurat_annotations_colors', 'stim_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 55 batches of size 256 100%|██████████| 1000/1000 [14:04<00:00, 1.18it/s, Loss=1.12e+7, Rel. impr.=-0.00035] INFO:scDEF:Stopping learning: reached max epochs (n_epoch=1000). INFO:scDEF:Continuing scDEF from previous fit with layer sizes [30, 16, 9, 5, 3, 1]. INFO:scDEF:Refit: rescaled BRD warm start to geometric mean 1 (range 1.29–6.42 -> 0.512–2.55). INFO:scDEF:Refit: rescaled ARD warm start to geometric mean 1 (range 2.54e-05–0.00583 -> 0.141–7.07). INFO:scDEF:Each epoch contains 55 batches of size 256 24%|██▍ | 239/1000 [03:09<10:02, 1.26it/s, Loss=1.11e+7, Rel. impr.=-0.000308] INFO:scDEF:Converged at epoch 240.
scDEF object with 6 layers
Layer names: L0, L1, L2, L3, L4, L5
Layer sizes: 23, 15, 8, 5, 3, 1
alpha parameter: 4.44
Using BRD
Number of batches: 2
Contains AnnData object with n_obs × n_vars = 13999 × 4000
obs: 'orig.ident', 'nCount_RNA', 'nFeature_RNA', 'stim', 'seurat_annotations', 'n_genes', 'n_genes_by_counts', 'total_counts', 'total_counts_mt', 'pct_counts_mt', 'cell_state', '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', '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', 'L2_0_score', 'L2_1_score', 'L2_2_score', 'L2_3_score', 'L2_4_score', 'L2_5_score', 'L2_6_score', 'L2_7_score', 'L3_0_score', 'L3_1_score', 'L3_2_score', 'L3_3_score', 'L3_4_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', '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', 'L2_0_prob', 'L2_1_prob', 'L2_2_prob', 'L2_3_prob', 'L2_4_prob', 'L2_5_prob', 'L2_6_prob', 'L2_7_prob', 'L3_0_prob', 'L3_1_prob', 'L3_2_prob', 'L3_3_prob', 'L3_4_prob', 'L4_0_prob', 'L4_1_prob', 'L4_2_prob', 'L5_0_prob'
var: 'features', 'n_cells', 'mt', '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: 'hvg', 'log1p', 'pca', 'neighbors', 'umap', 'seurat_annotations_colors', 'stim_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', 'L5_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
[23, 15, 8, 5, 3, 1]
With batch annotations, the conditions mix¶
Across layers, cell types separate and the two conditions mix. The monocytes, which respond most strongly to interferon, separate by condition only slightly (cell_state): the per-batch gene scale has absorbed most of their response. Here that response is the signal to keep, and the decomposition below recovers it.
scd.tl.umap(ref)
scd.pl.umap(ref, color=['cell_state', 'stim'])
scd.pl.obs_scores(ref, ['cell_state', 'stim'], mode='weights')
scd.pl.make_graph(ref, wedged='stim', show_signatures=True, n_cells_label=True)
Decompose and inspect layer 0¶
Same procedure as the two-batch notebook: re-learn the lower layers without the batch term and read the batch-structure report. Fitting with batch_key pushed the condition signal into the per-batch gene scale, so everything condition-specific is clearest on the decomposed model dec — that's where the interferon factors re-appear.
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='stim') # batch structure + gene signatures for decomposed L0
rep = scd.tl.batch_structure_report(dec, batch_key='stim') # `shape` = each L0 factor's batch structure
rep
INFO:scDEF:batch_cell_scale=True: keeping the per-batch cell_scale prior from `stim` (2 batches) while gene_scale stays a single shared row. INFO:scDEF:Found 2 values for `stim` in data: ['CTRL' 'STIM'] 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 55 batches of size 256 55%|█████▌ | 221/400 [02:37<02:07, 1.40it/s, Loss=1.17e+7, Rel. impr.=-0.000487] INFO:scDEF:Converged at epoch 222.
| n_cells | dom_batch | frac_dom_batch | batch_purity_soft | loading_ratio | eff_parents | parent | opp_batch_sibling | branch_auc | shape | gene_scale_affinity_CTRL | gene_scale_affinity_STIM | gene_scale_affinity_max | gene_scale_affinity_batch | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| L0 | ||||||||||||||
| L0_1 | 26 | CTRL | 1.000000 | 0.730117 | 2.771078 | 2.026653 | L1_3 | False | 0.999854 | overlaid | 0.336251 | -0.336251 | 0.336251 | CTRL |
| L0_22 | 149 | CTRL | 1.000000 | 0.772809 | 4.489899 | 1.853394 | L1_3 | False | 0.999854 | overlaid | 0.188906 | -0.188906 | 0.188906 | CTRL |
| L0_14 | 982 | CTRL | 0.998982 | 0.861964 | 2.134418 | 1.000586 | L1_3 | False | 0.999854 | branch_skewed | 0.298270 | -0.298270 | 0.298270 | CTRL |
| L0_5 | 1340 | STIM | 0.997015 | 0.899226 | 9.877928 | 2.884199 | L1_13 | True | 0.998188 | overlaid | -0.232306 | 0.232306 | 0.232306 | STIM |
| L0_0 | 592 | CTRL | 0.996622 | 0.720249 | 2.187682 | 2.045351 | L1_4 | False | NaN | overlaid | 0.163896 | -0.163896 | 0.163896 | CTRL |
| L0_2 | 117 | CTRL | 0.991453 | 0.680119 | 1.795659 | 1.840897 | L1_4 | False | NaN | overlaid | 0.017937 | -0.017937 | 0.017937 | CTRL |
| L0_17 | 1142 | STIM | 0.991243 | 0.902843 | 1.894525 | 1.000410 | L1_8 | False | NaN | branch_skewed | -0.459920 | 0.459920 | 0.459920 | STIM |
| L0_18 | 894 | STIM | 0.989933 | 0.874082 | 1.798003 | 1.007597 | L1_8 | False | NaN | branch_skewed | -0.250729 | 0.250729 | 0.250729 | STIM |
| L0_21 | 183 | CTRL | 0.983607 | 0.738883 | 2.093168 | 2.009997 | L1_2 | True | 0.999902 | overlaid | 0.193649 | -0.193649 | 0.193649 | CTRL |
| L0_6 | 75 | CTRL | 0.933333 | 0.588100 | 1.571770 | 1.361355 | L1_2 | True | 0.999902 | branch_split | 0.122357 | -0.122357 | 0.122357 | CTRL |
| L0_7 | 528 | CTRL | 0.888258 | 0.641192 | 1.735145 | 1.013875 | L1_7 | False | 0.999228 | branch_skewed | 0.062504 | -0.062504 | 0.062504 | CTRL |
| L0_4 | 763 | STIM | 0.727392 | 0.715799 | 0.838673 | 1.007486 | L1_5 | False | 0.999930 | branch_skewed | -0.106877 | 0.106877 | 0.106877 | STIM |
| L0_3 | 23 | STIM | 0.695652 | 0.586272 | 1.221423 | 3.511534 | L1_8 | False | NaN | balanced | 0.016940 | -0.016940 | 0.016940 | CTRL |
| L0_12 | 301 | STIM | 0.691030 | 0.638298 | 0.679766 | 1.424975 | L1_6 | False | 0.999766 | balanced | -0.056296 | 0.056296 | 0.056296 | STIM |
| L0_10 | 1854 | CTRL | 0.605178 | 0.586869 | 1.136832 | 1.001447 | L1_13 | True | 0.998188 | balanced | 0.214567 | -0.214567 | 0.214567 | CTRL |
| L0_9 | 188 | STIM | 0.569149 | 0.500845 | 0.874031 | 1.068427 | L1_2 | True | 0.999902 | balanced | 0.002229 | -0.002229 | 0.002229 | CTRL |
| L0_13 | 62 | STIM | 0.564516 | 0.560144 | 1.248171 | 1.097087 | L1_10 | False | NaN | balanced | 0.135483 | -0.135483 | 0.135483 | CTRL |
| L0_16 | 1006 | STIM | 0.558648 | 0.500075 | 0.956854 | 1.370635 | L1_11 | False | 0.998297 | balanced | 0.140050 | -0.140050 | 0.140050 | CTRL |
| L0_19 | 1661 | CTRL | 0.558098 | 0.504238 | 1.222532 | 1.001623 | L1_13 | True | 0.998188 | balanced | 0.166693 | -0.166693 | 0.166693 | CTRL |
| L0_20 | 228 | STIM | 0.526316 | 0.505790 | 1.110022 | 1.618739 | L1_9 | False | NaN | balanced | 0.197031 | -0.197031 | 0.197031 | CTRL |
| L0_15 | 567 | CTRL | 0.525573 | 0.528974 | 0.953493 | 1.305771 | L1_1 | False | 0.988972 | balanced | 0.110523 | -0.110523 | 0.110523 | CTRL |
| L0_8 | 379 | STIM | 0.525066 | 0.502342 | 0.958725 | 1.366807 | L1_0 | False | 0.977539 | balanced | 0.142280 | -0.142280 | 0.142280 | CTRL |
| L0_11 | 939 | STIM | 0.521832 | 0.506168 | 1.223339 | 1.082873 | L1_12 | False | 0.993644 | balanced | 0.170438 | -0.170438 | 0.170438 | CTRL |
Which factors respond to the condition, within a cell type¶
On dec, a per-cell factor heatmap restricted to one cell type and grouped by condition shows which factors carry the response (values='prob' = normalized memberships). Stimulated monocytes light up a block of interferon factors that control monocytes lack: interferon-stimulated genes (ISG15, IFI27, RSAD2), CXCL10 with the IFIT genes, and the chemokines CCL2, CCL7 and CCL8, which part of the control monocytes also use. Stimulated naive CD4 T cells use an interferon-stimulated-gene factor of their own (ISG15, IFI6, ISG20) and none of the monocyte factors: the same genes respond in both cell types, but in separate, cell-type-specific factors.
scd.pl.obs_cell_factor_heatmap(dec, subset_obs_key='seurat_annotations',
subset_obs='CD14 Mono', group_obs_key='stim', values='prob',
figsize=(8, 4))
scd.pl.obs_cell_factor_heatmap(dec, subset_obs_key='seurat_annotations',
subset_obs='CD4 Naive T', group_obs_key='stim', values='prob',
figsize=(8, 4))
Biological vs technical decision¶
The report describes only geometry. Run the same flagging line as the two-batch notebook, then inspect what it caught: the batch-skewed monocyte factors carry the interferon response (CCL8/CXCL10/ISG15). That is biological — a real, cell-type-specific reaction — so, unlike the two-batch case, we deliberately do not call set_batch_technical_factors.
flagged = rep.index[rep['shape'].isin(['branch_split', 'branch_skewed'])]
print('batch-skewed factors:', list(flagged))
sigs = scd.tl.get_stored_confident_signatures(dec, layer_idx=0, max_genes=10)
sigs = sigs[0] if isinstance(sigs, tuple) else sigs
for f in flagged:
print(f, list(sigs.get(f, []))[:10]) # the interferon program sits among these -> keep
batch-skewed factors: ['L0_14', 'L0_17', 'L0_18', 'L0_6', 'L0_7', 'L0_4'] L0_14 ['IL8', 'S100A8', 'CXCL3', 'IL1B', 'CD14', 'VCAN', 'TIMP1', 'CLEC5A', 'OSM', 'CTB-61M7.2'] L0_17 ['ISG15', 'APOBEC3A', 'IFITM3', 'IDO1', 'IFI27', 'DEFB1', 'HESX1', 'ISG20', 'RSAD2', 'SERPING1'] L0_18 ['CXCL10', 'CXCL11', 'TNFSF10', 'IFIT2', 'IFIT3', 'IFIT1', 'FAM26F', 'GBP1', 'CD69', 'ANKRD22'] L0_6 ['HLA-DRA', 'CD74', 'HLA-DRB1', 'HLA-DPB1', 'HLA-DPA1', 'HLA-DQA1', 'HLA-DQB1', 'HLA-DMA', 'PABPC1', 'FABP5'] L0_7 ['FCGR3A', 'VMO1', 'MS4A4A', 'TIMP1', 'C1QB', 'CDKN1C', 'PPM1N', 'CASP5', 'SMPDL3A', 'MS4A7'] L0_4 ['CCL8', 'CCL2', 'CCL7', 'CTSL', 'SDS', 'LYZ', 'S100A9', 'HPSE', 'CTSB', 'RSAD2']
scd.pl.make_graph(dec, wedged='stim', show_signatures=True, n_cells_label=True)
Conclusion. On healthy batches (the two-batch notebook) the same report yields technical per-batch splits, which we fold away with set_batch_technical_factors + factor_batch_correction. Here the identical geometry is a biological, cell-type-specific response — so we leave it untouched. Same procedure, opposite decision, made from the experimental design.
Save the fitted models¶
ref.save('scdef-ifn-ref', overwrite=True)
dec.save('scdef-ifn-dec', overwrite=True)