API reference#

The public API is also available from the flat cytogater namespace, for example cytogater.run_tree_gating().

Marker-aware gating#

cytogater.fit_gmm_2(x, cutoff_method='mean', gmm_model_names=None)#

Fit the R package’s two-component, one-dimensional GMM.

Mirrors mclust::Mclust(x, G = 2): both the equal-variance (“E”) and unequal-variance (“V”) models are fitted and the better BIC wins, except that variance-collapsed “V” fits are discarded first. gmm_model_names accepts “E” or “V” to pin the model, matching R’s modelNames.

Parameters:
  • x (array-like) – One-dimensional marker-expression values. Non-finite values are removed before fitting.

  • cutoff_method ({"mean", "equal_posteriors"}, default="mean") – Rule for placing the cutoff between fitted components.

  • gmm_model_names ({"E", "V"} or None, default=None) – Restrict fitting to equal ("E") or unequal ("V") component variances. By default both models are compared by BIC.

Returns:

Fitted means, standard deviations, weights, cutoff, and separation score. Returns None when fewer than 50 usable observations, fewer than three unique values, or no valid model is available.

Return type:

dict or None

Raises:

ValueError – If gmm_model_names is not "E", "V", or None.

cytogater.fit_marker_stats(spe, markers, assay_name='exprs', min_n=50)#

Fit gating statistics for a collection of markers.

Parameters:
  • spe (anndata.AnnData) – Cells-by-markers data object.

  • markers (sequence of str) – Marker names to fit. Names absent from spe.var_names are skipped.

  • assay_name (str or None, default="exprs") – Layer containing expression values. Use None or "X" for spe.X.

  • min_n (int, default=50) – Minimum finite observations required to attempt a two-component GMM.

Returns:

Mapping from marker name to valid, cutoff, scale, weight, and mu_high statistics. A robust quantile fallback is returned when a marker cannot be fitted.

Return type:

dict

cytogater.gmm_equal_posterior_cutoff(mu1, mu2, s1, s2, p1, p2)#

Find the equal-posterior cutoff between two Gaussian components.

Parameters:
  • mu1 (float) – Component means, normally ordered from low to high.

  • mu2 (float) – Component means, normally ordered from low to high.

  • s1 (float) – Component standard deviations.

  • s2 (float) – Component standard deviations.

  • p1 (float) – Component mixing proportions.

  • p2 (float) – Component mixing proportions.

Returns:

A root between the two means where the weighted component densities are equal. Falls back to the midpoint when no suitable root exists.

Return type:

float

cytogater.marker_separability(x)#

Measure separation between two fitted marker-expression components.

Parameters:

x (array-like) – One-dimensional marker-expression values.

Returns:

Absolute difference between fitted component means divided by their pooled standard deviation, or numpy.nan if fitting fails.

Return type:

float

cytogater.score_marker_logistic(x, cutoff, scale)#

Convert marker expression to a smooth positivity score.

Parameters:
  • x (array-like) – Marker-expression values.

  • cutoff (float) – Expression value mapped to probability 0.5.

  • scale (float) – Logistic transition scale; larger values produce a gentler change.

Returns:

Values between zero and one with the same shape as x.

Return type:

numpy.ndarray

cytogater.score_marker_rank(x)#

Scale marker expression to fractional ranks.

Parameters:

x (array-like) – Marker-expression values.

Returns:

Rank scores between zero and one. Missing values remain missing.

Return type:

numpy.ndarray

cytogater.calculate_soft_scores(spe, marker_stats, lineage_table, assay_name='exprs', neg_strength=0.8)#

Calculate marker-aware soft scores for every cell type.

Positive-marker scores are combined using marker separation weights, then reduced by expression of negative markers.

Parameters:
  • spe (anndata.AnnData) – Cells-by-markers data object.

  • marker_stats (dict) – Output from fit_marker_stats().

  • lineage_table (pandas.DataFrame) – Table containing cell_type, pos_markers, and neg_markers.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" to use spe.X.

  • neg_strength (float, default=0.8) – Strength of each negative-marker penalty.

Returns:

Cell-by-cell-type score matrix indexed like spe.obs.

Return type:

pandas.DataFrame

cytogater.assign_soft_labels(prob_mat, unknown_thresh=0.4)#

Assign the highest-probability cell type to each cell.

Parameters:
  • prob_mat (pandas.DataFrame or array-like) – Cell-by-cell-type probability matrix. Data-frame column names become output labels.

  • unknown_thresh (float, default=0.4) – Minimum winning probability; cells below it become "Unknown".

Returns:

One string label per row of prob_mat.

Return type:

numpy.ndarray

cytogater.run_soft_gating(spe, lineage_table, assay_name='exprs', unknown_thresh=0.4, store=True)#

Run soft marker gating for all cell types.

Parameters:
  • spe (anndata.AnnData) – Cells-by-markers data object. Modified in place when store=True.

  • lineage_table (pandas.DataFrame) – Cell types and their positive and negative markers.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • unknown_thresh (float, default=0.4) – Minimum winning score required for a non-unknown label.

  • store (bool, default=True) – Store probabilities and labels in spe.obs, spe.obsm, and spe.uns.

