| Title: | Marker-Aware Cell Type Annotation for Protein Imaging Data |
|---|---|
| Description: | Provides marker-aware gating and classification methods for cell type annotation in spatial protein imaging data. The package constructs interpretable cell-type gating hierarchies, quantifies annotation uncertainty, and supports supervised prediction of cells that cannot be confidently gated. It operates on SummarizedExperiment and SpatialExperiment objects to support interoperable analysis of single-cell spatial proteomics data. |
| Authors: | Matthew Li [aut], Nikhil Karthik [aut], Harry Robertson [aut], Jean Yang [aut], Lijia Yu [aut, cre] |
| Maintainer: | Lijia Yu <[email protected]> |
| License: | GPL-2 |
| Version: | 0.99.1 |
| Built: | 2026-12-04 16:10:27 UTC |
| Source: | https://github.com/BiocStaging/cytoGateR |
Takes a 'res' object (as returned by 'run_soft_gating()' or 'run_tree_gating()'), builds a per-cell-type label matrix using a cutoff function, stores it as 'res$label_mat', and writes a single-label assignment into 'colData(res$spe)'.
apply_cutoff_labels( res, cutoff_fn = prob_quantile_cutoff, label_col = "cutoff_label", unknown_label = "Unknown" )apply_cutoff_labels( res, cutoff_fn = prob_quantile_cutoff, label_col = "cutoff_label", unknown_label = "Unknown" )
res |
List containing at least 'spe' and 'prob_mat'. |
cutoff_fn |
Function passed to [probability_label_matrix()] to compute per-column cutoffs (default [prob_quantile_cutoff()]). |
label_col |
Name of the column to add to 'colData(res$spe)' (default "cutoff_label"). |
unknown_label |
Label used when zero or multiple cell types pass their cutoff (default "Unknown"). |
A cell receives a label only if exactly one cell type passes its cutoff; if multiple (or zero) cell types pass, the cell is labeled 'unknown_label'.
The input 'res' list with updated 'spe' and a new 'label_mat' element.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) result <- apply_cutoff_labels( list(spe = spe, prob_mat = prob_mat), cutoff_fn = function(x) 0.5 ) table(SummarizedExperiment::colData(result$spe)$cutoff_label)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) result <- apply_cutoff_labels( list(spe = spe, prob_mat = prob_mat), cutoff_fn = function(x) 0.5 ) table(SummarizedExperiment::colData(result$spe)$cutoff_label)
Use a probability matrix and confidence flags to assign lineage labels; cells that are not confident receive 'unknown_label'.
assign_confident_labels(prob_mat, confidence_flags, unknown_label = "Unknown")assign_confident_labels(prob_mat, confidence_flags, unknown_label = "Unknown")
prob_mat |
Numeric matrix of probabilities (cells x lineages). |
confidence_flags |
Logical vector length 'nrow(prob_mat)'. |
unknown_label |
Character label for uncertain cells (default "Unknown"). |
Character vector of labels length 'nrow(prob_mat)'.
prob_mat <- rbind( cell1 = c(Bcell = 0.9, Tcell = 0.1), cell2 = c(Bcell = 0.5, Tcell = 0.5) ) assign_confident_labels(prob_mat, c(TRUE, FALSE))prob_mat <- rbind( cell1 = c(Bcell = 0.9, Tcell = 0.1), cell2 = c(Bcell = 0.5, Tcell = 0.5) ) assign_confident_labels(prob_mat, c(TRUE, FALSE))
Assign hard labels from probability matrix
assign_soft_labels(prob_mat, unknown_thresh = 0.4)assign_soft_labels(prob_mat, unknown_thresh = 0.4)
prob_mat |
Matrix [cells x types]. |
unknown_thresh |
If max prob < this, label as "Unknown" (default 0.4). |
Character vector of labels length nrow(prob_mat).
prob_mat <- rbind( cell1 = c(Bcell = 0.8, Tcell = 0.2), cell2 = c(Bcell = 0.3, Tcell = 0.35) ) assign_soft_labels(prob_mat, unknown_thresh = 0.4)prob_mat <- rbind( cell1 = c(Bcell = 0.8, Tcell = 0.2), cell2 = c(Bcell = 0.3, Tcell = 0.35) ) assign_soft_labels(prob_mat, unknown_thresh = 0.4)
Build full-coverage gating tree
build_fullcoverage_tree( expr_mat, markers_pos, markers_neg = character(0), cell_idx = seq_len(ncol(expr_mat)), depth = 0, max_depth = 4, min_cells = 200, min_score = 0.5, cutoff_method = c("mean", "equal_posteriors"), gmm_model_names = NULL )build_fullcoverage_tree( expr_mat, markers_pos, markers_neg = character(0), cell_idx = seq_len(ncol(expr_mat)), depth = 0, max_depth = 4, min_cells = 200, min_score = 0.5, cutoff_method = c("mean", "equal_posteriors"), gmm_model_names = NULL )
expr_mat |
expression matrix |
markers_pos |
positive markers |
markers_neg |
negative markers |
cell_idx |
indices |
depth |
depth |
max_depth |
max depth |
min_cells |
minimum cells |
min_score |
minimum separability |
cutoff_method |
Cutoff selection method passed to [fit_gmm_2()]. |
gmm_model_names |
Optional character vector of model names to pass to [mclust::Mclust()] (e.g., "V" to forbid equal-variance in 1D). |
tree object
set.seed(1) expr_mat <- rbind( CD3 = c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2)), CD20 = c(rnorm(50, 2, 0.2), rnorm(50, 0, 0.2)) ) tree <- build_fullcoverage_tree( expr_mat, markers_pos = c("CD3", "CD20"), max_depth = 2, min_cells = 20, min_score = 0.1 ) tree$typeset.seed(1) expr_mat <- rbind( CD3 = c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2)), CD20 = c(rnorm(50, 2, 0.2), rnorm(50, 0, 0.2)) ) tree <- build_fullcoverage_tree( expr_mat, markers_pos = c("CD3", "CD20"), max_depth = 2, min_cells = 20, min_score = 0.1 ) tree$type
Build Hierarchical Reference with Flexible Marker Selection
build_hierarchical_reference( spe, hc_tree, marker_stats = NULL, label_col = "cleaned_core_label", top_n = 5, assay_name = "exprs", unknown_label = "Unassigned" )build_hierarchical_reference( spe, hc_tree, marker_stats = NULL, label_col = "cleaned_core_label", top_n = 5, assay_name = "exprs", unknown_label = "Unassigned" )
spe |
SpatialExperiment containing core cells. |
hc_tree |
The hclust object from build_lineage_hierarchy. |
marker_stats |
Output from fit_marker_stats(). Required if top_n is not NULL. |
label_col |
Column with core labels (e.g., "cleaned_core_label"). |
top_n |
Number of top DE markers to use per node. Set to NULL to use all markers. |
assay_name |
Assay to use (default "exprs"). |
unknown_label |
Character label for unassigned cells (default "Unassigned"). |
A named list of node-specific references. Each element contains training data, binary left/right labels, selected markers, and the lineage members represented by each side of the node.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] SummarizedExperiment::colData(spe)$cleaned_core_label <- SummarizedExperiment::colData(spe)$core_group SummarizedExperiment::colData(spe)$cleaned_core_label[ SummarizedExperiment::colData(spe)$cleaned_core_label == "Unassigned" ] <- "Unknown" hc_tree <- build_lineage_hierarchy(spe) hier_ref <- build_hierarchical_reference( spe, hc_tree, top_n = NULL, unknown_label = "Unknown" ) names(hier_ref) hier_ref[[1L]]$markersdata("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] SummarizedExperiment::colData(spe)$cleaned_core_label <- SummarizedExperiment::colData(spe)$core_group SummarizedExperiment::colData(spe)$cleaned_core_label[ SummarizedExperiment::colData(spe)$cleaned_core_label == "Unassigned" ] <- "Unknown" hc_tree <- build_lineage_hierarchy(spe) hier_ref <- build_hierarchical_reference( spe, hc_tree, top_n = NULL, unknown_label = "Unknown" ) names(hier_ref) hier_ref[[1L]]$markers
Build Lineage Hierarchy from Core Cells
build_lineage_hierarchy( spe, label_col = "cleaned_core_label", assay_name = "exprs" )build_lineage_hierarchy( spe, label_col = "cleaned_core_label", assay_name = "exprs" )
spe |
A SpatialExperiment object with gated core labels. |
label_col |
The column containing gated labels (e.g., "cleaned_core_label"). |
assay_name |
Assay to use for pseudobulk calculation. |
An hclust object representing the cell type hierarchy.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] SummarizedExperiment::colData(spe)$cleaned_core_label <- SummarizedExperiment::colData(spe)$core_group SummarizedExperiment::colData(spe)$cleaned_core_label[ SummarizedExperiment::colData(spe)$cleaned_core_label == "Unassigned" ] <- "Unknown" hc_tree <- build_lineage_hierarchy(spe) hc_tree$labels plot(hc_tree)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] SummarizedExperiment::colData(spe)$cleaned_core_label <- SummarizedExperiment::colData(spe)$core_group SummarizedExperiment::colData(spe)$cleaned_core_label[ SummarizedExperiment::colData(spe)$cleaned_core_label == "Unassigned" ] <- "Unknown" hc_tree <- build_lineage_hierarchy(spe) hc_tree$labels plot(hc_tree)
Calculate F1 Score per Cell Type
calculate_f1(spe, ref_col = "ref_broad", pred_col = "pred_broad")calculate_f1(spe, ref_col = "ref_broad", pred_col = "pred_broad")
spe |
SpatialExperiment object |
ref_col |
Column name for ground truth (e.g., "manual_label") |
pred_col |
Column name for results (e.g., "hier_label") |
A data frame with Precision, Recall, and F1 score per type
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] calculate_f1(spe, ref_col = "cell_type", pred_col = "knn_label")data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] calculate_f1(spe, ref_col = "cell_type", pred_col = "knn_label")
Computes a probability matrix [cells x cell_types] by combining per-marker logistic scores weighted by separability, with optional negative-marker penalties.
calculate_soft_scores( spe, marker_stats, lineage_table, assay_name = "exprs", neg_strength = 0.8 )calculate_soft_scores( spe, marker_stats, lineage_table, assay_name = "exprs", neg_strength = 0.8 )
spe |
SpatialExperiment / SingleCellExperiment. |
marker_stats |
Output of fit_marker_stats(). |
lineage_table |
Tibble with columns: cell_type, pos_markers (list), neg_markers (list). |
assay_name |
Assay to use (default "exprs"). |
neg_strength |
Penalty strength multiplier for negative markers (default 0.8). |
Numeric matrix [ncol(spe) x n_types].
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] lineage_table <- data.frame( cell_type = c("Tcell", "Bcell"), pos_markers = I(list("CD3e", "CD20")), neg_markers = I(list("CD20", "CD3e")) ) marker_stats <- fit_marker_stats( spe, markers = c("CD3e", "CD20") ) prob_mat <- calculate_soft_scores(spe, marker_stats, lineage_table) head(prob_mat)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] lineage_table <- data.frame( cell_type = c("Tcell", "Bcell"), pos_markers = I(list("CD3e", "CD20")), neg_markers = I(list("CD20", "CD3e")) ) marker_stats <- fit_marker_stats( spe, markers = c("CD3e", "CD20") ) prob_mat <- calculate_soft_scores(spe, marker_stats, lineage_table) head(prob_mat)
Apply Protected Spatial Priors to kNN Probabilities
calculate_spatial_prior_labels( spe, prob_mat, k_spatial = 50, lambda = 0.2, protect_threshold = 0.85, out_col = "knn_spatial_label" )calculate_spatial_prior_labels( spe, prob_mat, k_spatial = 50, lambda = 0.2, protect_threshold = 0.85, out_col = "knn_spatial_label" )
spe |
SpatialExperiment object. |
prob_mat |
The full probability matrix [Cells x Types] from predict_unknown_with_knn. |
k_spatial |
Number of physical neighbors for the "Prior" (default 50). |
lambda |
The "Spatial Weight" (default 0.2). |
protect_threshold |
Confidence level above which spatial priors are ignored (default 0.85). |
out_col |
Column name for the new labels. |
The input 'SpatialExperiment' with the spatially adjusted labels stored in 'colData()' under 'out_col'.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) spe <- calculate_spatial_prior_labels( spe, prob_mat, k_spatial = 3, out_col = "spatial_label" ) table(SummarizedExperiment::colData(spe)$spatial_label)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) spe <- calculate_spatial_prior_labels( spe, prob_mat, k_spatial = 3, out_col = "spatial_label" ) table(SummarizedExperiment::colData(spe)$spatial_label)
Calculate Full Uncertainty Suite with Sample Grouping
calculate_uncertainty(prob_mat, spe, sample_col = "sample_id", k_spatial = 15)calculate_uncertainty(prob_mat, spe, sample_col = "sample_id", k_spatial = 15)
prob_mat |
The [Cells x Types] matrix from your kNN or randomforest |
spe |
The SpatialExperiment object. |
sample_col |
The column identifying different images/samples. |
k_spatial |
Neighbors for the spatial discordance check (default 15). from training) to rbind with prob_mat before processing. Both must share the same column names. |
A data frame with one row per cell and columns for normalized entropy, Gini impurity, margin uncertainty, and spatial discordance.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) uncertainty <- calculate_uncertainty( prob_mat, spe, sample_col = "sample_id", k_spatial = 3 ) head(uncertainty)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) uncertainty <- calculate_uncertainty( prob_mat, spe, sample_col = "sample_id", k_spatial = 3 ) head(uncertainty)
Prefers cross-validation class metrics when available; otherwise derives metrics from the provided truth and prediction vectors.
class_metrics_from_fit(fit, test_truth = NULL, test_pred = NULL)class_metrics_from_fit(fit, test_truth = NULL, test_pred = NULL)
fit |
List returned by [train_custom_rf()]. |
test_truth |
Optional truth vector (used only if CV metrics absent). |
test_pred |
Optional prediction vector (used only if CV metrics absent). |
Data frame with columns 'class', 'tp', 'fp', 'fn', 'support', 'precision', 'recall', 'f1', and optionally 'fold' when sourced from CV.
truth <- c("Bcell", "Bcell", "Tcell", "Tcell") pred <- c("Bcell", "Tcell", "Tcell", "Tcell") class_metrics_from_fit(list(), truth, pred)truth <- c("Bcell", "Bcell", "Tcell", "Tcell") pred <- c("Bcell", "Tcell", "Tcell", "Tcell") class_metrics_from_fit(list(), truth, pred)
Traverse a gating tree for a single cell and compute node-wise marker scores along the deterministic path defined by comparing marker expression to each node's cutoff.
collect_path_scores(tree, expr_mat, cell_i)collect_path_scores(tree, expr_mat, cell_i)
tree |
A gating tree as produced by [build_fullcoverage_tree()]. |
expr_mat |
Numeric matrix-like expression object with markers in rows and cells in columns (e.g. 'assay(spe, "norm")'). Row names must include marker names. |
cell_i |
Integer index of the cell/column to score. |
A numeric vector of per-node scores (may contain 'NA_real_' if a marker value is not finite for that cell).
tree <- list( type = "node", marker = "CD3", cutoff = 1, scale = 0.5, left = list(type = "leaf"), right = list(type = "leaf") ) expr_mat <- rbind(CD3 = c(0.5, 1.5)) collect_path_scores(tree, expr_mat, cell_i = 1)tree <- list( type = "node", marker = "CD3", cutoff = 1, scale = 0.5, left = list(type = "leaf"), right = list(type = "leaf") ) expr_mat <- rbind(CD3 = c(0.5, 1.5)) collect_path_scores(tree, expr_mat, cell_i = 1)
Compute per-cell confidence using a user-supplied decision function or a robust Tukey-style rule: a cell is considered confident if its maximum lineage probability exceeds 'max(base_thresh, quantile + iqr_mult * IQR)' for that cell.
compute_custom_labels( prob_mat, base_thresh = 0.4, quantile_cut = 0.75, iqr_mult = 1.5, flag_fn = NULL )compute_custom_labels( prob_mat, base_thresh = 0.4, quantile_cut = 0.75, iqr_mult = 1.5, flag_fn = NULL )
prob_mat |
Numeric matrix of probabilities (cells x lineages). |
base_thresh |
Minimum allowable threshold (default 0.4) used only for the default rule. |
quantile_cut |
Quantile used to set the adaptive threshold (default 0.75) for the default rule. |
iqr_mult |
Multiplier applied to the IQR (default 1.5) for the default rule. |
flag_fn |
Optional function taking a numeric vector of probabilities and returning a single logical value. Defaults to the Tukey-style rule above. |
Logical vector length 'nrow(prob_mat)' indicating confident cells.
prob_mat <- rbind( cell1 = c(Bcell = 0.9, Tcell = 0.1), cell2 = c(Bcell = 0.5, Tcell = 0.5) ) compute_custom_labels( prob_mat, flag_fn = function(x) max(x) >= 0.8 )prob_mat <- rbind( cell1 = c(Bcell = 0.9, Tcell = 0.1), cell2 = c(Bcell = 0.5, Tcell = 0.5) ) compute_custom_labels( prob_mat, flag_fn = function(x) max(x) >= 0.8 )
Applies the confidence-based labelling scheme to a probability matrix and stores the resulting labels in 'colData(spe)'.
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 = NULL )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 = NULL )
spe |
A 'SpatialExperiment' or 'SingleCellExperiment'. |
prob_mat |
Numeric probability matrix (cells x lineages). Rows must correspond to 'colnames(spe)'; if rownames are present they are checked. |
colname |
Name of the output column in 'colData' (default "custom_label"). |
base_thresh |
Minimum allowable threshold (default 0.4). |
quantile_cut |
Quantile used to set the adaptive threshold (default 0.75). |
iqr_mult |
Multiplier applied to the IQR (default 1.5). |
unknown_label |
Label assigned to uncertain cells (default "Unknown"). |
flag_fn |
Optional function taking a probability vector and returning a logical indicating confidence; defaults to the internal Tukey-style rule. |
The input 'spe' with a new 'colData' column containing custom labels.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) spe <- custom_labels( spe, prob_mat, flag_fn = function(x) max(x) >= 0.8 ) table(SummarizedExperiment::colData(spe)$custom_label)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] prob_cols <- grep( "^KNN_P_", names(SummarizedExperiment::colData(spe)), value = TRUE ) prob_mat <- as.matrix(SummarizedExperiment::colData(spe)[, prob_cols]) rownames(prob_mat) <- colnames(spe) colnames(prob_mat) <- sub("^KNN_P_", "", colnames(prob_mat)) spe <- custom_labels( spe, prob_mat, flag_fn = function(x) max(x) >= 0.8 ) table(SummarizedExperiment::colData(spe)$custom_label)
A small 'SpatialExperiment' containing selected samples for demonstrating cytoGateR visualization and annotation functions.
data(cytoGateR_example)data(cytoGateR_example)
A 'SpatialExperiment' with 40 markers and the selected cells. The object contains:
An '"exprs"' expression assay.
Sample identifiers, image names, reference labels, tree-gating labels and probabilities, high-confidence core labels, and weighted k-nearest-neighbour predictions, confidence values, and full 'KNN_P_*' class-probability columns.
Two-dimensional cell coordinates.
A subset of the IMMUcan 2022 Cancer Example dataset from the 'imcdatasets' package.
Fit a 2-component Gaussian mixture model
fit_gmm_2( x, cutoff_method = c("mean", "equal_posteriors"), gmm_model_names = NULL )fit_gmm_2( x, cutoff_method = c("mean", "equal_posteriors"), gmm_model_names = NULL )
x |
numeric vector |
cutoff_method |
Character. One of "mean" (midpoint of means) or "equal_posteriors" (threshold where component posteriors are equal). |
gmm_model_names |
Optional character vector of model names to pass to [mclust::Mclust()] (e.g., "V" to forbid equal-variance in 1D). |
list with GMM parameters or NULL
set.seed(1) x <- c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2)) fit <- fit_gmm_2(x) fit$cutoffset.seed(1) x <- c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2)) fit <- fit_gmm_2(x) fit$cutoff
Fits a 2-component Gaussian Mixture Model (GMM) per marker and returns a list of per-marker stats (cutoff, scale, weight, mu_high, valid).
fit_marker_stats(spe, markers, assay_name = "exprs", min_n = 50L)fit_marker_stats(spe, markers, assay_name = "exprs", min_n = 50L)
spe |
SpatialExperiment / SingleCellExperiment. |
markers |
Character vector of marker names. |
assay_name |
Assay to use (default "exprs"). |
min_n |
Minimum finite observations required to fit GMM (default 50). |
Named list. Each element is a list with fields: valid, cutoff, scale, weight, mu_high.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] marker_stats <- fit_marker_stats( spe, markers = c("CD3e", "CD20") ) marker_statsdata("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] marker_stats <- fit_marker_stats( spe, markers = c("CD3e", "CD20") ) marker_stats
Compute the cutoff where posteriors are equal
gmm_equal_posterior_cutoff(mu1, mu2, s1, s2, p1, p2)gmm_equal_posterior_cutoff(mu1, mu2, s1, s2, p1, p2)
mu1 |
Numeric mean of component 1. |
mu2 |
Numeric mean of component 2. |
s1 |
Numeric SD of component 1. |
s2 |
Numeric SD of component 2. |
p1 |
Numeric mixing weight of component 1. |
p2 |
Numeric mixing weight of component 2. |
Numeric cutoff. Defaults to midpoint if root finding fails.
Computes per-label agreement between two label columns in 'colData(spe)'. For each label (union of both columns), agreement is defined as the number of cells where both labels match that value divided by the number of cells where either column uses that value (Jaccard-style overlap).
label_agreement_rates(spe, label_col1, label_col2, drop_na = TRUE)label_agreement_rates(spe, label_col1, label_col2, drop_na = TRUE)
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_col1 |
First label column name. |
label_col2 |
Second label column name. |
drop_na |
Logical; if TRUE, rows with NA in either label are dropped. Default TRUE. |
A data frame with columns 'label', 'match_n', 'union_n', and 'agreement'.
data("cytoGateR_example", package = "cytoGateR") label_agreement_rates( cytoGateR_example, "cell_type_hard", "knn_label" )data("cytoGateR_example", package = "cytoGateR") label_agreement_rates( cytoGateR_example, "cell_type_hard", "knn_label" )
Builds a confusion matrix comparing two label columns in 'colData(spe)', with aligned levels so missing categories are represented.
label_confusion_matrix(spe, label_col1, label_col2, drop_na = TRUE)label_confusion_matrix(spe, label_col1, label_col2, drop_na = TRUE)
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_col1 |
First label column name. |
label_col2 |
Second label column name. |
drop_na |
Logical; if TRUE, rows with NA in either label are dropped. Default TRUE. |
A table with rows = 'label_col1' levels and columns = 'label_col2' levels.
data("cytoGateR_example", package = "cytoGateR") label_confusion_matrix( cytoGateR_example, "cell_type_hard", "knn_label" )data("cytoGateR_example", package = "cytoGateR") label_confusion_matrix( cytoGateR_example, "cell_type_hard", "knn_label" )
Marker separability
marker_separability(x)marker_separability(x)
x |
numeric |
numeric
set.seed(1) x <- c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2)) marker_separability(x)set.seed(1) x <- c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2)) marker_separability(x)
Compute a multiplicative penalty factor in the range [0, 1] for a given cell based on the expression of predefined negative markers.
neg_penalty( expr_mat, neg_markers, cell_i, marker_stats = NULL, neg_strength = 0.8 )neg_penalty( expr_mat, neg_markers, cell_i, marker_stats = NULL, neg_strength = 0.8 )
expr_mat |
A numeric matrix-like object containing expression values, with markers in rows and cells in columns. |
neg_markers |
A character vector of marker names to penalize. |
cell_i |
An integer index specifying the column (cell) to evaluate. |
marker_stats |
A named list containing per-marker statistics. Each element must include at least:
|
neg_strength |
A numeric scalar in [0, 1] controlling the strength of the penalty. Larger values increase the impact of negative-marker expression. |
For each negative marker, a logistic scoring function is used to estimate the probability ('p_bad') that the marker is expressed above its expected background level. The final penalty is computed as the product of (1 - p_bad * neg_strength) across all negative markers.
Higher negative-marker expression results in a stronger penalty (i.e., a smaller multiplicative factor).
If no valid negative markers are found in marker_stats, the function
returns 1 (no penalty).
A numeric scalar in the range [0, 1] representing the multiplicative penalty factor for the specified cell.
expr_mat <- rbind(CD3 = c(0.2, 2)) marker_stats <- list(CD3 = list(cutoff = 1, scale = 0.5)) neg_penalty( expr_mat, neg_markers = "CD3", cell_i = 1, marker_stats = marker_stats )expr_mat <- rbind(CD3 = c(0.2, 2)) marker_stats <- list(CD3 = list(cutoff = 1, scale = 0.5)) neg_penalty( expr_mat, neg_markers = "CD3", cell_i = 1, marker_stats = marker_stats )
Plot a cell-type gating tree
plot_celltype_tree(tree, title = "")plot_celltype_tree(tree, title = "")
tree |
A gating tree produced by [build_fullcoverage_tree()]. |
title |
Plot title string. |
A 'ggplot' object.
tree <- list( type = "node", depth = 0, cells = 1:6, marker = "CD3e", cutoff = 0.5, sep_score = 0.8, left = list(type = "leaf", depth = 1, cells = 1:3), right = list(type = "leaf", depth = 1, cells = 4:6) ) plot_celltype_tree(tree, title = "Example gating tree")tree <- list( type = "node", depth = 0, cells = 1:6, marker = "CD3e", cutoff = 0.5, sep_score = 0.8, left = list(type = "leaf", depth = 1, cells = 1:3), right = list(type = "leaf", depth = 1, cells = 4:6) ) plot_celltype_tree(tree, title = "Example gating tree")
Displays grouped bar plots for per-class precision, recall, and F1 with support annotations. If a 'fold' column is present (e.g., cross-validation results), draws boxplots per class and facets by metric.
plot_class_metrics( class_metrics, title = "Per-class precision/recall/F1", subtitle = NULL )plot_class_metrics( class_metrics, title = "Per-class precision/recall/F1", subtitle = NULL )
class_metrics |
Data frame with columns 'class', 'precision', 'recall', 'f1', optionally 'support', and optionally 'fold' for cross-validation. |
title |
Plot title. |
subtitle |
Optional subtitle for the plot. If 'NULL', an automatic |
A 'ggplot' object.
metrics <- data.frame( class = c("Tumor", "Stroma"), precision = c(0.90, 0.82), recall = c(0.85, 0.88), f1 = c(0.87, 0.85), support = c(60, 40) ) plot_class_metrics(metrics)metrics <- data.frame( class = c("Tumor", "Stroma"), precision = c(0.90, 0.82), recall = c(0.85, 0.88), f1 = c(0.87, 0.85), support = c(60, 40) ) plot_class_metrics(metrics)
Creates a heatmap with counts overlaid for a confusion matrix (table or matrix) of truth vs. predicted classes.
plot_confusion_matrix( conf_mat, title = "Confusion matrix", subtitle = NULL, cv_folds = NULL, aggregated = TRUE, fill_low = "#f0f9e8", fill_high = "#08589e", plot_marginals = TRUE )plot_confusion_matrix( conf_mat, title = "Confusion matrix", subtitle = NULL, cv_folds = NULL, aggregated = TRUE, fill_low = "#f0f9e8", fill_high = "#08589e", plot_marginals = TRUE )
conf_mat |
A confusion matrix as 'table', 'matrix', or data frame with columns 'truth', 'pred', and 'Freq'. |
title |
Plot title. |
subtitle |
Optional subtitle for the plot. If 'NULL', an automatic subtitle is generated (aggregation flag, CV folds if provided, and total 'n'). |
cv_folds |
Optional number of cross-validation folds to display in the subtitle. Use 'NULL' to omit. |
aggregated |
Logical. If 'TRUE', indicates the confusion matrix is summed/aggregated (used for subtitle text only). |
fill_low |
Low-end color for the fill gradient. |
fill_high |
High-end color for the fill gradient. |
plot_marginals |
Logical. If 'TRUE', add an extra "TOTAL" row/column showing marginal totals and the grand total. |
A 'ggplot' object.
conf <- matrix( c(18, 2, 3, 17), nrow = 2, dimnames = list(truth = c("A", "B"), predicted = c("A", "B")) ) plot_confusion_matrix(conf)conf <- matrix( c(18, 2, 3, 17), nrow = 2, dimnames = list(truth = c("A", "B"), predicted = c("A", "B")) ) plot_confusion_matrix(conf)
Visualizes a marker distribution, optionally with a two-component GMM fit and cutoff overlays. Useful for QC and comparing marker behavior across groups.
plot_ct_marker_intensity( spe, marker, subtitle, binwidth = NULL, label_col = NULL, cell_type = NULL, do_fit = TRUE, cutoff_method = "equal_posteriors", gmm_model_names = NULL, label_levels = NULL, label_colors = NULL, drop_levels = FALSE, assay_name = "exprs" )plot_ct_marker_intensity( spe, marker, subtitle, binwidth = NULL, label_col = NULL, cell_type = NULL, do_fit = TRUE, cutoff_method = "equal_posteriors", gmm_model_names = NULL, label_levels = NULL, label_colors = NULL, drop_levels = FALSE, assay_name = "exprs" )
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
marker |
Marker name to plot (must match a row in the assay). |
subtitle |
Subtitle for the plot. |
binwidth |
Histogram bin width. If NULL, uses range/100. |
label_col |
Optional column in 'colData(spe)' used to subset to a specific cell type and to color the histogram. |
cell_type |
Optional cell type value to subset when 'label_col' is set. |
do_fit |
Logical; fit a 2-component GMM and draw the components. |
cutoff_method |
Passed to [fit_gmm_2()]. |
gmm_model_names |
Passed to [fit_gmm_2()]. |
label_levels |
Optional character vector of label levels to enforce for legend consistency. |
label_colors |
Optional named or unnamed vector of colors to use for the label levels. If provided alongside 'label_levels', lengths must match. |
drop_levels |
Logical; if FALSE, keep unused levels in the legend. Default FALSE. |
assay_name |
Assay name to pull values from. Default "exprs". |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example[, seq_len(min(200L, ncol(cytoGateR_example)))] plot_ct_marker_intensity( spe, marker = rownames(spe)[1], subtitle = "Example cells", do_fit = FALSE )data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example[, seq_len(min(200L, ncol(cytoGateR_example)))] plot_ct_marker_intensity( spe, marker = rownames(spe)[1], subtitle = "Example cells", do_fit = FALSE )
Computes per-label agreement (Jaccard overlap) between two label columns in 'colData(spe)' and visualises it as a horizontal bar plot with class sizes.
plot_label_agreement( spe, label_col1, label_col2, drop_na = TRUE, title = "Label agreement", subtitle = "total matches / union" )plot_label_agreement( spe, label_col1, label_col2, drop_na = TRUE, title = "Label agreement", subtitle = "total matches / union" )
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_col1 |
First label column name. |
label_col2 |
Second label column name. |
drop_na |
Logical; drop rows with NA in either label. Default TRUE. |
title |
Plot title. |
subtitle |
Optional subtitle. |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_agreement(spe, "cell_type", "knn_label")data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_agreement(spe, "cell_type", "knn_label")
Given a logical/boolean label matrix (cells x cell types), counts how many labels are positive for each cell and plots the distribution from 0 up to the maximum observed positives.
plot_label_cardinality( label_mat, title = "Positive labels per cell", xlab = "Number of positive labels", ylab = "Cell count" )plot_label_cardinality( label_mat, title = "Positive labels per cell", xlab = "Number of positive labels", ylab = "Cell count" )
label_mat |
Logical or numeric matrix with cells in rows and cell types in columns. |
title |
Plot title. Default "Positive labels per cell". |
xlab |
X-axis label. Default "Number of positive labels". |
ylab |
Y-axis label. Default "Cell count". |
A 'ggplot' object showing counts per cardinality.
label_mat <- matrix( c(TRUE, FALSE, TRUE, TRUE, FALSE, FALSE), nrow = 3, dimnames = list(NULL, c("Tumor", "Stroma")) ) plot_label_cardinality(label_mat)label_mat <- matrix( c(TRUE, FALSE, TRUE, TRUE, FALSE, FALSE), nrow = 3, dimnames = list(NULL, c("Tumor", "Stroma")) ) plot_label_cardinality(label_mat)
Computes a confusion matrix for two label columns in 'colData(spe)' and visualises it with counts overlaid.
plot_label_confusion_matrix( spe, label_col1, label_col2, drop_na = TRUE, title = "Label confusion matrix", subtitle = NULL, fill_low = "#f0f9e8", fill_high = "#08589e", plot_marginals = FALSE )plot_label_confusion_matrix( spe, label_col1, label_col2, drop_na = TRUE, title = "Label confusion matrix", subtitle = NULL, fill_low = "#f0f9e8", fill_high = "#08589e", plot_marginals = FALSE )
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_col1 |
First label column name. |
label_col2 |
Second label column name. |
drop_na |
Logical; drop rows with NA in either label. Default TRUE. |
title |
Plot title. |
subtitle |
Optional subtitle; defaults to "label_col1 vs label_col2". |
fill_low |
Low-end color for the fill gradient. Default "#f0f9e8". |
fill_high |
High-end color for the fill gradient. Default "#08589e". |
plot_marginals |
Logical; if TRUE, plot marginal totals on the edges (right side and top) of the confusion matrix. Default FALSE. |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_confusion_matrix(spe, "cell_type", "knn_label")data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_confusion_matrix(spe, "cell_type", "knn_label")
Horizontal bar plot of label counts with count annotations. Useful for quickly checking class balance in 'colData()' label columns.
plot_label_counts( spe, label_col, title = "Label counts", subtitle = NULL, include_na = FALSE, show_legend = FALSE )plot_label_counts( spe, label_col, title = "Label counts", subtitle = NULL, include_na = FALSE, show_legend = FALSE )
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_col |
Column in 'colData(spe)' containing labels to count. |
title |
Plot title. |
subtitle |
Optional subtitle. If no value provided, 'label_col' is used. |
include_na |
Logical; if TRUE, include missing values as "NA" level. Default FALSE. |
show_legend |
Logical; show legend for bars. Default FALSE. |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_counts(spe, label_col = "knn_label")data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_counts(spe, label_col = "knn_label")
Creates a dotplot comparing cell type distributions across multiple label columns. The y-axis shows all unique cell types found across the specified label columns (excluding Unknown/NA), x-axis shows counts, and points are colored by which label column they came from.
plot_label_dotplot( spe, label_cols, title = "Label comparison", subtitle = NULL, drop_unknown = TRUE, drop_na = TRUE, point_size = 4, show_legend = TRUE )plot_label_dotplot( spe, label_cols, title = "Label comparison", subtitle = NULL, drop_unknown = TRUE, drop_na = TRUE, point_size = 4, show_legend = TRUE )
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_cols |
Character vector of column names in 'colData(spe)' to compare. Each column should contain cell type labels. |
title |
Plot title. |
subtitle |
Optional subtitle. |
drop_unknown |
Logical; if TRUE, exclude "Unknown" from cell types. Default TRUE. |
drop_na |
Logical; if TRUE, drop NA values. Default TRUE. |
point_size |
Size of points. Default 4. |
show_legend |
Logical; show legend. Default TRUE. |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_dotplot(spe, c("cell_type", "cell_type_hard", "knn_label"))data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_label_dotplot(spe, c("cell_type", "cell_type_hard", "knn_label"))
Takes cell labels and coordinates from a SpatialExperiment; can plot a single image or facet over multiple images with points colored by the provided label column.
plot_labelled_cells( spe, col_label, image_index = 1, image_col = "imageID", x_col = NULL, y_col = NULL, point_size = 0.8, label_levels = NULL, label_colors = NULL, drop_levels = FALSE, facet = TRUE )plot_labelled_cells( spe, col_label, image_index = 1, image_col = "imageID", x_col = NULL, y_col = NULL, point_size = 0.8, label_levels = NULL, label_colors = NULL, drop_levels = FALSE, facet = TRUE )
spe |
SpatialExperiment object. |
col_label |
Column in 'colData(spe)' containing cell labels to color by. |
image_index |
Index (or name) of the image(s) to view. Can be a single numeric, a numeric vector, or character vector of image IDs. Default 1. |
image_col |
Column in 'colData(spe)' containing image IDs. Default "imageID". |
x_col |
Optional x-coordinate column in 'colData(spe)'; auto-detected from 'spatialCoords(spe)' when available. |
y_col |
Optional y-coordinate column in 'colData(spe)'; auto-detected from 'spatialCoords(spe)' when available. |
point_size |
Point size. Default 0.8. |
label_levels |
Optional character vector of label levels to enforce for legend consistency. If provided, labels are coerced to a factor with these levels. |
label_colors |
Optional named or unnamed vector of colors to use for the label levels. If provided alongside 'label_levels', lengths must match. |
drop_levels |
Logical; if FALSE, keep unused levels in the legend. Default FALSE. |
facet |
Logical; if TRUE, facet over selected images. If FALSE, plot a single image (first selected). Default TRUE. |
'ggplot' object
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_labelled_cells( spe, col_label = "knn_label", image_col = "image_name", image_index = 1 )data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_labelled_cells( spe, col_label = "knn_label", image_col = "image_name", image_index = 1 )
Generates a density plot for a single marker using the specified assay, with curves colored by the image/sample column. Useful for quick QC of normalisation steps.
plot_marker_density( spe, marker, assay_name = "exprs", image_col = "image_name", title = NULL, show_legend = FALSE )plot_marker_density( spe, marker, assay_name = "exprs", image_col = "image_name", title = NULL, show_legend = FALSE )
spe |
A 'SpatialExperiment'/'SingleCellExperiment' with the target assay and metadata in 'colData()'. |
marker |
Marker name to plot (must match a row in the assay). |
assay_name |
Assay name to pull values from. Default "exprs". |
image_col |
Column in 'colData()' used to color densities. Default "image_name". |
title |
Optional plot title. Defaults to "Density of {marker} (assay: {assay_name})". |
show_legend |
Logical; whether to show the legend. Default 'FALSE'. |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_marker_density( spe, marker = rownames(spe)[1], image_col = "image_name" )data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_marker_density( spe, marker = rownames(spe)[1], image_col = "image_name" )
This is a simple visualization: markers ordered by weight and connected as a chain ROOT -> marker1 -> marker2 -> ...
plot_marker_priority_tree(lineage_table, marker_stats, cell_type_name)plot_marker_priority_tree(lineage_table, marker_stats, cell_type_name)
lineage_table |
Tibble with cell_type/pos_markers/neg_markers. |
marker_stats |
Output of fit_marker_stats(). |
cell_type_name |
Which cell type to plot. |
A ggraph/ggplot object (requires igraph + ggraph).
markers <- c("CD3e", "CD20") lineage <- data.frame( cell_type = "Immune", pos_markers = I(list(markers)), neg_markers = I(list(character())) ) marker_stats <- list( CD3e = list(weight = 0.9), CD20 = list(weight = 0.7) ) plot_marker_priority_tree(lineage, marker_stats, "Immune")markers <- c("CD3e", "CD20") lineage <- data.frame( cell_type = "Immune", pos_markers = I(list(markers)), neg_markers = I(list(character())) ) marker_stats <- list( CD3e = list(weight = 0.9), CD20 = list(weight = 0.7) ) plot_marker_priority_tree(lineage, marker_stats, "Immune")
Draws a spatial scatter plot colored by soft-gating probability for a given cell type (e.g., "T cell", "Tumor").
plot_probability_map( spe, cell_type, image_col = "imageID", image_index = NULL, x_col = NULL, y_col = NULL, point_size = 0.8 )plot_probability_map( spe, cell_type, image_col = "imageID", image_index = NULL, x_col = NULL, y_col = NULL, point_size = 0.8 )
spe |
SpatialExperiment / SingleCellExperiment with P_* columns in colData. |
cell_type |
Character. Must match the lineage_table$cell_type used in run_soft_gating(). |
image_col |
Column name for image ID (default "imageID"). |
image_index |
Numeric indices or character IDs of images to plot. Defaults to all images. If length > 1, results are faceted by image. |
x_col |
Coordinate column names (default auto-detect). |
y_col |
Coordinate column names (default auto-detect). |
point_size |
Size of points. |
A ggplot object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_probability_map( spe, cell_type = "Tumor", image_col = "image_name", image_index = 1 )data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_probability_map( spe, cell_type = "Tumor", image_col = "image_name", image_index = 1 )
Computes mean marker expression per label group and plots a heatmap restricted to relevant markers defined in a lineage table.
plot_pseudobulk_heatmap( spe, label_col, lineage_table = NULL, assay_name = "exprs", cell_types = NULL, marker_groups = c("pos_markers", "neg_markers"), include_all_markers = TRUE, drop_unknown = TRUE, drop_na = TRUE, cluster_rows = FALSE, cluster_cols = FALSE, show_values = TRUE, value_digits = 2, title = "Pseudobulk marker expression", scale = "none", row_order = NULL, col_order = NULL, highlight_lineage = TRUE, heatmap_palette = "RdYlBu", heatmap_direction = 1, text_size = 2.5 )plot_pseudobulk_heatmap( spe, label_col, lineage_table = NULL, assay_name = "exprs", cell_types = NULL, marker_groups = c("pos_markers", "neg_markers"), include_all_markers = TRUE, drop_unknown = TRUE, drop_na = TRUE, cluster_rows = FALSE, cluster_cols = FALSE, show_values = TRUE, value_digits = 2, title = "Pseudobulk marker expression", scale = "none", row_order = NULL, col_order = NULL, highlight_lineage = TRUE, heatmap_palette = "RdYlBu", heatmap_direction = 1, text_size = 2.5 )
spe |
A 'SpatialExperiment'/'SingleCellExperiment'. |
label_col |
Column in 'colData(spe)' containing labels. |
lineage_table |
Tibble with cell_type/pos_markers/neg_markers. |
assay_name |
Assay name to pull values from. Default "exprs". |
cell_types |
Optional character vector to restrict label groups. |
marker_groups |
Which marker sets to include from lineage_table. Default 'c("pos_markers", "neg_markers")'. |
include_all_markers |
Logical; if TRUE, use all assay markers rather than only lineage_table markers. Default TRUE. |
drop_unknown |
Logical; drop "Unknown" labels. Default TRUE. |
drop_na |
Logical; drop NA labels. Default TRUE. |
cluster_rows |
Logical; if TRUE, cluster markers (rows). Default FALSE. |
cluster_cols |
Logical; if TRUE, cluster labels (cols). Default FALSE. |
show_values |
Logical; draw mean values on tiles. Default TRUE. |
value_digits |
Digits for tile labels. Default 2. |
title |
Plot title. Default "Pseudobulk marker expression". |
scale |
Scaling for the heatmap. One of "none", "row", or "column". Default "none". |
row_order |
Optional character vector of marker names to enforce when 'cluster_rows = FALSE'. Any missing markers are ignored; any remaining markers not listed are appended in their existing order. |
col_order |
Optional character vector of label names to enforce when 'cluster_cols = FALSE'. Any missing labels are ignored; any remaining labels not listed are appended in their existing order. |
highlight_lineage |
Logical; draw outlines for lineage markers per cell type. Positive markers are green, negative markers are red. Default FALSE. |
heatmap_palette |
Palette name for the heatmap. Default "RdYlBu" for a blue-yellow-red diverging scale (pheatmap style). Set to a viridis option (e.g., "viridis", "magma") to use 'ggplot2::scale_fill_viridis_c()'. |
heatmap_direction |
Direction for viridis palettes. Default 1. |
text_size |
Numeric. Text size for numeric values drawn on heatmap tiles |
A 'ggplot' object.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example labels <- unique(as.character(SummarizedExperiment::colData(spe)$knn_label)) labels <- labels[!is.na(labels)][seq_len(min(2L, sum(!is.na(labels))))] markers <- rownames(spe)[seq_len(min(3L, nrow(spe)))] lineage <- data.frame( cell_type = labels, pos_markers = I(rep(list(markers), length(labels))), neg_markers = I(rep(list(character()), length(labels))) ) plot_pseudobulk_heatmap( spe, label_col = "knn_label", lineage_table = lineage, cell_types = labels, include_all_markers = FALSE, show_values = FALSE )data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example labels <- unique(as.character(SummarizedExperiment::colData(spe)$knn_label)) labels <- labels[!is.na(labels)][seq_len(min(2L, sum(!is.na(labels))))] markers <- rownames(spe)[seq_len(min(3L, nrow(spe)))] lineage <- data.frame( cell_type = labels, pos_markers = I(rep(list(markers), length(labels))), neg_markers = I(rep(list(character()), length(labels))) ) plot_pseudobulk_heatmap( spe, label_col = "knn_label", lineage_table = lineage, cell_types = labels, include_all_markers = FALSE, show_values = FALSE )
Plot the cell type probabilities of a random sample of cells
plot_rand_cell_probs( spe = NULL, image_index = 1, sample_size = 20, image_col = "image_name", flag_fn = NULL, base_thresh = 0.4, quantile_cut = 0.75, iqr_mult = 1.5, summary_fun = NULL )plot_rand_cell_probs( spe = NULL, image_index = 1, sample_size = 20, image_col = "image_name", flag_fn = NULL, base_thresh = 0.4, quantile_cut = 0.75, iqr_mult = 1.5, summary_fun = NULL )
spe |
A spatial experiment object returned by 'run_soft_gating()' or 'run_tree_gating()' containing cell type probabilities in 'colData()'. If omitted, tries 'res$spe' when available. |
image_index |
Index of the image from which to sample cells. Default 1. |
sample_size |
Number of cells to sample (capped at available cells). Default 20. |
image_col |
Column in 'colData' holding the image IDs. Default "image_name". |
flag_fn |
Optional function taking a numeric vector of probabilities for a cell and returning a single logical indicating confidence. Defaults to a Tukey-style rule matching [custom_labels()]. |
base_thresh |
Minimum threshold used by the default rule. Default 0.4. |
quantile_cut |
Quantile used by the default rule. Default 0.75. |
iqr_mult |
IQR multiplier for the default rule. Default 1.5. |
summary_fun |
Function that returns a single numeric summary value per group (e.g., median or upper whisker). The value is plotted as y/ymin/ymax in 'stat_summary'. Defaults to the same rule as the confidence flag (max(base_thresh, Q3 + iqr_mult * IQR)). |
a 'ggplot' object
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example set.seed(1) plot_rand_cell_probs(spe, sample_size = 10)data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example set.seed(1) plot_rand_cell_probs(spe, sample_size = 10)
Faceted histograms of per-cell probabilities for each cell type, using the probability columns already stored in 'colData(spe)' (e.g., 'P_T_cell', 'P_Tumor').
plot_score_hist( res, prob_prefix = "P_", binwidth = 0.01, drop_na = TRUE, cutoff_fn = prob_quantile_cutoff, label_col = NULL, label_levels = NULL, label_colors = NULL, drop_levels = FALSE )plot_score_hist( res, prob_prefix = "P_", binwidth = 0.01, drop_na = TRUE, cutoff_fn = prob_quantile_cutoff, label_col = NULL, label_levels = NULL, label_colors = NULL, drop_levels = FALSE )
res |
Result list containing an 'spe' element with probability columns. |
prob_prefix |
Prefix used for probability columns in 'colData(spe)'. Default "P_". |
binwidth |
Histogram bin width. Default 0.01. |
drop_na |
Logical; drop NA probabilities before plotting. Default TRUE. |
cutoff_fn |
Function taking a numeric vector of probabilities for a cell type and returning a single numeric cutoff to draw. Default [prob_quantile_cutoff()], which uses the 0.98 quantile. |
label_col |
Optional column in 'colData(spe)' used to color histograms by ground truth (or any label column). |
label_levels |
Optional character vector of label levels to enforce for legend consistency. |
label_colors |
Optional named or unnamed vector of colors to use for the label levels. If provided alongside 'label_levels', lengths must match. |
drop_levels |
Logical; if FALSE, keep unused levels in the legend. Default FALSE. |
A 'ggplot' object with faceted histograms.
data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_score_hist(list(spe = spe), binwidth = 0.1)data("cytoGateR_example", package = "cytoGateR") spe <- cytoGateR_example plot_score_hist(list(spe = spe), binwidth = 0.1)
Recursive Hierarchical kNN with BiocParallel Ensemble
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 = c("pearson", "cosine"), BPPARAM = BiocParallel::SerialParam(), out_col = "hier_label", chunk_size = 1000L, unassigned_label = "Unassigned" )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 = c("pearson", "cosine"), BPPARAM = BiocParallel::SerialParam(), out_col = "hier_label", chunk_size = 1000L, unassigned_label = "Unassigned" )
spe |
SpatialExperiment object. |
hier_ref |
List of node-specific references from build_hierarchical_reference. |
hc_tree |
hclust object defining the hierarchy. |
assay_name |
Assay to use (default "exprs"). |
threshold |
Confidence threshold (average kNN probability). |
agreement_threshold |
Minimum % of ensemble members that must agree (0-1). |
k |
Number of neighbors for kNN. |
repeats |
Number of bootstrap repeats per distance method. |
dist_methods |
Vector of methods, e.g., c("pearson", "cosine"). |
BPPARAM |
BiocParallel parameter (default: SerialParam()). |
out_col |
Column name for final labels. |
chunk_size |
Integer specifying the number of cells processed per chunk
during prediction. Increasing this value may improve speed but requires
more memory. Default is |
unassigned_label |
character label for Unassigned cells (default "Unassigned") |
The input spe with an added colData column named by
out_col (default "hier_label") holding the predicted
leaf label for each cell, or unassigned_label for cells that could
not be confidently assigned.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] SummarizedExperiment::colData(spe)$cleaned_core_label <- SummarizedExperiment::colData(spe)$core_group SummarizedExperiment::colData(spe)$cleaned_core_label[ SummarizedExperiment::colData(spe)$cleaned_core_label == "Unassigned" ] <- "Unknown" hc_tree <- build_lineage_hierarchy( spe, label_col = "cleaned_core_label" ) hier_ref <- build_hierarchical_reference( spe, hc_tree, label_col = "cleaned_core_label", top_n = NULL, unknown_label = "Unknown" ) spe <- predict_hierarchical_knn_recursive( spe, hier_ref, hc_tree, repeats = 1, dist_methods = "pearson", k = 3 ) head(SummarizedExperiment::colData(spe)$hier_label)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] SummarizedExperiment::colData(spe)$cleaned_core_label <- SummarizedExperiment::colData(spe)$core_group SummarizedExperiment::colData(spe)$cleaned_core_label[ SummarizedExperiment::colData(spe)$cleaned_core_label == "Unassigned" ] <- "Unknown" hc_tree <- build_lineage_hierarchy( spe, label_col = "cleaned_core_label" ) hier_ref <- build_hierarchical_reference( spe, hc_tree, label_col = "cleaned_core_label", top_n = NULL, unknown_label = "Unknown" ) spe <- predict_hierarchical_knn_recursive( spe, hier_ref, hc_tree, repeats = 1, dist_methods = "pearson", k = 3 ) head(SummarizedExperiment::colData(spe)$hier_label)
Drop-in deep-learning counterpart to
predict_unknown_with_randomforest. Applies a
"cytoGateR_dl" model (from train_custom_dl) to cells
currently labelled unknown_label (or NA) and fills in
predictions above threshold.
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" )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" )
spe |
A |
model |
A |
assay_name |
Character scalar naming the assay used as features (default |
label_col |
Column in |
out_col |
Column name to store the filled-in labels (default |
pred_col |
Column name to store raw predictions for the unknown subset (default |
unknown_label |
Character label treated as unlabeled (default |
threshold |
Minimum softmax probability required to accept a prediction (default |
unassigned_label |
Label assigned when the top probability is below |
A named list with spe (updated) and prob_mat (probability
matrix for the predicted-on cells only).
if (requireNamespace("torch", quietly = TRUE) && torch::torch_is_installed()) { data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] dl_fit <- train_custom_dl( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), hidden_dims = 8, epochs = 2, batch_size = 256, cv_folds = 2, repeats = 1, agreement_thresh = 0, patience = 1 ) dl_prediction <- predict_unknown_with_dl( dl_fit$spe, dl_fit$model, label_col = "cleaned_core_label", unknown_label = "Unassigned", threshold = 0.5 ) head(SummarizedExperiment::colData(dl_prediction$spe)$dl_pred) }if (requireNamespace("torch", quietly = TRUE) && torch::torch_is_installed()) { data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] dl_fit <- train_custom_dl( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), hidden_dims = 8, epochs = 2, batch_size = 256, cv_folds = 2, repeats = 1, agreement_thresh = 0, patience = 1 ) dl_prediction <- predict_unknown_with_dl( dl_fit$spe, dl_fit$model, label_col = "cleaned_core_label", unknown_label = "Unassigned", threshold = 0.5 ) head(SummarizedExperiment::colData(dl_prediction$spe)$dl_pred) }
This function takes a SpatialExperiment object and a trained kNN reference to predict labels for "Unknown" or NA cells. It returns the updated SPE and a probability matrix for the predicted cells only.
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 = 10000L )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 = 10000L )
spe |
A SpatialExperiment or SingleCellExperiment object. |
knn_ref |
A list containing the reference data, labels, and features (from train_custom_knn). |
assay_name |
Name of the assay to use for features (default "exprs"). |
label_col |
The original label column containing "Unknown" cells. |
out_col |
Output column name for filled labels. |
pred_col |
Column name for raw kNN predictions. |
unknown_label |
String identifying missing labels (default "Unknown"). |
unassigned_label |
Label for cells below the confidence threshold. |
threshold |
Minimum vote proportion (0-1) to accept a label (default 0.6). |
k |
Number of neighbors. |
dist_method |
Distance metric ("pearson", "cosine", etc.). |
chunk_size |
Number of cells to process per chunk for memory management. |
A list containing the updated spe and the prob_mat (unknowns only).
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] knn_ref <- train_custom_knn( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), cv_folds = 2, repeats = 1, agreement_thresh = 0.5, k = 3 ) prediction <- predict_unknown_with_knn( knn_ref$spe, knn_ref, label_col = "cleaned_core_label", unknown_label = "Unassigned", threshold = 0.5, k = 3 ) head(SummarizedExperiment::colData(prediction$spe)$knn_label_filled)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] knn_ref <- train_custom_knn( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), cv_folds = 2, repeats = 1, agreement_thresh = 0.5, k = 3 ) prediction <- predict_unknown_with_knn( knn_ref$spe, knn_ref, label_col = "cleaned_core_label", unknown_label = "Unassigned", threshold = 0.5, k = 3 ) head(SummarizedExperiment::colData(prediction$spe)$knn_label_filled)
Use a trained ranger classification model to predict cell-type labels
for all cells in a SpatialExperiment or SingleCellExperiment
object. Predicted labels are used to fill entries in label_col that
are either NA or equal to unknown_label.
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" )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" )
spe |
A |
model |
A fitted |
assay_name |
Character scalar specifying which assay to use as feature
input (default |
label_col |
Character scalar naming the existing label column in
|
out_col |
Character scalar naming the output column that will contain
the filled labels (default |
pred_col |
Character scalar naming the column used to store raw model
predictions (default |
unknown_label |
Character value treated as missing and eligible for
replacement (default |
threshold |
Numeric value in [0,1] specifying the minimum required
class probability for a prediction to be accepted (default |
unassigned_label |
Character label assigned to cells whose maximum
class probability is below |
If the model was trained with probability = TRUE, class probabilities
are used to compute a confidence score for each prediction. Predictions with
maximum class probability below threshold are reassigned to
unassigned_label. The maximum probability is stored for quality control.
Feature columns are automatically aligned to match the variables used during
model training. Only cells originally labeled as NA or
unknown_label are replaced in the output column.
The input spe object with updated colData columns:
pred_colRaw predicted labels from the random forest.
out_colFilled labels, replacing only NA or
unknown_label entries in label_col.
rf_confidenceMaximum predicted class probability per cell.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] fit <- train_custom_randomforest( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), num.trees = 25, cv_folds = 2, repeats = 1, agreement_thresh = 0, num_threads = 1 ) prediction <- predict_unknown_with_randomforest( fit$spe, fit$model, label_col = "cleaned_core_label", unknown_label = "Unassigned", threshold = 0.5 ) table(SummarizedExperiment::colData(prediction$spe)$soft_tree_label_filled)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] fit <- train_custom_randomforest( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), num.trees = 25, cv_folds = 2, repeats = 1, agreement_thresh = 0, num_threads = 1 ) prediction <- predict_unknown_with_randomforest( fit$spe, fit$model, label_col = "cleaned_core_label", unknown_label = "Unassigned", threshold = 0.5 ) table(SummarizedExperiment::colData(prediction$spe)$soft_tree_label_filled)
Multi-Metric Weighted kNN
predict_wknn_multi( train_data, test_data, train_labels, k = 5, method = "pearson", return_matrix = FALSE, chunk_size = 10000L )predict_wknn_multi( train_data, test_data, train_labels, k = 5, method = "pearson", return_matrix = FALSE, chunk_size = 10000L )
train_data |
Data frame or matrix of training cells (rows = markers, cols = cells). |
test_data |
Data frame or matrix of test cells (rows = markers, cols = cells). |
train_labels |
Factor of labels for the training data. |
k |
Number of neighbors. |
method |
One of "pearson", "spearman", "cosine", or "euclidean" |
return_matrix |
Logical indicating whether to return the full probability
matrix for all classes. If |
chunk_size |
Optional integer number of test cells per block. If
|
A list containing predicted 'labels' and 'probs'.
Print a cell-type gating tree
print_celltype_tree(node, indent = "")print_celltype_tree(node, indent = "")
node |
A gating tree (node or leaf) produced by [build_fullcoverage_tree()]. |
indent |
String used internally for indentation during recursive printing. |
Invisibly returns 'NULL'.
tree <- list( type = "node", depth = 0, cells = 1:6, marker = "CD3e", cutoff = 0.5, sep_score = 0.8, left = list(type = "leaf", depth = 1, cells = 1:3), right = list(type = "leaf", depth = 1, cells = 4:6) ) print_celltype_tree(tree)tree <- list( type = "node", depth = 0, cells = 1:6, marker = "CD3e", cutoff = 0.5, sep_score = 0.8, left = list(type = "leaf", depth = 1, cells = 1:3), right = list(type = "leaf", depth = 1, cells = 4:6) ) print_celltype_tree(tree)
Computes a cutoff as median(x) + 'mad_mult' * MAD(x).
prob_mad_cutoff(x, mad_mult = 3)prob_mad_cutoff(x, mad_mult = 3)
x |
Numeric vector of probabilities. |
mad_mult |
Multiplier on MAD (default 3). |
Numeric scalar cutoff.
prob_mad_cutoff(c(0.1, 0.1, 0.2, 0.9), mad_mult = 2)prob_mad_cutoff(c(0.1, 0.1, 0.2, 0.9), mad_mult = 2)
Computes a per-vector cutoff using the specified quantile.
prob_quantile_cutoff(x, prob = 0.98)prob_quantile_cutoff(x, prob = 0.98)
x |
Numeric vector of probabilities. |
prob |
Quantile to use (default 0.98). |
Numeric scalar cutoff.
prob_quantile_cutoff(c(0.1, 0.2, 0.8, 0.9), prob = 0.75)prob_quantile_cutoff(c(0.1, 0.2, 0.8, 0.9), prob = 0.75)
Applies a per-cell-type cutoff function to each probability column to build a logical matrix indicating which cell types pass their cutoff for each cell.
probability_label_matrix(prob_mat, cutoff_fn = prob_quantile_cutoff)probability_label_matrix(prob_mat, cutoff_fn = prob_quantile_cutoff)
prob_mat |
Numeric probability matrix (cells x cell types). |
cutoff_fn |
Function taking a numeric vector and returning a single numeric cutoff (default [prob_quantile_cutoff()]). |
Logical matrix with the same dimensions and dimnames as 'prob_mat'.
prob_mat <- rbind( cell1 = c(Bcell = 0.9, Tcell = 0.1), cell2 = c(Bcell = 0.2, Tcell = 0.8), cell3 = c(Bcell = 0.4, Tcell = 0.3) ) probability_label_matrix( prob_mat, cutoff_fn = function(x) 0.5 )prob_mat <- rbind( cell1 = c(Bcell = 0.9, Tcell = 0.1), cell2 = c(Bcell = 0.2, Tcell = 0.8), cell3 = c(Bcell = 0.4, Tcell = 0.3) ) probability_label_matrix( prob_mat, cutoff_fn = function(x) 0.5 )
Convenience helpers to expose overall metrics, cross-validation summaries, and per-class statistics in both tabular and text-friendly formats.
rf_metric_table(fit)rf_metric_table(fit)
fit |
List returned by [train_custom_rf()]. |
'rf_metric_table()' returns a list of tables: 'overall', 'cv_overall', 'cv_overall_summary', 'class', and 'class_raw'. 'rf_metric_text()' returns a character vector of summary lines.
fit <- list( metrics = list( accuracy = 0.75, f1_macro = 0.73, cv_overall = data.frame( accuracy = c(0.7, 0.8), f1_macro = c(0.68, 0.78) ) ), test_truth = c("Bcell", "Bcell", "Tcell", "Tcell"), test_pred = c("Bcell", "Tcell", "Tcell", "Tcell") ) rf_metric_table(fit)fit <- list( metrics = list( accuracy = 0.75, f1_macro = 0.73, cv_overall = data.frame( accuracy = c(0.7, 0.8), f1_macro = c(0.68, 0.78) ) ), test_truth = c("Bcell", "Bcell", "Tcell", "Tcell"), test_pred = c("Bcell", "Tcell", "Tcell", "Tcell") ) rf_metric_table(fit)
Formats key overall and cross-validation metrics from a fitted model returned by [train_custom_rf()] into a character vector of human-readable lines.
rf_metric_text(fit, digits = 3)rf_metric_text(fit, digits = 3)
fit |
List returned by [train_custom_rf()]. |
digits |
Number of digits when formatting numeric values (default 3). |
A character vector of summary lines.
fit <- list( metrics = list( accuracy = 0.75, f1_macro = 0.73, cv_overall = NULL ), test_truth = c("Bcell", "Bcell", "Tcell", "Tcell"), test_pred = c("Bcell", "Tcell", "Tcell", "Tcell") ) rf_metric_text(fit)fit <- list( metrics = list( accuracy = 0.75, f1_macro = 0.73, cv_overall = NULL ), test_truth = c("Bcell", "Bcell", "Tcell", "Tcell"), test_pred = c("Bcell", "Tcell", "Tcell", "Tcell") ) rf_metric_text(fit)
Run soft-gating pipeline end-to-end
run_soft_gating( spe, lineage_table, assay_name = "exprs", unknown_thresh = 0.4, store = TRUE )run_soft_gating( spe, lineage_table, assay_name = "exprs", unknown_thresh = 0.4, store = TRUE )
spe |
SpatialExperiment / SingleCellExperiment. |
lineage_table |
Tibble with cell_type/pos_markers/neg_markers. |
assay_name |
Assay to use (default "exprs"). |
unknown_thresh |
Threshold for Unknown label (default 0.4). |
store |
Store results back into spe (default TRUE). |
A list with: spe (if store=TRUE), marker_stats, prob_mat, labels.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] lineage_table <- data.frame( cell_type = c("Tcell", "Bcell"), pos_markers = I(list("CD3e", "CD20")), neg_markers = I(list("CD20", "CD3e")) ) soft_result <- run_soft_gating(spe, lineage_table) head(soft_result$labels)data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] lineage_table <- data.frame( cell_type = c("Tcell", "Bcell"), pos_markers = I(list("CD3e", "CD20")), neg_markers = I(list("CD20", "CD3e")) ) soft_result <- run_soft_gating(spe, lineage_table) head(soft_result$labels)
Build a marker-based, hierarchical soft-gating model for each lineage in a marker table, compute per-cell membership probabilities, and derive hard lineage/state labels.
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 = c("mean", "equal_posteriors"), gmm_model_names = NULL, BPPARAM = BiocParallel::SerialParam() )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 = c("mean", "equal_posteriors"), gmm_model_names = NULL, BPPARAM = BiocParallel::SerialParam() )
spe |
A |
lineage_table |
A |
assay_name |
Character scalar naming the assay in |
max_depth |
Integer; maximum recursion depth of each gating tree. |
min_cells |
Integer; minimum number of cells required to allow a node split. |
min_score |
Numeric; minimum separability score required to accept a split. |
uncert_thresh |
Numeric in [0,1]; cells whose best (non-proliferating)
lineage probability is below this threshold are labeled |
neg_strength |
Numeric in [0,1]; strength of the negative-marker penalty
applied within |
cutoff_method |
Cutoff selection method passed to |
gmm_model_names |
Optional character vector of model names to pass to
|
BPPARAM |
A |
For each cell_type in lineage_table, a gating tree is fit from
positive and (optionally) negative marker sets. Per-cell probabilities are
then computed by evaluating each fitted tree via tree_prob(), with an
optional negative-marker penalty controlled by neg_strength.
Hard labels are assigned as the lineage with the highest probability (excluding
"Proliferating"), unless the best probability is below
uncert_thresh, in which case the cell is labeled "Uncertain".
If a "Proliferating" lineage is present, cells with proliferating
probability and not "Uncertain" receive a "Prolif "
prefix in cell_type_state.
Marker statistics used for logistic scoring/penalization are precomputed once
across all markers appearing in lineage_table via fit_marker_stats().
Trees are built with build_fullcoverage_tree() and evaluated with
tree_prob().
A named list with components:
The input spe with added colData columns:
P_* (per-lineage probabilities), cell_type_hard,
cell_type_state, prob_best, and prob_prolif.
A named list of fitted gating trees, one per cell_type.
Numeric matrix of per-cell probabilities
(cells cell types).
Character vector of hard lineage labels after applying
uncert_thresh.
The cleaned marker table actually used to build the trees.
### This is a minimal example, for the full example, please see vignettes data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] lineage_table <- data.frame( cell_type = c("Tcell", "Bcell"), pos_markers = I(list("CD3e", "CD20")), neg_markers = I(list("CD20", "CD3e")) ) tree_result <- run_tree_gating( spe, lineage_table, max_depth = 1, min_cells = 100, min_score = 0.1, BPPARAM = BiocParallel::SerialParam() ) head(tree_result$hard_label)### This is a minimal example, for the full example, please see vignettes data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] lineage_table <- data.frame( cell_type = c("Tcell", "Bcell"), pos_markers = I(list("CD3e", "CD20")), neg_markers = I(list("CD20", "CD3e")) ) tree_result <- run_tree_gating( spe, lineage_table, max_depth = 1, min_cells = 100, min_score = 0.1, BPPARAM = BiocParallel::SerialParam() ) head(tree_result$hard_label)
Logistic marker score
score_marker_logistic(x, cutoff, scale)score_marker_logistic(x, cutoff, scale)
x |
numeric |
cutoff |
numeric |
scale |
numeric |
numeric in [0,1]
score_marker_logistic(c(0, 1, 2), cutoff = 1, scale = 0.5)score_marker_logistic(c(0, 1, 2), cutoff = 1, scale = 0.5)
Rank based marker score
score_marker_rank(x)score_marker_rank(x)
x |
numeric |
numeric in [0,1]
score_marker_rank(c(3, 1, 2, NA))score_marker_rank(c(3, 1, 2, NA))
Drop-in deep-learning counterpart to train_custom_randomforest.
Same two-stage workflow: repeated stratified cross-validation is used to
flag unreliable labels (consensus cleaning), then a final network is
trained on the cleaned labelled cells. Uses a small feedforward neural
network (via the torch package) instead of ranger.
train_custom_dl( spe, label_col = "cutoff_label", assay_name = "exprs", unknown_label = "Unknown", features = "all", hidden_dims = c(64, 32), dropout = 0.3, epochs = 50, lr = 0.001, weight_decay = 1e-04, 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 )train_custom_dl( spe, label_col = "cutoff_label", assay_name = "exprs", unknown_label = "Unknown", features = "all", hidden_dims = c(64, 32), dropout = 0.3, epochs = 50, lr = 0.001, weight_decay = 1e-04, 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 )
spe |
A |
label_col |
Character scalar naming the label column in
|
assay_name |
Character scalar naming the assay used as features
(default |
unknown_label |
Character label treated as unlabeled and excluded from
training/cleaning (default |
features |
Character vector of feature (marker) names to use, or
|
|
Integer vector of hidden layer sizes (default |
|
dropout |
Dropout probability applied after each hidden layer (default |
epochs |
Integer maximum training epochs per fold/final fit; actual
training usually stops earlier via early stopping (see |
lr |
Learning rate for Adam (default |
weight_decay |
L2 penalty for Adam (default |
batch_size |
Minibatch size (default |
cv_folds |
Integer number of folds used for stratified cross-validation
(default |
repeats |
Integer number of repeated CV rounds used during consensus
cleaning (default |
agreement_thresh |
Numeric in [0,1] specifying the minimum agreement rate
required to keep an originally labelled cell during cleaning (default |
val_frac |
Fraction of each training set held out (stratified by class)
as a validation split for best-epoch selection and early stopping (default |
patience |
Integer epochs to wait for validation-loss improvement before
stopping early; set to |
verbose_training |
Logical; if |
class_balanced_loss |
Logical; if |
A named list with components:
The input spe with an added colData column
cleaned_core_label, mirroring train_custom_randomforest.
An object of class "cytoGateR_dl" wrapping the trained
torch network together with the feature names, class levels, and
scaling stats needed to reproduce predictions.
Consensus probability matrix for the kept cells.
Named numeric vector of per-cell agreement rates.
Character vector of feature names used for training.
Per-epoch train/val loss for the *final* model fit (not the CV/cleaning folds), plus which epoch was selected as best.
if (requireNamespace("torch", quietly = TRUE) && torch::torch_is_installed()) { data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] dl_fit <- train_custom_dl( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), hidden_dims = 8, epochs = 2, batch_size = 256, cv_folds = 2, repeats = 1, agreement_thresh = 0, patience = 1 ) dl_fit$training_history }if (requireNamespace("torch", quietly = TRUE) && torch::torch_is_installed()) { data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] dl_fit <- train_custom_dl( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), hidden_dims = 8, epochs = 2, batch_size = 256, cv_folds = 2, repeats = 1, agreement_thresh = 0, patience = 1 ) dl_fit$training_history }
Trains a kNN-based cell type classifier using a consensus cleaning approach. Core cells are iteratively validated across repeated cross-validation folds, and cells with low label agreement are reassigned as unknown before a clean reference set is returned for downstream prediction.
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", chunk_size = 250L, BPPARAM = BiocParallel::SerialParam() )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", chunk_size = 250L, BPPARAM = BiocParallel::SerialParam() )
spe |
A |
label_col |
Character string specifying the column in |
assay_name |
Character string specifying the assay to use for marker
expression. Default is |
unknown_label |
Character string specifying the label used to identify
unknown or unclassified cells, which are excluded from training. Default is
|
features |
Either |
cv_folds |
Integer specifying the number of cross-validation folds used
during consensus cleaning. Default is |
repeats |
Integer specifying the number of cleaning repetitions. Higher
values produce more stable agreement rates. Default is |
agreement_thresh |
Numeric value between 0 and 1 specifying the minimum
proportion of repeats a cell must be correctly predicted to be retained in
the reference set. Default is |
k |
Integer specifying the number of nearest neighbours used in the
kNN classifier during consensus cleaning. Default is |
method |
Character string specifying the similarity or distance metric
used for kNN. Options include |
chunk_size |
Integer number of test cells processed per block inside
weighted kNN calls. Smaller values reduce peak RAM with identical
predictions at the cost of runtime. Default is |
BPPARAM |
A |
A named list containing:
speThe input SpatialExperiment object with a new
cleaned_core_label column added to colData.
reference_dataA data frame of marker expression for the high-confidence reference cells.
reference_labelsA factor of cell type labels corresponding
to reference_data.
features_usedCharacter vector of feature names used in training.
agreement_ratesNamed numeric vector of per-cell agreement rates from consensus cleaning.
cleaned_core_namesCharacter vector of cell names retained in the reference set after cleaning.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] knn_ref <- train_custom_knn( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), cv_folds = 2, repeats = 1, agreement_thresh = 0.5, k = 3 ) knn_ref$modeldata("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] knn_ref <- train_custom_knn( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), cv_folds = 2, repeats = 1, agreement_thresh = 0.5, k = 3 ) knn_ref$model
Train a ranger random forest classifier on labelled cells from a
SpatialExperiment or SingleCellExperiment. The workflow has two
stages:
Consensus cleaning: repeated stratified cross-validation is
used to estimate how consistently each labelled cell is predicted as its
original label. Cells with agreement below agreement_thresh are
flagged as unreliable and relabeled as unknown_label in
colData(spe)$cleaned_core_label.
Model evaluation and final training: cross-validation is run on the cleaned labelled set to report accuracy and macro-F1, and a final probability random forest model is trained on all cleaned labelled cells.
train_custom_randomforest( spe, label_col = "cutoff_label", assay_name = "exprs", unknown_label = "Unknown", num.trees = 200, mtry = NULL, features = "all", cv_folds = 5, repeats = 10, agreement_thresh = 0.8, num_threads = 2 )train_custom_randomforest( spe, label_col = "cutoff_label", assay_name = "exprs", unknown_label = "Unknown", num.trees = 200, mtry = NULL, features = "all", cv_folds = 5, repeats = 10, agreement_thresh = 0.8, num_threads = 2 )
spe |
A |
label_col |
Character scalar naming the label column in
|
assay_name |
Character scalar naming the assay used as features
(default |
unknown_label |
Character label treated as unlabeled and excluded from
training/cleaning (default |
num.trees |
Integer number of trees for the final |
mtry |
Optional integer |
features |
Character vector of feature (marker) names to use, or
|
cv_folds |
Integer number of folds used for stratified cross-validation
(default |
repeats |
Integer number of repeated CV rounds used during consensus
cleaning (default |
agreement_thresh |
Numeric in [0,1] specifying the minimum agreement rate
required to keep an originally labelled cell during cleaning (default
|
num_threads |
Integer requested number of threads for model fitting. |
During consensus cleaning, models are trained without probability estimation.
The final model is trained with probability = TRUE to support downstream
thresholding workflows.
A named list with components:
The input spe with an added colData column
cleaned_core_label, where low-agreement labelled cells are set to
unknown_label.
A fitted ranger model trained on the cleaned labelled
cells with probability = TRUE.
Named numeric vector of per-cell agreement rates from the consensus cleaning stage (indexed by training-row names).
Character vector of feature names used for training.
List of evaluation outputs on the cleaned labelled set:
Confusion matrix for pooled CV predictions.
Overall pooled CV accuracy.
Overall pooled macro-F1.
Per-fold data.frame with accuracy and macro-F1.
Per-fold, per-class precision/recall/F1 table.
Factor of pooled cross-validated predictions on cleaned labelled cells.
Factor of pooled cross-validated true labels on cleaned labelled cells.
data("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] fit <- train_custom_randomforest( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), num.trees = 25, cv_folds = 2, repeats = 1, agreement_thresh = 0, num_threads = 1 ) fit$modeldata("cytoGateR_example", package = "cytoGateR") image_ids <- SummarizedExperiment::colData(cytoGateR_example)$image_name spe <- cytoGateR_example[, image_ids == image_ids[1L]] fit <- train_custom_randomforest( spe, label_col = "core_group", unknown_label = "Unassigned", features = c("CD3e", "CD20", "CD4", "CD8a"), num.trees = 25, cv_folds = 2, repeats = 1, agreement_thresh = 0, num_threads = 1 ) fit$model
Compute the probability that a single cell belongs to a given cell type by combining per-node scores along a tree path, applying a complexity-based weight, and an optional negative marker penalty.
tree_prob( tree, expr_mat, cell_i, combine = c("mean", "product"), neg_markers = character(0), marker_stats = NULL, neg_strength = 0.8, lambda = 2 )tree_prob( tree, expr_mat, cell_i, combine = c("mean", "product"), neg_markers = character(0), marker_stats = NULL, neg_strength = 0.8, lambda = 2 )
tree |
A gating tree as produced by [build_fullcoverage_tree()]. |
expr_mat |
Numeric matrix-like expression object with markers in rows and cells in columns. |
cell_i |
Integer index of the cell/column to score. |
combine |
How to combine node-wise scores along the path. One of '"mean"' or '"product"'. |
neg_markers |
Character vector of negative marker names used for penalty. |
marker_stats |
A list of marker statistics (including cutoff and scale) produced by [fit_marker_stats()] used to calculate the penalty. |
neg_strength |
Numeric scalar in [0,1] defining how strongly negative marker expression should penalize the final score. Default is 0.8. |
lambda |
Numeric scalar representing the "Skepticism Factor." Higher values place a heavier penalty on cell types defined by fewer markers. Default is 0.2. |
Numeric scalar probability (typically in [0,1]) or 'NA_real_' if no usable node scores are available for the cell.
tree <- list( type = "node", marker = "CD3", cutoff = 1, scale = 0.5, left = list(type = "leaf"), right = list(type = "leaf") ) expr_mat <- rbind(CD3 = c(0.5, 1.5)) tree_prob(tree, expr_mat, cell_i = 2)tree <- list( type = "node", marker = "CD3", cutoff = 1, scale = 0.5, left = list(type = "leaf"), right = list(type = "leaf") ) expr_mat <- rbind(CD3 = c(0.5, 1.5)) tree_prob(tree, expr_mat, cell_i = 2)
Convert a tree to a tibble representation
tree_to_df(node, parent = NA_character_, id = "root")tree_to_df(node, parent = NA_character_, id = "root")
node |
A gating tree (node or leaf). |
parent |
Parent node id (used internally for recursion). |
id |
Node id for the current subtree (used internally for recursion). |
A tibble with columns 'id', 'parent', 'type', 'label'.
tree <- list( type = "node", depth = 0, cells = 1:6, marker = "CD3e", cutoff = 0.5, sep_score = 0.8, left = list(type = "leaf", depth = 1, cells = 1:3), right = list(type = "leaf", depth = 1, cells = 4:6) ) tree_to_df(tree)tree <- list( type = "node", depth = 0, cells = 1:6, marker = "CD3e", cutoff = 0.5, sep_score = 0.8, left = list(type = "leaf", depth = 1, cells = 1:3), right = list(type = "leaf", depth = 1, cells = 4:6) ) tree_to_df(tree)