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 referencegene_scalelearned 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
|
required |
reference
|
Union['scDEF', DataFrame, ndarray, None]
|
where the per-batch
|
None
|
reference_batches
|
Optional[Sequence[str]]
|
batch labels for the raw-array form of |
None
|
top_n_genes
|
Optional[int]
|
if given, restrict each factor's correlation to that
factor's own top- |
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
|
2.0
|
reference_mode
|
Literal['mean_other_batches', 'global_mean']
|
|
'mean_other_batches'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame indexed by |
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
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
the reference and the model disagree on the gene axis (both
shapes are named in the message); the reference |
TypeError
|
|
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]