Returns:

Annotated spe, marker statistics, probability matrix, labels, and cleaned lineage table.

Return type:

dict

cytogater.run_tree_gating(spe, lineage_table, assay_name='exprs', max_depth=4, min_cells=200, min_score=0.5, uncert_thresh=0.25, neg_strength=0.4, cutoff_method='mean', gmm_model_names=None, workers=1)#

Run marker-priority tree gating for all cell types.

Parameters and defaults align with the R implementation.

Parameters:
  • spe (anndata.AnnData) – Cells-by-markers data object. Results are stored on this object.

  • lineage_table (pandas.DataFrame) – Cell types and their positive and negative markers.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • max_depth (int, default=4) – Maximum depth of each cell-type gating tree.

  • min_cells (int, default=200) – Minimum cells required to split a tree node.

  • min_score (float, default=0.5) – Minimum marker separation required for a split.

  • uncert_thresh (float, default=0.25) – Minimum winning probability for a hard cell-type label.

  • neg_strength (float, default=0.4) – Strength of negative-marker penalties.

  • cutoff_method ({"mean", "equal_posteriors"}, default="mean") – GMM cutoff rule.

  • gmm_model_names ({"E", "V"} or None, default=None) – Optional GMM variance-model restriction.

  • workers (int, default=1) – Accepted for R API compatibility; execution is currently serial.

Returns:

Annotated spe, one tree per cell type, probability matrix, hard labels, and cleaned lineage table.

Return type:

dict

cytogater.build_fullcoverage_tree(expr_mat, markers_pos, markers_neg=(), cell_idx=None, depth=0, max_depth=4, min_cells=200, min_score=0.5, cutoff_method='mean', gmm_model_names=None)#

Build a recursive marker-priority gating tree.

Parameters:
  • expr_mat (pandas.DataFrame or array-like) – Cells-by-markers expression matrix.

  • markers_pos (sequence of str) – Candidate positive markers used for recursive splits.

  • markers_neg (sequence of str, default=()) – Negative markers used when forming the provisional split target.

  • cell_idx (array-like or None, default=None) – Row positions assigned to the current node. The root uses all rows.

  • depth (int, default=0) – Current recursion depth.

  • max_depth (int, default=4) – Maximum tree depth.

  • min_cells (int, default=200) – Minimum cells required to split a node.

  • min_score (float, default=0.5) – Minimum marker separation score required for a split.

  • cutoff_method ({"mean", "equal_posteriors"}, default="mean") – GMM cutoff rule.

  • gmm_model_names ({"E", "V"} or None, default=None) – Optional GMM variance-model restriction.

Returns:

Nested node/leaf dictionaries containing split markers, cutoffs, separation scores, cell indices, and child nodes.

Return type:

dict

cytogater.collect_path_scores(tree, expr_mat, cell_i)#

Collect logistic split scores along one cell’s tree path.

Parameters:
  • tree (dict) – Tree returned by build_fullcoverage_tree().

  • expr_mat (pandas.DataFrame or array-like) – Cells-by-markers expression matrix used to build the tree.

  • cell_i (int) – Positional row index of the cell.

Returns:

One positivity score for each internal node visited by the cell.

Return type:

numpy.ndarray

cytogater.neg_penalty(expr_mat, neg_markers, cell_i, marker_stats=None, neg_strength=0.8)#

Calculate the multiplicative negative-marker penalty for one cell.

Parameters:
  • expr_mat (pandas.DataFrame or array-like) – Cells-by-markers expression matrix.

  • neg_markers (sequence of str) – Markers whose expression argues against the cell type.

  • cell_i (int) – Positional row index of the cell.

  • marker_stats (dict or None, default=None) – Per-marker cutoff and scale statistics.

  • neg_strength (float, default=0.8) – Maximum penalty contributed by each negative marker.

Returns:

Combined penalty clipped to the interval zero to one.

Return type:

float

cytogater.tree_prob(tree, expr_mat, cell_i, combine='mean', neg_markers=(), marker_stats=None, neg_strength=0.8, lambda_=2)#

Calculate one cell’s probability for a marker-priority tree.

Parameters:
  • tree (dict) – Tree returned by build_fullcoverage_tree().

  • expr_mat (pandas.DataFrame or array-like) – Cells-by-markers expression matrix.

  • cell_i (int) – Positional row index of the cell.

  • combine ({"mean", "product"}, default="mean") – How to combine scores along the tree path. Values other than mean use the product.

  • neg_markers (sequence of str, default=()) – Negative markers used to penalise the path score.

  • marker_stats (dict or None, default=None) – Per-marker statistics used by the negative-marker penalty.

  • neg_strength (float, default=0.8) – Negative-marker penalty strength.

  • lambda_ – Shrinkage applied to short tree paths.

Returns:

Cell-type probability, or numpy.nan for a path without scores.

