Package 'cytoGateR'

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

Help Index


Apply cutoff-based labels to a result list

Description

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)'.

Usage

apply_cutoff_labels(
  res,
  cutoff_fn = prob_quantile_cutoff,
  label_col = "cutoff_label",
  unknown_label = "Unknown"
)

Arguments

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").

Details

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'.

Value

The input 'res' list with updated 'spe' and a new 'label_mat' element.

Examples

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)

Assign labels with uncertainty handling

Description

Use a probability matrix and confidence flags to assign lineage labels; cells that are not confident receive 'unknown_label'.

Usage

assign_confident_labels(prob_mat, confidence_flags, unknown_label = "Unknown")

Arguments

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").

Value

Character vector of labels length 'nrow(prob_mat)'.

Examples

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

Description

Assign hard labels from probability matrix

Usage

assign_soft_labels(prob_mat, unknown_thresh = 0.4)

Arguments

prob_mat

Matrix [cells x types].

unknown_thresh

If max prob < this, label as "Unknown" (default 0.4).

Value

Character vector of labels length nrow(prob_mat).

Examples

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

Description

Build full-coverage gating tree

Usage

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
)

Arguments

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).

Value

tree object

Examples

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$type

Build Hierarchical Reference with Flexible Marker Selection

Description

Build Hierarchical Reference with Flexible Marker Selection

Usage

build_hierarchical_reference(
  spe,
  hc_tree,
  marker_stats = NULL,
  label_col = "cleaned_core_label",
  top_n = 5,
  assay_name = "exprs",
  unknown_label = "Unassigned"
)

Arguments

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").

Value

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.

Examples

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]]$markers

Build Lineage Hierarchy from Core Cells

Description

Build Lineage Hierarchy from Core Cells

Usage

build_lineage_hierarchy(
  spe,
  label_col = "cleaned_core_label",
  assay_name = "exprs"
)

Arguments

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.

Value

An hclust object representing the cell type hierarchy.

Examples

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

Description

Calculate F1 Score per Cell Type

Usage

calculate_f1(spe, ref_col = "ref_broad", pred_col = "pred_broad")

Arguments

spe

SpatialExperiment object

ref_col

Column name for ground truth (e.g., "manual_label")

pred_col

Column name for results (e.g., "hier_label")

Value

A data frame with Precision, Recall, and F1 score per type

Examples

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")

Calculate soft gating probabilities per cell type

Description

Computes a probability matrix [cells x cell_types] by combining per-marker logistic scores weighted by separability, with optional negative-marker penalties.

Usage

calculate_soft_scores(
  spe,
  marker_stats,
  lineage_table,
  assay_name = "exprs",
  neg_strength = 0.8
)

Arguments

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).

Value

Numeric matrix [ncol(spe) x n_types].

Examples

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

Description

Apply Protected Spatial Priors to kNN Probabilities

Usage

calculate_spatial_prior_labels(
  spe,
  prob_mat,
  k_spatial = 50,
  lambda = 0.2,
  protect_threshold = 0.85,
  out_col = "knn_spatial_label"
)

Arguments

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.

Value

The input 'SpatialExperiment' with the spatially adjusted labels stored in 'colData()' under 'out_col'.

Examples

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

Description

Calculate Full Uncertainty Suite with Sample Grouping

Usage

calculate_uncertainty(prob_mat, spe, sample_col = "sample_id", k_spatial = 15)

Arguments

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.

Value

A data frame with one row per cell and columns for normalized entropy, Gini impurity, margin uncertainty, and spatial discordance.

Examples

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)

Derive per-class metrics from a fitted model

Description

Prefers cross-validation class metrics when available; otherwise derives metrics from the provided truth and prediction vectors.

Usage

class_metrics_from_fit(fit, test_truth = NULL, test_pred = NULL)

Arguments

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).

Value

Data frame with columns 'class', 'tp', 'fp', 'fn', 'support', 'precision', 'recall', 'f1', and optionally 'fold' when sourced from CV.

Examples

truth <- c("Bcell", "Bcell", "Tcell", "Tcell")
pred <- c("Bcell", "Tcell", "Tcell", "Tcell")
class_metrics_from_fit(list(), truth, pred)

