Skip to content

scdef.tl.get_factor_batch_gene_scale_affinity

get_factor_batch_gene_scale_affinity(model: 'scDEF', reference: Union['scDEF', DataFrame, ndarray, None] = None, *, reference_batches: Optional[Sequence[str]] = None, top_n_genes: Optional[int] = None, eps: float = 1e-12, log_base: float = 2.0, reference_mode: Literal['mean_other_batches', 'global_mean'] = 'mean_other_batches') -> DataFrame

Score each layer-0 factor by its affinity for the reference fit's per-batch gene_scale contrast.

Named to match get_batch_specific_genes_from_gene_scale, which produces the contrast this reads: that function answers which genes the reference fit's per-batch gene_scale term singled out, this one answers which factors of the decomposed fit look like those genes — hence "factor ... gene_scale affinity".

What it measures. A reference fit made with batch_key (and batch_gene_scale=True) carries a per-batch, per-gene multiplier, pmeans['gene_scale'] of shape (n_batches, n_genes), which soaks up the gene-level differences between batches so the hierarchy does not have to. decompose_batch_effects then freezes the batch-corrected upper hierarchy and re-learns layer 0 without per-batch gene scales, so whatever that term was holding has to reappear in the layer-0 factors. This function measures how much of it landed in each factor: for every batch b it takes the per-gene log-ratio log(gene_scale[b, g] / ref[g]) from get_batch_specific_genes_from_gene_scale, and for every kept layer-0 factor k computes the Spearman rank correlation between that vector and the factor's gene loadings pmeans['L0W'][k, :], over all genes.

Rank correlation over all genes is deliberate. The loadings and the log-ratios live on incomparable scales and both have heavy tails, so a Pearson correlation would be decided by a handful of genes; and restricting to a factor's top genes throws away the (informative) fact that a factor down-weights the batch-associated genes. top_n_genes is offered for exploration but changes the estimand — it conditions on the factor's own top genes, so scores are no longer comparable across factors with different loading profiles.

This is gene-side evidence. Every other batch diagnostic in scdef is cell-side — batch_purity / batch_purity_soft and the batch_split_* columns of factor_diagnostics. Those ask which cells score on a factor and how they are distributed over batches. This one never looks at a cell: it asks whether the factor's gene programme is the one the reference fit's per-batch term absorbed. A factor can be perfectly mixed across batches at the cell level and still be built out of exactly those genes, and vice versa.

.. warning::

This does not separate technical from biological factors, and must not be used as if it did. 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. Two worked cases, both scored with this function:

  • Kang CTRL/STIM (batch_key='stim') — the reference gene_scale learned the interferon response: a 16-gene ISG panel sits at median rank 48 of 4000 in the STIM log-ratio (chance is 2000), with IFIT1 #8, ISG15 #16 and CXCL10 #18 at a 62.3x per-batch ratio. So here the top-scoring factor is the ISG factor — which is biology, the entire point of the experiment, and must be kept.
  • pbmcs2b (batch_key='Experiment', two runs of one donor) — the same term captured platelet/ambient genes, lncRNA and a dissociation/immediate-early block, so the top-scoring factor is a stress-response factor — an artefact to remove.

Identical statistic, opposite verdicts. Read the score as "how strongly this factor matches the gene programme the reference fit's per-batch scale absorbed" — a pointer to the batch-associated programme. Inspect the flagged factor's genes (model.adata.uns['L0_signatures'], get_confident_signatures) and decide from the experimental design. A high score on a condition-like batch key is expected and is not grounds for dropping the factor.

Parameters:

Name Type Description Default
model 'scDEF'

the decomposed scDEF model (after decompose_batch_effects) whose layer-0 factors are scored. Its pmeans['L0W'] is full width; only the factors in model.factor_lists[0] are scored, and they are labelled with model.factor_names[0].

required
reference Union['scDEF', DataFrame, ndarray, None]

where the per-batch gene_scale contrast comes from. One of

  • a fitted reference scDEF model (batch_key set, gene_scale of shape (n_batches, n_genes)) — the log-ratios are computed from it with get_batch_specific_genes_from_gene_scale;
  • a DataFrame of precomputed log-ratios, genes-by-batches, indexed by var_names — exactly what that function returns;
  • a raw array of gene_scale, shape (n_batches, n_genes), matching pmeans['gene_scale'].

None (default) looks for adata.uns['reference_gene_scale_log_ratios'] or adata.uns['reference_gene_scale'] on the decomposed model, which decompose_batch_effects records from the fit it decomposed, and raises if neither is present. Supplying it explicitly is only needed for a model decomposed before that record existed, or to score against a different reference.

None
reference_batches Optional[Sequence[str]]

batch labels for the raw-array form of reference (ignored otherwise). Defaults to batch_0, batch_1, ...

None
top_n_genes Optional[int]

if given, restrict each factor's correlation to that factor's own top-N genes by loading. Default None uses every gene, which is the intended statistic; see above.

None
eps float

numerical-stability constant passed through to the log-ratios.

1e-12
log_base float

log base for the log-ratios. Irrelevant to the result — a rank correlation is invariant to any monotone rescaling — and kept only so the underlying table matches what you would get from get_batch_specific_genes_from_gene_scale.

2.0
reference_mode Literal['mean_other_batches', 'global_mean']

mean_other_batches (default) or global_mean, passed straight through. With exactly two batches the two columns are mirror images either way, so the two scores of a factor are exact negatives of each other.

'mean_other_batches'

Returns:

Type Description
DataFrame

A DataFrame indexed by model.factor_names[0] (one row per kept

DataFrame

layer-0 factor), with one column per batch label holding the Spearman

DataFrame

correlation of that factor's loadings with that batch's gene-scale

DataFrame

log-ratio, plus

DataFrame
  • top_batch — the batch whose column is largest for that factor;
DataFrame
  • top_score — that correlation, negative only when the factor is anti-correlated with every batch's contrast;
DataFrame
  • abs_top_score — its magnitude, for ranking regardless of sign.
DataFrame

attrs['n_genes_used'], attrs['reference_mode'] and

DataFrame

attrs['top_n_genes'] record the settings. Rows are in

DataFrame

factor_names[0] order, not sorted by score.

Raises:

Type Description
ValueError

the reference and the model disagree on the gene axis (both shapes are named in the message); the reference gene_scale has a single batch row, so no contrast exists; model.pmeans['L0W'] is missing or its gene dimension does not match adata.n_vars; or top_n_genes is not positive.

TypeError

reference is not a model, DataFrame or array.

Example
decomposed = scdef.scDEF.load("ifn_batch_model")
ref = scdef.scDEF.load("ifn_model")          # fitted with batch_key='stim'
aff = scdef.tl.get_factor_batch_gene_scale_affinity(decomposed, ref)
aff.sort_values("abs_top_score", ascending=False).head()

# then LOOK at the genes before concluding anything:
top = aff["abs_top_score"].idxmax()
decomposed.adata.uns["L0_signatures"][top][:10]