Skip to content

scdef.tl.assign_confident

assign_confident(model: scDEF, n_samples: int = 500, tau: float = 0.3, credible_level: float = 0.9, key_added: str = 'confident', rng_key: Optional[Any] = None, exclude_technical: bool = False, exclude_batch_technical: bool = False, batch_technical_top_layer: Optional[int] = None) -> None

Pick the finest scDEF layer at which each cell is confidently assigned.

For each cell c and layer k (restricted to filtered factors model.factor_lists[k]), draws n_samples reparameterized samples z^(s) ~ q(z_{c,k}) from the log-normal variational posterior and normalizes each sample: ẑ^(s) = z^(s) / sum(z^(s)). exclude_technical / exclude_batch_technical narrow that per-layer candidate set further, and all scores below are then computed among the remaining factors only.

The confidence score is defined on the gap between the cell-level winner and its nearest competitor, so the score is invariant to layer size K_k (only the top two factors enter, dormant factors don't inflate it):

  • Cell-level winner f* = argmax_f E_s[ẑ_f].
  • Per-sample gap gap^(s) = ẑ^(s)_{f*} - max_{g != f*} ẑ^(s)_g. Equals 0 when the winner and runner-up are tied, 1 when the winner holds all the mass, and goes negative in samples where some other factor out-competes f* (so identity flipping directly penalizes the score).
  • Effect size = E_s[gap^(s)] — posterior-mean margin by which the winner beats its nearest competitor.
  • Posterior SD = SD_s[gap^(s)] — uncertainty of that margin (diagnostic).
  • Confidence = quantile_{1 - credible_level}({gap^(s)}) — the empirical (1 - credible_level)-quantile of the gap across posterior samples. Reads as:

    "In at least credible_level of posterior samples, the winning factor f* had at least confidence more normalized mass than any competing factor."

Layer-size invariant: a value of e.g. 0.3 means "winner leads runner-up by 30 percentage points of normalized mass" regardless of the number of factors at the layer.

Two auxiliary diagnostic scores are also computed:

  • winner_probability[c, k] = max_f P_s[argmax = f] — how often the winner is the argmax across samples. Identity-stability only; ignores magnitude (a tight 0.51/0.49 scores 1.0 here).
  • entropy_confidence[c, k] = 1 - H(p) / log(K_k) — normalized entropy of the argmax distribution.

Selection rule (finest-that-clears). For each cell, the "best" layer is the finest (lowest index) multi-factor layer (K_k >= 2) whose confidence clears tau. If no multi-factor layer clears tau, the cell is assigned to the top-most single-factor layer (typically the root) as a "stem-cell-like" catch-all. This encodes the biological intuition:

  • Terminally differentiated cells have a clear dominant factor at L0 with tight posterior → assigned at L0.
  • Partially differentiated cells are ambiguous between siblings at L0 but clear at their parent layer L1 → assigned at L1.
  • Stem-like cells are ambiguous everywhere → assigned at the root.

Writes:

  • adata.obsm[f"{key_added}_effect_size"] — (n_cells, n_layers) float. Posterior-mean gap between winner and nearest competitor.
  • adata.obsm[f"{key_added}_posterior_sd"] — (n_cells, n_layers) float. Posterior SD of the gap.
  • adata.obsm[f"{key_added}_confidence"] — (n_cells, n_layers) float. Lower empirical quantile of the gap — the layer-size-invariant score that tau gates on.
  • adata.obsm[f"{key_added}_winner_mass"] — (n_cells, n_layers) float. Diagnostic: posterior mean of the winner's normalized mass (E[ẑ_{f*}]). Not K-invariant.
  • adata.obsm[f"{key_added}_winner_probability"] — (n_cells, n_layers) float. Diagnostic: posterior argmax-identity probability.
  • adata.obsm[f"{key_added}_entropy_confidence"] — (n_cells, n_layers) float. Diagnostic: normalized-entropy score.
  • adata.obsm[f"{key_added}_argmax_factor"] — (n_cells, n_layers) int, slot indices into the effective candidate list of each layer — the filtered factor list minus any factors excluded by exclude_technical / exclude_batch_technical (-1 if the layer has no candidates left).
  • adata.obs[f"{key_added}_confidence_{layer_name}"] per layer.
  • adata.obs[f"{key_added}_argmax_{layer_name}"] per layer (factor name).
  • adata.obs[f"{key_added}_best_layer"] — layer name of the chosen layer.
  • adata.obs[f"{key_added}_best_layer_idx"] — integer index of that layer in model.layer_names (0 = finest). -1 if no layer was chosen.
  • adata.obs[f"{key_added}_best_factor_idx"] — slot within the best layer's filtered factor list.
  • adata.obs[f"{key_added}_factor"] — factor name at the best layer.
  • adata.obs[f"{key_added}_best_effect_size"] — effect size at the best layer.
  • adata.obs[f"{key_added}_best_posterior_sd"] — posterior SD at the best layer.
  • adata.obs[f"{key_added}_best_confidence"] — combined confidence at the best layer.
  • adata.obs[f"{key_added}_depth_score"] — assignment-centric depth in [0, 1]: best_layer_index / (n_layers - 1), so 0 at the finest layer (L0) and 1 at the coarsest layer (root). If n_layers == 1, the score is 0 for assigned cells. Cells with no valid layer (best_layer_index < 0) get NaN.
  • adata.uns[key_added] — metadata (layer names, sizes, tau, n_samples, credible_level, metric name, fit revision).

Parameters:

Name Type Description Default
model scDEF

scDEF model instance (must already be fitted).

required
n_samples int

number of Monte Carlo samples S drawn per cell/layer.

500
tau float

minimum confidence (lower quantile of the winner-runner-up gap) for a multi-factor layer to be eligible as the cell's best layer (in [0, 1]). Reads as "in at least credible_level of posterior samples, the winner must lead the runner-up by at least tau of the normalized mass".

0.3
credible_level float

posterior credibility of the lower bound, in (0, 1). The confidence is the empirical (1 - credible_level)-quantile of the per-sample gap. Default 0.9 → "in 90% of posterior samples, the winner led by at least confidence". Set higher (e.g. 0.95) for a stricter score.

0.9
key_added str

prefix used for all written keys in adata.

'confident'
rng_key Optional[Any]

optional jax.random key; if None, derived from model.seed.

None
exclude_technical bool

if True, factors marked technical in factor_obs (see set_technical_factors) are removed from the candidate set at every layer, so no cell is ever assigned to an ambient/stress program. Confidence is then computed among the remaining factors only.

False
exclude_batch_technical bool

if True, factors marked batch_technical (see set_batch_technical_factors) are removed from the candidate set at every layer below batch_technical_top_layer, and any cell whose layer-0 winner is one of them is rolled up to that layer. Per-batch splits only exist below the roll-up layer, so the flag is deliberately not applied at or above it.

False
batch_technical_top_layer Optional[int]

layer index the batch-technical roll-up targets. Defaults to adata.uns['batch_technical_top_layer'], recorded by decompose_batch_effects, else 1.

None
Example

After flagging per-batch splits, their cells attach to the

batch-corrected L1 parent instead of overshooting to the root.

scdef.tl.set_batch_technical_factors(model, splits) scdef.tl.assign_confident(model, exclude_batch_technical=True) model.adata.obs["confident_best_layer"].value_counts()