Collect scores along a tree path

Description

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.

Usage

collect_path_scores(tree, expr_mat, cell_i)

Arguments

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.

Value

A numeric vector of per-node scores (may contain 'NA_real_' if a marker value is not finite for that cell).

Examples

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)

Flag confident cells from a probability matrix

Description

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.

Usage

compute_custom_labels(
  prob_mat,
  base_thresh = 0.4,
  quantile_cut = 0.75,
  iqr_mult = 1.5,
  flag_fn = NULL
)

Arguments

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.

Value

Logical vector length 'nrow(prob_mat)' indicating confident cells.

Examples

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
)

Add custom labels to a SpatialExperiment

Description

Applies the confidence-based labelling scheme to a probability matrix and stores the resulting labels in 'colData(spe)'.

Usage

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
)

Arguments

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.

Value

The input 'spe' with a new 'colData' column containing custom labels.

Examples

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)

Minimal spatial proteomics example

Description

A small 'SpatialExperiment' containing selected samples for demonstrating cytoGateR visualization and annotation functions.

Usage

data(cytoGateR_example)

Format

A 'SpatialExperiment' with 40 markers and the selected cells. The object contains:

assay

An '"exprs"' expression assay.

colData

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.

spatialCoords

Two-dimensional cell coordinates.

Source

A subset of the IMMUcan 2022 Cancer Example dataset from the 'imcdatasets' package.


Fit a 2-component Gaussian mixture model

Description

Fit a 2-component Gaussian mixture model

Usage

fit_gmm_2(
  x,
  cutoff_method = c("mean", "equal_posteriors"),
  gmm_model_names = NULL
)

Arguments

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).

Value

list with GMM parameters or NULL

Examples

set.seed(1)
x <- c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2))
fit <- fit_gmm_2(x)
fit$cutoff

Fit per-marker 2-GMM statistics for soft gating

Description

Fits a 2-component Gaussian Mixture Model (GMM) per marker and returns a list of per-marker stats (cutoff, scale, weight, mu_high, valid).

Usage

fit_marker_stats(spe, markers, assay_name = "exprs", min_n = 50L)

Arguments

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).

Value

Named list. Each element is a list with fields: valid, cutoff, scale, weight, mu_high.

Examples

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_stats

Compute the cutoff where posteriors are equal

Description

Compute the cutoff where posteriors are equal

Usage

gmm_equal_posterior_cutoff(mu1, mu2, s1, s2, p1, p2)

Arguments

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.

Value

Numeric cutoff. Defaults to midpoint if root finding fails.


Agreement rates between two label columns

Description

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).

Usage

label_agreement_rates(spe, label_col1, label_col2, drop_na = TRUE)

Arguments

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.

Value

A data frame with columns 'label', 'match_n', 'union_n', and 'agreement'.

Examples

data("cytoGateR_example", package = "cytoGateR")
label_agreement_rates(
  cytoGateR_example,
  "cell_type_hard",
  "knn_label"
)

Confusion matrix between two label columns

Description

Builds a confusion matrix comparing two label columns in 'colData(spe)', with aligned levels so missing categories are represented.

Usage

label_confusion_matrix(spe, label_col1, label_col2, drop_na = TRUE)

Arguments

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.

Value

A table with rows = 'label_col1' levels and columns = 'label_col2' levels.

Examples

data("cytoGateR_example", package = "cytoGateR")
label_confusion_matrix(
  cytoGateR_example,
  "cell_type_hard",
  "knn_label"
)

Marker separability

Description

Marker separability

Usage

marker_separability(x)

Arguments

x

numeric

Value

numeric

Examples

set.seed(1)
x <- c(rnorm(50, 0, 0.2), rnorm(50, 2, 0.2))
marker_separability(x)

Negative marker penalty

Description

Compute a multiplicative penalty factor in the range [0, 1] for a given cell based on the expression of predefined negative markers.

Usage

neg_penalty(
  expr_mat,
  neg_markers,
  cell_i,
  marker_stats = NULL,
  neg_strength = 0.8
)

Arguments

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:

cutoff