Return type:

float

Reference selection and prediction#

cytogater.apply_cutoff_labels(res, cutoff_fn=<function prob_quantile_cutoff>, label_col='cutoff_label', unknown_label='Unknown')#

Assign labels to cells that exceed exactly one probability cutoff.

Parameters:
  • res (dict) – Gating result containing prob_mat and spe.

  • cutoff_fn (callable, default=prob_quantile_cutoff) – Per-cell-type cutoff function.

  • label_col (str, default="cutoff_label") – Destination column in res["spe"].obs.

  • unknown_label (str, default="Unknown") – Label for cells exceeding zero or multiple cutoffs.

Returns:

The input result with annotated spe and a nullable boolean label_mat entry added.

Return type:

dict

cytogater.assign_confident_labels(prob_mat, confidence_flags, unknown_label='Unknown')#

Assign winning cell types only to cells flagged as confident.

Parameters:
  • prob_mat (pandas.DataFrame) – Cell-by-cell-type probability matrix.

  • confidence_flags (array-like of bool) – One confidence decision per cell.

  • unknown_label (str, default="Unknown") – Label used for unconfident rows or rows without finite probabilities.

Returns:

One label per probability-matrix row.

Return type:

numpy.ndarray

cytogater.compute_custom_labels(prob_mat, base_thresh=0.4, quantile_cut=0.75, iqr_mult=1.5, flag_fn=None)#

Flag cells whose winning probability is unusually high.

Parameters:
  • prob_mat (array-like) – Cell-by-cell-type probability matrix.

  • base_thresh (float, default=0.4) – Absolute lower bound for the winning probability.

  • quantile_cut (float, default=0.75) – Within-cell probability quantile used in the adaptive cutoff.

  • iqr_mult (float, default=1.5) – Number of within-cell interquartile ranges added to the quantile.

  • flag_fn (callable or None, default=None) – Optional function receiving one probability row and returning a boolean. When supplied, it replaces the default cutoff rule.

Returns:

Boolean confidence flag for every cell.

Return type:

numpy.ndarray

cytogater.custom_labels(spe, prob_mat, colname='custom_label', base_thresh=0.4, quantile_cut=0.75, iqr_mult=1.5, unknown_label='Unknown', flag_fn=None)#

Store confidence-filtered probability labels in an AnnData object.

Parameters:
  • spe (anndata.AnnData) – Object to annotate in place.

  • prob_mat (pandas.DataFrame) – Cell-by-cell-type probability matrix.

  • colname (str, default="custom_label") – Destination column in spe.obs.

  • base_thresh (float) – Confidence-rule parameters passed to compute_custom_labels().

  • quantile_cut (float) – Confidence-rule parameters passed to compute_custom_labels().

  • iqr_mult (float) – Confidence-rule parameters passed to compute_custom_labels().

  • unknown_label (str, default="Unknown") – Label assigned to cells that do not pass the confidence rule.

  • flag_fn (callable or None, default=None) – Optional custom confidence function.

Returns:

The same object, with spe.obs[colname] added.

Return type:

anndata.AnnData

cytogater.prob_mad_cutoff(x, mad_mult=3)#

Calculate a median-plus-MAD probability cutoff.

Parameters:
  • x (array-like) – Probability values.

  • mad_mult (float, default=3) – Number of unscaled median absolute deviations above the median.

Returns:

Robust probability cutoff.

Return type:

float

cytogater.prob_quantile_cutoff(x, prob=0.98)#

Calculate a finite-value probability quantile cutoff.

Parameters:
  • x (array-like) – Probability values.

  • prob (float, default=0.98) – Quantile between zero and one.

Returns:

Requested quantile, ignoring missing values.

Return type:

float

cytogater.probability_label_matrix(prob_mat, cutoff_fn=<function prob_quantile_cutoff>)#

Threshold every cell-type probability column independently.

Parameters:
  • prob_mat (pandas.DataFrame or array-like) – Cell-by-cell-type probability matrix.

  • cutoff_fn (callable, default=prob_quantile_cutoff) – Function mapping one probability column to a scalar cutoff.

Returns:

Nullable boolean matrix indicating which cell-type cutoffs each cell exceeds. Missing input values and invalid cutoffs remain missing.

Return type:

pandas.DataFrame

cytogater.train_custom_knn(spe, label_col='cutoff_label', assay_name='exprs', unknown_label='Unknown', features='all', cv_folds=5, repeats=10, agreement_thresh=0.8, k=5, method='pearson', seed=None, chunk_size=250, BPPARAM=None)#

