Skip to content

scdef.decompose_batch_effects

decompose_batch_effects(reference_model: 'scDEF', *, adata: Optional[AnnData] = None, counts_layer: Optional[str] = None, batch_cell_scale: bool = True, top_layer: int = 1, n_epoch: int = 400, lr: float = 0.05, tolerance: float = 0.0001, nmf_init: bool = False, init_gene_scale: Union[str, ndarray] = 'reference', **fit_kwargs: Any) -> 'scDEF'

Re-learn lower layers under a frozen upper hierarchy to discover batch programs.

Two-stage workflow:

  1. reference_model was fitted with a batch_key, producing a hierarchy where per-batch gene_scale absorbed between-batch variance.
  2. This function creates a new model with the per-batch gene_scale switched off, warm-starts all W from the reference, and re-learns all layers up to top_layer. At the boundary (top_layer), only W is re-learned while z stays fixed — preserving the cell-to-group assignments as the structural constraint. Layers below top_layer are fully re-learned (both W and z). Layers above top_layer remain completely fixed.

Which half of batch_key is discarded. batch_key in scDEF controls two independent quantities:

  • the gene side — gene_scale with one row per batch, i.e. a gene-specific per-batch multiplier;
  • the cell side — batch_lib_sizes / batch_lib_ratio, the per-batch Gamma prior that cell_scale shrinks toward, i.e. a gene-independent per-batch multiplier.

Only the gene side must go. A gene-specific term can express a gene programme, so leaving it in place would let it re-absorb exactly the structure this function is trying to surface in the L0 factors. A gene-independent term cannot express a programme at all — it is one number per batch, so the most it can represent is sequencing depth. Historically both were discarded together; batch_cell_scale=True (the default) now keeps the cell side.

Keeping the cell side is expected to reduce the depth component that would otherwise have to land in z: with batch_key=None the model shrinks every cell_scale toward a single Gamma fitted to the pooled library-size mean and variance, which is misspecified for both batches when they differ in depth. This expectation has not been validated by refitting; no claim is made here about the effect on the resulting factors.

L0 factor BRD and ARD are re-initialized from model priors rather than copied from the reference, so factor relevance can be re-estimated during decomposition.

How the shared gene_scale is warm-started. The count-derived prior alone leaves a large reconstruction gap here, because the batch-key model often learns per-batch scales orders of magnitude above it. The default (init_gene_scale='reference') instead solves for the shared scale directly: with the likelihood mean (z @ W) * cell_scale * gene_scale, summing over cells at this model's own initialization gives U_g = ((cell_scale^T z_0) W_0)_g, and s_g = X.sum(0)_g / U_g is the maximum-likelihood shared scale for the pooled marginal of gene g. It is computed from the target data and this model's warm starts, so it needs no transplant of the reference's fitted scale, and it applies whether the reference had one gene_scale row or several.

This is exact for the pooled marginal only. A single shared row still cannot fit two batches whose levels for a gene differ — no shared scale can. That residual is left deliberately unabsorbed: pushing it into z @ W is what makes per-batch structure visible in the re-learned lower layers, which is the point of the decomposition. What the pooled MLE removes is the part that is not structure, namely a systematic level offset in the warm start.

With top_layer=1 (default): - L0: W warm-started and re-learned, z re-learned - L1: W warm-started and re-learned, z frozen - L2+: fully frozen

With top_layer=2: - L0: W warm-started and re-learned, z re-learned - L1: W warm-started and re-learned, z re-learned - L2: W warm-started and re-learned, z frozen - L3+: fully frozen

Parameters:

Name Type Description Default
reference_model 'scDEF'

a fitted scDEF that was trained with batch_key.

required
adata Optional[AnnData]

AnnData for the second stage. Defaults to reference_model.adata.

None
counts_layer Optional[str]

counts layer for adata.

None
batch_cell_scale bool

if True (default), carry the reference model's batch_key into the decomposed model with batch_gene_scale=False, so the per-batch cell_scale prior is kept while gene_scale stays a single shared row. Degrades gracefully (with a log message) to no batch key when the reference has no batch_key, when that key is absent from the target adata.obs, or when fewer than two batches are present in the cells being fitted. Set to False to reproduce the historical construction, which discarded both sides.

True
top_layer int

the highest layer whose W is re-learned. Its z remains frozen as the structural anchor. Default 1.

1
n_epoch int

training epochs for the re-learning phase.

400
lr float

learning rate for the re-learning phase.

0.05
tolerance float

early-stopping tolerance.

0.0001
nmf_init bool

if True, initialize L0 W via NMF on the data instead of warm-starting from the reference. Default False.

False
init_gene_scale Union[str, ndarray]

warm start for the shared gene_scale in the decomposed model.

  • "reference" (default): the pooled-marginal MLE X.sum(0)_g / ((cell_scale^T z_0) W_0)_g, which reproduces the observed pooled counts exactly at initialization (see above). Falls back to the geometric mean of reference_model.pmeans['gene_scale'] across batches when nmf_init=True — layer-0 W is then set by NMF, so a profile derived from the reference W would not describe the model's actual initialization — and, per gene, for genes with no factor support.
  • "prior": only the count-derived prior mean (1 / gene_ratio_init).
  • an explicit (n_genes,) array.
'reference'
**fit_kwargs Any

additional keyword arguments forwarded to _learn.

{}

Returns:

Type Description
'scDEF'

A new fitted model whose lower-layer factors reveal batch-specific

'scDEF'

and shared gene programs under the frozen upper-layer cell assignments.