Numeric value representing the logistic midpoint.

scale

Numeric value controlling the logistic slope.

neg_strength

A numeric scalar in [0, 1] controlling the strength of the penalty. Larger values increase the impact of negative-marker expression.

Details

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).

Value

A numeric scalar in the range [0, 1] representing the multiplicative penalty factor for the specified cell.

Examples

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

Description

Plot a cell-type gating tree

Usage

plot_celltype_tree(tree, title = "")

Arguments

tree

A gating tree produced by [build_fullcoverage_tree()].

title

Plot title string.

Value

A 'ggplot' object.

Examples

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")

Plot per-class precision, recall, and F1

Description

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.

Usage

plot_class_metrics(
  class_metrics,
  title = "Per-class precision/recall/F1",
  subtitle = NULL
)

Arguments

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

Value

A 'ggplot' object.

Examples

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)

Plot a confusion matrix heatmap

Description

Creates a heatmap with counts overlaid for a confusion matrix (table or matrix) of truth vs. predicted classes.

Usage

plot_confusion_matrix(
  conf_mat,
  title = "Confusion matrix",
  subtitle = NULL,
  cv_folds = NULL,
  aggregated = TRUE,
  fill_low = "#f0f9e8",
  fill_high = "#08589e",
  plot_marginals = TRUE
)

Arguments

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.

Value

A 'ggplot' object.

Examples

conf <- matrix(
  c(18, 2, 3, 17),
  nrow = 2,
  dimnames = list(truth = c("A", "B"), predicted = c("A", "B"))
)
plot_confusion_matrix(conf)

Plot marker intensity with optional GMM fit

Description

Visualizes a marker distribution, optionally with a two-component GMM fit and cutoff overlays. Useful for QC and comparing marker behavior across groups.

Usage

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"
)

Arguments

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".

Value

A 'ggplot' object.

Examples

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
)

Plot agreement between two label columns

Description

Computes per-label agreement (Jaccard overlap) between two label columns in 'colData(spe)' and visualises it as a horizontal bar plot with class sizes.

Usage

plot_label_agreement(
  spe,
  label_col1,
  label_col2,
  drop_na = TRUE,
  title = "Label agreement",
  subtitle = "total matches / union"
)

Arguments

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.

Value

A 'ggplot' object.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_label_agreement(spe, "cell_type", "knn_label")

Barplot of positive label counts per cell

Description

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.

Usage

plot_label_cardinality(
  label_mat,
  title = "Positive labels per cell",
  xlab = "Number of positive labels",
  ylab = "Cell count"
)

Arguments

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".

Value

A 'ggplot' object showing counts per cardinality.

Examples

label_mat <- matrix(
  c(TRUE, FALSE, TRUE, TRUE, FALSE, FALSE),
  nrow = 3,
  dimnames = list(NULL, c("Tumor", "Stroma"))
)
plot_label_cardinality(label_mat)

Plot confusion matrix between two label columns

Description

Computes a confusion matrix for two label columns in 'colData(spe)' and visualises it with counts overlaid.

Usage

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
)

Arguments

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.

Value

A 'ggplot' object.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_label_confusion_matrix(spe, "cell_type", "knn_label")

Plot counts of a label column

Description

Horizontal bar plot of label counts with count annotations. Useful for quickly checking class balance in 'colData()' label columns.

Usage

plot_label_counts(
  spe,
  label_col,
  title = "Label counts",
  subtitle = NULL,
  include_na = FALSE,
  show_legend = FALSE
)

Arguments

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.

Value

A 'ggplot' object.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_label_counts(spe, label_col = "knn_label")

Plot label comparison dotplot

Description

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.

Usage

plot_label_dotplot(
  spe,
  label_cols,
  title = "Label comparison",
  subtitle = NULL,
  drop_unknown = TRUE,
  drop_na = TRUE,
  point_size = 4,
  show_legend = TRUE
)

Arguments

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.

Value

A 'ggplot' object.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_label_dotplot(spe, c("cell_type", "cell_type_hard", "knn_label"))

Plots the spatial arrangement of classified cells

Description

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.

Usage

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
)

Arguments

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.