Clean reference labels by repeated cross-validation and fit kNN.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object, modified in place.

  • label_col (str, default="cutoff_label") – spe.obs column containing initial reference labels.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • unknown_label (str, default="Unknown") – Label excluded from reference training.

  • features ("all" or sequence of str, default="all") – Marker features used by the classifier.

  • cv_folds (int, default=5) – Number of stratified folds per repeat.

  • repeats (int, default=10) – Number of repeated cross-validation rounds.

  • agreement_thresh (float, default=0.8) – Minimum fraction of correct out-of-fold predictions required to retain a reference cell.

  • k (int, default=5) – Number of neighbours.

  • method ({"pearson", "spearman", "cosine", "euclidean"}, default="pearson") – Neighbour similarity or distance measure.

  • seed (int or None, default=None) – Random seed for fold assignment.

  • chunk_size (int, default=250) – Query block size during cross-validation.

  • BPPARAM (object or None, default=None) – Accepted for R API compatibility; currently ignored.

Returns:

Annotated spe, model/reference matrices, retained labels, cross-validated probabilities, features, agreement rates, and retained cell names. Cleaned labels are stored in spe.obs["cleaned_core_label"].

Return type:

dict

cytogater.predict_unknown_with_knn(spe, knn_ref, assay_name='exprs', label_col='cutoff_label', out_col='knn_label_filled', pred_col='knn_pred', unknown_label='Unknown', unassigned_label='Unassigned', threshold=0.6, k=5, dist_method='pearson', chunk_size=10000)#

Fill unknown labels from a cleaned weighted-kNN reference.

Parameters:
  • spe (anndata.AnnData) – Object containing cells to predict; modified in place.

  • knn_ref (dict) – Result from train_custom_knn(), or a compatible model mapping.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • label_col (str, default="cutoff_label") – Existing labels; only missing or unknown_label cells are replaced.

  • out_col (str, default="knn_label_filled") – Destination for the combined existing and predicted labels.

  • pred_col (str, default="knn_pred") – Destination for predictions on replaced cells only.

  • unknown_label (str, default="Unknown") – Label marking cells that require prediction.

  • unassigned_label (str, default="Unassigned") – Label used when prediction confidence is below threshold.

  • threshold (float, default=0.6) – Minimum winning class probability.

  • k (int, default=5) – Number of neighbours.

  • dist_method ({"pearson", "spearman", "cosine", "euclidean"}, default="pearson") – Neighbour similarity or distance measure.

  • chunk_size (int, default=10000) – Query block size.

Returns:

Annotated spe and probabilities for predicted cells. prob_mat is None when no cells require prediction.

Return type:

dict

Raises:

KeyError – If label_col is absent from spe.obs.

cytogater.predict_wknn_multi(train_data, test_data, train_labels, k=5, method='pearson', return_matrix=False, chunk_size=10000)#

Predict labels with a weighted k-nearest-neighbour classifier.

Parameters:
  • train_data (array-like) – Training and query matrices with cells in rows and identical marker columns.

  • test_data (array-like) – Training and query matrices with cells in rows and identical marker columns.

  • train_labels (array-like) – One class label per training row. Categorical levels are preserved.

  • k (int, default=5) – Number of neighbours.

  • method ({"pearson", "spearman", "cosine", "euclidean"}, default="pearson") – Similarity or distance measure used to find and weight neighbours.

  • return_matrix (bool, default=False) – Include the complete cell-by-class probability matrix.

  • chunk_size (int or None, default=10000) – Number of query cells processed together. Cosine mode currently uses all query cells in one block.

Returns:

labels and winning probs for query cells. When requested, prob_matrix and its compatibility alias prob_mat contain the full probability data frame.

Return type:

dict

Raises:

ValueError – If matrix dimensions differ or method is unsupported.

cytogater.train_custom_randomforest(spe, label_col='cutoff_label', assay_name='exprs', unknown_label='Unknown', num_trees=200, mtry=None, seed=None, features='all', cv_folds=5, repeats=10, agreement_thresh=0.8, num_threads=2, **kwargs)#

Train the R-equivalent probability random forest.

num.trees may be supplied through kwargs for direct R-call migration.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object, modified in place.

  • label_col (str, default="cutoff_label") – spe.obs column containing initial reference labels.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • unknown_label (str, default="Unknown") – Label excluded from reference training.

  • num_trees (int, default=200) – Trees in the final random forest.

  • mtry (int, float, str, or None, default=None) – Features considered at each split; None uses "sqrt".

  • seed (int or None, default=None) – Random seed for cross-validation and model fitting.

  • features ("all" or sequence of str, default="all") – Marker features used by the model.

  • cv_folds (int, default=5) – Requested stratified folds, capped by the smallest eligible class.

  • repeats (int, default=10) – Repeated cross-validation rounds.

  • agreement_thresh (float, default=0.8) – Minimum correct out-of-fold fraction required to retain a reference.

  • num_threads (int, default=2) – Parallel threads used by scikit-learn.

  • **kwargs – Compatibility arguments. num.trees overrides num_trees.

Returns:

Annotated spe, fitted model, retained-cell probabilities, agreement rates, and feature names. Cleaned labels are stored in spe.obs["cleaned_core_label"].

Return type:

dict

Raises:

ValueError – If no label has at least two reference cells.

