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
shapebuckets were designed around. - a fit made with
batch_key— what is left is the residual structure the per-batchgene_scaledid 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 ton_obsover the frame. This is the only column that counts cells with a missingbatch_keyvalue; every batch-derived column below is computed on the labelled cells alone.dom_batch: modal batch ofS_k(empty string if the factor has no cells with a batch label).frac_dom_batch: fraction of the batch-labelled cells ofS_kthat lie indom_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_bwheremass_b = sum_{c in batch b} Znorm[c, k]over all cells. Floored near1/n_batchesand strongly compressed relative tofrac_dom_batch, because normalized loading has a wide background across cells that the factor does not explain.loading_ratio: medianZnorm[:, k]indom_batchover 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))forpthe factor'sWcolumn normalized to a distribution, i.e. the effective number ofgroup_layerparents it loads on. Range[1, n_kept_group]. Values below ~1.1 are indistinguishable from the numerical noise in tinyWentries; read the column as a coarse "one parent" vs "several parents" flag.parent: current name of theargmaxgroup_layerparent.opp_batch_sibling:Truewhen another kept L0 factor shares thisparentand has a differentdom_batch— the geometry of a per-batch split of one branch, whatever its cause.branch_auc: cross-validated AUC (3-fold stratified logistic regression onlog1p(Z), standardized in-fold) for predicting batch from the L0 scores of the cells inparent's branch. A branch-level quantity: it is identical for all children of a parent and cannot separate siblings.NaNwhen the branch has fewer thanmin_group_cellslabelled 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, plusgene_scale_affinity_maxandgene_scale_affinity_batch: present only when the reference fit's per-batch gene_scale is available (seereference). 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'sgene_scaleagainst the other batches._maxis the largest of them and_batchnames which batch attains it — thetop_scoreandtop_batchofget_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,_maxis non-negative and_batchonly 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 |
None
|
group_layer
|
int
|
layer whose factors define the branches (default |
1
|
min_group_cells
|
int
|
minimum labelled cells in a branch before its
|
80
|
random_seed
|
int
|
seed for the cross-validation splits. |
0
|
reference
|
Union[scDEF, DataFrame, ndarray, None]
|
where the per-batch |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame indexed by current L0 factor name with columns |
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
no |
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()