Value

'ggplot' object

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_labelled_cells(
  spe,
  col_label = "knn_label",
  image_col = "image_name",
  image_index = 1
)

Plot marker density across images

Description

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.

Usage

plot_marker_density(
  spe,
  marker,
  assay_name = "exprs",
  image_col = "image_name",
  title = NULL,
  show_legend = FALSE
)

Arguments

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'.

Value

A 'ggplot' object.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_marker_density(
  spe,
  marker = rownames(spe)[1],
  image_col = "image_name"
)

Plot a marker priority "tree" for a given cell type (weights order)

Description

This is a simple visualization: markers ordered by weight and connected as a chain ROOT -> marker1 -> marker2 -> ...

Usage

plot_marker_priority_tree(lineage_table, marker_stats, cell_type_name)

Arguments

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.

Value

A ggraph/ggplot object (requires igraph + ggraph).

Examples

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")

Plot spatial probability map for a cell type

Description

Draws a spatial scatter plot colored by soft-gating probability for a given cell type (e.g., "T cell", "Tumor").

Usage

plot_probability_map(
  spe,
  cell_type,
  image_col = "imageID",
  image_index = NULL,
  x_col = NULL,
  y_col = NULL,
  point_size = 0.8
)

Arguments

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.

Value

A ggplot object.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_probability_map(
  spe,
  cell_type = "Tumor",
  image_col = "image_name",
  image_index = 1
)

Plot pseudobulk marker heatmap

Description

Computes mean marker expression per label group and plots a heatmap restricted to relevant markers defined in a lineage table.

Usage

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
)

Arguments

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

Value

A 'ggplot' object.

Examples

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

Description

Plot the cell type probabilities of a random sample of cells

Usage

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
)

Arguments

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)).

Value

a 'ggplot' object

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
set.seed(1)
plot_rand_cell_probs(spe, sample_size = 10)

Plot cell-type probability histograms

Description

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').

Usage

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
)

Arguments

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.

Value

A 'ggplot' object with faceted histograms.

Examples

data("cytoGateR_example", package = "cytoGateR")
spe <- cytoGateR_example
plot_score_hist(list(spe = spe), binwidth = 0.1)

Recursive Hierarchical kNN with BiocParallel Ensemble

Description

Recursive Hierarchical kNN with BiocParallel Ensemble

Usage

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"
)

Arguments

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 1000L

unassigned_label

character label for Unassigned cells (default "Unassigned")

Value

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.

Examples

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)

Predict unknown cells using a trained deep-learning model

Description

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.

Usage

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"
)

Arguments

spe

A SpatialExperiment or SingleCellExperiment.

model

A "cytoGateR_dl" object, as returned by train_custom_dl()$model.

assay_name

Character scalar naming the assay used as features (default "exprs").

label_col

Column in colData(spe) identifying which cells are unknown (default "custom_label").

out_col

Column name to store the filled-in labels (default "soft_tree_label_filled").

pred_col

Column name to store raw predictions for the unknown subset (default "dl_pred").

unknown_label

Character label treated as unlabeled (default "Unknown").

threshold

Minimum softmax probability required to accept a prediction (default 0.5).

unassigned_label

Label assigned when the top probability is below threshold (default "Unassigned").

Value

A named list with spe (updated) and prob_mat (probability matrix for the predicted-on cells only).

Examples

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)
}

Predict and fill unknown labels using a weighted kNN model

Description

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.

Usage

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
)

Arguments

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.

Value

A list containing the updated spe and the prob_mat (unknowns only).

Examples

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)

Predict and fill unknown labels using a trained random forest model

Description

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.

Usage

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"
)

Arguments

spe

A SpatialExperiment or SingleCellExperiment object.

model

A fitted ranger model returned by train_custom_rf(). The model should be trained with probability = TRUE to enable threshold-based filtering.

assay_name

Character scalar specifying which assay to use as feature input (default "exprs").

label_col

Character scalar naming the existing label column in colData(spe) (default "custom_label").

out_col

Character scalar naming the output column that will contain the filled labels (default "soft_tree_label_filled").

pred_col