cytogater.predict_unknown_with_randomforest(spe, model, assay_name='exprs', label_col='custom_label', out_col='soft_tree_label_filled', pred_col='rf_pred', unknown_label='Unknown', threshold=0.5, unassigned_label='Unassigned')#

Fill unknown labels using a trained random forest.

Parameters:
  • spe (anndata.AnnData) – Object containing cells to predict; modified in place.

  • model (sklearn.ensemble.RandomForestClassifier) – Model returned in train_custom_randomforest(...)["model"].

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • label_col (str, default="custom_label") – Existing labels; only missing or unknown_label cells are replaced.

  • out_col (str, default="soft_tree_label_filled") – Destination for combined existing and predicted labels.

  • pred_col (str, default="rf_pred") – Destination for predictions on replaced cells only.

  • unknown_label (str, default="Unknown") – Label marking cells that require prediction.

  • threshold (float, default=0.5) – Minimum winning class probability.

  • unassigned_label (str, default="Unassigned") – Label used below the confidence threshold.

Returns:

Annotated spe and a probability matrix for predicted cells. prob_mat is None when no cells require prediction.

Return type:

dict

cytogater.train_custom_dl(spe, label_col='cutoff_label', assay_name='exprs', unknown_label='Unknown', features='all', hidden_dims=(64, 32), dropout=0.3, epochs=50, lr=0.001, weight_decay=0.0001, batch_size=256, cv_folds=5, repeats=3, agreement_thresh=0.8, val_frac=0.15, patience=10, verbose_training=False, class_balanced_loss=True, seed=None, **kwargs)#

Train a small feed-forward probability network.

PyTorch is an optional dependency and is imported only when this function is called.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object.

  • label_col (str, default="cutoff_label") – spe.obs column containing training labels.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • unknown_label (str, default="Unknown") – Label excluded from training.

  • features ("all" or sequence of str, default="all") – Marker features used by the network.

  • hidden_dims (sequence of int, default=(64, 32)) – Width of each hidden layer.

  • dropout (float, default=0.3) – Dropout probability after each hidden activation.

  • epochs (int, default=50) – Training epochs.

  • lr (float, default=1e-3) – Adam learning rate.

  • weight_decay (float, default=1e-4) – Adam L2 weight decay.

  • batch_size (int, default=256) – Mini-batch size.

  • cv_folds – Accepted for compatibility with the R workflow; currently unused.

  • repeats – Accepted for compatibility with the R workflow; currently unused.

  • agreement_thresh – Accepted for compatibility with the R workflow; currently unused.

  • val_frac – Accepted for compatibility with the R workflow; currently unused.

  • patience – Accepted for compatibility with the R workflow; currently unused.

  • verbose_training (bool, default=False) – Print the loss after each epoch.

  • class_balanced_loss (bool, default=True) – Weight cross-entropy inversely by class frequency.

  • seed (int or None, default=None) – PyTorch random seed.

  • **kwargs – Additional options retained in the returned model metadata.

Returns:

Input spe, fitted network metadata, and feature names. The model mapping includes the network, class levels, scaling values, and device.

Return type:

dict

cytogater.predict_unknown_with_dl(spe, model, assay_name='exprs', label_col='custom_label', out_col='soft_tree_label_filled', pred_col='dl_pred', unknown_label='Unknown', threshold=0.5, unassigned_label='Unassigned')#

Fill unknown labels using a trained PyTorch network.

Parameters:
  • spe (anndata.AnnData) – Object containing cells to predict; modified in place.

  • model (dict) – Network metadata returned in train_custom_dl(...)["model"].

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • label_col (str, default="custom_label") – Existing labels; only missing or unknown_label cells are replaced.

  • out_col (str, default="soft_tree_label_filled") – Destination for combined existing and predicted labels.

  • pred_col (str, default="dl_pred") – Destination for predictions on replaced cells only.

  • unknown_label (str, default="Unknown") – Label marking cells that require prediction.

  • threshold (float, default=0.5) – Minimum winning softmax probability.

  • unassigned_label (str, default="Unassigned") – Label used below the confidence threshold.

Returns:

Annotated spe and a probability matrix for predicted cells. prob_mat is None when no cells require prediction.

Return type:

dict

cytogater.build_lineage_hierarchy(spe, label_col='cleaned_core_label', assay_name='exprs')#

Build a complete-linkage hierarchy from cell-type pseudobulks.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object.

  • label_col (str, default="cleaned_core_label") – spe.obs column containing cleaned reference labels. Missing and "Unknown" labels are excluded.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

Returns:

linkage contains the SciPy complete-linkage matrix and labels gives the corresponding cell-type leaf names.

Return type:

dict

cytogater.build_hierarchical_reference(spe, hc_tree, marker_stats=None, label_col='cleaned_core_label', top_n=5, assay_name='exprs', unknown_label='Unassigned')#

