API reference¶
Core scorers¶
- class scCS.SingleScorer(adata, root=None, branches=None, obs_key='leiden', copy=False, *, furcation=None)[source]¶
Bases:
objectQuantify commitment at one manually annotated furcation.
- Parameters:
adata – AnnData containing the root and terminal populations.
root (Optional[LabelSpec]) – One annotation label, or a group of labels representing one root population. Retained for the familiar pre-v0.8 constructor.
branches (Optional[TerminalSpec]) – Ordered terminal labels, or a mapping from terminal name to one or more annotation labels.
obs_key (str) – Annotation column in
adata.obs.furcation (Optional[Furcation]) – Optional pre-built
scCS.Furcation. Supply eitherfurcationorroot/branches, not both.copy (bool) – Work on a copy of
adata.
Notes
scCS is supervised. The root and terminal populations are supplied by annotation; the scorer does not infer topology or discover terminal states.
- build_embedding(ordering_metric='pseudotime', invert_ordering=False, arm_scale=1.0, ordering_scaler=None, write_to_adata=True, cache_subset=True, verbose=True)[source]¶
Build the deterministic root-plus-simplex scientific star.
Plot jitter, display angles, and random seeds are intentionally absent because display choices must not alter scientific scores.
Set
cache_subset=Falsefor large datasets to avoid materializing an additional AnnData copy of the selected furcation. The scientific embedding and all scoring results remain available on the scorer.- Parameters:
ordering_metric (str | Sequence[float] | ndarray)
invert_ordering (bool)
arm_scale (float)
ordering_scaler (FurcationOrderingScaler | None)
write_to_adata (bool)
cache_subset (bool)
verbose (bool)
- Return type:
- compute_velocity(mode='deterministic', n_pcs=30, n_neighbors=30, min_shared_counts=20, random_state=0, n_jobs=None, pseudotime_root_key=None, compute_pseudotime=True, pseudotime_scope='furcation', pseudotime_key_added='velocity_pseudotime', pseudotime_n_dcs=10, verbose=True)[source]¶
Compute a current-scVelo velocity graph on the full AnnData object.
The method uses Scanpy for PCA and neighbors and does not pass the removed
n_top_genesargument to scVelo. No model fallback is performed silently: the requested velocity model either succeeds or raises its original error.- Parameters:
mode (str)
n_pcs (int)
n_neighbors (int)
min_shared_counts (int)
random_state (int)
n_jobs (int | None)
pseudotime_root_key (int | str | None)
compute_pseudotime (bool)
pseudotime_scope (str)
pseudotime_key_added (str)
pseudotime_n_dcs (int)
verbose (bool)
- Return type:
- compute_velocity_pseudotime(root_key=None, *, scope='furcation', key_added='velocity_pseudotime', vkey='velocity', n_dcs=10, use_velocity_graph=True, verbose=True)[source]¶
Compute root-guided velocity pseudotime globally or on the furcation.
- Parameters:
root_key (int | str | None) – Root cell index, observation name, or scVelo-compatible root-prior column. A full-data integer index is translated automatically when
scope='furcation'.scope (str) –
'full'computes pseudotime on the complete velocity graph.'furcation'induces the graph on the manually selected root and terminal populations before computing pseudotime, then transfers the values back to the full AnnData object. The latter is usually the appropriate ordering for a supervised scCS trajectory when unrelated lineages are present in the same object.key_added (str) – Destination column in
adata.obs. Cells outside a furcation-scoped calculation receiveNaN.vkey (str) – Passed to
scvelo.tl.velocity_pseudotime().n_dcs (int) – Passed to
scvelo.tl.velocity_pseudotime().use_velocity_graph (bool) – Passed to
scvelo.tl.velocity_pseudotime().verbose (bool)
- Return type:
Notes
This method does not recompute velocity. Furcation-scoped pseudotime uses the induced subgraph of the already fitted full-data velocity graph, so RNA-velocity estimation and scCS transition projection remain unchanged.
- display_velocity_projection(result=None, *, terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, vkey='velocity', projection_mode='transition')[source]¶
Return display-space velocities in the two-dimensional star.
projection_mode='transition'returns direct transition-expected displacement;'scvelo'returns scVelo’s centered embedding projection. Both remain display-only and are not used by the scientific scorer.- Parameters:
result (FurcationScoreResult | None)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
vkey (str)
projection_mode (str)
- Return type:
tuple[ndarray, ProjectionResult]
- property embedding: ndarray | None¶
- fit(transition_matrix=None, *, scoring_mode='instantaneous', future_fate_options=None, aligned_probability=0.9, magnitude_scaler=None, magnitude_fit_population='root', renormalize_retained=True, min_transition_coverage=0.05, committed_strength_threshold=0.25, committed_specificity_threshold=0.25, verbose=True)[source]¶
Fit one of the two explicit scCS scoring modes.
- Parameters:
scoring_mode (str) –
"instantaneous"retains the transition-pushforward and cosine-softmax model."future_fate"uses discounted hitting probabilities on the original velocity graph.future_fate_options (Mapping[str, object] | None) – Keyword arguments forwarded to
fit_future_fate(). This keeps mode-specific parameters out of the established instantaneous API.aligned_probability (float)
magnitude_scaler (MagnitudeScaler | None)
magnitude_fit_population (str)
renormalize_retained (bool)
min_transition_coverage (float)
committed_strength_threshold (float)
committed_specificity_threshold (float)
verbose (bool)
- Return type:
- fit_future_fate(transition_matrix=None, *, effective_horizon=64, anchor_quantile=0.9, min_anchor_cells=10, competing_outcomes=None, min_reach=1e-06, progression_values=None, progression_scale='rank', solver='auto', direct_max_states=50000, tolerance=1e-10, max_iter=20000, committed_reach_threshold=0.25, committed_specificity_threshold=0.25, verbose=True)[source]¶
Fit discounted future-fate scoring on the original velocity graph.
This mode does not transfer a scientific velocity vector into the star. It estimates discounted hitting probabilities for late cells in each supervised fate, while signed progression is calculated separately from expected changes in the supplied ordering.
competing_outcomesis optional and explicit. Each mapping value may be a full-length Boolean mask or full-data cell indices. Unmodelled futures remain unresolved rather than being automatically assigned to a guessed competing terminal state.- Parameters:
effective_horizon (int)
anchor_quantile (float)
min_anchor_cells (int)
competing_outcomes (Mapping[str, Sequence[int] | ndarray] | None)
min_reach (float)
progression_values (Sequence[float] | None)
progression_scale (str)
solver (str)
direct_max_states (int)
tolerance (float)
max_iter (int)
committed_reach_threshold (float)
committed_specificity_threshold (float)
verbose (bool)
- Return type:
- get_commitment_associated_genes(**kwargs)[source]¶
Associate genes with fitted v0.8 commitment outcomes.
This is a convenience wrapper around
scCS.get_commitment_associated_genes(). Cell-level inference is explicitly exploratory; useinference_unit="replicate"with a biologicalreplicate_keyfor formal gene-level inference.
- get_fate_markers(**kwargs)[source]¶
Find terminal annotation markers versus the supplied root.
Fate markers describe annotated cell identity and are distinct from commitment-associated genes.
- property is_fitted: bool¶
- classmethod load(path, adata)[source]¶
Load a scorer saved by
save(). Only load trusted files.- Parameters:
path (str)
- Return type:
- load_velocity_vectors(velocity, vy=None)[source]¶
Supply projected velocity directly in scientific star coordinates.
velocityshould normally have shape(n_selected, k). For a two-fate furcation only, the familiarvx, vyform remains accepted. Directly supplied vectors are treated as fully covered projections.- Parameters:
vy (ndarray | None)
- Return type:
- plot_branch_velocity_profiles(result=None, *, n_bins=24, normalization='within_branch', terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, projection_mode='scvelo', vkey='velocity', ncols=None, title=None)[source]¶
Plot branch-relative terminal velocity directions in separate roses.
Each terminal population is kept attached to its own annotated branch. The angle is measured relative to that branch’s outward display axis:
0°is outward,±90°is transverse, and180°is inward. This avoids the misleading behavior of a pooled display rose, where an inward or curved vector from one annotated branch can be relabeled as the nearest other branch sector.This figure is a display-space RNA-velocity diagnostic. It does not define discounted future-fate affinity, reach, specificity, or signed progression.
- Parameters:
normalization (str) –
"within_branch"(default) shows the fraction of each branch’s own display-embedded velocity magnitude in every angular bin."mass"shows raw display-embedded velocity magnitude, and"global_fraction"divides by total terminal velocity magnitude.projection_mode (str) – Passed to
prepare_scvelo_star_embedding()."scvelo"is recommended for comparison with scVelo’s embedding projection.result (FurcationScoreResult | None)
n_bins (int)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
vkey (str)
ncols (int | None)
title (str | None)
- plot_commitment_bar(result=None, *, population='root', mask=None, metric='commitment_composition', ax=None)[source]¶
Compatibility wrapper for a v0.8 population commitment bar chart.
- Parameters:
result (FurcationScoreResult | None)
population (str)
mask (ndarray | None)
metric (str)
- plot_commitment_heatmap(result=None, *, metric='directional_affinity', population='root', mask=None, sort_by='ordering', max_cells=500, row_annotation=None, show_annotation_labels=True, show_annotation_legends=False, show_fate_strip=True, ax=None)[source]¶
Plot per-cell fate outputs with aligned row and fate annotations.
- Parameters:
row_annotation (str | Sequence[str] | None) – Optional categorical strip, or sequence of strips, shown to the left of the heatmap. Supported values are
"population","status","dominant_affinity", and"dominant_fate".show_fate_strip (bool) – Draw a color strip above the heatmap columns using the same fate colors as the star plots.
show_annotation_legends (bool) – Draw legends for non-contiguous row annotations. This is off by default because the fate strip already identifies branch colors.
sort_by (str) – In addition to continuous scCS metrics, use
"population_then_ordering"to group the annotated root and terminal populations while preserving fitted ordering within each population.result (FurcationScoreResult | None)
metric (str)
population (str)
mask (ndarray | None)
max_cells (int)
show_annotation_labels (bool)
- plot_direction_strength_map(result=None, *, population='root', point_size=14.0, alpha=0.7, show_thresholds=True, ax=None)[source]¶
Plot directional specificity against commitment strength.
This separates the two ingredients of specific commitment. Points are colored by dominant annotated fate; cells without a defined dominant fate are shown as
unassigned.- Parameters:
result (FurcationScoreResult | None)
population (str)
point_size (float)
alpha (float)
show_thresholds (bool)
- plot_expression_trends(genes, result=None, *, fate=None, x_axis='ordering', population='root', layer=None, n_bins=20, ncols=3, figsize_per_panel=(4.4, 3.5))[source]¶
Plot binned mean expression along a v0.8 commitment axis.
- Parameters:
genes (Sequence[str])
result (FurcationScoreResult | None)
fate (str | None)
x_axis (str)
population (str)
layer (str | None)
n_bins (int)
ncols (int)
figsize_per_panel (tuple[float, float])
- plot_gene_expression_star(genes, result=None, *, layer=None, use_raw=False, gene_symbols=None, log1p=False, cmap='viridis', vmin=None, vmax=None, percentile_range=(1.0, 99.0), shared_scale=False, sort_cells=True, cell_mask=None, ncols=3, figsize_per_panel=(6.2, 5.3), **plot_star_kwargs)[source]¶
Plot one or more genes directly on the display-only scCS star.
Expression is read from
adata.Xby default, an AnnDatalayerwhen provided, oradata.raw.Xwithuse_raw=True. Coordinates come from the already fitted star display and therefore preserve the selected ordering metric. Gene expression never enters scientific projection or commitment scoring.- Parameters:
genes (str | Sequence[str]) – One gene identifier or a sequence of identifiers.
gene_symbols (str | None) – Optional column in
adata.var(oradata.raw.var) containing display gene symbols whenvar_namesuses another identifier.percentile_range (tuple[float, float] | None) – Robust display limits calculated independently per gene by default. Set to
Noneto use the full range.shared_scale (bool) – Use one color scale across all requested genes. This is most useful for genes measured on a directly comparable scale.
sort_cells (bool) – Draw low-expression cells first so high-expression cells remain visible on top.
result (FurcationScoreResult | None)
layer (str | None)
use_raw (bool)
log1p (bool)
cmap (str)
vmin (float | None)
vmax (float | None)
cell_mask (ndarray | None)
ncols (int)
figsize_per_panel (tuple[float, float])
- plot_pairwise_cs(result=None, *, population='root', mask=None, ax=None)[source]¶
Plot the v0.8 pairwise log commitment-ratio matrix.
The familiar method name is retained, but the plotted quantity is not the pre-v0.8 angular-sector nCS. Entry
[i, j]islog(mean_commitment_i / mean_commitment_j)for the selected population.- Parameters:
result (FurcationScoreResult | None)
population (str)
mask (ndarray | None)
- plot_population_commitment(result=None, *, population='root', mask=None, metric='mean_commitment_contribution', ax=None)[source]¶
Plot one population-level commitment summary.
- Parameters:
population (str) –
"root"(default) or"all". Ignored whenmaskis supplied.mask (ndarray | None) – Optional Boolean mask aligned to
result.cell_ids.metric (str) – One of
"total_commitment_mass","mean_commitment_contribution","commitment_composition", or"pairwise_log_commitment_ratio".result (FurcationScoreResult | None)
- plot_projection_geometry_diagnostics(result=None, *, max_cells=500, sort_by='ordering', cmap='viridis', figsize=(13.0, 7.0), show_branch_strip=True, show_fate_strip=True, branch_tie_tolerance=1e-12)[source]¶
Plot direct terminal-transition mass beside reconstructed affinity.
Rows are root cells only. The left panel is computed directly from retained transition destinations; the right panel is the stored cosine-softmax directional affinity. They need not have identical numerical scales, but their dominant fate must agree whenever direct terminal-transition mass has a unique maximum. The optional left strip identifies the dominant directly reached terminal branch for each root cell, while the optional top strips preserve the fate-color mapping across both matrices.
- Parameters:
result (FurcationScoreResult | None)
max_cells (int)
sort_by (str)
cmap (str)
figsize (tuple[float, float])
show_branch_strip (bool)
show_fate_strip (bool)
branch_tie_tolerance (float)
- plot_root_progression_direction_diagnostics(result=None, *, diagnostics=None, figsize=(15.0, 4.5))[source]¶
Plot root ordering and forward-direction consistency diagnostics.
- Parameters:
result (FurcationScoreResult | None)
diagnostics (RootProgressionDirectionDiagnostics | None)
figsize (tuple[float, float])
- plot_rose(result=None, *, population='root', mask=None, mode='auto', n_bins=24, normalization='auto', terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, vkey='velocity', title=None, ax=None)[source]¶
Plot a binned polar summary of fate-directed branch velocity.
mode='angular'is an exact global angular histogram for a three-fate simplex, whose branch subspace is two-dimensional.For four or more fates, the scientific branch subspace has dimension greater than two and therefore has no distortion-free global polar angle.
mode='deviation'provides a permutation-equivariant binned alternative: cells are assigned to their nearest ideal fate axis, and each fate-centered polar sector is subdivided by the unsigned angular deviation from that axis. Bars are mirrored around the fate-axis label so that no arbitrary left/right direction is invented.mode='branch'is the recommended public rose plot. It removes incoming-root progression by using only the scientific branch component, maps the fate-affinity composition onto an evenly spaced 2D fate polygon, and bins specific fate-directed velocity mass by angle. No incoming-root direction is forced into a terminal-fate label.mode='display'summarizes the two-dimensional star-display velocity. Usepopulation='terminal'when comparing terminal branches so that incoming-root progression cannot be assigned to the nearest terminal display sector. Display mode is visual QC and does not define scCS future-fate scores.mode='fate_mass'is the compact one-bar-per-fate summary.mode='auto'uses'fate_mass'for two fates, the exact'angular'plot for three fates, and'branch'for four or more fates.normalization='auto'uses absolute velocity mass for two- and three-fate plots and a within-fate distribution for four-or-more-fate angular-deviation plots. The latter prevents a high-mass fate from visually compressing the angular profiles of the other fates. Usenormalization='mass'for absolute mass ornormalization='global_fraction'for fractions of total mass.- Parameters:
result (FurcationScoreResult | None)
population (str)
mask (ndarray | None)
mode (str)
n_bins (int)
normalization (str)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
vkey (str)
title (str | None)
- plot_star(result=None, *, color_by='specific_commitment', color_values=None, color_label=None, cmap=None, vmin=None, vmax=None, colorbar=True, sort_by_color=False, jitter=0.025, terminal_radial_jitter=None, seed=0, point_size=10.0, alpha=0.75, terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, show_guides=True, label_arms=True, cell_mask=None, color_mask=None, background_color='0.82', background_alpha=0.45, background_point_size=None, title=None, ordering_label=None, ax=None)[source]¶
Plot a readable 2D display-only star.
The scientific embedding is the high-dimensional simplex stored in
X_sccs_score. Root cells preserve radial ordering. By default, terminal cells are spread along each display branch using the fitted ordering metric on one shared 0–1 scale. In the common velocity- pseudotime workflow, this is direct pseudotime-based positioning; the same display also supports latent time or any other fitted continuous ordering.terminal_layout="rank"equalizes visual coverage within each fate, andterminal_layout="endpoint"draws compact endpoint clouds. None of these display layouts enters scientific scoring.- Parameters:
terminal_layout (str) –
"ordering"(default) spreads terminal cells using one shared scale of the fitted ordering values."pseudotime"and"branch"are compatibility aliases."rank"uses within-fate fractional ranks."endpoint"places compact endpoint clouds.terminal_inner_radius (float) – Inner radial fraction for
terminal_layout="ordering"orterminal_layout="rank". A value of 0.15 fills most of each branch while keeping terminal cells visually separate from the furcation origin.color_mask (ndarray | None) – Optional Boolean mask selecting cells that receive the requested coloring. Other displayed cells remain as neutral gray context. This is useful for root-focused commitment plots that retain the annotated terminal branches as visual anchors.
result (FurcationScoreResult | None)
color_by (str)
color_values (Sequence[float] | None)
color_label (str | None)
cmap (str | None)
vmin (float | None)
vmax (float | None)
colorbar (bool)
sort_by_color (bool)
jitter (float)
terminal_radial_jitter (float | None)
seed (int)
point_size (float)
alpha (float)
terminal_span_degrees (float)
show_guides (bool)
label_arms (bool)
cell_mask (ndarray | None)
background_color (str)
background_alpha (float)
background_point_size (float | None)
title (str | None)
ordering_label (str | None)
- plot_star_panels(result=None, *, panels=None, ncols=3, figsize_per_panel=(6.2, 5.3), **plot_star_kwargs)[source]¶
Plot a grid of star views using the current v0.8 outputs.
- Parameters:
result (FurcationScoreResult | None)
panels (Sequence[str] | None)
ncols (int)
figsize_per_panel (tuple[float, float])
- plot_subset_comparison(subset_results, *, metric='commitment_composition', ax=None)[source]¶
Compare descriptive population summaries across named subsets.
- Parameters:
subset_results (Mapping[object, PopulationCommitmentSummary])
metric (str)
- plot_velocity_embedding_grid(result=None, *, population='all', mask=None, basis='sccs', vkey='velocity', density=1.0, smooth=0.5, min_mass=1.0, n_neighbors=None, arrow_size=1.4, arrow_length=3.0, scale=None, autoscale=True, terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, projection_mode='transition', point_size=22.0, alpha=0.45, title=None, write_to_adata=True, ax=None)[source]¶
Call
scv.pl.velocity_embedding_gridon the selected star cells.Root and terminal cells are included by default. The arrows are smoothed with
scvelo.pl.velocity_embedding_grid(). By default, the vectors are direct transition-expected displacements inX_sccs; useprojection_mode='scvelo'only to inspect scVelo’s normalized, baseline-centered embedding projection. This plot is visual QC; the scientific scCS projection remains the high-dimensional result.- Parameters:
result (FurcationScoreResult | None)
population (str)
mask (ndarray | None)
basis (str)
vkey (str)
density (float)
smooth (float)
min_mass (float)
n_neighbors (int | None)
arrow_size (float)
arrow_length (float)
scale (float | None)
autoscale (bool)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
projection_mode (str)
point_size (float)
alpha (float)
title (str | None)
write_to_adata (bool)
- plot_velocity_star(result=None, *, population='all', mask=None, mode='grid', terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, projection_mode='transition', title=None, ax=None, **kwargs)[source]¶
Compatibility wrapper for velocity plots on the star.
mode='grid'andmode='cell'use scVelo’s plotting functions. The default vectors are direct transition-expected displacements; setprojection_mode='scvelo'for the native centered projection. All selected root and terminal cells are included by default.- Parameters:
result (FurcationScoreResult | None)
population (str)
mask (ndarray | None)
mode (str)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
projection_mode (str)
title (str | None)
- preflight(*, ordering_metric='pseudotime', check_velocity=True, raise_on_error=False)[source]¶
Run annotation, ordering, velocity, and fitted-result diagnostics.
- Parameters:
check_velocity (bool)
raise_on_error (bool)
- prepare_scvelo_star_embedding(result=None, *, basis='sccs', vkey='velocity', terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, projection_mode='transition', autoscale=True, write_to_adata=True)[source]¶
Prepare a selected-cell AnnData for native scVelo star visualization.
The method writes deterministic two-dimensional display coordinates to
X_<basis>.projection_mode='transition'stores the direct transition-expected displacementE_T[X_j] - X_iand is the recommended star field.projection_mode='scvelo'reproducesscvelo.tl.velocity_embedding(), whose normalized and baseline-centered formula can reverse arrows on a nearly collinear star and is retained as an explicit sensitivity view. Both are visualization-only; scientific scCS scores continue to useX_sccs_scoreand the full regular-simplex projection.- Parameters:
result (FurcationScoreResult | None)
basis (str)
vkey (str)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
projection_mode (str)
autoscale (bool)
write_to_adata (bool)
- project_velocity(transition_matrix=None, renormalize_retained=True, min_transition_coverage=0.05, verbose=True)[source]¶
Project full-graph transitions into the scientific star.
- Parameters:
renormalize_retained (bool)
min_transition_coverage (float)
verbose (bool)
- Return type:
- property projected_velocity: ndarray | None¶
- projection_geometry_diagnostics(result=None, *, tie_tolerance=1e-12)[source]¶
Verify root-cell fate direction directly from transition destinations.
The scientific root arm lies entirely on the axis orthogonal to the regular-simplex fate subspace. Consequently, for every root cell, the fate-directed component of the projected velocity must equal the retained transition mass entering each annotated terminal population multiplied by that terminal’s ideal simplex direction.
This method reconstructs the branch velocity from the transition matrix without using the stored projected vector, then recomputes the cosine-softmax affinity. Near-zero reconstruction errors demonstrate that the geometry conversion has not rotated or relabeled the RNA- velocity direction. The check is available only when scCS projected a transition matrix; it is undefined for externally supplied projected vectors.
- Parameters:
result (FurcationScoreResult | None)
tie_tolerance (float)
- Return type:
RootProjectionGeometryDiagnostics
- property result: FurcationScoreResult | FutureFateScoreResult | None¶
- root_progression_direction_diagnostics(result=None, *, terminal_span_degrees=150.0, terminal_layout='ordering', terminal_inner_radius=0.15, vkey='velocity')[source]¶
Diagnose whether root velocity follows increasing fitted ordering.
For root cells, terminal destinations are assigned progression 1. The direct transition-weighted change in this coordinate must equal the scientific progression component divided by
arm_scale. The method also contrasts the recommended transition-expected star displacement with scVelo’s normalized, baseline-centered embedding projection.- Parameters:
result (FurcationScoreResult | None)
terminal_span_degrees (float)
terminal_layout (str)
terminal_inner_radius (float)
vkey (str)
- Return type:
RootProgressionDirectionDiagnostics
- save(path)[source]¶
Serialize the scorer state. Only load trusted files.
- Parameters:
path (str)
- Return type:
None
- score(cell_mask=None, *, write_to_adata=True, verbose=True)[source]¶
Return cell-level scores and summarize an explicit population.
The fitted cell-level result is common to all summaries. If
cell_maskis supplied, it must be aligned to the selected furcation cells and only changesscorer.population_summary.- Parameters:
cell_mask (ndarray | None)
write_to_adata (bool)
verbose (bool)
- Return type:
- score_per_subset(split_by, *, population='root', min_cells=5, verbose=False)[source]¶
Summarize fitted commitment separately for annotated subsets.
This method is descriptive. Formal condition inference will be provided by the replicate-aware PairScorer/MultiScorer redesign.
- Parameters:
split_by (str)
population (str)
min_cells (int)
verbose (bool)
- Return type:
dict[object, PopulationCommitmentSummary]
- property scoring_mode: str¶
Currently fitted scoring mode.
- transfer_labels(adata=None, result=None)[source]¶
Write the fitted v0.8 result to an AnnData object.
- Parameters:
result (FurcationScoreResult | None)
- Return type:
None
- class scCS.PairScorer(adata, root=None, branches=None, condition_obs_key='condition', obs_key='leiden', replicate_obs_key=None, copy=False, *, furcation=None, replicate_key=None, condition_order=None, design='independent')[source]¶
Bases:
ConditionScorerCompare commitment between exactly two conditions.
One shared
SingleScoreris fit on the pooled data. Formal inference is performed on biological-replicate summaries supplied throughreplicate_obs_key(or its aliasreplicate_key).- Parameters:
root (Optional[LabelSpec])
branches (Optional[TerminalSpec])
condition_obs_key (str)
obs_key (str)
replicate_obs_key (Optional[str])
copy (bool)
furcation (Optional[Furcation])
replicate_key (Optional[str])
condition_order (Optional[Sequence[object]])
design (str)
- compare_conditions(results=None, *, condition_a=None, condition_b=None, metric='mean_commitment_contribution', fate=None, fate_pair=None, n_permutations=9999, max_exact=100000, n_bootstrap=0, confidence_level=0.95, resample_cells_within_replicate=True, random_state=0, adjust_pvalues=True, verbose=True)[source]¶
Compare replicate-level commitment outcomes between two conditions.
The reported effect is
mean(condition_b) - mean(condition_a). Exact label permutation is used whenever the number of allocations is small enough; otherwise a corrected Monte Carlo p-value is used.- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
condition_a (str | None)
condition_b (str | None)
metric (str)
fate (str | None)
fate_pair (tuple[str, str] | None)
n_permutations (int)
max_exact (int)
n_bootstrap (int)
confidence_level (float)
resample_cells_within_replicate (bool)
random_state (int)
adjust_pvalues (bool)
verbose (bool)
- Return type:
DataFrame
- compute_delta_CS(condition_a=None, condition_b=None, *, results=None, n_permutations=9999, n_bootstrap=2000, confidence_level=0.95, random_state=0, verbose=True)[source]¶
Return fate-specific changes in mean commitment contribution.
This preserves the familiar function name while replacing the old angular-sector nCS difference.
delta_CSis now a finite, replicate-aware difference in mean soft commitment contribution.- Parameters:
condition_a (str | None)
condition_b (str | None)
results (Mapping[str, ConditionCommitmentResult] | None)
n_permutations (int)
n_bootstrap (int)
confidence_level (float)
random_state (int)
verbose (bool)
- Return type:
DataFrame
- fit_mixed_model(*, fate=None, metric='mean_commitment_contribution', results=None, condition_a=None, condition_b=None, on_invalid='return')[source]¶
Fit optional cell-level mixed models with replicate random intercepts.
Replicate-level permutation and hierarchical bootstrap remain the primary inference methods. This sensitivity analysis fails closed: singular, boundary, non-converged, or ill-conditioned fits return no coefficient or p-value when
on_invalid="return"(default), or raiseRuntimeErrorwhenon_invalid="raise".- Parameters:
fate (str | None)
metric (str)
results (Mapping[str, ConditionCommitmentResult] | None)
condition_a (str | None)
condition_b (str | None)
on_invalid (str)
- Return type:
DataFrame
- maximum_conditions: int | None = 2¶
- minimum_conditions: int = 2¶
- plot_affinity_distributions(results=None, *, metric='directional_affinity', fate=None, plot_type='box', figsize=None, title=None, ax=None)[source]¶
Plot biological-replicate outcome distributions by condition.
This retains the familiar pre-v0.8 method name while using biological replicates, rather than cells, as the displayed independent units.
plot_typemay be"box","violin", or"strip".- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
metric (str)
fate (str | None)
plot_type (str)
figsize (tuple[float, float] | None)
title (str | None)
- plot_commitment_decomposition(results=None, *, fate, condition_a=None, condition_b=None, n_bootstrap=1000, confidence_level=0.95, resample_cells_within_replicate=True, random_state=0, ax=None)[source]¶
Decompose a condition effect into direction, strength, and contribution.
The three displayed effects are condition B minus condition A for: directional affinity toward
fate, scalar commitment strength, and fate-specific mean commitment contribution.- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
fate (str)
condition_a (str | None)
condition_b (str | None)
n_bootstrap (int)
confidence_level (float)
resample_cells_within_replicate (bool)
random_state (int)
- plot_delta_CS_heatmap(statistics, *, annotate=True, use_adjusted_pvalue=True, title=None, figsize=None, ax=None)[source]¶
Plot fate-specific v0.8
delta_CSvalues as a heatmap.delta_CSis the replicate-aware condition-B minus condition-A difference in mean soft commitment contribution. It is not the old angular-sector nCS statistic from pre-v0.8 releases.- Parameters:
statistics (DataFrame)
annotate (bool)
use_adjusted_pvalue (bool)
title (str | None)
figsize (tuple[float, float] | None)
- plot_delta_cs_heatmap(*args, **kwargs)[source]¶
Lower-case compatibility alias for
plot_delta_CS_heatmap().
- plot_effects(statistics, *, alpha=0.05, use_adjusted_pvalue=True, ax=None)[source]¶
Plot effect sizes and hierarchical-bootstrap confidence intervals.
statisticsshould normally be returned bycompare_conditionswithn_bootstrap > 0or bycompute_delta_CS.- Parameters:
statistics (DataFrame)
alpha (float)
use_adjusted_pvalue (bool)
- plot_replicate_outcomes(results=None, *, metric='mean_commitment_contribution', fate=None, fate_pair=None, show_ci=True, ax=None)[source]¶
Plot biological-replicate outcomes for the two conditions.
- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
metric (str)
fate (str | None)
fate_pair (tuple[str, str] | None)
show_ci (bool)
- trajectory_shift(results=None, **kwargs)[source]¶
Compare replicate-level mean root progression velocity.
The old cell-level pseudotime distribution test was removed. This preserved method name now performs replicate-aware inference on the progression component of the projected velocity.
- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
- Return type:
DataFrame
- class scCS.MultiScorer(adata, root=None, branches=None, condition_obs_key='condition', obs_key='leiden', replicate_obs_key=None, copy=False, *, furcation=None, replicate_key=None, condition_order=None, design='independent')[source]¶
Bases:
ConditionScorerCompare commitment across three or more biological conditions.
- Parameters:
root (Optional[LabelSpec])
branches (Optional[TerminalSpec])
condition_obs_key (str)
obs_key (str)
replicate_obs_key (Optional[str])
copy (bool)
furcation (Optional[Furcation])
replicate_key (Optional[str])
condition_order (Optional[Sequence[object]])
design (str)
- compare_contrast(weights, results=None, *, metric='mean_commitment_contribution', fate=None, fate_pair=None, n_permutations=9999, random_state=0)[source]¶
Test a planned zero-sum contrast on replicate-level outcomes.
- Parameters:
weights (Mapping[object, float])
results (Mapping[str, ConditionCommitmentResult] | None)
metric (str)
fate (str | None)
fate_pair (tuple[str, str] | None)
n_permutations (int)
random_state (int)
- Return type:
DataFrame
- compare_omnibus(results=None, *, metric='mean_commitment_contribution', fate=None, fate_pair=None, n_permutations=9999, random_state=0, adjust_pvalues=True, verbose=True)[source]¶
Replicate-label permutation omnibus test across all conditions.
- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
metric (str)
fate (str | None)
fate_pair (tuple[str, str] | None)
n_permutations (int)
random_state (int)
adjust_pvalues (bool)
verbose (bool)
- Return type:
DataFrame
- compare_posthoc(results=None, *, metric='mean_commitment_contribution', fate=None, fate_pair=None, omnibus_results=None, only_significant_omnibus=True, omnibus_alpha=0.05, n_permutations=9999, max_exact=100000, random_state=0, verbose=True)[source]¶
Pairwise replicate-label tests with Holm correction.
- Parameters:
results (Mapping[str, ConditionCommitmentResult] | None)
metric (str)
fate (str | None)
fate_pair (tuple[str, str] | None)
omnibus_results (DataFrame | None)
only_significant_omnibus (bool)
omnibus_alpha (float)
n_permutations (int)
max_exact (int)
random_state (int)
verbose (bool)
- Return type:
DataFrame
- fit_mixed_model(*, metric='mean_commitment_contribution', fate=None, results=None, on_invalid='return')[source]¶
Fit optional mixed models with fail-closed omnibus Wald tests.
Replicate-level permutation remains the primary omnibus inference. Singular, boundary, non-converged, or ill-conditioned fits return no coefficient or p-value by default instead of reporting misleading
converged=Trueresults from an invalid covariance estimate.- Parameters:
metric (str)
fate (str | None)
results (Mapping[str, ConditionCommitmentResult] | None)
on_invalid (str)
- Return type:
DataFrame
- maximum_conditions: int | None = None¶
- minimum_conditions: int = 3¶
- plot_omnibus_summary(omnibus_results, results=None, *, posthoc_df=None, annotate=True, use_adjusted_pvalue=True, ax=None)[source]¶
Plot condition means and omnibus significance for each outcome.
resultsandposthoc_dfare accepted for tutorial compatibility. Omnibus annotations are taken fromomnibus_results; post-hoc effects should be shown withplot_posthoc_heatmap().- Parameters:
omnibus_results (DataFrame)
results (Mapping[str, ConditionCommitmentResult] | None)
posthoc_df (DataFrame | None)
annotate (bool)
use_adjusted_pvalue (bool)
- plot_pairwise_delta_grid(posthoc_results, *, ncols=3, annotate=True, use_adjusted_pvalue=True, figsize_per_panel=(5.6, 4.8))[source]¶
Plot one post-hoc condition-effect heatmap per fate.
- Parameters:
posthoc_results (DataFrame)
ncols (int)
annotate (bool)
use_adjusted_pvalue (bool)
figsize_per_panel (tuple[float, float])
Future-fate engine¶
- class scCS.FutureFateScoreResult(furcation, embedding, projection, commitment, selected_probability, competing_probability, unresolved_probability, selected_reach, competing_reach, progression_velocity, supported_progression_flux, one_step_outside_probability, outcome_names, selected_anchor_mask, outcome_anchor_mask, effective_horizon, solver, solver_iterations, solver_converged, solver_residual, min_reach, anchor_quantile, min_anchor_cells, progression_scale, status, dominant_fate, root_population_summary, transition_normalization, anchor_diagnostics, scoring_mode='future_fate', magnitude_scaler=None, magnitude_fit_population='not_applicable')[source]¶
Cell-level discounted future-fate result for one supervised furcation.
- Parameters:
furcation (Furcation)
embedding (ScoringEmbeddingResult)
projection (ProjectionResult)
commitment (CommitmentAffinityResult)
selected_probability (ndarray)
competing_probability (ndarray)
unresolved_probability (ndarray)
selected_reach (ndarray)
competing_reach (ndarray)
progression_velocity (ndarray)
supported_progression_flux (ndarray)
one_step_outside_probability (ndarray)
outcome_names (tuple[str, ...])
selected_anchor_mask (ndarray)
outcome_anchor_mask (ndarray)
effective_horizon (int)
solver (str)
solver_iterations (int)
solver_converged (bool)
solver_residual (float)
min_reach (float)
anchor_quantile (float)
min_anchor_cells (int)
progression_scale (str)
status (ndarray)
dominant_fate (ndarray)
root_population_summary (PopulationCommitmentSummary)
transition_normalization (TransitionNormalization)
anchor_diagnostics (tuple[dict[str, Any], ...])
scoring_mode (str)
magnitude_scaler (Any)
magnitude_fit_population (str)
- property commitment_contribution: ndarray¶
Discounted selected-fate probability allocated across fates.
- property commitment_strength: ndarray¶
Compatibility alias for
future_fate_reach.
- property conditional_fate_affinity: ndarray¶
Conditional Fate Affinity (CFA).
This documentation-level name emphasizes that the distribution is normalized across supervised fates after conditioning on selected-fate reach. It is an exact read-only alias of
future_fate_affinity.
- property directional_affinity: ndarray¶
Compatibility alias for
future_fate_affinity.
- property discounted_fate_reach: ndarray¶
Discounted Fate Reach (DFR), an alias of future-fate reach.
- property resolved_commitment: ndarray¶
Resolved Commitment (RC), reach multiplied by fate specificity.
- property selected_path_coverage: ndarray¶
One-step transition mass retained within the supervised cell set.
- property signed_ordering_flux: ndarray¶
Signed Ordering Flux (SOF), an alias of signed progression.
- property signed_progression: ndarray¶
Signed expected change in the supplied progression coordinate.
This is the public semantic alias for
progression_velocity. Positive values indicate movement toward larger ordering values; negative values preserve retrograde or loop-returning dynamics.
- property unresolved_future_probability: ndarray¶
Unresolved Future Probability (UFP).
- class scCS.DiscountedOutcomeSolution(outcome_names, probability, unresolved_probability, anchors, effective_horizon, gamma, solver, iterations, converged, residual)[source]¶
Discounted multi-outcome hitting probabilities and solver diagnostics.
- Parameters:
outcome_names (tuple[str, ...])
probability (ndarray)
unresolved_probability (ndarray)
anchors (ndarray)
effective_horizon (int)
gamma (float)
solver (str)
iterations (int)
converged (bool)
residual (float)
- scCS.score_future_fate(furcation, embedding, transition_matrix, *, effective_horizon=64, anchor_quantile=0.9, min_anchor_cells=10, competing_outcomes=None, min_reach=1e-06, progression_values=None, progression_scale='rank', solver='auto', direct_max_states=50000, tolerance=1e-10, max_iter=20000, committed_reach_threshold=0.25, committed_specificity_threshold=0.25)[source]¶
Score discounted future-fate identity and signed progression.
The transition graph must cover the full AnnData object. Selected fate anchors are chosen from the late ordering tail of each annotated terminal population. Optional competing outcomes must be supplied explicitly as full-length Boolean masks or full-state index sequences.
- Parameters:
furcation (Furcation)
embedding (ScoringEmbeddingResult)
effective_horizon (int)
anchor_quantile (float)
min_anchor_cells (int)
competing_outcomes (Mapping[str, Sequence[int] | ndarray] | None)
min_reach (float)
progression_values (Sequence[float] | None)
progression_scale (str)
solver (str)
direct_max_states (int)
tolerance (float)
max_iter (int)
committed_reach_threshold (float)
committed_specificity_threshold (float)
- Return type:
- scCS.solve_discounted_outcomes(transition_matrix, anchors, outcome_names, *, effective_horizon=64, solver='auto', direct_max_states=50000, tolerance=1e-10, max_iter=20000)[source]¶
Solve geometrically discounted hitting probabilities.
Before each transition the process stops with probability
1-gamma, wheregamma = h / (h + 1)andhiseffective_horizon. The unresolved probability is the chance of stopping before any supplied outcome anchor is reached.solver='auto'uses sparse LU on modest graphs and fixed-point iteration on larger graphs. The iterative solver uses only sparse matrix products and therefore avoids dense state-by-state objects.- Parameters:
anchors (ndarray)
outcome_names (Sequence[str])
effective_horizon (int)
solver (str)
direct_max_states (int)
tolerance (float)
max_iter (int)
- Return type:
- scCS.canonicalize_transition_matrix(transition_matrix)[source]¶
Return a non-negative, float64, row-stochastic transition matrix.
Sparse float32 accumulation may leave nominally normalized matrices a few ulps above or below one. Materially negative entries still raise. Empty rows receive self-loops so every row represents a valid Markov state.
- Return type:
TransitionNormalization
Supervised geometry and ordering¶
- class scCS.Furcation(*, obs_key, root, terminals, min_cells=2)[source]¶
A manually annotated root-to-terminal furcation.
- Parameters:
obs_key (str) – Column containing annotation labels.
root (LabelSpec) – One label, or a group of labels representing one biological root population.
terminals (TerminalSpec) – Either an ordered sequence of terminal labels, or an ordered mapping from biological terminal name to one or more annotation labels.
min_cells (int) – Minimum number of cells required in the root and in every terminal population during validation.
Notes
Grouping multiple annotation labels under one root or terminal is only a naming convenience. It does not introduce intermediate-state modelling.
- masks(labels)[source]¶
Return Boolean masks for the root and each terminal population.
- Parameters:
labels (Sequence[object])
- Return type:
Dict[str, ndarray]
- property root_name: str¶
Human-readable name of the grouped root population.
- class scCS.FurcationOrderingScaler(root_lower_quantile=0.05, root_upper_quantile=0.95, higher_is_later=True, root_lower_=None, root_upper_=None, fitted_=False)[source]¶
Map an ordering metric onto the incoming annotated root arm.
- Parameters:
root_lower_quantile (float) – Robust bounds for root radial placement. Earlier root cells map farther from the furcation; later root cells map closer to the origin.
root_upper_quantile (float) – Robust bounds for root radial placement. Earlier root cells map farther from the furcation; later root cells map closer to the origin.
higher_is_later (bool) – Whether larger ordering values indicate later developmental progress.
root_lower_ (float | None)
root_upper_ (float | None)
fitted_ (bool)
Notes
Terminal ordering values are intentionally not fitted or used for the scientific geometry. Every manually annotated terminal population is an equal-radius endpoint anchor. Terminal ordering is used only by the display layer to spread overplotted cells along a 2D ray.
- scCS.build_scoring_embedding(adata, furcation, *, ordering, ordering_scaler=None, arm_scale=1.0, write_to_adata=False, coordinate_key='X_sccs_score')[source]¶
Build deterministic root-plus-simplex scientific coordinates.
The function performs no topology inference and adds no jitter. Only the manually annotated root and terminal populations are selected. Root cells are ordered along the incoming arm; terminal cells are fixed at equal simplex vertices independent of terminal pseudotime or abundance.
- Parameters:
furcation (Furcation)
ordering (str | Sequence[float] | ndarray)
ordering_scaler (FurcationOrderingScaler | None)
arm_scale (float)
write_to_adata (bool)
coordinate_key (str)
- Return type:
ScoringEmbeddingResult
Instantaneous engine¶
- class scCS.FurcationScoreResult(furcation, embedding, projection, projected_velocity, progression_velocity, branch_velocity, aligned_probability, commitment, status, dominant_fate, root_population_summary, magnitude_scaler, magnitude_fit_population)[source]¶
Cell- and population-level commitment result for one furcation.
The result deliberately separates fate direction, fate-directed magnitude, and magnitude-weighted commitment.
directional_affinityis not a calibrated future-fate probability; it is a supervised allocation across the manually defined terminal populations.- Parameters:
furcation (Furcation)
embedding (ScoringEmbeddingResult)
projection (ProjectionResult)
projected_velocity (ndarray)
progression_velocity (ndarray)
branch_velocity (ndarray)
aligned_probability (float)
commitment (CommitmentAffinityResult)
status (ndarray)
dominant_fate (ndarray)
root_population_summary (PopulationCommitmentSummary)
magnitude_scaler (Any)
magnitude_fit_population (str)
- property aligned_directional_entropy: float¶
Attainable entropy floor for a perfectly aligned fate vector.
- property commitment_entropy: ndarray¶
Entropy after weak velocities are blended toward uniform affinity.
- property directional_entropy: ndarray¶
Raw normalized Shannon entropy of cosine-softmax fate affinity.
- property directional_specificity: ndarray¶
uniform=0 and perfect alignment=1.
- Type:
Support-adjusted specificity
- property fate_cosine_similarity: ndarray¶
Cosine similarity of branch velocity to every ideal fate axis.
Rows with undefined or zero fate-directed velocity are returned as
NaNbecause an angle is not defined without a direction.
- property n_cells: int¶
Number of cells in the manually selected furcation.
- property n_root: int¶
Number of cells in the manually annotated root population.
- property n_terminal: int¶
Number of cells in all manually annotated terminal populations.
- property nearest_fate_angle_degrees: ndarray¶
Smallest angular deviation from any ideal fate axis, in degrees.
- scCS.project_transition_velocity(transition_matrix, selected_coordinates, *, selected_indices=None, renormalize_retained=True, min_coverage=0.05)[source]¶
Project directed transitions into a selected scCS scoring geometry.
- Parameters:
transition_matrix – Square dense or scipy-sparse directed transition matrix. It may cover the full dataset or only the selected furcation cells.
selected_coordinates (ndarray) – Scientific coordinates for selected furcation cells, shape
(n_selected, dimension).selected_indices (Sequence[int] | None) – Indices of selected cells in the full transition matrix. Omit when the transition matrix already contains exactly the selected cells.
renormalize_retained (bool) – If true, normalize transition mass retained within the furcation before computing expected displacement.
min_coverage (float) – Minimum fraction of outgoing transition mass retained within the selected furcation. Lower-coverage velocities are returned as NaN and marked undefined.
- Return type:
ProjectionResult
Notes
Excluded cells are never assigned artificial coordinates. Their outgoing transition mass is reported as external mass instead of pulling projected vectors toward an arbitrary origin.
- scCS.cosine_softmax_affinity(branch_velocity, fate_directions, *, aligned_probability=0.9)[source]¶
Calculate calibrated cosine-softmax fate affinity.
A zero branch velocity receives a uniform directional affinity. This is a neutral mathematical value only; no-signal status is carried separately in
CommitmentAffinityResultand the scorer result.- Parameters:
branch_velocity (ndarray)
fate_directions (ndarray)
aligned_probability (float)
- Return type:
ndarray