Character scalar naming the column used to store raw model predictions (default "rf_pred").

unknown_label

Character value treated as missing and eligible for replacement (default "Unknown").

threshold

Numeric value in [0,1] specifying the minimum required class probability for a prediction to be accepted (default 0.5). Ignored if the model was not trained with probability = TRUE.

unassigned_label

Character label assigned to cells whose maximum class probability is below threshold (default "Unassigned").

Details

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.

Value

The input spe object with updated colData columns:

pred_col

Raw predicted labels from the random forest.

out_col

Filled labels, replacing only NA or unknown_label entries in label_col.

rf_confidence

Maximum predicted class probability per cell.

Examples

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

Description

Multi-Metric Weighted kNN

Usage

predict_wknn_multi(
  train_data,
  test_data,
  train_labels,
  k = 5,
  method = "pearson",
  return_matrix = FALSE,
  chunk_size = 10000L
)

Arguments

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 FALSE, only the predicted labels and associated probabilities are returned. Default is FALSE.

chunk_size

Optional integer number of test cells per block. If NULL, all test cells are processed in a single block (legacy behavior).

Value

A list containing predicted 'labels' and 'probs'.


Median + MAD cutoff helper

Description

Computes a cutoff as median(x) + 'mad_mult' * MAD(x).

Usage

prob_mad_cutoff(x, mad_mult = 3)

Arguments

x

Numeric vector of probabilities.

mad_mult

Multiplier on MAD (default 3).

Value

Numeric scalar cutoff.

Examples

prob_mad_cutoff(c(0.1, 0.1, 0.2, 0.9), mad_mult = 2)

Default quantile-based cutoff

Description

Computes a per-vector cutoff using the specified quantile.

Usage

prob_quantile_cutoff(x, prob = 0.98)

Arguments

x

Numeric vector of probabilities.

prob

Quantile to use (default 0.98).

Value

Numeric scalar cutoff.

Examples

prob_quantile_cutoff(c(0.1, 0.2, 0.8, 0.9), prob = 0.75)

Build a binary label matrix from probabilities

Description

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.

Usage

probability_label_matrix(prob_mat, cutoff_fn = prob_quantile_cutoff)

Arguments

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()]).

Value

Logical matrix with the same dimensions and dimnames as 'prob_mat'.

Examples

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
)

Tabular and text summaries of RF performance

Description

Convenience helpers to expose overall metrics, cross-validation summaries, and per-class statistics in both tabular and text-friendly formats.

Usage

rf_metric_table(fit)

Arguments

fit

List returned by [train_custom_rf()].

Value

'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.

Examples

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)

Text summary of random forest performance

Description

Formats key overall and cross-validation metrics from a fitted model returned by [train_custom_rf()] into a character vector of human-readable lines.

Usage

rf_metric_text(fit, digits = 3)

Arguments

fit

List returned by [train_custom_rf()].

digits

Number of digits when formatting numeric values (default 3).

Value

A character vector of summary lines.

Examples

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

Description

Run soft-gating pipeline end-to-end

Usage

run_soft_gating(
  spe,
  lineage_table,
  assay_name = "exprs",
  unknown_thresh = 0.4,
  store = TRUE
)

Arguments

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).

Value

A list with: spe (if store=TRUE), marker_stats, prob_mat, labels.

Examples

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)

Run tree-based soft gating on a SpatialExperiment

Description

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.

Usage

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()
)

Arguments

spe

A SpatialExperiment or SingleCellExperiment containing per-cell marker expression.

lineage_table

A data.frame/tibble with at least the columns cell_type, pos_markers, and neg_markers. Marker columns must be list-columns of character vectors. Markers not present in spe are dropped during cleaning.

assay_name

Character scalar naming the assay in spe used as the expression matrix (default "exprs").

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 "Uncertain".

neg_strength

Numeric in [0,1]; strength of the negative-marker penalty applied within tree_prob() (default 0.4). Larger values increase the penalty from negative-marker expression.

cutoff_method

Cutoff selection method passed to fit_gmm_2(). One of "mean" or "equal_posteriors".

gmm_model_names