Create a binary training reference for every hierarchy node.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object.

  • hc_tree (dict) – Hierarchy returned by build_lineage_hierarchy().

  • marker_stats (dict or None, default=None) – Optional marker statistics from gating. When supplied, node-specific markers are ranked by weighted mean difference.

  • label_col (str, default="cleaned_core_label") – spe.obs column containing reference cell types.

  • top_n (int or None, default=5) – Number of discriminating markers retained per node. None keeps all.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • unknown_label (str, default="Unassigned") – Reference label excluded from training.

Returns:

Entries named Node_* contain binary training data, labels, marker names, descendant cell types, and cluster IDs. _root identifies the root cluster.

Return type:

dict

cytogater.predict_hierarchical_knn_recursive(spe, hier_ref, hc_tree, assay_name='exprs', threshold=0.7, agreement_threshold=0.8, k=5, repeats=5, dist_methods=('pearson', 'cosine'), BPPARAM=None, out_col='hier_label', chunk_size=1000, unassigned_label='Unassigned')#

Traverse node references using the R implementation’s kNN ensemble.

At every hierarchy node, each distance-method/repeat task draws 80% of the node reference without replacement. Predictions are made for all active cells in chunks, then sufficiently confident cells are routed to the left or right child. BPPARAM is accepted for API parity; Python currently executes the ensemble tasks serially.

Parameters:
  • spe (anndata.AnnData) – Cells to annotate; modified in place.

  • hier_ref (dict) – Node references from cytogater.build_hierarchical_reference().

  • hc_tree (dict) – Hierarchy from cytogater.build_lineage_hierarchy().

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • threshold (float, default=0.7) – Minimum mean winning probability at each node.

  • agreement_threshold (float, default=0.8) – Minimum ensemble vote agreement at each node.

  • k (int, default=5) – Number of neighbours per ensemble task.

  • repeats (int, default=5) – Subsampling repeats for each distance method.

  • dist_methods (str or sequence of str, default=("pearson", "cosine")) – kNN similarity/distance methods used by the ensemble.

  • BPPARAM (object or None, default=None) – Accepted for R API compatibility; currently ignored.

  • out_col (str, default="hier_label") – Destination column in spe.obs.

  • chunk_size (int, default=1000) – Number of active cells routed together.

  • unassigned_label (str, default="Unassigned") – Label for cells failing confidence or agreement thresholds.

Returns:

The annotated input object.

Return type:

anndata.AnnData

Metrics and uncertainty#

cytogater.calculate_f1(spe, ref_col='ref_broad', pred_col='pred_broad')#

Summarise annotation precision, recall, and F1 from AnnData labels.

Parameters:
  • spe (anndata.AnnData) – Annotated data object.

  • ref_col (str, default="ref_broad") – spe.obs column containing reference labels.

  • pred_col (str, default="pred_broad") – spe.obs column containing predicted labels.

Returns:

Per-class metrics excluding unassigned, undefined, and unknown labels.

Return type:

pandas.DataFrame

cytogater.calculate_uncertainty(prob_mat, spe, sample_col='sample_id', k_spatial=15)#

Calculate probability and spatial uncertainty for every cell.

Parameters:
  • prob_mat (pandas.DataFrame or array-like) – Cell-by-cell-type probabilities. Data-frame rows are aligned to spe.obs_names.

  • spe (anndata.AnnData) – Annotated object with coordinates in spe.obsm["spatial"].

  • sample_col (str, default="sample_id") – spe.obs column defining independent spatial samples.

  • k_spatial (int, default=15) – Nearest neighbours used for spatial label discordance.

Returns:

Entropy, Gini impurity, top-two probability margin uncertainty, and within-sample spatial discordance for each cell.

Return type:

pandas.DataFrame

Notes

Spatial discordance is missing for samples with at most k_spatial cells.

cytogater.calculate_spatial_prior_labels(spe, prob_mat, k_spatial=50, lambda_=0.2, protect_threshold=0.85, out_col='knn_spatial_label')#

Refine low-confidence predictions with a local spatial prior.

Parameters:
  • spe (anndata.AnnData) – Object with coordinates in spe.obsm["spatial"]; modified in place.

  • prob_mat (pandas.DataFrame or array-like) – Cell-by-cell-type probability matrix.

  • k_spatial (int, default=50) – Number of spatial neighbours used to estimate the local prior.

  • lambda_ – Exponent controlling the influence of the neighbour prior.

  • protect_threshold (float, default=0.85) – Predictions at or above this confidence are never changed.

  • out_col (str, default="knn_spatial_label") – Destination label column in spe.obs.

Returns:

The same object with spatially refined labels.

Return type:

anndata.AnnData

cytogater.class_metrics_from_fit(fit, test_truth=None, test_pred=None)#

Calculate per-class precision, recall, and F1 scores.

Parameters:
  • fit (dict) – Model result. If it contains cv_class_metrics, that table is returned directly; otherwise test_truth and test_pred may be read from it.

  • test_truth (array-like or None, default=None) – Optional true and predicted labels overriding values in fit.

  • test_pred (array-like or None, default=None) – Optional true and predicted labels overriding values in fit.

Returns:

One row per class with counts, support, precision, recall, and F1.

Return type:

