Skip to content

scdef.tl.batch_structure_report

batch_structure_report(model: scDEF, batch_key: Optional[str] = None, group_layer: int = 1, min_group_cells: int = 80, random_seed: int = 0, reference: Union[scDEF, DataFrame, ndarray, None] = None) -> DataFrame

Describe how batch structure appears among the layer-0 factors.

Summarises the shape of that structure — how batch-skewed each L0 factor is, whether it has an opposite-batch sibling under the same parent, whether it is confined to one branch or overlaid across several, and how separable the batches are inside each branch — so that the analyst can decide what to filter, correct (factor_batch_correction) or keep.

Any fitted model with two layers works, provided batch_key is a column of adata.obs. The model need not have been fitted with that key, and need not have come from decompose_batch_effects. What the report means does depend on which it is:

  • a plain fit with no batch_key — the batch was never corrected, so this is the raw batch structure as the factorization happened to capture it. The natural first look, before deciding whether to use a batch key at all.
  • a decomposed model — the upper layers are batch-corrected and frozen while L0 was re-learned without per-batch gene scales, so batch structure is pushed into L0 and read against a corrected hierarchy. This is the configuration the shape buckets were designed around.
  • a fit made with batch_key — what is left is the residual structure the per-batch gene_scale did not absorb, which is a smaller and different quantity. Useful for auditing a correction, but do not read its magnitudes as the batch effect in the data.

It deliberately emits no verdict. Nothing here distinguishes a technical per-batch duplication of one cell type from a genuine condition-specific biological program: in paired reference data the two are indistinguishable on every column below (same eff_parents ~1, same opp_batch_sibling, same near-ceiling branch_auc). Only the experimental design can settle that, which is why shape is a geometric label and never a cause.

This function supersedes the removed verdict-style "which factors look technical" suggester, whose flag columns did not hold up: its split rule fired on the IFN data's biological monocyte factors, and the batch_split_corr it ranked on saturates at 0.79-0.99 across factor pairs sharing no genes, placing the genuine pbmcs2b Cytotoxic-T split below unrelated pairs. The same geometry is reported here, descriptively.

No cell-type or other biological annotation is read. The inputs are model.pmeans, model.factor_lists / factor_names, adata.obs[batch_key], and — for the two optional gene-side columns — the reference fit's per-batch gene_scale.

Cell side and gene side. Every column below except the last two is cell-side: it asks which cells score on a factor and how they are spread over batches. gene_scale_affinity is gene-side: it asks whether the factor's gene programme is the one the reference fit's per-batch gene_scale absorbed, and never looks at a cell. A factor can be perfectly mixed across batches and still be built from exactly those genes, or the reverse, so the two are worth reading together.

.. warning::

gene_scale_affinity is not a technical-vs-biological score and must not be sorted on as if it were. The per-batch gene_scale absorbs whatever differs between batches at the gene level, and what that is depends entirely on what the batch key encodes. On Kang CTRL/STIM the top-scoring factor is the interferon-response factor — the biology the experiment is about, which must be kept. On pbmcs2b (two runs of one donor) the top-scoring factor is a stress/ambient programme — an artefact to remove. Identical statistic, opposite verdicts; only the experimental design settles it. This is the same trap that the removed "which factors look technical" suggester fell into.