Optional character vector of model names to pass to mclust::Mclust() for 1D GMM fitting (e.g., "V", "E"). Use NULL (default) to allow selection by BIC.

BPPARAM

A BiocParallelParam object controlling parallel tree building, one tree per cell type (default BiocParallel::SerialParam()). Use, for example, BiocParallel::MulticoreParam(4) or BiocParallel::SnowParam(4) to build trees in parallel.

Details

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 ≥0.5\ge 0.5 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().

Value

A named list with components:

spe

The input spe with added colData columns: P_* (per-lineage probabilities), cell_type_hard, cell_type_state, prob_best, and prob_prolif.

trees

A named list of fitted gating trees, one per cell_type.

prob_mat

Numeric matrix of per-cell probabilities (cells ×\times cell types).

hard_label

Character vector of hard lineage labels after applying uncert_thresh.

lineage_table

The cleaned marker table actually used to build the trees.

Examples

### 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

Description

Logistic marker score

Usage

score_marker_logistic(x, cutoff, scale)

Arguments

x

numeric

cutoff

numeric

scale

numeric

Value

numeric in [0,1]

Examples

score_marker_logistic(c(0, 1, 2), cutoff = 1, scale = 0.5)

Rank based marker score

Description

Rank based marker score

Usage

score_marker_rank(x)

Arguments

x

numeric

Value

numeric in [0,1]

Examples

score_marker_rank(c(3, 1, 2, NA))

Train a custom deep-learning classifier with consensus label cleaning

Description

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.

Usage

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
)

Arguments

spe

A SpatialExperiment or SingleCellExperiment.

label_col

Character scalar naming the label column in colData(spe) (default "cutoff_label").

assay_name

Character scalar naming the assay used as features (default "exprs").

unknown_label

Character label treated as unlabeled and excluded from training/cleaning (default "Unknown").

features

Character vector of feature (marker) names to use, or "all" to use all assay rows (default "all").

hidden_dims

Integer vector of hidden layer sizes (default c(64, 32)).

dropout

Dropout probability applied after each hidden layer (default 0.3).

epochs

Integer maximum training epochs per fold/final fit; actual training usually stops earlier via early stopping (see patience) once validation loss stops improving (default 100).

lr

Learning rate for Adam (default 1e-3).

weight_decay

L2 penalty for Adam (default 1e-4).

batch_size

Minibatch size (default 256).

cv_folds

Integer number of folds used for stratified cross-validation (default 5).

repeats

Integer number of repeated CV rounds used during consensus cleaning (default 3; kept lower than the random-forest default since each round trains a full network rather than a fast forest).

agreement_thresh

Numeric in [0,1] specifying the minimum agreement rate required to keep an originally labelled cell during cleaning (default 0.8).

val_frac

Fraction of each training set held out (stratified by class) as a validation split for best-epoch selection and early stopping (default 0.15).

patience

Integer epochs to wait for validation-loss improvement before stopping early; set to NULL to disable early stopping (default 10).

verbose_training

Logical; if TRUE, print per-epoch train/val loss during the final model fit (the CV/cleaning-stage folds always stay quiet to avoid flooding the console). Default FALSE.

class_balanced_loss

Logical; if TRUE (default), weight the loss by inverse class frequency to counter class imbalance.

Value

A named list with components:

spe

The input spe with an added colData column cleaned_core_label, mirroring train_custom_randomforest.

model

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.

core_prob_mat

Consensus probability matrix for the kept cells.

agreement_rates

Named numeric vector of per-cell agreement rates.

features_used

Character vector of feature names used for training.

training_history

Per-epoch train/val loss for the *final* model fit (not the CV/cleaning folds), plus which epoch was selected as best.

Examples

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
}

Train kNN Reference for Cell Type Prediction

Description

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.

Usage

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()
)

Arguments

spe

A SpatialExperiment or SummarizedExperiment object containing cell data.

label_col

Character string specifying the column in colData(spe) containing the initial cell type labels. Default is "cutoff_label".

assay_name

Character string specifying the assay to use for marker expression. Default is "exprs".

unknown_label

Character string specifying the label used to identify unknown or unclassified cells, which are excluded from training. Default is "Unknown".

features