pandas.DataFrame

Raises:

ValueError – If neither explicit labels nor labels in fit are available.

cytogater.label_agreement_rates(spe, label_col1, label_col2, drop_na=True)#

Calculate per-label intersection-over-union agreement.

Parameters:
  • spe (anndata.AnnData) – Annotated data object.

  • label_col1 (str) – Names of the two spe.obs label columns.

  • label_col2 (str) – Names of the two spe.obs label columns.

  • drop_na (bool, default=True) – Remove rows missing either label.

Returns:

Label, exact-match count, union count, and agreement rate.

Return type:

pandas.DataFrame

cytogater.label_confusion_matrix(spe, label_col1, label_col2, drop_na=True)#

Cross-tabulate two label columns using their combined label set.

Parameters:
  • spe (anndata.AnnData) – Annotated data object.

  • label_col1 (str) – Names of the two spe.obs label columns.

  • label_col2 (str) – Names of the two spe.obs label columns.

  • drop_na (bool, default=True) – Remove rows missing either label before tabulation.

Returns:

Square confusion/count matrix with identical row and column levels.

Return type:

pandas.DataFrame

cytogater.rf_metric_table(fit)#

Extract per-class classification metrics from a model result.

Parameters:

fit (dict) – Result containing cached cross-validation metrics or true/predicted test labels accepted by cytogater.class_metrics_from_fit().

Returns:

Mapping with a class data frame of precision, recall, and F1.

Return type:

dict

cytogater.rf_metric_text(fit, digits=3)#

Format random-forest class metrics as readable text lines.

Parameters:
  • fit (dict) – Model result accepted by rf_metric_table().

  • digits (int, default=3) – Decimal places used for metric values.

Returns:

One precision/recall/F1 summary per class.

Return type:

list of str

Visualisation#

cytogater.plot_celltype_tree(tree, title='', ax=None)#

Plot a top-down marker-priority gating tree.

Parameters:
  • tree (dict) – Root node returned by cytogater.build_fullcoverage_tree().

  • title (str, default="") – Plot title.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the tree diagram.

Return type:

matplotlib.axes.Axes

cytogater.plot_class_metrics(class_metrics, title='Per-class precision/recall/F1', subtitle=None, ax=None)#

Plot per-class precision, recall, and F1 as grouped bars.

Parameters:
  • class_metrics (pandas.DataFrame or mapping) – Table with class, precision, recall, and f1 columns.

  • title (str, default="Per-class precision/recall/F1") – Plot title.

  • subtitle (str or None, default=None) – Accepted for R API compatibility; currently unused.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the bar plot.

Return type:

matplotlib.axes.Axes

cytogater.plot_confusion_matrix(conf_mat, title='Confusion matrix', ax=None)#

Display a confusion/count matrix as a heatmap.

Parameters:
  • conf_mat (pandas.DataFrame or array-like) – Square count matrix. Data-frame labels are used as tick labels.

  • title (str, default="Confusion matrix") – Plot title.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the heatmap and colour bar.

Return type:

matplotlib.axes.Axes

cytogater.plot_ct_marker_intensity(spe, markers=None, label_col='cell_type_hard', assay_name='exprs', ax=None)#

Plot mean marker expression for each annotated cell type.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object.

  • markers (sequence of str or None, default=None) – Markers to display; None uses all markers.

  • label_col (str, default="cell_type_hard") – Cell-type column in spe.obs.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the cell-type-by-marker heatmap.

Return type:

matplotlib.axes.Axes

Notes

plot_pseudobulk_heatmap and plot_label_dotplot are aliases of this function in the current Python implementation.

cytogater.plot_label_agreement(agreement, ax=None)#

Plot per-label agreement rates.

Parameters:
  • agreement (pandas.DataFrame or mapping) – Table with label and agreement columns, such as the output of cytogater.label_agreement_rates().

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the agreement bars.

Return type:

matplotlib.axes.Axes

cytogater.plot_label_cardinality(label_mat, ax=None)#

Plot how many cutoff labels are positive for each cell.

Parameters:
  • label_mat (pandas.DataFrame or array-like) – Cell-by-cell-type boolean label matrix.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing counts by label cardinality.

Return type:

matplotlib.axes.Axes

cytogater.plot_label_confusion_matrix(spe, label_col1, label_col2, ax=None)#

Calculate and plot the confusion matrix between two label columns.

Parameters:
  • spe (anndata.AnnData) – Annotated data object.

  • label_col1 (str) – Label columns in spe.obs.

  • label_col2 (str) – Label columns in spe.obs.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the confusion heatmap.

Return type:

matplotlib.axes.Axes

cytogater.plot_label_counts(spe, label_col, ax=None)#

Plot the number of cells assigned to each label.

Parameters:
  • spe (anndata.AnnData) – Annotated data object.

  • label_col (str) – Label column in spe.obs.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the count bars.

Return type:

matplotlib.axes.Axes

cytogater.plot_label_dotplot(spe, markers=None, label_col='cell_type_hard', assay_name='exprs', ax=None)#