Notation: kept0 = model.factor_lists[0], Z = pmeans['L0z'][:, kept0], W the connection weights from L0 up to the kept group_layer factors, a0(c) = argmax_k Z[c, k] the hard L0 assignment, S_k the cells assigned to factor k, and Znorm the row-normalized Z (each cell's loading distributed over the kept L0 factors).

Columns, one row per kept L0 factor:

  • n_cells: |S_k|. Sums to n_obs over the frame. This is the only column that counts cells with a missing batch_key value; every batch-derived column below is computed on the labelled cells alone.
  • dom_batch: modal batch of S_k (empty string if the factor has no cells with a batch label).
  • frac_dom_batch: fraction of the batch-labelled cells of S_k that lie in dom_batch. Hard purity, with a floor at the largest batch prior and a ceiling of 1.
  • batch_purity_soft: max_b mass_b / sum_b mass_b where mass_b = sum_{c in batch b} Znorm[c, k] over all cells. Floored near 1/n_batches and strongly compressed relative to frac_dom_batch, because normalized loading has a wide background across cells that the factor does not explain.
  • loading_ratio: median Znorm[:, k] in dom_batch over the median in the other batches, taken over all cells. See the note on estimator sensitivity below — read it as a rough direction check, not as a ranking.
  • eff_parents: exp(H(p)) for p the factor's W column normalized to a distribution, i.e. the effective number of group_layer parents it loads on. Range [1, n_kept_group]. Values below ~1.1 are indistinguishable from the numerical noise in tiny W entries; read the column as a coarse "one parent" vs "several parents" flag.
  • parent: current name of the argmax group_layer parent.
  • opp_batch_sibling: True when another kept L0 factor shares this parent and has a different dom_batch — the geometry of a per-batch split of one branch, whatever its cause.
  • branch_auc: cross-validated AUC (3-fold stratified logistic regression on log1p(Z), standardized in-fold) for predicting batch from the L0 scores of the cells in parent's branch. A branch-level quantity: it is identical for all children of a parent and cannot separate siblings. NaN when the branch has fewer than min_group_cells labelled cells, fewer than two batches, or a batch with fewer than 15 cells.
  • shape: descriptive bucket, geometry only, never cause:

================== ========================================================== branch_split frac_dom_batch >= 0.7, eff_parents < 1.5, has an opposite-batch sibling. One branch appearing as two batch-skewed halves. branch_skewed same but with no opposite-batch sibling. A batch-skewed factor whose branch has no counterpart half. overlaid frac_dom_batch >= 0.7 and eff_parents >= 1.5. A batch-skewed program spread over several branches rather than confined to one. balanced everything else, i.e. frac_dom_batch < 0.7. ================== ==========================================================

  • gene_scale_affinity_<batch>, one per batch, plus gene_scale_affinity_max and gene_scale_affinity_batch: present only when the reference fit's per-batch gene_scale is available (see reference). Each per-batch column is the Spearman correlation, over all genes, between the factor's gene loadings and the per-gene log-ratio of that batch's gene_scale against the other batches. _max is the largest of them and _batch names which batch attains it — the top_score and top_batch of get_factor_batch_gene_scale_affinity. With exactly two batches the two contrasts are mirror images, so the per-batch columns are exact negatives of each other, _max is non-negative and _batch only says which side; the magnitude is the information. With many batches the frame gets correspondingly wide — attrs['gene_scale_affinity'] holds the same numbers. Read the warning above before using any of them.

Rows are sorted by frac_dom_batch descending.

result.attrs carries batch_key, group_layer, min_group_cells, random_seed, the shape cut points (frac_dom_min, eff_parents_max) and branch_summary: a DataFrame indexed by kept group_layer factor with n_cells (cells whose hard assignment at group_layer is this factor), n_l0_children (kept L0 factors whose argmax parent is this factor), batch_auc and max_child_frac_dom. When the gene-side columns are present it also carries gene_scale_affinity: the full factors-by-batches frame, with one column per batch rather than only the best one.

Parameters:

Name Type Description Default
model scDEF

any fitted scDEF model with at least two layers; see above for how the reading changes with how it was fitted.

required
batch_key Optional[str]

key in adata.obs holding the batch labels, needing at least two observed values. Defaults to the model's own batch_key when it has one — from being constructed with it, or from decompose_batch_effects, which carries it — and raises if there is neither. The model itself need not have been fitted with the key you pass: any obs column works.

None
group_layer int

layer whose factors define the branches (default 1, the layer usually frozen by the decomposition). Above 1 the per-layer W slices are chained, as in factor_batch_correction.

1
min_group_cells int

minimum labelled cells in a branch before its batch_auc is estimated; smaller branches report NaN.

80
random_seed int

seed for the cross-validation splits.

0
reference Union[scDEF, DataFrame, ndarray, None]

where the per-batch gene_scale contrast for the two gene-side columns comes from — a fitted reference scDEF model, a genes-by-batches DataFrame of log-ratios, or a (n_batches, n_genes) array, as accepted by get_factor_batch_gene_scale_affinity. None (default) uses the profile decompose_batch_effects stored on this model. If neither is available the two columns are simply omitted and the rest of the report is unaffected — a model decomposed before that record existed needs the reference passed explicitly.

None

Returns:

Type Description
DataFrame

DataFrame indexed by current L0 factor name with columns n_cells,

DataFrame

dom_batch, frac_dom_batch, batch_purity_soft,

DataFrame

loading_ratio, eff_parents, parent, opp_batch_sibling,

DataFrame

branch_auc and shape, sorted by frac_dom_batch descending.

Raises:

Type Description
KeyError

batch_key is not in adata.obs.

ValueError

no batch_key was given and the model carries none; batch_key has fewer than two observed values; or group_layer is out of range.

Note

Three caveats worth carrying into any reading of the frame.

loading_ratio is estimator-sensitive. Taking the median over all cells measures the factor's background loading level rather than its loading where it is active, and it can point at the opposite batch from frac_dom_batch. Restricting the median to S_k compresses every factor into a narrow band; using means tracks frac_dom_batch much more closely. The all-cell median is reported for continuity, but the column should not be used to rank factors.

parent and branch_auc use different definitions of the hierarchy: parent is the argmax over the W column, while the branch is defined by the argmax over the group_layer cell scores. These disagree for some factors, and where they do, branch_auc is measured on a cell population that largely excludes the factor's own cells.

Small n_cells rows (a few tens of cells) have a binomial standard error on frac_dom_batch of 0.05-0.10 and should not be compared with rows of several hundred cells.

Example

ref = scdef.scDEF(adata, counts_layer="counts", batch_key="stim") ref.fit() model = scdef.scDEF.decompose_batch_effects(ref, top_layer=1) report = scdef.tl.batch_structure_report(model, batch_key="stim") report.loc[report["shape"] == "branch_split", ["parent", "dom_batch"]] report.attrs["branch_summary"].head()