Either "all" to use all features in the assay, or a character vector of feature names to subset. Default is "all".

cv_folds

Integer specifying the number of cross-validation folds used during consensus cleaning. Default is 5.

repeats

Integer specifying the number of cleaning repetitions. Higher values produce more stable agreement rates. Default is 10.

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 0.8.

k

Integer specifying the number of nearest neighbours used in the kNN classifier during consensus cleaning. Default is 5.

method

Character string specifying the similarity or distance metric used for kNN. Options include "pearson", "spearman", "cosine", or "euclidean". Default is "pearson". Default is NULL.

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 250L.

BPPARAM

A BiocParallelParam object specifying the parallel back-end to use for processing repeats. Use MulticoreParam (Linux/Mac) or SnowParam (Windows) for speed. Default is BiocParallel::SerialParam().

Value

A named list containing:

spe

The input SpatialExperiment object with a new cleaned_core_label column added to colData.

reference_data

A data frame of marker expression for the high-confidence reference cells.

reference_labels

A factor of cell type labels corresponding to reference_data.

features_used

Character vector of feature names used in training.

agreement_rates

Named numeric vector of per-cell agreement rates from consensus cleaning.

cleaned_core_names

Character vector of cell names retained in the reference set after cleaning.

Examples

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$model

Train a custom random forest with consensus label cleaning

Description

Train a ranger random forest classifier on labelled cells from a SpatialExperiment or SingleCellExperiment. The workflow has two stages:

  1. 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.

  2. 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.

Usage

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
)

Arguments

spe

A SpatialExperiment or SingleCellExperiment.

label_col

Character scalar naming the label column in colData(spe) (default "cutoff_label").

assay_name

Character scalar naming the assay used as features (default "exprs").

unknown_label

Character label treated as unlabeled and excluded from training/cleaning (default "Unknown").

num.trees

Integer number of trees for the final ranger model (default 200).

mtry

Optional integer mtry for ranger. If NULL, uses floor(sqrt(p)) where p is the number of features used.

features

Character vector of feature (marker) names to use, or "all" to use all assay rows (default "all").

cv_folds

Integer number of folds used for stratified cross-validation (default 5).

repeats

Integer number of repeated CV rounds used during consensus cleaning (default 10).

agreement_thresh

Numeric in [0,1] specifying the minimum agreement rate required to keep an originally labelled cell during cleaning (default 0.8).

num_threads

Integer requested number of threads for model fitting.

Details

During consensus cleaning, models are trained without probability estimation. The final model is trained with probability = TRUE to support downstream thresholding workflows.

Value

A named list with components:

spe

The input spe with an added colData column cleaned_core_label, where low-agreement labelled cells are set to unknown_label.

model

A fitted ranger model trained on the cleaned labelled cells with probability = TRUE.

agreement_rates

Named numeric vector of per-cell agreement rates from the consensus cleaning stage (indexed by training-row names).

features_used

Character vector of feature names used for training.

metrics

List of evaluation outputs on the cleaned labelled set:

confusion_matrix

Confusion matrix for pooled CV predictions.

accuracy

Overall pooled CV accuracy.

f1_macro

Overall pooled macro-F1.

cv_overall

Per-fold data.frame with accuracy and macro-F1.

cv_class_metrics

Per-fold, per-class precision/recall/F1 table.

test_pred

Factor of pooled cross-validated predictions on cleaned labelled cells.

test_truth

Factor of pooled cross-validated true labels on cleaned labelled cells.

Examples

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$model

Tree probability for one cell

Description

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.

Usage

tree_prob(
  tree,
  expr_mat,
  cell_i,
  combine = c("mean", "product"),
  neg_markers = character(0),
  marker_stats = NULL,
  neg_strength = 0.8,
  lambda = 2
)

Arguments

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.

Value

Numeric scalar probability (typically in [0,1]) or 'NA_real_' if no usable node scores are available for the cell.

Examples

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

Description

Convert a tree to a tibble representation

Usage

tree_to_df(node, parent = NA_character_, id = "root")

Arguments

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).

Value

A tibble with columns 'id', 'parent', 'type', 'label'.

Examples

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)