Plot mean marker expression for each annotated cell type.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object.

  • markers (sequence of str or None, default=None) – Markers to display; None uses all markers.

  • label_col (str, default="cell_type_hard") – Cell-type column in spe.obs.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the cell-type-by-marker heatmap.

Return type:

matplotlib.axes.Axes

Notes

plot_pseudobulk_heatmap and plot_label_dotplot are aliases of this function in the current Python implementation.

cytogater.plot_labelled_cells(spe, label_col, spatial_key='spatial', ax=None, title=None, **kwargs)#

Plot categorical cell labels in spatial coordinates.

Parameters:
  • spe (anndata.AnnData) – Object containing labels and spatial coordinates.

  • label_col (str) – Categorical label column in spe.obs.

  • spatial_key (str, default="spatial") – Key in spe.obsm containing x/y coordinates.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

  • title (str or None, default=None) – Plot title; defaults to label_col.

  • **kwargs – Additional arguments passed to Axes.scatter.

Returns:

Axes containing the spatial label plot.

Return type:

matplotlib.axes.Axes

cytogater.plot_marker_density(spe, marker, assay_name='exprs', label_col=None, ax=None)#

Plot the expression density of one marker.

Parameters:
  • spe (anndata.AnnData) – Cells-by-markers object.

  • marker (str) – Marker in spe.var_names.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • label_col (str or None, default=None) – Optional spe.obs column used to draw one density per label.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the density histogram(s).

Return type:

matplotlib.axes.Axes

cytogater.plot_marker_priority_tree(lineage_table, marker_stats, cell_type_name, ax=None)#

Plot positive-marker priority weights for one cell type.

Parameters:
  • lineage_table (pandas.DataFrame) – Cell-type marker table.

  • marker_stats (dict) – Per-marker statistics from cytogater.fit_marker_stats().

  • cell_type_name (str) – Cell type selected from lineage_table.cell_type.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing marker separation weights.

Return type:

matplotlib.axes.Axes

cytogater.plot_probability_map(spe, probability, title=None, spatial_key='spatial', ax=None, **kwargs)#

Plot a probability or continuous value in spatial coordinates.

Parameters:
  • spe (anndata.AnnData) – Object containing spatial coordinates.

  • probability (str or array-like) – spe.obs column name or one value per cell.

  • title (str or None, default=None) – Plot title; defaults to probability.

  • spatial_key (str, default="spatial") – Key in spe.obsm containing x/y coordinates.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on; a new figure is created when omitted.

  • **kwargs – Additional arguments passed to Axes.scatter.

Returns:

Axes containing the scatter plot and colour bar.

Return type:

matplotlib.axes.Axes

cytogater.plot_pseudobulk_heatmap(spe, markers=None, label_col='cell_type_hard', assay_name='exprs', ax=None)#

Plot mean marker expression for each annotated cell type.

Parameters:
  • spe (anndata.AnnData) – Annotated cells-by-markers object.

  • markers (sequence of str or None, default=None) – Markers to display; None uses all markers.

  • label_col (str, default="cell_type_hard") – Cell-type column in spe.obs.

  • assay_name (str or None, default="exprs") – Expression layer, or None/"X" for spe.X.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing the cell-type-by-marker heatmap.

Return type:

matplotlib.axes.Axes

Notes

plot_pseudobulk_heatmap and plot_label_dotplot are aliases of this function in the current Python implementation.

cytogater.plot_rand_cell_probs(spe=None, prob_mat=None, n=20, seed=None, ax=None)#

Plot stacked probabilities for a random subset of cells.

Parameters:
  • spe (anndata.AnnData or None, default=None) – Accepted for R API compatibility; currently unused.

  • prob_mat (pandas.DataFrame or array-like) – Cell-by-cell-type probability matrix.

  • n (int, default=20) – Maximum cells sampled for display.

  • seed (int or None, default=None) – Random seed used for sampling.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing stacked probability bars.

Return type:

matplotlib.axes.Axes

cytogater.plot_score_hist(res, ax=None)#

Plot distributions of cell-type probabilities from a gating result.

Parameters:
  • res (dict) – Result containing a prob_mat entry.

  • ax (matplotlib.axes.Axes or None, default=None) – Axes to draw on.

Returns:

Axes containing overlaid probability histograms.

Return type:

matplotlib.axes.Axes

cytogater.print_celltype_tree(node, indent='')#

Print a compact text representation of a gating tree.

Parameters:
Returns:

The tree is written to standard output.

Return type:

None

cytogater.tree_to_df(node, parent=None, id='root')#

Convert a gating tree to a labelled node table.

Parameters:
  • node (dict) – Root node returned by cytogater.build_fullcoverage_tree().

  • parent (str or None, default=None) – Parent identifier used internally during recursion.

  • id (str, default="root") – Identifier assigned to the current node.

Returns:

One row per node with its parent, label, split statistics, depth, and cell count.

Return type:

pandas.DataFrame