| Title: | Integrative Toolkit for Linking Phenotypes to Cell Subpopulations via scRNA-seq and Bulk Data |
|---|---|
| Description: | Identifies phenotype-associated cell subpopulations by integrating phenotypic data (e.g., survival, drug sensitivity), bulk gene expression, and single-cell RNA-seq (scRNA-seq) profiles. It employs multiple algorithms to reliably connect cellular features with clinical or functional phenotypes, offering a unified pipeline for multi-modal analysis that uncovers biologically and clinically relevant cell states in heterogeneous datasets. |
| Authors: | Yuxi Yang [cre, aut] (ORCID: <https://orcid.org/0009-0006-1329-1224>), Shixiang Wang [aut] (ORCID: <https://orcid.org/0000-0001-9855-7357>), Zeyu Yan [ctb], Duanchen Sun [ctb, cph] (Author of the included Scissor code (https://github.com/sunduanchen/Scissor)), Travis Johnson [ctb, cph] (Author of the included DEGAS code (https://github.com/tsteelejohnson91/DEGAS), ORCID: <https://orcid.org/0000-0002-4628-2256>), Zhi Huang [ctb, cph] (Author of the included DEGAS code (https://github.com/tsteelejohnson91/DEGAS)), Qinran Zhang [ctb, cph] (Author of the included scAB code (https://github.com/jinworks/scAB), ORCID: <https://orcid.org/0000-0001-8920-586X>), Hongmei Zhang [ctb, cph] (Author of the included LP_SGL code (https://github.com/hongmeizhanghm/LP_SGL), ORCID: <https://orcid.org/0009-0003-0914-1539>), Dailin Gan [ctb, cph] (Author of the included SCIPAC code (https://github.com/mianaz/SCIPAC)), Jun Li [ctb, cph] (Author of the included SCIPAC code (https://github.com/mianaz/SCIPAC), ORCID: <https://orcid.org/0000-0003-4353-5761>), Xinjia Ruan [ctb, cph] (Author of the included PIPET code (https://github.com/ruan2ruan/PIPET), ORCID: <https://orcid.org/0000-0003-2309-2641>), Aimin Xie [ctb, cph] (Author of the included scPAS code (https://github.com/aiminXie/scPAS)), Xiaosheng Wang [ctb, cph] (Author of the included scPP code (https://github.com/WangX-Lab/ScPP), ORCID: <https://orcid.org/0000-0002-7199-7093>), Yasmin Jolasun [ctb, cph] (Author of the included SIDISH code (https://github.com/mcgilldinglab/SIDISH), ORCID: <https://orcid.org/0009-0009-2559-1015>), Jun Ding [ctb, cph] (Author of the included SIDISH code (https://github.com/mcgilldinglab/SIDISH), ORCID: <https://orcid.org/0000-0001-5183-6885>), Yuxiang Lin [ctb, cph] (Author of the included TiRank code (https://github.com/LenisLin/TiRank), ORCID: <https://orcid.org/0000-0001-8854-2995>) |
| Maintainer: | Yuxi Yang <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 4.0.0 |
| Built: | 2026-11-28 01:30:01 UTC |
| Source: | https://github.com/WangLabCSU/SigBridgeR |
Add multiple feature-level metadata (vectors or 2D tables) to a Seurat object. Handles vectors (length-checked), matrices, data.frames, data.tables, etc. Columns/variables with duplicated names are suffixed (e.g., "type_1"). Gene alignment is auto-detected: rows or cols must match nrow(seurat_obj).
AddMetaFeature(seurat_obj, ..., assay = "RNA")AddMetaFeature(seurat_obj, ..., assay = "RNA")
seurat_obj |
A Seurat object. |
... |
One or more metadata inputs:
|
assay |
Assay name (default: |
Modified seurat_obj (invisibly).
Adds arbitrary data to the @misc slot of a Seurat object with automatic key
conflict resolution. If the key already exists, automatically appends a numeric
suffix to ensure unique key naming (e.g., "mykey_1", "mykey_2").
AddMisc(seurat_obj, ..., cover = TRUE)AddMisc(seurat_obj, ..., cover = TRUE)
seurat_obj |
A Seurat object to modify |
... |
key-value pairs to add to the |
cover |
Logical indicating whether to overwrite existing data. If (default TRUE). |
The modified Seurat object with added @misc data. The original object
structure is preserved with no other modifications.
If key doesn't exist: uses as-is
If key exists: appends the next available number (e.g., "key_1", "key_2")
If numbered keys exist (e.g., "key_2"): increments the highest number
## Not run: # Basic usage seurat_obj <- AddMisc(seurat_obj, "QC_stats" = qc_df) # Auto-incrementing example seurat_obj <- AddMisc(seurat_obj, markers = markers1) seurat_obj <- AddMisc(seurat_obj, markers = markers2, cover=FALSE) # Stores as "markers" and "markers_1" ## End(Not run)## Not run: # Basic usage seurat_obj <- AddMisc(seurat_obj, "QC_stats" = qc_df) # Auto-incrementing example seurat_obj <- AddMisc(seurat_obj, markers = markers1) seurat_obj <- AddMisc(seurat_obj, markers = markers2, cover=FALSE) # Stores as "markers" and "markers_1" ## End(Not run)
These functions collapse duplicated row names (e.g., gene symbols) or column names (e.g., sample IDs) in matrix-like objects by aggregating values using configurable methods. They support:
Rows: AggregateDupRows: merges rows sharing the same row name.
Columns: AggregateDupCols: merges columns sharing the same column name.
Both: AggregateDups: convenience wrapper applying row-then-column aggregation.
Designed for expression matrices, count tables, or any numeric data where feature/sample duplication occurs.
Handles matrix, data.frame, and S4 Matrix classes (e.g. dgCMatrix) robustly.
Convenience wrapper that first aggregates duplicated rows, then duplicated columns. Useful for cleaning matrices where both feature and sample duplication may occur.
AggregateDupRows( x, method = c("max", "sum", "mean", "median", "first"), verbose = TRUE, ... ) AggregateDupCols( x, method = c("max", "sum", "mean", "median", "first"), verbose = TRUE, ... ) AggregateDups( x, method = c("max", "sum", "mean", "median", "first"), row_method = method, col_method = method, verbose = TRUE, ... )AggregateDupRows( x, method = c("max", "sum", "mean", "median", "first"), verbose = TRUE, ... ) AggregateDupCols( x, method = c("max", "sum", "mean", "median", "first"), verbose = TRUE, ... ) AggregateDups( x, method = c("max", "sum", "mean", "median", "first"), row_method = method, col_method = method, verbose = TRUE, ... )
x |
A numeric matrix-like object (see Details). |
method |
Character scalar. Aggregation method (see Methods below). |
verbose |
Whether to print messages |
... |
No usage |
row_method |
Aggregation method for rows. Defaults to |
col_method |
Aggregation method for columns. Defaults to |
An aggregated object of the same effective type as x, with unique row/column names.
Supported methods (applied column-wise for rows, row-wise for columns):
"max": Maximum value per group (default).
"sum": Sum of values per group.
"mean": Arithmetic mean (uses na.rm = TRUE).
"median": Median value.
"first": First occurrence in original order.
| Input class | Output class (unless noted) |
matrix |
matrix |
data.frame |
data.frame |
S4 Matrix |
matrix (dense) - S4 attributes dropped for generality
|
Row/column order in output follows first occurrence of each unique name in rownames(x) / colnames(x).
# Full deduplication in one step mat <- matrix(1:16, nrow = 4, dimnames = list(c("TP53", "TP53", "BRCA1", "ACTB"), c("S1", "S1", "S2", "S3"))) mat AggregateDups(mat, method = "sum")# Full deduplication in one step mat <- matrix(1:16, nrow = 4, dimnames = list(c("TP53", "TP53", "BRCA1", "ACTB"), c("S1", "S1", "S2", "S3"))) mat AggregateDups(mat, method = "sum")
AnnotationMethod is the S7 class for cell type annotation methods. It
extends Method with Python environment support, enabling annotation
methods that depend on Python-based tools (e.g., SingleR, scArches).
AnnotationMethod( method_name = character(), executor = function() { NULL }, pkg_name = character(), method_version = NULL, py_env = NULL, sigbridger_version = get_pkg_version() )AnnotationMethod( method_name = character(), executor = function() { NULL }, pkg_name = character(), method_version = NULL, py_env = NULL, sigbridger_version = get_pkg_version() )
method_name |
|
executor |
|
pkg_name |
The name of the R (Python) package when using this annotation method.
When |
method_version |
|
py_env |
|
sigbridger_version |
Package Version of SigBridgeR |
This class inherits from Method and adds a py_env property for
specifying a conda environment or Python path. When py_env is NULL,
the method version is resolved from an R package via
r_pkg_version(). When a Python environment is specified, the version
is resolved via py_pkg_version().
An AnnotationMethod S7 object.
Other S7-Classes:
BenchAccConfig(),
BenchConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodConfig(),
ScreenMethodResult()
A ggplot2 autoplot method for class ScreenMethodResult and SeuratObject
## S3 method for class 'Seurat' autoplot( object, reduction = "umap", group.by = NULL, label = FALSE, label.size = 4L, pt.size = NULL, cols = NULL, ... ) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' autoplot(object, ...)## S3 method for class 'Seurat' autoplot( object, reduction = "umap", group.by = NULL, label = FALSE, label.size = 4L, pt.size = NULL, cols = NULL, ... ) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' autoplot(object, ...)
object |
Seurat object |
reduction |
Which dimensionality reduction to use. If not specified, first searches for umap, then tsne, then pca |
group.by |
Name of one or more metadata columns to group (color) cells by (for example, orig.ident); pass 'ident' to group by identity class |
label |
Whether to label the clusters |
label.size |
Sets size of labels |
pt.size |
Adjust point size for plotting |
cols |
Vector of colors, each color corresponds to an identity class. This may also be a single character
or numeric value corresponding to a palette as specified by |
... |
Extra parameters passed to |
ggplot object
Computes binary classification metrics for every screening method present in
the input, by comparing each method's per-cell labels against ground-truth
labels. "Positive" is treated as the positive class and all other labels
as negative, so the accuracy of different screening methods can be compared
on the same cells.
BenchAcc(obj, ...) ## S3 method for class 'Seurat' BenchAcc( obj, bench_config = character(), ..., verbose = getFuncOption("verbose"), nthreads = getFuncOption("nthreads") ) ## S3 method for class ''SigBridgeR::BenchAccConfig'' BenchAcc(obj, ..., verbose = getFuncOption("verbose")) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' BenchAcc(obj, ...) ## Default S3 method: BenchAcc(obj, ...)BenchAcc(obj, ...) ## S3 method for class 'Seurat' BenchAcc( obj, bench_config = character(), ..., verbose = getFuncOption("verbose"), nthreads = getFuncOption("nthreads") ) ## S3 method for class ''SigBridgeR::BenchAccConfig'' BenchAcc(obj, ..., verbose = getFuncOption("verbose")) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' BenchAcc(obj, ...) ## Default S3 method: BenchAcc(obj, ...)
obj |
The object to evaluate, one of:
|
... |
Additional arguments passed between the S3 methods. Currently unused apart from forwarding |
bench_config |
|
verbose |
Logical. Whether to report progress information.
Default: |
nthreads |
Integer. Number of threads used by the C++ metric
computation. Default: |
BenchAcc() dispatches on the class of obj: a BenchAccConfig is screened
first, a ScreenMethodResult is unwrapped to its scRNA_data slot, and
BenchAcc.Seurat() performs the computation. Unsupported classes abort with
an informative error.
Columns of [email protected] whose names match a supported screening method
(case-insensitive) are taken as the predicted labels; other columns are
ignored. The function aborts when no such column exists.
A length-one bench_config is looked up as a column of [email protected];
otherwise it is used directly as a per-cell label vector. The labels must
include "Positive", and the vector form must have one element per cell.
With P, N, TP, FP, TN and FN denoting the numbers of positive
cells, negative cells, true/false positives and true/false negatives
A named list with one element per screening method found in
meta.data. Each element is a 1-row numeric matrix with columns TPR,
FPR, TNR, FNR, F1, Accuracy and so on.
BenchAccConfig(), ScreenMethodResult, Screen(),
BenchGSEA(), BenchMemory(), BenchGeneScore()
Other Benchmark:
BenchGSEA(),
BenchGeneScore(),
BenchMemory()
counts <- matrix( rep(1:10, 6L), nrow = 10L, dimnames = list(paste0("Gene", 1:10), paste0("Cell", 1:6)) ) obj <- Seurat::CreateSeuratObject(counts = counts) obj$truth <- c("Positive", "Negative", "Positive", "Other", "Positive", "Negative") obj$Scissor <- c("Positive", "Negative", "Positive", "Other", "Negative", "Negative") BenchAcc(obj, bench_config = "truth", verbose = FALSE)counts <- matrix( rep(1:10, 6L), nrow = 10L, dimnames = list(paste0("Gene", 1:10), paste0("Cell", 1:6)) ) obj <- Seurat::CreateSeuratObject(counts = counts) obj$truth <- c("Positive", "Negative", "Positive", "Other", "Positive", "Negative") obj$Scissor <- c("Positive", "Negative", "Positive", "Other", "Negative", "Negative") BenchAcc(obj, bench_config = "truth", verbose = FALSE)
BenchAccConfig stores the configuration of an accuracy benchmark run
performed by BenchAcc(). It extends BenchConfig with the ground-truth
cell labels collected in bench_config; the inputs shared by every
screening method (matched_bulk, sc_data, phenotype, label_type,
phenotype_class, screen_method) and the method specific arguments
collected in method_param are inherited from BenchConfig.
BenchAccConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = character(), ... )BenchAccConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = character(), ... )
matched_bulk |
|
sc_data |
A Seurat object to be screened. |
phenotype |
Phenotype data, either a named vector or a patient survival
data frame. See |
label_type |
|
phenotype_class |
|
screen_method |
|
method_param |
Named |
bench_config |
|
... |
Must be empty. Method specific arguments belong in |
bench_config supplies the reference ("ground-truth") labels that the
screening results are scored against. It is a character vector interpreted
in one of two ways:
Length one: the name of a column in [email protected] holding the
per-cell labels. The column must exist and contain a "Positive" level.
Length greater than one: a per-cell label vector, one label per cell. It
must contain a "Positive" level and have the same length as the number
of cells in sc_data.
In both cases a "Positive" label is required, since BenchAcc() computes
binary classification metrics (TPR, FPR, TNR, FNR, F1, Accuracy) treating
"Positive" as the positive class. An empty bench_config is rejected by
the validator.
A BenchAccConfig S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodConfig(),
ScreenMethodResult()
BenchConfig is the common parent of the benchmark configurations in
SigBridgeR. It stores the inputs shared by every screening method
(matched_bulk, sc_data, phenotype, label_type, phenotype_class,
screen_method), the method specific arguments collected in method_param,
and an optional param list used by subclasses that forward extra arguments.
BenchConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), sigbridger_version = get_pkg_version(), ... )BenchConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), sigbridger_version = get_pkg_version(), ... )
matched_bulk |
|
sc_data |
A Seurat object to be screened. |
phenotype |
Phenotype data, either a named vector or a patient survival
data frame. See |
label_type |
|
phenotype_class |
|
screen_method |
|
method_param |
Named |
sigbridger_version |
Package Version of SigBridgeR |
... |
unused |
A single configuration may describe several screening runs: the benchmark
screens the same data with each method listed in screen_method, one method
at a time.
screen_method may only contain methods registered in ScreenStrategy
(e.g. "Scissor", "scPAS", "LP_SGL"); the constructor of the concrete
configuration aborts on any unknown name. It also aborts when the selected
methods have no phenotype class in common.
method_param is a named list with one entry per method, named
"<method>_param" (e.g. list(Scissor_param = list(alpha = 0.05))).
Each entry is spliced into the arguments of that method's executor, after
its ScreenMethod mapper has run. Use MethodParamSet() to build the full
set with empty defaults, so unspecified methods simply run with their own
defaults.
label_type is a length-one template. The default "{method_name}" is
resolved by the benchmark with the name of the method currently being
benchmarked, so a single configuration can serve methods whose executors
expect differently named phenotype labels.
A BenchConfig S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodConfig(),
ScreenMethodResult()
Scores one or more gene sets in every cell of a screened single-cell dataset
with ssGSEA, AUCell, UCell or AddModuleScore. All backends return the
same gene-set-by-cell matrix layout, so the cell-level signal recovered by
different screening methods can be compared on a common ground.
BenchGeneScore(obj, ...) ## S3 method for class ''SigBridgeR::BenchGeneScoreConfig'' BenchGeneScore(obj, ..., verbose = getFuncOption("verbose")) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' BenchGeneScore(obj, ...) ## S3 method for class 'Seurat' BenchGeneScore( obj, method = c("ssGSEA", "AUCell", "UCell", "AddModuleScore"), ... )BenchGeneScore(obj, ...) ## S3 method for class ''SigBridgeR::BenchGeneScoreConfig'' BenchGeneScore(obj, ..., verbose = getFuncOption("verbose")) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' BenchGeneScore(obj, ...) ## S3 method for class 'Seurat' BenchGeneScore( obj, method = c("ssGSEA", "AUCell", "UCell", "AddModuleScore"), ... )
obj |
The object to score, one of:
|
... |
Additional named arguments forwarded to the selected backend. Arguments are matched against the formal argument names of the backend and split automatically over the two stages when a method needs two calls:
|
verbose |
Logical. Whether to report progress information.
Default: |
method |
Character. Scoring backend, one of |
BenchGeneScore() dispatches on the class of obj, so a
BenchGeneScoreConfig is benchmarked and a ScreenMethodResult is unwrapped
before the actual scoring happens. BenchGeneScore.Seurat() is itself a
generic dispatching on method: every backend lives in its own
BenchGeneScoreSeurat.<method> function and its package is loaded on demand
by rlang::check_installed(), so neither GSVA, AUCell, UCell nor
Seurat is required to merely call the generic.
For a BenchGeneScoreConfig input, the configured screen_method entries
are run one after another with Screen(). Every run adds its labels to the
meta.data of the working Seurat object and the labels are accumulated
across methods, after which the scores are computed once. Scores are
therefore comparable across screening methods by construction.
"UCell" is called with name = "" so that gene-set names stay untouched,
and its cell-by-gene-set output is transposed to the common layout.
"AddModuleScore" drops the genes absent from assay, drops the gene sets
that become empty, and stores the scores under an internal
.BenchGeneScore prefix so that the meta.data of obj is left untouched.
It aborts when no gene set survives the filtering.
"AUCell" builds the rankings with plotStats = FALSE, since the plot is
only meaningful for a manual inspection.
A numeric matrix with gene sets in rows and cells in columns. Gene sets dropped by backend-specific filtering are omitted from the result.
BenchGeneScoreConfig(), BenchGeneScoreConfigSet(),
Screen(), BenchGSEA(), BenchAcc()
Other Benchmark:
BenchAcc(),
BenchGSEA(),
BenchMemory()
counts <- matrix( rep(seq_len(20), times = 5) + rep(seq_len(5), each = 20), nrow = 20, dimnames = list(paste0("Gene", seq_len(20)), paste0("Cell", seq_len(5))) ) obj <- Seurat::CreateSeuratObject(counts = counts) obj <- Seurat::NormalizeData(obj, verbose = FALSE) pathways <- list( First = paste0("Gene", 1:5), Second = paste0("Gene", 6:10) ) scores <- try(BenchGeneScore(obj, pathways, method = "ssGSEA", verbose = FALSE)) # require GSVAcounts <- matrix( rep(seq_len(20), times = 5) + rep(seq_len(5), each = 20), nrow = 20, dimnames = list(paste0("Gene", seq_len(20)), paste0("Cell", seq_len(5))) ) obj <- Seurat::CreateSeuratObject(counts = counts) obj <- Seurat::NormalizeData(obj, verbose = FALSE) pathways <- list( First = paste0("Gene", 1:5), Second = paste0("Gene", 6:10) ) scores <- try(BenchGeneScore(obj, pathways, method = "ssGSEA", verbose = FALSE)) # require GSVA
BenchGeneScoreConfig stores the configuration of a gene set scoring
benchmark run performed by BenchGeneScore(). It extends BenchConfig with
the scoring controls collected in bench_config; the inputs shared by every
screening method (matched_bulk, sc_data, phenotype, label_type,
phenotype_class, screen_method) and the method specific arguments
collected in method_param are inherited from BenchConfig.
BenchGeneScoreConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = BenchGeneScoreConfigSet(), ... )BenchGeneScoreConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = BenchGeneScoreConfigSet(), ... )
matched_bulk |
|
sc_data |
A Seurat object to be screened. |
phenotype |
Phenotype data, either a named vector or a patient survival
data frame. See |
label_type |
|
phenotype_class |
|
screen_method |
|
method_param |
Named |
bench_config |
Named |
... |
Must be empty. Method specific arguments belong in |
For a BenchGeneScoreConfig input, BenchGeneScore() screens the data with
each method in screen_method and scores the accumulated cell labels in a
single pass, so the scores are comparable across screening methods by
construction. bench_config selects the scoring backend and collects the
arguments forwarded to it, as built by BenchGeneScoreConfigSet().
A BenchGeneScoreConfig S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchConfig(),
BenchGSEAConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodConfig(),
ScreenMethodResult()
## Not run: BenchGeneScoreConfig( matched_bulk = bulk_matrix, sc_data = seurat, phenotype = phenotype, label_type = "{method_name}", phenotype_class = "binary", screen_method = "ssGSEA", method_param = list( nperm = 1000 ) ) ## End(Not run)## Not run: BenchGeneScoreConfig( matched_bulk = bulk_matrix, sc_data = seurat, phenotype = phenotype, label_type = "{method_name}", phenotype_class = "binary", screen_method = "ssGSEA", method_param = list( nperm = 1000 ) ) ## End(Not run)
Collects the arguments of a gene set scoring benchmark into the
bench_config list of BenchGeneScoreConfig(). method selects the scoring
backend, and additional named arguments are forwarded to that backend when
BenchGeneScore() computes the scores.
BenchGeneScoreConfigSet( method = c("ssGSEA", "AUCell", "UCell", "AddModuleScore"), ... )BenchGeneScoreConfigSet( method = c("ssGSEA", "AUCell", "UCell", "AddModuleScore"), ... )
method |
Character. Scoring backend to benchmark, one of |
... |
Additional named arguments forwarded to the selected scoring
backend. They are matched against the backend's formal arguments and, when
a method needs two calls, split over its stages (e.g.
|
A named list holding method and the extra backend arguments, to
be used as the bench_config of BenchGeneScoreConfig().
BenchGeneScoreConfig(), BenchGeneScore()
Other ConfigSet:
BenchGSEAConfigSet(),
BenchMemoryConfigSet(),
MethodParamSet()
BenchGeneScoreConfigSet(method = "ssGSEA")BenchGeneScoreConfigSet(method = "ssGSEA")
Runs gene set enrichment analysis (GSEA) on the marker genes of every screening method present in the input, so that the functional signals recovered by different methods can be compared side by side.
BenchGSEA(obj, ...) ## S3 method for class 'Seurat' BenchGSEA( obj, group, pathway, p_value_threshold = NULL, ..., verbose = getFuncOption("verbose") ) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' BenchGSEA(obj, ...) ## S3 method for class ''SigBridgeR::BenchGSEAConfig'' BenchGSEA(obj, ..., verbose = getFuncOption("verbose")) ## Default S3 method: BenchGSEA(obj, ...)BenchGSEA(obj, ...) ## S3 method for class 'Seurat' BenchGSEA( obj, group, pathway, p_value_threshold = NULL, ..., verbose = getFuncOption("verbose") ) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' BenchGSEA(obj, ...) ## S3 method for class ''SigBridgeR::BenchGSEAConfig'' BenchGSEA(obj, ..., verbose = getFuncOption("verbose")) ## Default S3 method: BenchGSEA(obj, ...)
obj |
A |
... |
Additional arguments, automatically split by formal argument
names between |
group |
A vector of length equal to the number of cells, with each element being the group label of the corresponding cell. |
pathway |
A named list of gene sets, each element a character vector of
gene symbols. Passed to |
p_value_threshold |
Numeric or |
verbose |
Logical. Whether to report progress.
Default: |
For each screening method found in meta.data:
Labels are binarised to "Positive" vs "Other";
Seurat::FindMarkers() is run with ident.1 = "Positive",
ident.2 = "Other" and group.by set to the method column;
Markers are ranked by sign(avg_log2FC) * -log10(p_val_adj);
fgsea::fgsea() is run on the ranked list, and the ranking statistics of
the leading-edge genes are attached as leadingEdgeStats.
For a BenchGSEAConfig input, every configured screening method is first
run via Screen() on the same data before the GSEA comparison.
A data.table of fgsea::fgsea() results stacked across screening
methods, with an extra screenMethod column identifying the method and a
leadingEdgeStats list column holding the ranking statistics of the
leading-edge genes. Methods without markers are dropped with a warning.
BenchGSEAConfig(), Screen(), fgsea::fgsea(),
Seurat::FindMarkers(), BenchAcc(), BenchMemory()
Other Benchmark:
BenchAcc(),
BenchGeneScore(),
BenchMemory()
## Not run: # sc is a Seurat object already screened by e.g. Scissor and scPAS pathways <- list( pathway_a = c("Gene1", "Gene2", "Gene3"), pathway_b = c("Gene4", "Gene5", "Gene6") ) res <- BenchGSEA(sc, pathway = pathways) ## End(Not run)## Not run: # sc is a Seurat object already screened by e.g. Scissor and scPAS pathways <- list( pathway_a = c("Gene1", "Gene2", "Gene3"), pathway_b = c("Gene4", "Gene5", "Gene6") ) res <- BenchGSEA(sc, pathway = pathways) ## End(Not run)
BenchGSEAConfig stores the configuration of a GSEA benchmark run
performed by BenchGSEA(). It extends BenchConfig with the GSEA-specific
controls collected in bench_config; the inputs shared by every screening
method (matched_bulk, sc_data, phenotype, label_type,
phenotype_class, screen_method) and the method specific arguments
collected in method_param are inherited from BenchConfig.
BenchGSEAConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = list(), ... )BenchGSEAConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = list(), ... )
matched_bulk |
|
sc_data |
A Seurat object to be screened. |
phenotype |
Phenotype data, either a named vector or a patient survival
data frame. See |
label_type |
|
phenotype_class |
|
screen_method |
|
method_param |
Named |
bench_config |
Named |
... |
Must be empty. Method specific arguments belong in |
A BenchGSEAConfig S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodConfig(),
ScreenMethodResult()
Collects the arguments of a GSEA benchmark into the bench_config list of
BenchGSEAConfig(). Arguments matching fgsea::fgsea() formals are handed
over to it; all other named arguments are kept as-is.
BenchGSEAConfigSet(sc_data, pathway, group = NULL, ...)BenchGSEAConfigSet(sc_data, pathway, group = NULL, ...)
sc_data |
A Seurat object to be screened.
It defines the cells that |
pathway |
A named |
group |
|
... |
Additional named arguments, typically further |
A list of parameters for fgsea::fgsea() and BenchGSEAConfig().
Other ConfigSet:
BenchGeneScoreConfigSet(),
BenchMemoryConfigSet(),
MethodParamSet()
## Not run: config <- BenchGSEAConfigSet( sc_data = sc, pathway = fgsea::examplePathways, group = sc$cell_type ) ## End(Not run)## Not run: config <- BenchGSEAConfigSet( sc_data = sc, pathway = fgsea::examplePathways, group = sc$cell_type ) ## End(Not run)
Runs every screening method listed in a BenchMemoryConfig on the same data
and measures its wall time and memory footprint with bench::mark().
BenchMemory(obj, ...) ## S3 method for class ''SigBridgeR::BenchMemoryConfig'' BenchMemory(obj, ..., verbose = getFuncOption("verbose")) ## Default S3 method: BenchMemory(obj, ...)BenchMemory(obj, ...) ## S3 method for class ''SigBridgeR::BenchMemoryConfig'' BenchMemory(obj, ..., verbose = getFuncOption("verbose")) ## Default S3 method: BenchMemory(obj, ...)
obj |
An object of class BenchMemoryConfig |
... |
Additional arguments passed to methods. Currently unused. |
verbose |
|
The benchmark is organised in rounds. Within a round every method is screened once, and the round order is shuffled by default so that cold-cache, lazy-loading and package-level caching effects are spread across methods instead of always penalising the first one. One row is returned per method per round; summaries across rounds are left to the caller.
Each measurement runs in its own background R process (callr::r_bg()) with
its own copies of the inputs, staged in a temporary directory with qs2.
A child process therefore cannot leak package-level caches, loaded Python
runtimes or large result objects into the next measurement. The child is
always terminated on exit so it cannot outlive the call, and timeout_sec
bounds the wall time of a single method in a single round.
Three memory numbers are reported because they mean different things:
mem_alloc - bytes allocated during the run (allocation churn, from
bench::mark()).
mem_peak_mb - peak R heap high-water mark, from gc(reset = TRUE).
rss_peak_mb - peak process resident set size, recorded only when
measure_rss = TRUE (Linux only).
Before the benchmark starts, bench_probe_resources() collects a machine
resource summary. Set probe_resources = FALSE in the bench_config
controls (see BenchMemoryConfigSet()) to skip this probe, for example when
the workspace is large and the probe's full gc() would add noticeable
startup time.
A data.table with one row per screening method per round. Each row
contains the bench::mark() columns (min, median, itr/sec,
mem_alloc, n_itr, n_gc, total_time, ...), with expression
replaced by the method name, plus method_name, round, position,
status, error, mem_peak_mb, rss_peak_mb and elapsed. Successful
measurements have status = "ok"; failed or timed-out measurements are
kept with status set to "error" or "timeout" and NA memory
metrics, while their benchmark columns are filled with NA.
bench_config)rounds (3L): number of rounds; every method is screened once per
round.
probe_resources (TRUE): whether to call bench_probe_resources()
before staging the inputs. Set to FALSE to skip the probe and its full
gc().
min_iterations, max_iterations (1L, 1L): iteration bounds passed
to bench::mark().
order ("random"): "random" shuffles methods within each round using
seed plus the round number; "fixed" keeps the given order.
seed (getFuncOption("seed")): base seed for shuffling and for each
measurement child.
memory, filter_gc, check, min_time, relative, time_unit:
forwarded to bench::mark().
measure_rss (FALSE): also record peak process RSS (Linux only).
on_failure ("skip"): "skip" records the failure and continues,
"stop" aborts the whole benchmark.
set_threads (1L): number of threads the child process is pinned to.
timeout_sec (10800L): maximum wall-clock seconds for one method in one
round; use Inf to disable the limit.
BenchMemoryConfig(), BenchMemoryConfigSet(), bench::mark()
Other Benchmark:
BenchAcc(),
BenchGSEA(),
BenchGeneScore()
## Not run: config <- BenchMemoryConfig( matched_bulk = bulk, sc_data = sc, phenotype = pheno, screen_method = c("scPP", "scPAS", "LP_SGL"), method_param = MethodParamSet(list( scPP_param = list(Log2FC_cutoff = 0.585), scPAS_param = list(permutation_times = 500) )), bench_config = list(rounds = 3L, timeout_sec = 1800) ) res <- BenchMemory(config) res res[status == "ok", .(median_sec = median(median)), by = method_name] ## End(Not run)## Not run: config <- BenchMemoryConfig( matched_bulk = bulk, sc_data = sc, phenotype = pheno, screen_method = c("scPP", "scPAS", "LP_SGL"), method_param = MethodParamSet(list( scPP_param = list(Log2FC_cutoff = 0.585), scPAS_param = list(permutation_times = 500) )), bench_config = list(rounds = 3L, timeout_sec = 1800) ) res <- BenchMemory(config) res res[status == "ok", .(median_sec = median(median)), by = method_name] ## End(Not run)
BenchMemoryConfig stores the configuration of a time and memory benchmark
run performed by BenchMemory(). It extends BenchConfig with the
benchmarking controls collected in bench_config; the inputs shared by every
screening method (matched_bulk, sc_data, phenotype, label_type,
phenotype_class, screen_method) and the method specific arguments
collected in method_param are inherited from BenchConfig.
BenchMemoryConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = BenchMemoryConfigSet(), ... )BenchMemoryConfig( matched_bulk, sc_data, phenotype, label_type = "{method_name}", phenotype_class = c("binary", "survival", "continuous"), screen_method = names(ScreenStrategy), method_param = MethodParamSet(), bench_config = BenchMemoryConfigSet(), ... )
matched_bulk |
|
sc_data |
A Seurat object to be screened. |
phenotype |
Phenotype data, either a named vector or a patient survival
data frame. See |
label_type |
|
phenotype_class |
|
screen_method |
|
method_param |
Named |
bench_config |
Named |
... |
Must be empty. Method specific arguments belong in |
A BenchMemoryConfig S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
ScreenMethodCache(),
ScreenMethodConfig(),
ScreenMethodResult()
Merges the user supplied bench_config with the defaults and validates the
names, so that a typo aborts instead of being silently ignored.
BenchMemoryConfigSet( rounds = 3L, probe_resources = TRUE, min_iterations = 1L, max_iterations = 1L, order = c("random", "fixed"), seed = getFuncOption("seed"), memory = TRUE, filter_gc = FALSE, check = FALSE, measure_rss = FALSE, on_failure = c("skip", "stop"), set_threads = 1L, min_time = 0.5, relative = FALSE, time_unit = NULL, timeout_sec = 10800L, ... )BenchMemoryConfigSet( rounds = 3L, probe_resources = TRUE, min_iterations = 1L, max_iterations = 1L, order = c("random", "fixed"), seed = getFuncOption("seed"), memory = TRUE, filter_gc = FALSE, check = FALSE, measure_rss = FALSE, on_failure = c("skip", "stop"), set_threads = 1L, min_time = 0.5, relative = FALSE, time_unit = NULL, timeout_sec = 10800L, ... )
rounds |
|
probe_resources |
|
min_iterations |
Each expression will be evaluated a minimum of |
max_iterations |
Each expression will be evaluated a maximum of |
order |
|
seed |
|
memory |
If |
filter_gc |
If |
check |
Check if results are consistent. If |
measure_rss |
|
on_failure |
|
set_threads |
|
min_time |
The minimum number of seconds to run each expression, set to
|
relative |
If |
time_unit |
If |
timeout_sec |
|
... |
Expressions to benchmark, if named the |
A named list of resolved controls.
Other ConfigSet:
BenchGSEAConfigSet(),
BenchGeneScoreConfigSet(),
MethodParamSet()
BenchMemoryConfigSet()BenchMemoryConfigSet()
Resolves a user-specified path to the cache layer directory. In
"save" mode, the necessary directory structure is created
automatically. In "load" mode, an existing cache directory is
identified.
CacheSetHere( path, cache_config, mode = c("load", "save"), timestamp = NULL, ... )CacheSetHere( path, cache_config, mode = c("load", "save"), timestamp = NULL, ... )
path |
|
cache_config |
A |
mode |
|
timestamp |
|
... |
Additional arguments (must be empty, checked by
|
The function detects which cache layer the given path belongs to:
Cache layer: The path directly contains a cache_config.json
file. In save mode this triggers an error (recursive caching is not
supported); in load mode the path is returned as-is.
Root layer: The path's basename matches {method_name}_res
(e.g., "Scissor_res"). In save mode a new cache subdirectory is
created; in load mode ChooseCache() is called to select an existing
cache.
Parent layer: The path is a parent directory. A
{method_name}_res subdirectory is created (save) or located (load)
underneath it.
In save mode, the cache directory is named
{phenotype_class}_{timestamp} (e.g.,
"survival_20250730120000").
A character string: the absolute path to the cache directory.
Other cache_config:
CacheSysCall(),
CheckCache(),
ChooseCache(),
LoadCache(),
WriteCache(),
WriteCacheMeta()
## Not run: config <- ScreenMethodConfig( method_name = "Scissor", param = list(alpha = 0.05) ) # Save: create a new cache under the root CacheSetHere("Scissor_res", config, mode = "save") # Load: select an existing cache from the root CacheSetHere("Scissor_res", config, mode = "load") # Load: point directly to a specific cache CacheSetHere("Scissor_res/survival_207701011212", config, mode = "load") ## End(Not run)## Not run: config <- ScreenMethodConfig( method_name = "Scissor", param = list(alpha = 0.05) ) # Save: create a new cache under the root CacheSetHere("Scissor_res", config, mode = "save") # Load: select an existing cache from the root CacheSetHere("Scissor_res", config, mode = "load") # Load: point directly to a specific cache CacheSetHere("Scissor_res/survival_207701011212", config, mode = "load") ## End(Not run)
High-level wrapper for loading and saving cached screening results.
Combines cache path resolution (via CacheSetHere()), configuration
validation (via CheckCache()), and data I/O (via LoadCache() or
WriteCache()) into a single call.
CacheSysCall( mode = c("load", "save"), path = NULL, cache, verbose = TRUE, timestamp = NULL, ... )CacheSysCall( mode = c("load", "save"), path = NULL, cache, verbose = TRUE, timestamp = NULL, ... )
mode |
|
path |
|
cache |
A |
verbose |
|
timestamp |
|
... |
Additional arguments passed to |
CacheSysCall is the primary entry point for cache operations in the
SigBridgeR pipeline. It dispatches to either CacheSysCall.load() or
CacheSysCall.save() based on the mode argument.
In "load" mode, the function:
Resolves the cache path via CacheSetHere().
Validates cache consistency via CheckCache().
Loads each cached data object via LoadCache() and returns them
as a named list.
In "save" mode, the function:
Resolves and creates the cache directory via CacheSetHere().
Writes the cache data and metadata via WriteCache().
Returns the cache data invisibly.
In "load" mode, a named list of loaded cache data objects. In
"save" mode, the cache data invisibly.
Other cache_config:
CacheSetHere(),
CheckCache(),
ChooseCache(),
LoadCache(),
WriteCache(),
WriteCacheMeta()
## Not run: # Load cached results cache <- ScreenMethodCache( cache_path = "Scissor_res/", cache_config_path = "Scissor_res/cache_config.json", cache_data = list(), screen_method_config = ScreenMethodConfig( screen_method = "Scissor", param = list(alpha = 0.05) ) ) result <- CacheSysCall( "load", path = "Scissor_res/survival_2025_01_01", cache = cache ) # Save results to cache cache <- ScreenMethodCache( cache_path = "Scissor_res/", cache_config_path = "Scissor_res/cache_config.json", cache_data = list(result = my_matrix), screen_method_config = ScreenMethodConfig( screen_method = "Scissor", param = list(alpha = 0.05) ) ) CacheSysCall("save", cache = cache) ## End(Not run)## Not run: # Load cached results cache <- ScreenMethodCache( cache_path = "Scissor_res/", cache_config_path = "Scissor_res/cache_config.json", cache_data = list(), screen_method_config = ScreenMethodConfig( screen_method = "Scissor", param = list(alpha = 0.05) ) ) result <- CacheSysCall( "load", path = "Scissor_res/survival_2025_01_01", cache = cache ) # Save results to cache cache <- ScreenMethodCache( cache_path = "Scissor_res/", cache_config_path = "Scissor_res/cache_config.json", cache_data = list(result = my_matrix), screen_method_config = ScreenMethodConfig( screen_method = "Scissor", param = list(alpha = 0.05) ) ) CacheSysCall("save", cache = cache) ## End(Not run)
Performs automated cell type annotation via the celltypist Python package
using reticulate integration. Accepts a Seurat object as input and
returns it enriched with CellTypist prediction results as metadata columns.
Requires a Python environment with celltypist installed (see
https://github.com/Teichlab/celltypist). By default the function locates a
suitable Python interpreter automatically via reticulate; use
reticulate::use_python() to pin a specific environment beforehand.
CellTypistAnnotate(sc, ...) ## Default S3 method: CellTypistAnnotate(sc, ...) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' CellTypistAnnotate(sc, ...) ## S3 method for class 'SingleCellExperiment' CellTypistAnnotate(sc, ...) ## S3 method for class 'Seurat' CellTypistAnnotate( sc, model = NULL, download = TRUE, force_update = FALSE, majority_voting = FALSE, mode = c("best match", "prob match"), p_thres = 0.5, transpose_input = FALSE, gene_file = NULL, cell_file = NULL, over_clustering = NULL, use_GPU = FALSE, min_prop = 0L, verbose = getFuncOption("verbose"), assay = "RNA", ... )CellTypistAnnotate(sc, ...) ## Default S3 method: CellTypistAnnotate(sc, ...) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' CellTypistAnnotate(sc, ...) ## S3 method for class 'SingleCellExperiment' CellTypistAnnotate(sc, ...) ## S3 method for class 'Seurat' CellTypistAnnotate( sc, model = NULL, download = TRUE, force_update = FALSE, majority_voting = FALSE, mode = c("best match", "prob match"), p_thres = 0.5, transpose_input = FALSE, gene_file = NULL, cell_file = NULL, over_clustering = NULL, use_GPU = FALSE, min_prop = 0L, verbose = getFuncOption("verbose"), assay = "RNA", ... )
sc |
A single-cell dataset, one of:
|
... |
Additional arguments passed through to the CellTypist Python backend. |
model |
Character. CellTypist model specification. One of:
|
download |
Logical. Whether to automatically download the model first.
Default: |
force_update |
Logical. Whether to force re-downloading the model files
when |
majority_voting |
Logical. Whether to refine predicted labels by running a
majority voting classifier after over-clustering. Default: |
mode |
Character. Prediction mode: |
p_thres |
Numeric. Probability threshold for multi-label classification in
|
transpose_input |
Logical. Whether to transpose the input matrix. Set to
|
gene_file |
Character. Path to a file with genes (one per line) corresponding
to rows of the input matrix. Default: |
cell_file |
Character. Path to a file with cells (one per line) corresponding
to columns of the input matrix. Default: |
over_clustering |
Character or vector. Over-clustering specification used for
majority voting: (1) path to a plain file with one cluster ID per line;
(2) metadata column name in AnnData; (3) vector/array of cluster assignments;
or (4) omitted for the heuristic approach. Ignored when
|
use_GPU |
Logical. Whether to use GPU acceleration (via rapids-singlecell)
for over-clustering. Only relevant when |
min_prop |
Numeric. Minimum proportion of the dominant cell type required to
name a subcluster; subclusters below the threshold are labeled |
verbose |
Logical. Whether to print progress messages during annotation.
Default: |
assay |
which Seurat assay to use |
The input Seurat object with prediction results added:
cell type labels are stored as new columns in meta.data (prefixed with
celltypist_), and the scoring matrices are stored in misc$celltypist.
Column names may vary slightly depending on the CellTypist version and options used.
SingleCellExperiment and ScreenMethodResult inputs are annotated as
Seurat objects and returned as such.
R packages: reticulate, AnnDataR
Python packages: celltypist, scanpy, anndata
A working Python environment discoverable by reticulate
Other Single_Cell_Annotation_Method:
DownloadCellTypistModels(),
ListCellTypistModels(),
RegisterAnnoMethod(),
SCAnnotateStrategy,
SingleRAnnotate(),
mLLMCelltypeAnnotate()
## Not run: # Use a built-in immune model with majority voting annotated <- CellTypistAnnotate( sc = seurat_obj, model = "Immune_All_Low", majority_voting = TRUE ) # Probability-based multi-label annotation annotated <- CellTypistAnnotate( sc = seurat_obj, model = "Immune_All_Low", mode = "prob match", p_thres = 0.5 ) # Use a local model file annotated <- CellTypistAnnotate( sc = seurat_obj, model = "/path/to/My_Model.pkl" ) ## End(Not run)## Not run: # Use a built-in immune model with majority voting annotated <- CellTypistAnnotate( sc = seurat_obj, model = "Immune_All_Low", majority_voting = TRUE ) # Probability-based multi-label annotation annotated <- CellTypistAnnotate( sc = seurat_obj, model = "Immune_All_Low", mode = "prob match", p_thres = 0.5 ) # Use a local model file annotated <- CellTypistAnnotate( sc = seurat_obj, model = "/path/to/My_Model.pkl" ) ## End(Not run)
Validates whether the cached configuration matches the current parameters. This function reads a cache metadata JSON file and compares it with the provided screen method, phenotype class, label type, and parameters.
CheckCache(cache_config, ...)CheckCache(cache_config, ...)
cache_config |
A |
... |
Additional arguments to be passed to the method: For
|
The function compares each field in the current configuration against the cached metadata. If any field differs (method name, method version, phenotype class, label type, or parameters), the function aborts with a formatted error message showing which parameter differs and both the provided and actual values.
Invisible TRUE if the cache configuration is consistent with
the current parameters. Otherwise, aborts with an error message
displaying the differences.
CheckCache is an S7 generic with methods available for the following
classes:
ANY
SigBridgeR::ScreenMethodCache
SigBridgeR::ScreenMethodConfig
Other cache_config:
CacheSetHere(),
CacheSysCall(),
ChooseCache(),
LoadCache(),
WriteCache(),
WriteCacheMeta()
## Not run: # Check cache consistency for a ScreenMethodConfig config <- ScreenMethodConfig( method_name = "Scissor", param = list(alpha = 0.05) ) CheckCache(config, path = "cache/cache_config.json") # Check using a ScreenMethodCache object cache <- ScreenMethodCache( cache_path = "cache/", cache_config_path = "cache/cache_config.json", cache_data = list(), screen_method_config = config ) CheckCache(cache) ## End(Not run)## Not run: # Check cache consistency for a ScreenMethodConfig config <- ScreenMethodConfig( method_name = "Scissor", param = list(alpha = 0.05) ) CheckCache(config, path = "cache/cache_config.json") # Check using a ScreenMethodCache object cache <- ScreenMethodCache( cache_path = "cache/", cache_config_path = "cache/cache_config.json", cache_data = list(), screen_method_config = config ) CheckCache(cache) ## End(Not run)
Identifies and reports the presence of missing values (NA) in vectors or two-dimensional data structures. Provides detailed positional information including row/column indices and names when available. Returns structured information for programmatic use while displaying user-friendly messages.
CheckNA(data, max_print = 5L, ...)CheckNA(data, max_print = 5L, ...)
data |
A vector, matrix, data frame, or Matrix object to check for NA values. |
max_print |
Integer. Maximum number of NA positions to display in console output.
Set to |
... |
Additional arguments (currently unused, reserved for future extensions). |
Invisible list containing NA information:
count: Total number of NA values found
positions: For vectors: integer vector of positions; For 2D data:
data frame with row/column indices and names (if available)
names: For named vectors: character vector of names corresponding to NA positions
Returns empty list components when no NA values are found.
No NAs found: Prints success message and returns empty list
NAs found: Prints warning with count and up to max_print positions
Position details: Includes row/column names when available for easier debugging
is.na, complete.cases, na.omit
## Not run: # Example 1: Vector with NAs vec <- c(10, 20, NA, 40, NA, 60) result <- CheckNA(vec) # Output: Found 2 NA values # Positions: 3, 5 # Example 2: Named vector named_vec <- c(Sample1 = 10, Sample2 = NA, Sample3 = 30, Sample4 = NA) result <- CheckNA(named_vec) # Output: Found 2 NA values # Positions: 2, 4 # with names: Sample2, Sample4 # Example 3: Data frame with row and column names df <- data.frame( Gene1 = c(1.0, 2.0, NA), Gene2 = c(NA, 2.5, 3.0), Gene3 = c(1.5, NA, 3.5), row.names = c("Cell1", "Cell2", "Cell3") ) result <- CheckNA(df) # Output: Found 3 NA values in data # First 3 positions: # Row 3 (Cell3), Col 1 (Gene1) # Row 1 (Cell1), Col 2 (Gene2) # Row 2 (Cell2), Col 3 (Gene3) # Example 4: Matrix without names mat <- matrix(c(1, NA, 3, 4, 5, NA), nrow = 2, ncol = 3) result <- CheckNA(mat) # Output: Found 2 NA values in data # First 2 positions: # Row 2, Col 1 # Row 1, Col 3 # Example 5: No NAs found clean_data <- c(1, 2, 3, 4, 5) result <- CheckNA(clean_data) # Output: No NA values found in the vector # Example 6: Programmatic use - extract NA count df <- data.frame(a = c(1, NA, 3), b = c(NA, 2, 3)) na_info <- CheckNA(df) na_info$count # Returns: 2 na_info$positions # Returns: data frame with positions ## End(Not run)## Not run: # Example 1: Vector with NAs vec <- c(10, 20, NA, 40, NA, 60) result <- CheckNA(vec) # Output: Found 2 NA values # Positions: 3, 5 # Example 2: Named vector named_vec <- c(Sample1 = 10, Sample2 = NA, Sample3 = 30, Sample4 = NA) result <- CheckNA(named_vec) # Output: Found 2 NA values # Positions: 2, 4 # with names: Sample2, Sample4 # Example 3: Data frame with row and column names df <- data.frame( Gene1 = c(1.0, 2.0, NA), Gene2 = c(NA, 2.5, 3.0), Gene3 = c(1.5, NA, 3.5), row.names = c("Cell1", "Cell2", "Cell3") ) result <- CheckNA(df) # Output: Found 3 NA values in data # First 3 positions: # Row 3 (Cell3), Col 1 (Gene1) # Row 1 (Cell1), Col 2 (Gene2) # Row 2 (Cell2), Col 3 (Gene3) # Example 4: Matrix without names mat <- matrix(c(1, NA, 3, 4, 5, NA), nrow = 2, ncol = 3) result <- CheckNA(mat) # Output: Found 2 NA values in data # First 2 positions: # Row 2, Col 1 # Row 1, Col 3 # Example 5: No NAs found clean_data <- c(1, 2, 3, 4, 5) result <- CheckNA(clean_data) # Output: No NA values found in the vector # Example 6: Programmatic use - extract NA count df <- data.frame(a = c(1, NA, 3), b = c(NA, 2, 3)) na_info <- CheckNA(df) na_info$count # Returns: 2 na_info$positions # Returns: data frame with positions ## End(Not run)
Selects a cache directory from the specified path. If only one cache subdirectory exists, it is returned automatically; if multiple are found, an interactive menu is presented for the user to choose.
ChooseCache(directory)ChooseCache(directory)
directory |
|
The function expects the parent directory name to follow the convention
{method_name}_res (e.g., "Scissor_res", "scPAS_res"). It validates
the directory name against the registered screening methods in
ScreenStrategy.
If no cache subdirectories are found, the function aborts with an error.
If exactly one subdirectory exists, it is returned without prompting.
If multiple subdirectories exist, utils::menu() is used to present an
interactive selection menu.
A character string: the path to the selected cache directory.
Other cache_config:
CacheSetHere(),
CacheSysCall(),
CheckCache(),
LoadCache(),
WriteCache(),
WriteCacheMeta()
## Not run: cache_path <- ChooseCache("./Scissor_res") ## End(Not run)## Not run: cache_path <- ChooseCache("./Scissor_res") ## End(Not run)
A quantitative framework for selecting optimal normalization strategies (e.g., SCTransform vs. LogNormalization) based on diagnostic metrics rather than heuristics. Evaluates three critical dimensions of preprocessing quality:
Variance stabilization: Decoupling of mean-variance relationship in normalized expression (lower correlation = better).
Biological signal retention: Preservation of known marker genes within highly variable genes (higher retention = better).
Dropout robustness: Removal of technical dropout bias from normalized values (lower correlation with dropout rate = better).
Methods are ranked using a weighted composite score. Designed for head-to-head comparison of preprocessed Seurat objects.
ChooseNormalization( ..., subset_size = integer(), known_hvgs = list(), n_hvgs = 2000L, low_expressed_thresh = 0.2, weight = c(variance_stability = 0.4, marker_signal = 0.35, dropout_robustness = 0.25), verbose = getFuncOption("verbose"), seed = getFuncOption("seed") )ChooseNormalization( ..., subset_size = integer(), known_hvgs = list(), n_hvgs = 2000L, low_expressed_thresh = 0.2, weight = c(variance_stability = 0.4, marker_signal = 0.35, dropout_robustness = 0.25), verbose = getFuncOption("verbose"), seed = getFuncOption("seed") )
... |
Named arguments where each value is a
|
subset_size |
Integer. Number of cells to subsample for diagnostics.
If missing or empty, defaults to |
known_hvgs |
Named list of canonical marker genes for cell types. Format:
|
n_hvgs |
Integer. Number of top highly variable genes to evaluate for marker
retention. Default: |
low_expressed_thresh |
Numeric (0-1). Quantile threshold for filtering lowly
expressed genes during variance-mean correlation calculation. Genes below this
quantile of mean expression are excluded. Default: |
weight |
Named numeric vector specifying weights for composite scoring. Must contain exactly these components summing to 1:
|
verbose |
Logical. Whether to print progress messages. |
seed |
Integer. Seed for reproducible random sampling. |
A list containing:
metrics: A data.table with diagnostic metrics per method:
variance_mean_cor: Pearson correlation between log10(mean) and
log10(variance) of normalized expression (lower = better)
marker_retention: Proportion of known markers in top HVGs
(higher = better; NA if known_hvgs not provided)
mean_dropout_residual: Absolute Spearman correlation between
dropout rate (from counts) and normalized means (lower = better)
composite_score: Weighted combination of normalized metrics (0-1 scale)
rank: Method ranking (1 = best)
recommendation: Character string naming the top-ranked method
plots: (Optional) Diagnostic visualizations if ggplot2 available
Validates input objects (naming, cell count consistency, data slot presence)
Subsamples cells (if needed) for computational efficiency
Computes three core metrics per method:
Variance stabilization: Correlation between log-transformed mean and variance of normalized expression
Marker retention: Overlap between user-provided markers and top HVGs
Dropout robustness: Correlation between gene dropout rate (from counts) and normalized expression means
Normalizes metrics to 0-1 scale (inverting where lower=better)
Computes weighted composite score and ranks methods
Returns top recommendation with full diagnostic report
Requires pre-normalized Seurat objects-this function does not
perform normalization itself. Users must first run SCTransform(),
NormalizeData(), etc., and store results in the data slot.
Marker retention metric is only computed when known_hvgs is provided.
Without it, scoring relies solely on variance stabilization and dropout robustness.
Weights should sum to 1 (not enforced but recommended for interpretable scores).
## Not run: # Compare two preprocessed Seurat objects sct_obj <- SCTransform(seurat_raw, verbose = FALSE) log_obj <- NormalizeData(seurat_raw, normalization.method = "LogNormalize") result <- ChooseNormalization( SCT = sct_obj, Log = log_obj, subset_size = 5000, verbose = TRUE ) # Top recommendation result$recommendation # Full metrics table result$metrics[, .(method, composite_score, rank)] # With marker genes for refined scoring markers <- list( T_cell = c("CD3D", "CD3E", "CD8A"), B_cell = c("CD79A", "MS4A1", "CD19"), Myeloid = c("CD14", "LYZ", "FCGR3A") ) result <- ChooseNormalization( SCT = sct_obj, Log = log_obj, known_hvgs = markers, weight = c(variance_stability = 0.3, marker_signal = 0.5, dropout_robustness = 0.2) ) ## End(Not run)## Not run: # Compare two preprocessed Seurat objects sct_obj <- SCTransform(seurat_raw, verbose = FALSE) log_obj <- NormalizeData(seurat_raw, normalization.method = "LogNormalize") result <- ChooseNormalization( SCT = sct_obj, Log = log_obj, subset_size = 5000, verbose = TRUE ) # Top recommendation result$recommendation # Full metrics table result$metrics[, .(method, composite_score, rank)] # With marker genes for refined scoring markers <- list( T_cell = c("CD3D", "CD3E", "CD8A"), B_cell = c("CD79A", "MS4A1", "CD19"), Myeloid = c("CD14", "LYZ", "FCGR3A") ) result <- ChooseNormalization( SCT = sct_obj, Log = log_obj, known_hvgs = markers, weight = c(variance_stability = 0.3, marker_signal = 0.5, dropout_robustness = 0.2) ) ## End(Not run)
Convert bulk RNA-seq raw counts to TPM
CountsToTPM(counts, gene_length)CountsToTPM(counts, gene_length)
counts |
A base matrix or Matrix object. Rows are genes, columns are samples. |
gene_length |
A named numeric vector or named list. Names are gene IDs, values are gene lengths in bp. |
TPM matrix. Base matrix input returns base matrix; Matrix input returns Matrix object.
## Not run: # Create a counts matrix (3 genes x 2 samples) counts <- matrix( c(100, 200, 300, 150, 250, 350), nrow = 3, ncol = 2, dimnames = list(c("GENE1", "GENE2", "GENE3"), c("Sample1", "Sample2")) ) # Gene lengths in bp (must be named and match rownames) gene_length <- c(GENE1 = 1000, GENE2 = 2000, GENE3 = 1500) # Convert counts to TPM tpm <- CountsToTPM(counts, gene_length) colSums(tpm) # Each column should sum to 1e6 # Also works with sparse matrices (dgCMatrix) sparse_counts <- Matrix::Matrix(counts, sparse = TRUE) tpm_sparse <- CountsToTPM(sparse_counts, gene_length) ## End(Not run)## Not run: # Create a counts matrix (3 genes x 2 samples) counts <- matrix( c(100, 200, 300, 150, 250, 350), nrow = 3, ncol = 2, dimnames = list(c("GENE1", "GENE2", "GENE3"), c("Sample1", "Sample2")) ) # Gene lengths in bp (must be named and match rownames) gene_length <- c(GENE1 = 1000, GENE2 = 2000, GENE3 = 1500) # Convert counts to TPM tpm <- CountsToTPM(counts, gene_length) colSums(tpm) # Each column should sum to 1e6 # Also works with sparse matrices (dgCMatrix) sparse_counts <- Matrix::Matrix(counts, sparse = TRUE) tpm_sparse <- CountsToTPM(sparse_counts, gene_length) ## End(Not run)
This function performs DEGAS to integrate single-cell and bulk RNA-seq data, identifying phenotype-associated cells using a bootstrap aggregated multi-task learning approach.
DoDEGAS( select_fraction = 0.05, min_thresh = 0.4, matched_bulk, sc_data, phenotype = NULL, sc_data.pheno_colname = NULL, label_type = "DEGAS", phenotype_class = c("binary", "continuous", "survival"), tmp_dir = "DEGAS_res", env_params = lifecycle::deprecated(), degas_params = list(), normality_test_method = "jarque-bera", ... )DoDEGAS( select_fraction = 0.05, min_thresh = 0.4, matched_bulk, sc_data, phenotype = NULL, sc_data.pheno_colname = NULL, label_type = "DEGAS", phenotype_class = c("binary", "continuous", "survival"), tmp_dir = "DEGAS_res", env_params = lifecycle::deprecated(), degas_params = list(), normality_test_method = "jarque-bera", ... )
select_fraction |
The top percentage of selected cells will be considered as Positive cells, without considering how much larger the possible correlation coefficient of the observation group is compared to that of the control group. Only usedl when |
min_thresh |
DEGAS will calculate the possible correlation coefficients for each cell related to the phenotype. When the coefficient of the observation group is at least |
matched_bulk |
Bulk RNA-seq data as matrix or data.frame (rows=genes, columns=samples) |
sc_data |
Single-cell data as Seurat object containing RNA assay |
phenotype |
Bulk-level phenotype data. For classification: binary matrix with one-hot encoding. For survival: matrix with two columns (time and event status). Can be NULL, matrix, data.frame, or vector. |
sc_data.pheno_colname |
Column name for single-cell phenotype in metadata (if available), default: |
label_type |
Label type for DEGAS results (default: " |
phenotype_class |
Type of phenotype: "binary" (classification), "continuous", or "survival" |
tmp_dir |
(Soft-deprecated) Temporary directory for DEGAS intermediate
files (default: |
env_params |
|
degas_params |
List of DEGAS algorithm parameters including:
|
normality_test_method |
Method for normality testing: "jarque-bera", "d'agostino", or "kolmogorov-smirnov" |
... |
Additional arguments. Currently supports:
|
The function performs the following steps:
Validates input data and parameters
Sets up Python environment with required dependencies
Trains bootstrap aggregated DEGAS model using runCCMTLBag
Generates cell-level predictions using predClassBag
Applies statistical testing to identify phenotype-associated cells
Labels cells as "Positive" or "Other" based on selection criteria
Model type is automatically determined:
BlankClass: only bulk phenotype specified (scLab = NULL)
ClassBlank: only single-cell phenotype specified (patLab = NULL)
ClassClass: both single-cell and bulk phenotypes specified
ClassCox: single-cell phenotype + bulk survival data
BlankCox: only bulk survival data specified
A list containing:
scRNA_data: Seurat object with DEGAS labels added to metadata
model: The model trained using the input data, andit can be used for cell classification prediction.
DEGAS_prediction: Data table with DEGAS predictions containing:
Predicted label probabilities for each cell
Cell labels ("Positive"/"Other") based on selection criteria
Difference scores for binary phenotypes
Cell identifiers
Johnson TS, Yu CY, Huang Z, Xu S, Wang T, Dong C, et al. Diagnostic Evidence GAuge of Single cells (DEGAS): a flexible deep transfer learning framework for prioritizing cells in relation to disease. Genome Med. 2022 Feb 1;14(1):11.
Other screen_method:
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
Other DEGAS:
DEGASEnvSet(),
DEGASModelDetect(),
DEGASParamSet(),
TrainDEGASModel(),
ValidateDEGASParams()
## Not run: # Binary classification example result <- DoDEGAS( select_fraction = 0.05, # `select_fraction` only used in binary and survival phenotyping matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = bulk_phenotype, phenotype_class = "binary" ) # Survival analysis example result <- DoDEGAS( select_fraction = 0.05, # `select_fraction` only used in binary and survival phenotyping matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = survival_data, phenotype_class = "survival" ) ## End(Not run)## Not run: # Binary classification example result <- DoDEGAS( select_fraction = 0.05, # `select_fraction` only used in binary and survival phenotyping matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = bulk_phenotype, phenotype_class = "binary" ) # Survival analysis example result <- DoDEGAS( select_fraction = 0.05, # `select_fraction` only used in binary and survival phenotyping matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = survival_data, phenotype_class = "survival" ) ## End(Not run)
Screen Function Template
DoDEGASv2( matched_bulk, sc_data, phenotype, label_type = NULL, phenotype_class = c("binary", "survival", "continuous"), top_fraction_pos = 0.2, sclab = NULL, bulk_hvg = TRUE, bulk_de = TRUE, sc_de = TRUE, add_genes = NULL, n_hvg = 250L, n_bulk_de = 250L, n_sc_de = 200L, padj.thresh = 0.05, only.pos = FALSE, min.pct = 0.25, logfc.threshold = 0.25, n_st_classes = length(unique(sc_data$seurat_clusters)), loss_type = c("cross_entropy", "log_neg", "rank_loss"), transfer_type = c("Wasserstein", "MMD"), model_save_dir = "DEGASv2_res", lambda1 = 1L, lambda2 = 3L, lambda3 = 3L, tot_seeds = 10L, tot_iters = 300L, extract_embs = FALSE, random_feat = FALSE, random_perc = 0.8, early_stopping = FALSE, ... )DoDEGASv2( matched_bulk, sc_data, phenotype, label_type = NULL, phenotype_class = c("binary", "survival", "continuous"), top_fraction_pos = 0.2, sclab = NULL, bulk_hvg = TRUE, bulk_de = TRUE, sc_de = TRUE, add_genes = NULL, n_hvg = 250L, n_bulk_de = 250L, n_sc_de = 200L, padj.thresh = 0.05, only.pos = FALSE, min.pct = 0.25, logfc.threshold = 0.25, n_st_classes = length(unique(sc_data$seurat_clusters)), loss_type = c("cross_entropy", "log_neg", "rank_loss"), transfer_type = c("Wasserstein", "MMD"), model_save_dir = "DEGASv2_res", lambda1 = 1L, lambda2 = 3L, lambda3 = 3L, tot_seeds = 10L, tot_iters = 300L, extract_embs = FALSE, random_feat = FALSE, random_perc = 0.8, early_stopping = FALSE, ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression
data (genes x samples). Column names must match names/IDs in |
sc_data |
A matrix/Matrix (genes x cells) or a Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type |
phenotype_class |
Type of phenotypic outcome (must be consistent with input data):
|
top_fraction_pos |
Proportion of cells to be labelled as |
sclab |
Metadata for scRNA-seq e.g. cell type, clusters (required), default = NULL |
bulk_hvg |
Whether user wants to use sample (bulk) level high variable genes as input in DEGAS. Default is |
bulk_de |
Whether user wants to use sample (bulk) differential expression genes for phenotype using DEseq2, commonly set Normal or Control as reference. Default is |
sc_de |
Whether user wants to use single cell differential expression genes for each cluster. Default is |
add_genes |
The user decides whether to add their own gene list by preference. If the user set bulk_hvg, bulk_de and sc_de as FALSE, this gene list is necessary. Default is |
n_hvg |
Number of bulk high variable genes, default = 250. |
n_bulk_de |
Number of bulk differential expression genes for phenotype, default = 250. |
n_sc_de |
Number of genes for each single cell clusters, default = 200. |
padj.thresh |
Threshold for differential expression analysis, default = 0.05 |
only.pos |
Only return positive markers (FALSE by default) |
min.pct |
only test genes that are detected in a minimum fraction of min.pct cells in either of the two populations. Meant to speed up the function by not testing genes that are very infrequently expressed. Default is 0.01 |
logfc.threshold |
Limit testing to genes which show, on average, at least
X-fold difference (log-scale) between the two groups of cells. Default is 0.1
Increasing logfc.threshold speeds up the function, but can miss weaker signals.
If the |
n_st_classes |
Integer specifying the number of distinct single-cell/spatial
labels (cell types, clusters, or spatial annotations). This defines the output
dimension of the high-resolution (single-cell/spatial) branch, and is passed to
the Python backend as |
loss_type |
String specifying the loss function used for training the low-resolution (patient) branch.
Typically, classification models use |
transfer_type |
String indicating the cross-domain alignment method.
The backend currently supports |
model_save_dir |
String specifying the output directory for model files. The function will automatically create the directory if it does not exist and will save configuration files, prediction results, and optionally embedding vectors for each submodel. |
lambda1 |
Numeric value, a weighting coefficient that controls the contribution
of the high-resolution branch (single-cell/spatial supervision loss).
Only applicable to models with the |
lambda2 |
Numeric value, a weighting coefficient that controls the loss strength for the low-resolution (patient) branch. This parameter applies to all model types. Default = 2. |
lambda3 |
Numeric value, a weighting coefficient that controls
the contribution of the domain-alignment (transfer) loss.
Works jointly with |
tot_seeds |
Integer specifying the number of bagging iterations. Default = 10. |
tot_iters |
Integer specifying the total number of training iterations (epochs). |
extract_embs |
Logical value. If |
random_feat |
Logical value. If |
random_perc |
Numeric value between 0 and 1 specifying the proportion of features to retain
when |
early_stopping |
Logical value. A reserved flag for early stopping; |
... |
Additional arguments passed to the function. Common parameters include:
|
A named list containing:
Modified single-cell data object with integrated screening results.
Identifies phenotype-associated cell subpopulations using Lasso-Penalized Sparse Group Lasso (LP-SGL) with Leiden community detection. This method integrates bulk and single-cell RNA-seq data to identify cell subpopulations associated with phenotypic outcomes.
DoLP_SGL( matched_bulk, sc_data, phenotype, label_type = "LP_SGL", phenotype_class = c("binary", "continuous", "survival"), family = lifecycle::deprecated(), resolution = 0.6, alpha = 0.5, nfold = 5L, dge_analysis = list(run = FALSE, logFC_threshold = 1L, pval_threshold = 0.05), ... )DoLP_SGL( matched_bulk, sc_data, phenotype, label_type = "LP_SGL", phenotype_class = c("binary", "continuous", "survival"), family = lifecycle::deprecated(), resolution = 0.6, alpha = 0.5, nfold = 5L, dge_analysis = list(run = FALSE, logFC_threshold = 1L, pval_threshold = 0.05), ... )
A list containing:
scRNA_data: Seurat object with LP-SGL results integrated
sgl_fit: Fitted SGL model object
cvfit: Cross-validation results
dge_res: Differential expression results if requested (NULL otherwise)
Li J, Zhang H, Mu B, Zuo H, Zhou K. Identifying phenotype-associated subpopulations through LP_SGL. Briefings in Bioinformatics. 2023 Nov 22;25(1):bbad424.
Other screen_method:
DoDEGAS(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
Other LP_SGL:
ValidateLPSGLParams()
## Not run: # Example using simulated data set.seed(123) # Create simulated data bulk_data <- matrix(rnorm(1000*50), nrow=1000, ncol=50) sc_data <- matrix(rnorm(1000*500), nrow=1000, ncol=500) phenotype <- rep(c(0, 1), each=25) # Run LP-SGL analysis results <- DoLP_SGL( matched_bulk = bulk_data, sc_data = sc_data, phenotype = phenotype, family = "logit", resolution = 0.6, dge_analysis = list(run = TRUE, logFC_threshold = 1, pval_threshold = 0.05) ) # Access results lpsgl_seurat <- results$scRNA_data sgl_model <- results$sgl_fit deg_results <- results$dge_res ## End(Not run)## Not run: # Example using simulated data set.seed(123) # Create simulated data bulk_data <- matrix(rnorm(1000*50), nrow=1000, ncol=50) sc_data <- matrix(rnorm(1000*500), nrow=1000, ncol=500) phenotype <- rep(c(0, 1), each=25) # Run LP-SGL analysis results <- DoLP_SGL( matched_bulk = bulk_data, sc_data = sc_data, phenotype = phenotype, family = "logit", resolution = 0.6, dge_analysis = list(run = TRUE, logFC_threshold = 1, pval_threshold = 0.05) ) # Access results lpsgl_seurat <- results$scRNA_data sgl_model <- results$sgl_fit deg_results <- results$dge_res ## End(Not run)
Derives a gene-level reference z-score from matched bulk expression and a phenotype (binary, continuous, or survival), then scores single cells and assigns tail phenotype groups via PhenoMapR.
DoPhenoMapR( matched_bulk, sc_data, phenotype, label_type = "PhenoMapR", phenotype_class = c("binary", "survival", "continuous"), phenotype_column = NULL, survival_time = "time", survival_event = "status", normalize = TRUE, platform = c("auto", "rnaseq", "microarray"), probe_annotation = NULL, hugo_species = c("human", "mouse"), binary_positive_reference = c("second", "first"), assay = "RNA", layer = "data", z_score_cutoff = 2L, reference_sign = 1L, score_mode = c("weighted_sum", "activity_adjusted"), vars_to_regress = c("S.Score", "G2M.Score", "nCount_RNA"), cancer_type = NULL, pseudobulk = FALSE, group_by = NULL, sample_metadata = NULL, percentile = 0.05, permutation_n = NULL, permutation_seed = NULL, ..., seed = SigBridgeRUtils::getFuncOption("seed"), verbose = SigBridgeRUtils::getFuncOption("verbose") )DoPhenoMapR( matched_bulk, sc_data, phenotype, label_type = "PhenoMapR", phenotype_class = c("binary", "survival", "continuous"), phenotype_column = NULL, survival_time = "time", survival_event = "status", normalize = TRUE, platform = c("auto", "rnaseq", "microarray"), probe_annotation = NULL, hugo_species = c("human", "mouse"), binary_positive_reference = c("second", "first"), assay = "RNA", layer = "data", z_score_cutoff = 2L, reference_sign = 1L, score_mode = c("weighted_sum", "activity_adjusted"), vars_to_regress = c("S.Score", "G2M.Score", "nCount_RNA"), cancer_type = NULL, pseudobulk = FALSE, group_by = NULL, sample_metadata = NULL, percentile = 0.05, permutation_n = NULL, permutation_seed = NULL, ..., seed = SigBridgeRUtils::getFuncOption("seed"), verbose = SigBridgeRUtils::getFuncOption("verbose") )
matched_bulk |
Matrix or data frame of bulk expression (genes x samples).
Column names must match |
sc_data |
A Seurat object containing the cells to be scored. |
phenotype |
Phenotype data. A named vector for binary/continuous traits,
or a data frame with time-to-event and event columns for survival traits;
names/row names must match |
label_type |
Character. |
phenotype_class |
One of |
phenotype_column |
Character. Column name in |
survival_time |
Character. Column name in |
survival_event |
Character. Column name in |
normalize |
Logical. If |
platform |
One of |
probe_annotation |
Optional data.frame with probe IDs and gene symbols
(required for probe-level microarray matrices unless row names are already
gene symbols). See |
hugo_species |
Character. Species for HUGO symbol cleaning:
|
binary_positive_reference |
For |
assay |
Assay name for Seurat/SCE objects (default: "RNA" for sc, "Spatial" for spatial) |
layer |
Seurat matrix to score ( |
z_score_cutoff |
Absolute z-score threshold for filtering genes
(default: 2). Built-in PRECOG/TCGA matrices shipped in the package are
already sparse at this cutoff (entries with |
reference_sign |
Multiply all reference gene z-scores by this value before
the weighted sum. Use |
score_mode |
Scoring mode: |
vars_to_regress |
Metadata columns to regress when
|
cancer_type |
Cancer type label. Required if using built-in reference datasets. Should match column names in reference data. For ICI PRECOG, use format "ABBREV" or "ABBREV_Metastatic" (e.g., "MELANOMA", "MELANOMA_Metastatic") |
pseudobulk |
Logical. If TRUE, aggregate expression before scoring (default: FALSE) |
group_by |
Column name for pseudobulk grouping. Required if pseudobulk = TRUE. For Seurat/SCE objects, should be a metadata column. |
sample_metadata |
Optional data.frame of per-cell/sample covariates for
|
percentile |
Fraction of cells in each tail (default 0.05 for top and bottom 5%). |
permutation_n |
If a positive integer, compute gene-shuffle permutation
null scores and add |
permutation_seed |
Random seed for permutation null (default |
... |
Additional arguments reserved for method compatibility. |
seed |
Integer. Random seed. Default: |
verbose |
Logical. Whether to print progress messages.
Default: |
define_phenotype_groups() labels the upper tail of the score distribution
"Most Adverse" and the lower tail "Most Favorable". The score increases
towards the phenotype-valued-as-1 end when the reference is derived with the
default orientation (for a numeric 0/1 phenotype,
binary_positive_reference = "second" regresses on the "1" level, and for
survival traits the Cox z-score is positive for hazard-increasing genes).
Therefore, when phenotype 1 denotes the unfavourable direction, the
"Most Adverse" tail is the one to be labelled "Positive"; the group
labels are mapped to the package-wide vocabulary as
"Most Adverse" -> "Positive", "Most Favorable" -> "Negative" and
"Other" -> "Neutral". Setting reference_sign = -1 mirrors the score axis,
in which case the two tails swap. If a phenotype is encoded so that the
adverse class is not the reference-positive level (e.g.
binary_positive_reference = "first" with numeric 0/1 labels), the
score direction is reversed as well; choose the arguments so that higher
scores track the adverse phenotype.
A list containing:
scRNA_data: Seurat object with label_type ("Positive",
"Negative", "Neutral", or NA) and a PhenoMapR_* score column in
meta.data.
phenomap_scores: Per-cell scores from PhenoMap.
reference: Gene-level reference z-scores.
PhenoMapR: mapping phenotypic information from bulk to single-cell data. https://github.com/brooksbenard/PhenoMapR
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
Other PhenoMapR:
ValidatePhenoMapRParams()
## Not run: res <- DoPhenoMapR( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = a_named_vector, label_type = "PhenoMapR", phenotype_class = "binary" ) ## End(Not run)## Not run: res <- DoPhenoMapR( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = a_named_vector, label_type = "PhenoMapR", phenotype_class = "binary" ) ## End(Not run)
Predicts cell subpopulations in single-cell data by matching expression profiles to predefined marker gene templates using various distance/similarity metrics. This function implements a template-based classification approach with permutation testing for significance assessment.
DoPIPET( matched_bulk, sc_data, phenotype, phenotype_class = c("binary", "continuous", "survival"), only_pos_marker = FALSE, group = NULL, discretize_method = c("kmeans", "median", "custom"), cutoff = NULL, label_type = "PIPET", marker_finder = c("limma", "DESeq2"), log2FC = 1L, p_adjust = 0.05, show_log2FC = TRUE, freq_counts = NULL, normalize = TRUE, scale = TRUE, nPerm = 1000L, distance = c("cosine", "pearson", "spearman", "kendall", "euclidean", "maximum"), ... )DoPIPET( matched_bulk, sc_data, phenotype, phenotype_class = c("binary", "continuous", "survival"), only_pos_marker = FALSE, group = NULL, discretize_method = c("kmeans", "median", "custom"), cutoff = NULL, label_type = "PIPET", marker_finder = c("limma", "DESeq2"), log2FC = 1L, p_adjust = 0.05, show_log2FC = TRUE, freq_counts = NULL, normalize = TRUE, scale = TRUE, nPerm = 1000L, distance = c("cosine", "pearson", "spearman", "kendall", "euclidean", "maximum"), ... )
matched_bulk |
Normalized bulk expression matrix (features x samples).
Column names must match |
sc_data |
Seurat object containing single-cell RNA-seq data. |
phenotype |
Clinical outcome data. Can be:
|
phenotype_class |
Analysis mode:
|
only_pos_marker |
A logical value. If |
group |
A character, name of one metadata column to group cells by (for example, orig.ident). The default value is |
discretize_method |
|
cutoff |
Numeric vector of length |
label_type |
Character specifying phenotype label type (e.g., "SBS1", "time"), stored in |
marker_finder |
A character, the marker finder method. The default value is |
log2FC |
In the DESeq differential expression analysis results, the cutoff value of log2FC. The default value is |
p_adjust |
In the DESeq differential expression analysis results, the cutoff value of adjust P. The default value is |
show_log2FC |
Select whether to show log2 fold changes. The default value is |
freq_counts |
An integer, keep genes expressed in more than a certain number of cells. The default value is |
normalize |
Select whether to perform normalization of count data. The default value is |
scale |
Select whether to scale and center features in the dataset. The default value is |
nPerm |
An integer, number of permutations to do. The default value is |
distance |
A character, the distance algorithm must be included in "cosine", "pearson", "spearman", "kendall","euclidean","maximum". default value is |
... |
Additional arguments to be passed to
|
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
Other PIPET:
ValidatePIPETParams()
Implements the scAB algorithm to identify phenotype-associated cell subpopulations in single-cell RNA-seq data by integrating matched bulk expression and phenotype information. Uses non-negative matrix factorization (NMF) with dual regularization for phenotype association and cell-cell similarity.
DoscAB( matched_bulk, sc_data, phenotype, label_type = "scAB", phenotype_class = c("binary", "survival"), alpha = c(0.005, NULL), alpha_2 = c(0.005, NULL), k_max = 20L, cross_k = 5L, repeat_times = 10L, maxiter = 2000L, tred = 2L, ... )DoscAB( matched_bulk, sc_data, phenotype, label_type = "scAB", phenotype_class = c("binary", "survival"), alpha = c(0.005, NULL), alpha_2 = c(0.005, NULL), k_max = 20L, cross_k = 5L, repeat_times = 10L, maxiter = 2000L, tred = 2L, ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression data (genes x samples). Column names must match names/IDs in phenotype. |
sc_data |
A Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type, e.g. "SBS1" or "time". |
phenotype_class |
Type of phenotypic outcome. Must be consistent with input data:
|
alpha |
Coefficient of phenotype regularization (default= |
alpha_2 |
Coefficent of cell-cell similarity regularization (default= |
k_max |
The maximum rank value to consider in the search. Must be at least 2. Defaults to |
cross_k |
Number of folds for k-fold cross-validation. Defaults to |
repeat_times |
The number of repeated NMF runs for each candidate rank to account for random initialization variability. Defaults to |
maxiter |
Maximum number of iterations for NMF (default=2000). |
tred |
Z-score threshold in finding subsets (default=2). |
... |
Additional arguments. Currently supports:
|
A list containing:
scRNA_data: Filtered Seurat object with selected cells
scAB_result: scAB screening result
Licensed under the GNU General Public License version 3 (GPL-3.0). A copy of the license is available at https://www.gnu.org/licenses/gpl-3.0.en.html.
Zhang Q, Jin S, Zou X. scAB detects multiresolution cell states with clinical significance by integrating single-cell genomics and bulk sequencing data. Nucleic Acids Research. 2022 Nov 28;50(21):12112-30.
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscPAS(),
DoscPP()
Other scAB:
ValidatescABParams()
## Not run: # Binary phenotype example result <- DoscAB( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = clinical_df, label_type = "disease_status", phenotype_class = "binary", alpha = 0.005, alpha_2 = 0.005, maxiter = 2000, tred = 2 ) ## End(Not run)## Not run: # Binary phenotype example result <- DoscAB( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = clinical_df, label_type = "disease_status", phenotype_class = "binary", alpha = 0.005, alpha_2 = 0.005, maxiter = 2000, tred = 2 ) ## End(Not run)
Performs single-cell phenotype association analysis using the SCIPAC method. Integrates bulk RNA-seq phenotype information with single-cell transcriptomic data to identify cell populations associated with clinical outcomes.
DoSCIPAC( matched_bulk, sc_data, phenotype, label_type = "SCIPAC", phenotype_class = c("binary", "survival", "continuous"), hvg = 1000L, do_pca_sc = FALSE, n_pc = 60L, sc_batch_col = NULL, resolution = 2L, ela_net_alpha = 0.4, bt_size = 50L, ncore = 7L, ci_alpha = 0.05, nfold = 10L, ... )DoSCIPAC( matched_bulk, sc_data, phenotype, label_type = "SCIPAC", phenotype_class = c("binary", "survival", "continuous"), hvg = 1000L, do_pca_sc = FALSE, n_pc = 60L, sc_batch_col = NULL, resolution = 2L, ela_net_alpha = 0.4, bt_size = 50L, ncore = 7L, ci_alpha = 0.05, nfold = 10L, ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression
data (genes x samples). Column names must match names/IDs in |
sc_data |
A Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character. Context info specifying the screening method identifier.
Default: |
phenotype_class |
Type of phenotypic outcome:
Partial matching is supported. |
hvg |
Integer. Number of highly variable genes to use for preprocessing.
Default: |
do_pca_sc |
Logical. if |
n_pc |
Integer. Number of principal components to use. Default: |
sc_batch_col |
Character or vector. Batch variable for single-cell data.
If character, should be a column name in |
resolution |
Numeric. Clustering resolution for cell type identification.
Higher values produce more clusters. Default: |
ela_net_alpha |
Numeric. Elastic net mixing parameter (0 = ridge, 1 = lasso).
Default: |
bt_size |
Integer. Bootstrap sample size for stability assessment.
Default: |
ncore |
Integer. Number of CPU cores for parallel computation.
Default: |
ci_alpha |
Numeric. Significance level for confidence intervals.
Default: |
nfold |
Integer. Number of folds for cross-validation for regression models. Default: |
... |
Additional arguments (support |
A named list containing:
scRNA_data: Modified Seurat object with SCIPAC screening results
added as metadata columns. Includes association statistics, p-values,
and confidence intervals for each cell cluster.
pca_res: PCA rotation results from SCIPAC::sc.bulk.pca()
cluster_res: Clustering results from SCIPAC::seurat.ct()
Gene overlap: Identifies common genes between scRNA-seq and bulk data
Preprocessing: Selects HVGs and preprocesses both datasets
PCA rotation: Aligns scRNA-seq and bulk data in shared PCA space
Clustering: Identifies cell populations using Seurat clustering
Association testing: Tests cluster-phenotype associations using elastic net regression with bootstrap validation
Result integration: Adds screening results to Seurat object metadata
R package: SCIPAC (install from Exceret/SCIPAC)
Gene symbols must be consistent between scRNA-seq and bulk datasets
Sufficient overlapping genes (typically >100) for reliable rotation
For survival analysis, phenotype must be a data frame with
"time" and "status" columns
Binary phenotypes are automatically converted to factors
Continuous phenotypes use Gaussian family in elastic net regression
Screening parameters are stored in scRNA_data@misc$SCIPAC_params
for reproducibility
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
## Not run: # Example 1: Binary phenotype (case/control) library(SCIPAC) # Prepare data bulk_expr <- matrix(rpois(1000, 10), nrow = 200, ncol = 5) colnames(bulk_expr) <- paste0("Sample", 1:5) rownames(bulk_expr) <- paste0("Gene", 1:200) seurat_obj <- CreateSeuratObject(counts = matrix(rpois(2000, 5), nrow = 200, ncol = 10)) phenotype_binary <- c(Sample1 = 1, Sample2 = 0, Sample3 = 1, Sample4 = 0, Sample5 = 1) # Run SCIPAC screening result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = phenotype_binary, phenotype_class = "binary", hvg = 100, resolution = 1, verbose = TRUE ) # Access results screened_seurat <- result$scRNA_data head(screened_seurat[[]]) # Example 2: Survival analysis survival_data <- data.frame( time = c(12.5, 24.3, 18.7, 36.2, 30.1), status = c(1, 0, 1, 1, 0), row.names = paste0("Sample", 1:5) ) result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = survival_data, phenotype_class = "survival", ela_net_alpha = 0.5, bt_size = 100, ncore = 4 ) # Example 3: Continuous phenotype with custom parameters continuous_pheno <- c(Sample1 = 25.3, Sample2 = 45.7, Sample3 = 38.2, Sample4 = 52.1, Sample5 = 31.8) result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = continuous_pheno, phenotype_class = "continuous", hvg = 500, n_pc = 30, resolution = 2, ela_net_alpha = 0.3, ci_alpha = 0.01, seed = 42 ) # View screening parameters used result$scRNA_data@misc$SCIPAC_params # Example 4: With batch correction seurat_obj$batch_id <- sample(c("Batch1", "Batch2"), ncol(seurat_obj), replace = TRUE) result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = phenotype_binary, phenotype_class = "binary", sc_batch_col = "batch_id", ncore = 8 ) ## End(Not run)## Not run: # Example 1: Binary phenotype (case/control) library(SCIPAC) # Prepare data bulk_expr <- matrix(rpois(1000, 10), nrow = 200, ncol = 5) colnames(bulk_expr) <- paste0("Sample", 1:5) rownames(bulk_expr) <- paste0("Gene", 1:200) seurat_obj <- CreateSeuratObject(counts = matrix(rpois(2000, 5), nrow = 200, ncol = 10)) phenotype_binary <- c(Sample1 = 1, Sample2 = 0, Sample3 = 1, Sample4 = 0, Sample5 = 1) # Run SCIPAC screening result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = phenotype_binary, phenotype_class = "binary", hvg = 100, resolution = 1, verbose = TRUE ) # Access results screened_seurat <- result$scRNA_data head(screened_seurat[[]]) # Example 2: Survival analysis survival_data <- data.frame( time = c(12.5, 24.3, 18.7, 36.2, 30.1), status = c(1, 0, 1, 1, 0), row.names = paste0("Sample", 1:5) ) result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = survival_data, phenotype_class = "survival", ela_net_alpha = 0.5, bt_size = 100, ncore = 4 ) # Example 3: Continuous phenotype with custom parameters continuous_pheno <- c(Sample1 = 25.3, Sample2 = 45.7, Sample3 = 38.2, Sample4 = 52.1, Sample5 = 31.8) result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = continuous_pheno, phenotype_class = "continuous", hvg = 500, n_pc = 30, resolution = 2, ela_net_alpha = 0.3, ci_alpha = 0.01, seed = 42 ) # View screening parameters used result$scRNA_data@misc$SCIPAC_params # Example 4: With batch correction seurat_obj$batch_id <- sample(c("Batch1", "Batch2"), ncol(seurat_obj), replace = TRUE) result <- DoSCIPAC( matched_bulk = bulk_expr, sc_data = seurat_obj, phenotype = phenotype_binary, phenotype_class = "binary", sc_batch_col = "batch_id", ncore = 8 ) ## End(Not run)
Identifies phenotype-associated cell subpopulations in single-cell data using regularized regression on matched bulk expression profiles. Scissor integrates bulk and single-cell RNA-seq data to identify cells that are significantly associated with phenotypic outcomes.
DoScissor( matched_bulk, sc_data, phenotype, label_type = "scissor", phenotype_class = c("binary", "continuous", "survival"), alpha = c(0.05, NULL), cutoff = 0.2, family = lifecycle::deprecated(), reliability_test = list(run = FALSE, n = 10L, nfold = 10L), cell_evaluation = list(run = FALSE, benchmark_data = "path_to_file.RData", FDR_cutoff = 0.05, bootstrap_n = 100L), ... )DoScissor( matched_bulk, sc_data, phenotype, label_type = "scissor", phenotype_class = c("binary", "continuous", "survival"), alpha = c(0.05, NULL), cutoff = 0.2, family = lifecycle::deprecated(), reliability_test = list(run = FALSE, n = 10L, nfold = 10L), cell_evaluation = list(run = FALSE, benchmark_data = "path_to_file.RData", FDR_cutoff = 0.05, bootstrap_n = 100L), ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression data (genes x samples). Column names must match names/IDs in phenotype. |
sc_data |
A Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type, e.g. "SBS1" or "time". |
phenotype_class |
Type of phenotypic outcome. Must be consistent with input data:
|
alpha |
Parameter used to balance the effect of the l1 norm and the network-based penalties. It can be a number or a searching vector. If alpha = NULL, a default searching vector is used. The range of alpha is between 0 and 1. A larger alpha lays more emphasis on the l1 norm. |
cutoff |
(default: |
family |
|
reliability_test |
List controlling reliability testing:
|
cell_evaluation |
List controlling cell evaluation:
|
... |
Additional arguments. Currently supports:
|
A list containing:
scRNA_data: A Seurat object with screened cells containing metadata:
scissor: "Positive"/"Negative"/"Neutral" classification
label_type: Outcome label used
scissor_result: Raw Scissor results
reliability_result: If reliability_test=TRUE, contains:
statistic: A value between 0 and 1
p: p-value of the test statistic
AUC_test_real: 10 values of AUC for real data
AUC_test_back: A list of AUC for background data
cell_evaluation: If cell_evaluation=TRUE, contains:
evaluation_res: A data.frame with some supporting information for each Scissor selected cell
Licensed under the GNU General Public License version 3 (GPL-3.0). A copy of the license is available at https://www.gnu.org/licenses/gpl-3.0.en.html.
Sun D, Guan X, Moran AE, Wu LY, Qian DZ, Schedin P, et al. Identifying phenotype-associated subpopulations by integrating bulk and single-cell sequencing data. Nat Biotechnol. 2022 Apr;40(4):527-38.
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
Other scissor:
DoScissorCellEval(),
DoScissorRelTest(),
ValidateScissorParams()
## Not run: # Binary outcome example res <- DoScissor( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = a_named_vector, family = "binomial" ) ## End(Not run)## Not run: # Binary outcome example res <- DoScissor( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = a_named_vector, family = "binomial" ) ## End(Not run)
This function performs scPAS screening analysis by integrating bulk and single-cell RNA-seq data. It includes data filtering steps and wraps the core scPAS::scPAS function.
DoscPAS( matched_bulk, sc_data, phenotype, label_type = "scPAS", phenotype_class = c("binary", "continuous", "survival"), assay = "RNA", imputation = FALSE, imputation_method = c("KNN", "ALRA"), nfeature = 3000L, alpha = c(0.01, NULL), cutoff = 0.2, network_class = c("SC", "bulk"), family = lifecycle::deprecated(), permutation_times = 2000L, FDR_threshold = 0.05, independent = TRUE, ... )DoscPAS( matched_bulk, sc_data, phenotype, label_type = "scPAS", phenotype_class = c("binary", "continuous", "survival"), assay = "RNA", imputation = FALSE, imputation_method = c("KNN", "ALRA"), nfeature = 3000L, alpha = c(0.01, NULL), cutoff = 0.2, network_class = c("SC", "bulk"), family = lifecycle::deprecated(), permutation_times = 2000L, FDR_threshold = 0.05, independent = TRUE, ... )
A Seurat object from scPAS analysis
Licensed under the GNU General Public License version 3 (GPL-3.0). A copy of the license is available at https://www.gnu.org/licenses/gpl-3.0.en.html.
Xie A, Wang H, Zhao J, Wang Z, Xu J, Xu Y. scPAS: single-cell phenotype-associated subpopulation identifier. Briefings in Bioinformatics. 2024 Nov 22;26(1):bbae655.
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPP()
Other scPAS:
ValidatescPASParams()
This function performs scPP screening on single-cell data using matched bulk data and phenotype information. It supports binary, continuous, and survival phenotype types.
DoscPP( matched_bulk, sc_data, phenotype, label_type = "scPP", phenotype_class = c("binary", "continuous", "survival"), ref_group = 0L, Log2FC_cutoff = 0.585, estimate_cutoff = 0.2, probs = c(0.2, NULL), ... )DoscPP( matched_bulk, sc_data, phenotype, label_type = "scPP", phenotype_class = c("binary", "continuous", "survival"), ref_group = 0L, Log2FC_cutoff = 0.585, estimate_cutoff = 0.2, probs = c(0.2, NULL), ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression data (genes x samples). Column names must match names/IDs in phenotype. |
sc_data |
A Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type, e.g. "SBS1" or "time". |
phenotype_class |
Type of phenotypic outcome. Must be consistent with input data:
|
ref_group |
Reference group or baseline for binary comparisons, e.g. "Normal" for Tumor/Normal studies and 0 for 0/1 case-control studies. (default: 0) |
Log2FC_cutoff |
Minimum log2 fold-change for binary markers (default: 0.585) |
estimate_cutoff |
Effect size threshold for continuous traits (default: 0.2) |
probs |
A numeric value indicating the quantile cutoff for cell classification. This parameter can also be a numeric vector, in which case an optimal threshold will be selected based on the AUC and enrichment score.(default: |
... |
Additional arguments. Currently supports:
|
A list containing:
scRNA_data: Seurat object with added metadata:
ScPP: "Positive"/"Negative"/"Neutral" classification
gene_list: List of genes used for screening
Data Validation: Checks sample alignment between bulk and phenotype data
Marker Selection: Identifies phenotype-associated genes from bulk data
Single-cell Screening: Projects bulk markers onto single-cell data
Cell Classification: Categorizes cells based on phenotype association
WangX-Lab/ScPP [Internet]. [cited 2025 Aug 31]. Available from: https://github.com/WangX-Lab/ScPP
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS()
Other scPP:
ValidatescPPParams()
## Not run: # Binary phenotype analysis res <- DoscPP( matched_bulk = bulk_data, sc_data = seurat_obj, phenotype = ms_data, label_type = "SBS1", phenotype_class = "Binary" ) # Survival analysis surv_res <- DoscPP( sc_data = seurat_obj, matched_bulk = bulk_data, phenotype = surv_df, label_type = "OS_status", phenotype_class = "Survival" ) ## End(Not run)## Not run: # Binary phenotype analysis res <- DoscPP( matched_bulk = bulk_data, sc_data = seurat_obj, phenotype = ms_data, label_type = "SBS1", phenotype_class = "Binary" ) # Survival analysis surv_res <- DoscPP( sc_data = seurat_obj, matched_bulk = bulk_data, phenotype = surv_df, label_type = "OS_status", phenotype_class = "Survival" ) ## End(Not run)
Perform SIDISH Screening Analysis
DoSIDISH( matched_bulk, sc_data, phenotype, label_type = "SIDISH", phenotype_class = "survival", sidish_params = list(), ... )DoSIDISH( matched_bulk, sc_data, phenotype, label_type = "SIDISH", phenotype_class = "survival", sidish_params = list(), ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression
data (genes x samples). Column names must match names/IDs in |
sc_data |
A Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type |
phenotype_class |
Type of phenotypic outcome (must be consistent with input data):
|
sidish_params |
List of SIDISH algorithm parameters including: Preprocessing parameters:
Execution environment:
Phase 1: VAE training parameters:
Phase 2: Deep Cox training parameters:
Training & risk definition parameters:
|
... |
Additional arguments passed to the function. Common parameters include:
|
A named list containing:
scRNA_data: Modified single-cell data object with integrated screening results.
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoScissor(),
DoTiRank(),
DoscAB(),
DoscPAS(),
DoscPP()
Other SIDISH:
SIDISHEnvSet(),
ValidateSIDISHParams()
Integrates single-cell and bulk RNA-seq data using the TiRank deep learning framework to identify phenotype-associated cells. TiRank employs a rank-based approach with neural network models to score and classify cells based on their association with the phenotype of interest.
DoTiRank( matched_bulk, sc_data, phenotype, label_type = "TiRank", phenotype_class = c("binary", "survival", "continuous"), tirank_params = list(validation_proportion = 0.15, sampling_thresh = 0.5, sampling_mode = c("smote", "downsample", "upsample", "tomeklinks"), top_var_genes = 2000L, top_gene_pairs = 1000L, p_value_threshold = 0.05, max_cutoff = 0.8, min_cutoff = -0.8, nhead = 2L, nhid1 = 96L, nhid2 = 8L, n_output = 32L, nlayers = 3L, n_pred = 2L, dropout = 0.5, encoder_type = c("MLP", "Transformer", "DenseNet"), infer_mode = c("SC", "ST"), n_trials = 5L, do_reject = TRUE, tolerance = 0.05), save_path = "./TiRank_res", load_cache = NULL, ... )DoTiRank( matched_bulk, sc_data, phenotype, label_type = "TiRank", phenotype_class = c("binary", "survival", "continuous"), tirank_params = list(validation_proportion = 0.15, sampling_thresh = 0.5, sampling_mode = c("smote", "downsample", "upsample", "tomeklinks"), top_var_genes = 2000L, top_gene_pairs = 1000L, p_value_threshold = 0.05, max_cutoff = 0.8, min_cutoff = -0.8, nhead = 2L, nhid1 = 96L, nhid2 = 8L, n_output = 32L, nlayers = 3L, n_pred = 2L, dropout = 0.5, encoder_type = c("MLP", "Transformer", "DenseNet"), infer_mode = c("SC", "ST"), n_trials = 5L, do_reject = TRUE, tolerance = 0.05), save_path = "./TiRank_res", load_cache = NULL, ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression
data (genes x samples). Column names must match names/IDs in |
sc_data |
A matrix/Matrix (genes x cells) or a Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type (default: |
phenotype_class |
Type of phenotypic outcome (must be consistent with input data):
|
tirank_params |
List of TiRank algorithm parameters: Data preprocessing:
Neural network architecture:
Training:
|
save_path |
(Soft-deprecated) Directory path for saving intermediate and
final results (default: |
load_cache |
(Soft-deprecated) Optional path to cached data (default: |
... |
Additional arguments passed to the function. Common parameters include:
|
The TiRank screening workflow consists of the following steps:
Data preprocessing: Normalizes bulk expression data and validates compatibility with phenotype information.
Expression transfer: Transfers the single-cell expression profile into the TiRank-compatible format.
Validation set generation: Splits bulk data into training and
validation sets according to validation_proportion.
Resampling: Applies the specified sampling strategy to address class imbalance in bulk data.
Cell-cell similarity: Computes cell-cell distance or similarity matrix from single-cell data.
Model training: Trains a TiRank neural network (MLP, Transformer, or DenseNet encoder) using bulk expression and phenotype.
Screening: Applies the trained model to score each cell, producing rank-based predictions with rejection handling.
Label assignment: Classifies cells as "Positive",
"Neutral", or "Negative" based on rank scores.
A named list containing:
scRNA_data: Modified single-cell data object with integrated screening
results added as metadata, including TiRank_Reject, TiRank_Rank_Score,
and TiRank (Positive/Neutral/Negative) columns, plus TiRank_para
and TiRank_type stored in misc slot.
cell_cell_distance: Computed cell-cell similarity/distance matrix.
Other TiRank:
ValidateTiRankParams()
Other screen_method:
DoDEGAS(),
DoLP_SGL(),
DoPIPET(),
DoPhenoMapR(),
DoSCIPAC(),
DoSIDISH(),
DoScissor(),
DoscAB(),
DoscPAS(),
DoscPP()
## Not run: # Binary classification example result <- DoTiRank( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = bulk_phenotype, phenotype_class = "binary", save_path = "./TiRank_res" ) # Survival analysis example result <- DoTiRank( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = survival_data, phenotype_class = "survival", tirank_params = list( encoder_type = "Transformer", n_trials = 3L ), save_path = "./TiRank_survival_res" ) # Access results modified_seurat <- result$scRNA_data head(modified_seurat[[]]) ## End(Not run)## Not run: # Binary classification example result <- DoTiRank( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = bulk_phenotype, phenotype_class = "binary", save_path = "./TiRank_res" ) # Survival analysis example result <- DoTiRank( matched_bulk = bulk_matrix, sc_data = seurat_obj, phenotype = survival_data, phenotype_class = "survival", tirank_params = list( encoder_type = "Transformer", n_trials = 3L ), save_path = "./TiRank_survival_res" ) # Access results modified_seurat <- result$scRNA_data head(modified_seurat[[]]) ## End(Not run)
Downloads CellTypist pre-trained models via the celltypist Python
backend. A single model, multiple models, or all models can be downloaded.
The models are saved to CellTypist's local models directory and can
subsequently be used by CellTypistAnnotate without
re-downloading each time.
To see all available models and their descriptions, see https://github.com/Teichlab/celltypist.
DownloadCellTypistModels(model = NULL, force_update = FALSE)DownloadCellTypistModels(model = NULL, force_update = FALSE)
model |
Character. Name(s) of the CellTypist model(s) to download,
e.g. |
force_update |
Logical. Whether to force re-downloading the CellTypist
model files even when they already exist locally. Default: |
Invisibly NULL. The models are downloaded to the CellTypist models
directory (see models.models_path in the Python backend).
A Python environment with celltypist installed, discoverable by reticulate.
Other Single_Cell_Annotation_Method:
CellTypistAnnotate(),
ListCellTypistModels(),
RegisterAnnoMethod(),
SCAnnotateStrategy,
SingleRAnnotate(),
mLLMCelltypeAnnotate()
## Not run: # Download all CellTypist models DownloadCellTypistModels() # Download a single model DownloadCellTypistModels(model = "Immune_All_Low") # Force re-downloading a specific model DownloadCellTypistModels(model = "Immune_All_Low", force_update = TRUE) ## End(Not run)## Not run: # Download all CellTypist models DownloadCellTypistModels() # Download a single model DownloadCellTypistModels(model = "Immune_All_Low") # Force re-downloading a specific model DownloadCellTypistModels(model = "Immune_All_Low", force_update = TRUE) ## End(Not run)
Performs PCA on transposed bulk expression data and visualizes the first two principal components as a scatter plot with marginal density plots. Optionally overlays batch information as point shapes (up to 4 batches).
The plot is composed via patchwork from:
A top marginal density plot for PC1.
A right marginal density plot for PC2.
A central scatter plot with group-colored ellipses (via ggforce::geom_mark_ellipse()).
DrawBulkPCA(bulk, group, batch = NULL, show_plot = TRUE, ...)DrawBulkPCA(bulk, group, batch = NULL, show_plot = TRUE, ...)
bulk |
A numeric matrix or data frame of bulk expression data (genes x samples). Column names are used as sample identifiers. |
group |
A vector of group labels, one per sample (column of |
batch |
An optional vector of batch labels, one per sample. When
provided, points are additionally shaped by batch (up to 4 batches
supported). Default: |
show_plot |
Logical. If |
... |
Additional arguments (currently unused). |
Invisibly returns the combined patchwork/ggplot object.
Other input_preprocess:
PhenoMap(),
PhenoPreProcess(),
SCPreProcess(),
SymbolConvert()
## Not run: # Small example matrix: 10 genes x 8 samples set.seed(123) bulk <- matrix( rnorm(100 * 80, mean = 10, sd = 2), nrow = 100, ncol = 80, dimnames = list( paste0("Gene", 1:100), paste0("Sample", 1:80) ) ) group <- rep(c("Control", "Treatment"), each = 40) # Basic PCA plot without batch DrawBulkPCA(bulk = bulk, group = group) # PCA plot with batch shapes batch <- rep(c("Batch1", "Batch2"), times = 40) DrawBulkPCA(bulk = bulk, group = group, batch = batch) ## End(Not run)## Not run: # Small example matrix: 10 genes x 8 samples set.seed(123) bulk <- matrix( rnorm(100 * 80, mean = 10, sd = 2), nrow = 100, ncol = 80, dimnames = list( paste0("Gene", 1:100), paste0("Sample", 1:80) ) ) group <- rep(c("Control", "Treatment"), each = 40) # Basic PCA plot without batch DrawBulkPCA(bulk = bulk, group = group) # PCA plot with batch shapes batch <- rep(c("Batch1", "Batch2"), times = 40) DrawBulkPCA(bulk = bulk, group = group, batch = batch) ## End(Not run)
This function combines multiple statistical approaches to automatically determine the optimal number of principal components (PCs) for downstream single-cell analysis. It integrates variance-based heuristics, elbow detection algorithms, and provides comprehensive visualization for result validation.
FindRobustElbow( obj, verbose = SigBridgeRUtils::getFuncOption("verbose") %||% TRUE, ndims = 50L )FindRobustElbow( obj, verbose = SigBridgeRUtils::getFuncOption("verbose") %||% TRUE, ndims = 50L )
obj |
A Seurat object that has PCA computed (after |
verbose |
Logical, if TRUE outputs detailed method results and creates
visualization plot. If |
ndims |
Integer, maximum number of dimensions to consider (default: |
The numerical work is delegated to the C++ routine find_robust_elbow_cpp(),
which receives the PCA cell embeddings as an S4-aware matrix view created by
beachmat::initializeCpp(). Columns are streamed through tatami (see
Rtatami.h), so the embeddings are never coerced into a dense base matrix
and only the requested ndims columns are touched. For each of those PCs the
routine computes the standard deviation, the explained variance, the
percentage of explained variance, and the cumulative percentage, which are
then fed into the six heuristics described below.
The recommended dimension is the second largest value among the following candidates:
cumulative variance above 90\
cumulative variance above 80\
last PC explaining more variance than the mean;
last PC explaining more than two standard deviations of the variance;
maximum second derivative of the variance curve;
largest distance between the variance curve and the chord joining the first and the last PC;
the fixed anchors 10, 15, 20, 25, 30 and 35.
The fixed anchors are independent of the data, so the raw recommendation can
exceed the number of PCs that were actually computed. The final value is
therefore capped at the number of available PCs (i.e. ndims).
When verbose = TRUE and the session is interactive, the per-method
candidates are plotted on top of the variance curve by the internal helper
plot_robust_elbow().
Integer, the recommended number of PCA dimensions for downstream analysis
Other single_cell_preprocess:
FilterTumorCell(),
Pattern2Colname(),
QCPatternDetect(),
RegisterSeuratMethod(),
SCAnnotate(),
SCIntegrate(),
SCPreProcess(),
SCPreProcessStrategy
## Not run: # After running PCA on Seurat object pbmc <- RunPCA(pbmc, npcs = 50) optimal_dims <- FindRobustElbow(pbmc, verbose = TRUE) pbmc <- FindNeighbors(pbmc, dims = 1:optimal_dims) ## End(Not run)## Not run: # After running PCA on Seurat object pbmc <- RunPCA(pbmc, npcs = 50) optimal_dims <- FindRobustElbow(pbmc, verbose = TRUE) pbmc <- FindNeighbors(pbmc, dims = 1:optimal_dims) ## End(Not run)
Converts a gene-level FPKM matrix to TPM (Transcripts Per Million). Because
the per-gene length factor is constant within a sample, the FPKM-to-TPM
transformation requires no gene lengths: each column is scaled so that its
values sum to .
For a given sample, every FPKM value is multiplied by
. Samples whose FPKM column sums to zero
produce a zero column in the result and trigger a warning.
Missing values (NA) are either replaced by zero
(na_as_zero = TRUE, the default) or trigger an error
(na_as_zero = FALSE).
FPKMToTPM(data, na_as_zero = TRUE, verbose = TRUE, ...)FPKMToTPM(data, na_as_zero = TRUE, verbose = TRUE, ...)
data |
A two-dimensional matrix-like object of FPKM values (a base
matrix, a data frame, or an S4 |
na_as_zero |
A logical flag. If |
verbose |
A logical flag. If |
... |
Additional arguments passed to |
A numeric TPM matrix with the same dimensions and dimnames as
data. Each column sums to unless the corresponding FPKM
column sums to zero.
## Not run: # Create an FPKM matrix (3 genes x 2 samples) fpkm <- matrix( c(10, 20, 30, 15, 25, 35), nrow = 3, ncol = 2, dimnames = list(c("GENE1", "GENE2", "GENE3"), c("Sample1", "Sample2")) ) # Convert FPKM to TPM tpm <- FPKMToTPM(fpkm) colSums(tpm) # Each column should sum to 1e6 # Error if missing values are present and na_as_zero = FALSE fpkm_na <- fpkm fpkm_na[1, 1] <- NA tpm2 <- FPKMToTPM(fpkm_na, na_as_zero = FALSE) ## End(Not run)## Not run: # Create an FPKM matrix (3 genes x 2 samples) fpkm <- matrix( c(10, 20, 30, 15, 25, 35), nrow = 3, ncol = 2, dimnames = list(c("GENE1", "GENE2", "GENE3"), c("Sample1", "Sample2")) ) # Convert FPKM to TPM tpm <- FPKMToTPM(fpkm) colSums(tpm) # Each column should sum to 1e6 # Error if missing values are present and na_as_zero = FALSE fpkm_na <- fpkm fpkm_na[1, 1] <- NA tpm2 <- FPKMToTPM(fpkm_na, na_as_zero = FALSE) ## End(Not run)
These functions provide a centralized configuration system for the SigBridgeR package, allowing users to set and retrieve package-specific options with automatic naming conventions.
setFunOption sets one or more configuration options for the SigBridgeR package. Options are automatically prefixed with "SigBridgeR." if not already present, ensuring proper namespace isolation.
getFuncOption retrieves configuration options for the SigBridgeR package. The function automatically handles the "SigBridgeR." prefix, allowing users to reference options with or without the explicit prefix.
checkFuncOption validates configuration options for the SigBridgeR package. This function ensures that all options meet type and value requirements before they are set in the global options.
getFuncOption(option = NULL, default = NULL)getFuncOption(option = NULL, default = NULL)
option |
Character string specifying the option name to check |
default |
The default value to return if the option is not set. Defaults to NULL. |
This function performs the following validations:
Must be single logical values (TRUE/FALSE)
Must be single integer values
Must be a single positive integer value
The function is automatically called by setFuncOption to ensure all configuration options are valid before they are set.
Invisibly returns NULL. The function is called for its side effects of setting package options.
The value of the specified option if it exists, otherwise the provided default value.
No return value. The function throws an error if the value doesn't meet the required specifications for the given option.
verbose: A logical value indicating whether to print verbose messages, defaults to TRUE
timeout: An integer specifying the timeout in seconds for parallel processing, defaults to '180L“
seed: An integer specifying the random seed for reproducible results, defaults to '123L“
nthreads: An integer specifying the number of threads for parallel processing, defaults to '1L“
# Set options with automatic prefixing setFuncOption(verbose = TRUE) # Retrieve options with automatic prefixing getFuncOption("verbose")# Set options with automatic prefixing setFuncOption(verbose = TRUE) # Retrieve options with automatic prefixing getFuncOption("verbose")
An S3 generic that computes per-gene lengths by parsing exon features
from either a GTF/GTF.GZ file or a character vector of GTF lines. The
reported length for each gene is the total merged (non-overlapping) span
of its exons.
The character method accepts two forms of input:
A single-element character vector x is treated as a GTF file path
(optionally gzip-compressed). The file is streamed line-by-line and is
never loaded fully into memory.
A multi-element character vector x is treated as the GTF lines
themselves (e.g. the output of readLines()).
Overlapping or adjacent exon intervals are merged within each (gene_id,
chromosome, strand) group, and the length of the merged span is reported.
Ensembl gene_id version suffixes (e.g. ENSG00000139618.15) are preserved,
so gene identifiers from different annotation builds remain distinct.
By default, exon records on every chromosome are kept. Set
canonical_chr_only = TRUE to restrict the analysis to canonical
chromosomes (autosomes 1-22 and chromosomes X, Y, and MT) and ignore
any other contigs or scaffolds present in the annotation.
GetGeneLength(x, verbose = TRUE, canonical_chr_only = FALSE, ...) ## Default S3 method: GetGeneLength(x, verbose = TRUE, canonical_chr_only = FALSE, ...) ## S3 method for class 'character' GetGeneLength(x, verbose = TRUE, canonical_chr_only = FALSE, ...)GetGeneLength(x, verbose = TRUE, canonical_chr_only = FALSE, ...) ## Default S3 method: GetGeneLength(x, verbose = TRUE, canonical_chr_only = FALSE, ...) ## S3 method for class 'character' GetGeneLength(x, verbose = TRUE, canonical_chr_only = FALSE, ...)
x |
The object to dispatch on:
|
verbose |
A logical flag. If |
canonical_chr_only |
A logical flag. If |
... |
Reserved for future use. |
A named numeric vector of gene lengths, one entry per gene, with
the gene ids as names. An empty (zero-length) named vector is returned
when the input contains no valid exon records.
## Not run: # Gene lengths from a gzip-compressed GTF file lengths <- GetGeneLength("Homo_sapiens.GRCh37.75.gtf.gz") # Gene lengths from GTF lines already read into R x <- readLines("Homo_sapiens.GRCh37.75.gtf.gz") lengths <- GetGeneLength(x) ## End(Not run)## Not run: # Gene lengths from a gzip-compressed GTF file lengths <- GetGeneLength("Homo_sapiens.GRCh37.75.gtf.gz") # Gene lengths from GTF lines already read into R x <- readLines("Homo_sapiens.GRCh37.75.gtf.gz") lengths <- GetGeneLength(x) ## End(Not run)
Lists and optionally inspects the contents of predefined strategy environments
(e.g., ScreenStrategy, SCPreProcessStrategy, AnnotationStrategy).
Returns a summary of registered methods or variables, with optional detailed
introspection of function signatures, body structure, and closure properties.
This utility aids in debugging, validation, and exploration of dynamically registered pipelines-particularly useful when developing or auditing extensible analysis frameworks.
InterceptStrategy( strategy = c("ScreenStrategy", "SCPreProcessStrategy", "SCAnnotateStrategy"), ... )InterceptStrategy( strategy = c("ScreenStrategy", "SCPreProcessStrategy", "SCAnnotateStrategy"), ... )
strategy |
Character/Environment. strategy environment to inspect.
Must be one of: |
... |
Additional arguments (currently unused, reserved for future extension). |
Invisibly returns a tibble
# List all preprocessing steps InterceptStrategy("SCPreProcessStrategy") # Get detailed function metadata for screen methods details <- InterceptStrategy("ScreenStrategy")# List all preprocessing steps InterceptStrategy("SCPreProcessStrategy") # Get detailed function metadata for screen methods details <- InterceptStrategy("ScreenStrategy")
Determines whether a numeric matrix is likely to be a bulk/single-cell RNA-seq raw counts matrix. A matrix is accepted only if it is non-empty, finite, non-negative, integer-like in a sufficiently high proportion, and has a positive library size for every sample. Useful for validating input before running count-based downstream analyses.
IsCountsMatrix( x, verbose = TRUE, integer_tol = 1e-08, min_integer_fraction = 0.95 )IsCountsMatrix( x, verbose = TRUE, integer_tol = 1e-08, min_integer_fraction = 0.95 )
x |
Numeric matrix. Rows are genes, columns are samples. |
verbose |
Logical. Whether to print diagnostic statistics (fractions of
non-negative, integer-like, and zero values, library sizes, and the reason
for rejection) to the console. Default: |
integer_tol |
Numeric in |
min_integer_fraction |
Numeric in |
IsCountsMatrix() rejects a matrix for any of the following reasons:
the matrix is empty;
the matrix contains NA, NaN, or infinite values;
the matrix contains negative values;
the fraction of integer-like values is below min_integer_fraction;
at least one sample (column) has a library size (column sum) <= 0.
When verbose = TRUE, the reason for rejection (or diagnostic statistics on
acceptance) is printed to the console.
A single logical value: TRUE if x is likely a bulk counts
matrix, FALSE otherwise.
# A typical bulk RNA-seq raw counts matrix (genes x samples) counts <- matrix( c(100, 200, 300, 150, 250, 350), nrow = 3, ncol = 2, dimnames = list(c("GENE1", "GENE2", "GENE3"), c("Sample1", "Sample2")) ) IsCountsMatrix(counts) # A log-normalized matrix is not counts IsCountsMatrix(log1p(counts)) # Matrices containing negative values are not counts IsCountsMatrix(counts - 1000) # Inspect diagnostic statistics IsCountsMatrix(counts, verbose = TRUE)# A typical bulk RNA-seq raw counts matrix (genes x samples) counts <- matrix( c(100, 200, 300, 150, 250, 350), nrow = 3, ncol = 2, dimnames = list(c("GENE1", "GENE2", "GENE3"), c("Sample1", "Sample2")) ) IsCountsMatrix(counts) # A log-normalized matrix is not counts IsCountsMatrix(log1p(counts)) # Matrices containing negative values are not counts IsCountsMatrix(counts - 1000) # Inspect diagnostic statistics IsCountsMatrix(counts, verbose = TRUE)
IsSkewedDynamic() tests whether the observed proportion of a specified
target/background value in a vector deviates substantially from an expected
proportion.
The function is designed for detecting highly skewed phenotype-like vectors,
especially binary or discrete vectors where one value represents the
background/control class. If the observed proportion of target differs from
expected_p by more than n_sd standard deviations under a binomial model,
the vector is considered skewed.
Formally, let:
and
The function returns TRUE when:
Otherwise, it returns FALSE.
If x has length zero, the function returns NA.
IsSkewedDynamic(x, target = 0L, expected_p = 0.8, n_sd = 4L)IsSkewedDynamic(x, target = 0L, expected_p = 0.8, n_sd = 4L)
x |
A vector to be tested. Must be numeric, integer, or logical. Missing values are not allowed. |
target |
A single numeric value indicating the target/background value
whose proportion should be evaluated. Default is |
expected_p |
A single numeric value between 0 and 1 indicating the
expected proportion of |
n_sd |
A single integer or numeric value specifying how many standard
deviations away from |
This function assumes the expected occurrence of target follows a binomial
proportion model with probability expected_p. The standard deviation is
computed as:
where n is the length of x.
The check is symmetric: both an unexpectedly high and unexpectedly low
proportion of target are considered skewed.
Internally, the computation is delegated to a C++ implementation via Rcpp for efficiency.
A logical vector of length 1:
TRUE if the observed proportion of target deviates from expected_p
by more than n_sd standard deviations.
FALSE otherwise.
NA if x has length zero.
x must not contain missing values. If any NA is present, the function
throws an error.
x may be one of:
numeric
integer
logical
Other input types are rejected by the underlying C++ implementation.
x1 <- c(rep(0, 80), rep(1, 20)) IsSkewedDynamic(x1) x2 <- c(rep(0, 95), rep(1, 5)) IsSkewedDynamic(x2) x3 <- c(rep(0, 50), rep(1, 50)) IsSkewedDynamic(x3, expected_p = 0.8) IsSkewedDynamic(numeric(0))x1 <- c(rep(0, 80), rep(1, 20)) IsSkewedDynamic(x1) x2 <- c(rep(0, 95), rep(1, 5)) IsSkewedDynamic(x2) x3 <- c(rep(0, 50), rep(1, 50)) IsSkewedDynamic(x3, expected_p = 0.8) IsSkewedDynamic(numeric(0))
Converts an R list into a single character string using the format
"key: value". Named elements use their names as keys, while unnamed
elements use their 1-based positions. Nested lists are converted
recursively and enclosed in parentheses.
This method is registered as list_to_chr, so it is called
automatically when as.character() is applied to a list.
list_to_chr(x)list_to_chr(x)
x |
A list to be converted. |
A character vector of length one.
x <- list(key1 = "val1", key2 = "val2") as.character(x) # "key1: val1, key2: val2" x <- list(key1 = list(key2 = list(key3 = "val3"))) as.character(x) # "key1: (key2: (key3: val3))" x <- list( a = 1, b = list( c = 2, d = list(e = "hello") ), f = c(1, 2, 3) ) as.character(x) # "a: 1, b: (c: 2, d: (e: hello)), f: 1, 2, 3" x <- list("foo", bar = NA, baz = NULL) as.character(x) # "1: foo, bar: NA, baz: NULL"x <- list(key1 = "val1", key2 = "val2") as.character(x) # "key1: val1, key2: val2" x <- list(key1 = list(key2 = list(key3 = "val3"))) as.character(x) # "key1: (key2: (key3: val3))" x <- list( a = 1, b = list( c = 2, d = list(e = "hello") ), f = c(1, 2, 3) ) as.character(x) # "a: 1, b: (c: 2, d: (e: hello)), f: 1, 2, 3" x <- list("foo", bar = NA, baz = NULL) as.character(x) # "1: foo, bar: NA, baz: NULL"
Converts an R list into a single character string in which every
element occupies its own line, using the format "key: value". Named
elements use their names as keys, while unnamed elements use their
1-based positions. Nested lists are expanded recursively, and each
nesting level is indented by two additional spaces.
list_to_chr_formated(x)list_to_chr_formated(x)
x |
A list to be converted. |
A character vector of length one, with lines separated by "\n"
(no trailing newline).
x <- list( a = 1, b = list( c = 2, d = list(e = "hello") ), f = c(1, 2, 3) ) cat(list_to_chr_formated(x), "\n") # a: 1 # b: # c: 2 # d: # e: hello # f: 1, 2, 3x <- list( a = 1, b = list( c = 2, d = list(e = "hello") ), f = c(1, 2, 3) ) cat(list_to_chr_formated(x), "\n") # a: 1 # b: # c: 2 # d: # e: hello # f: 1, 2, 3
Lists the CellTypist pre-trained models available locally. By default it
reads all model files under ~/.celltypist/data/models, the default
CellTypist models directory (overridable via the CELLTYPIST_FOLDER
environment variable). Models are downloaded with
DownloadCellTypistModels and used by
CellTypistAnnotate.
ListCellTypistModels(path = NULL, verbose = getFuncOption("verbose"))ListCellTypistModels(path = NULL, verbose = getFuncOption("verbose"))
path |
Character. Path to the CellTypist models directory. Default:
|
verbose |
Logical. Whether to print the model list to the console.
Default: |
A character vector of available model names (without the .pkl
suffix). Invisibly returned when verbose = TRUE.
Other Single_Cell_Annotation_Method:
CellTypistAnnotate(),
DownloadCellTypistModels(),
RegisterAnnoMethod(),
SCAnnotateStrategy,
SingleRAnnotate(),
mLLMCelltypeAnnotate()
## Not run: # List all locally available CellTypist models ListCellTypistModels() # List models in a custom directory, without printing ListCellTypistModels(path = "~/my_models", verbose = FALSE) ## End(Not run)## Not run: # List all locally available CellTypist models ListCellTypistModels() # List models in a custom directory, without printing ListCellTypistModels(path = "~/my_models", verbose = FALSE) ## End(Not run)
Discovers and lists available Python environments of various types on the system. This generic function provides a unified interface to find Conda environments and virtual environments (venv) through S3 method dispatch.
Default method that lists all Python environments by combining results from Conda and virtual environment discovery methods.
Discovers Conda environments using multiple detection strategies for maximum reliability. First attempts to use system Conda commands, then falls back to reticulate's built-in Conda interface if Conda command is unavailable or fails. Returns empty data frame if Conda is not available or no environments are found.
Discovers virtual environments by searching common venv locations including
user directories (~/.virtualenvs, ~/.venvs) and project folders
(./venv, ./.venv). Supports custom search paths through the
venv_locations parameter. Returns empty data frame if no virtual
environments are found in the specified locations.
ListPyEnv( env_type = c("all", "conda", "venv", "virtualenv"), timeout = 30000L, venv_locations = c("~/.virtualenvs", "~/.venvs", "./venv", "./.venv"), verbose = TRUE, ... )ListPyEnv( env_type = c("all", "conda", "venv", "virtualenv"), timeout = 30000L, venv_locations = c("~/.virtualenvs", "~/.venvs", "./venv", "./.venv"), verbose = TRUE, ... )
env_type |
Character string specifying the type of environments to list.
One of: |
timeout |
The maximum timeout time when using system commands, only effective when |
venv_locations |
Character vector of directory paths to search for virtual environments. Default includes standard locations and common project directories. |
verbose |
Logical indicating whether to print verbose output. |
... |
For future use. |
The function uses S3 method dispatch to handle different environment types:
"all": Combines results from all environment types using rbind()
"conda": Searches for Conda environments using multiple methods:
Primary: reticulate::conda_list() for reliable environment detection
Fallback: System conda info --envs command for broader compatibility
"venv": Searches common virtual environment locations including
user directories and project folders
Each method includes comprehensive error handling and will return empty results with informative warnings if no environments are found or if errors occur during discovery.
A data frame with the following columns:
name - Character vector of environment names
python - Character vector of paths to Python executables
type - Character vector indicating environment type ("conda" or "venv")
Returns an empty data frame with these columns if no environments are found.
## Not run: # List all Python environments ListPyEnv("all") # List only Conda environments ListPyEnv("conda") # List only virtual environments with custom search paths ListPyEnv("venv", venv_locations = c("~/my_envs", "./project_env")) ## End(Not run)## Not run: # List all Python environments ListPyEnv("all") # List only Conda environments ListPyEnv("conda") # List only virtual environments with custom search paths ListPyEnv("venv", venv_locations = c("~/my_envs", "./project_env")) ## End(Not run)
Reads a cached R object from disk. The file format is determined by the file extension:
.qs2: loaded via qs2::qs_read()
.RData / .rds: loaded via readRDS()
.csv: loaded via data.table::fread()
If the file was originally saved in .qs2 format but qs2 is
not installed on the current machine, a clear error message is shown with
installation instructions.
LoadCache(file)LoadCache(file)
file |
Character string. Path to the cache file to load. |
The cached R object.
Other cache_config:
CacheSetHere(),
CacheSysCall(),
CheckCache(),
ChooseCache(),
WriteCache(),
WriteCacheMeta()
## Not run: result <- LoadCache("Scissor_res/survival_2025_01_01/result.qs2") feature_df <- LoadCache("Scissor_res/survival_2025_01_01/feature_table.csv") ## End(Not run)## Not run: result <- LoadCache("Scissor_res/survival_2025_01_01/result.qs2") feature_df <- LoadCache("Scissor_res/survival_2025_01_01/feature_table.csv") ## End(Not run)
This function checks if the data already exists in a local cache. If not, it downloads the file from the remote repository using multiple sources with fallback.
LoadRefData( data_type = c("survival", "binary", "continuous"), path = NULL, timeout = SigBridgeRUtils::getFuncOption("timeout"), ... )LoadRefData( data_type = c("survival", "binary", "continuous"), path = NULL, timeout = SigBridgeRUtils::getFuncOption("timeout"), ... )
data_type |
The type of data to download. Must be one of "survival", "binary", or "continuous". |
path |
Optional path to save the downloaded file, default: NULL, saving in package. |
timeout |
Integer. Connection timeout in seconds (default: 60) |
... |
Additional arguments. Currently supports:
|
The requested datasets, stored in a list.
## Not run: ref_data <- LoadRefData(data_type = c("survival")) ## End(Not run)## Not run: ref_data <- LoadRefData(data_type = c("survival")) ## End(Not run)
Combines results from multiple single-cell screening analyses (e.g., Scissor, scPAS, scPP, scAB) by merging their metadata, slots, and miscellaneous information while preserving the original expression data from the first input. Performs an inner join on cell barcodes to ensure only cells present in all inputs are retained.
MergeResult( ..., weights = NULL, ties.method = c("random", "first", "last"), verbose = SigBridgeRUtils::getFuncOption("verbose") )MergeResult( ..., weights = NULL, ties.method = c("random", "first", "last"), verbose = SigBridgeRUtils::getFuncOption("verbose") )
... |
Input objects to merge. Can be:
The first object serves as the base for merging. When duplicate metadata columns are found, priority is given to the first occurrence. |
weights |
Named numeric vector specifying weights for voting when multiple
screening methods produce categorical labels. Names must match screening
method names (case-insensitive). If |
ties.method |
Character. Method for resolving ties in weighted voting:
|
verbose |
Logical. Whether to print progress messages. Default: inherits
from |
A merged Seurat object containing:
Expression data from the first input object
Combined metadata from all input objects (inner join on cell IDs)
Merged slots (assays, reductions, graphs, images) from all objects
Combined miscellaneous information from all objects
Optional vote column in metadata if weight is provided
Input Validation: Extracts Seurat objects from inputs (skips invalid objects with warning)
Metadata Extraction: Converts metadata to data.table format for efficient merging
Cell Intersection: Retains only cells present in all datasets (inner join)
Weighted Voting: If weight provided, performs weighted voting across screening methods
Slot Merging: Combines assays, reductions, graphs, and images from all objects
Misc Merging: Aggregates miscellaneous information from all objects
When weight is provided, the function:
Identifies columns in metadata matching registered screening method names
Extracts vote data (must contain "Positive", "Negative", "Neutral", or "Other")
Applies WeightedVote with specified weights
Adds vote column to merged metadata with final aggregated labels
Only cells present in all input objects are retained (inner join behavior)
Duplicate metadata columns are resolved by keeping the first occurrence
For integrating heterogeneous single-cell datasets (different samples),
use SCIntegrate instead
Weights should be non-negative; higher values indicate greater influence in voting
WeightedVote, SCIntegrate, AddMisc
## Not run: # Example 1: Merge results from different screening methods scissor_out <- RunScissor(...) scAB_out <- RunscAB(...) scPP_out <- RunscPP(...) merged <- MergeResult(scissor_out, scAB_out, scPP_out) # Check merged metadata head(merged[[]]) # Example 2: Weighted voting across methods weights <- c( Scissor = 3, # Highest confidence scAB = 2, # Medium confidence scPP = 1 # Lower confidence ) merged <- MergeResult( scissor_out, scAB_out, scPP_out, weight = weights, ties.method = "first" ) # View voting results table(merged$vote) # Example 3: Merge list-containing objects result_list1 <- list(scRNA_data = seurat_obj1, other_info = "...") result_list2 <- list(scRNA_data = seurat_obj2, other_info = "...") merged <- MergeResult(result_list1, result_list2) # Example 4: Check which cells were retained original_cells <- ncol(seurat_obj1) merged_cells <- ncol(merged) cat("Retained", merged_cells, "of", original_cells, "cells\n") # Example 5: Access merged slots # All unique assays from all inputs names(merged@assays) # All unique reductions names(merged@reductions) ## End(Not run)## Not run: # Example 1: Merge results from different screening methods scissor_out <- RunScissor(...) scAB_out <- RunscAB(...) scPP_out <- RunscPP(...) merged <- MergeResult(scissor_out, scAB_out, scPP_out) # Check merged metadata head(merged[[]]) # Example 2: Weighted voting across methods weights <- c( Scissor = 3, # Highest confidence scAB = 2, # Medium confidence scPP = 1 # Lower confidence ) merged <- MergeResult( scissor_out, scAB_out, scPP_out, weight = weights, ties.method = "first" ) # View voting results table(merged$vote) # Example 3: Merge list-containing objects result_list1 <- list(scRNA_data = seurat_obj1, other_info = "...") result_list2 <- list(scRNA_data = seurat_obj2, other_info = "...") merged <- MergeResult(result_list1, result_list2) # Example 4: Check which cells were retained original_cells <- ncol(seurat_obj1) merged_cells <- ncol(merged) cat("Retained", merged_cells, "of", original_cells, "cells\n") # Example 5: Access merged slots # All unique assays from all inputs names(merged@assays) # All unique reductions names(merged@reductions) ## End(Not run)
Method is the abstract base class for all analysis methods (screening and
annotation) in the SigBridgeR package. It defines the common interface that
every method must implement, including a method name, version, and executor
function.
Method( method_name, executor, method_version, sigbridger_version = get_pkg_version() )Method( method_name, executor, method_version, sigbridger_version = get_pkg_version() )
method_name |
|
executor |
|
method_version |
|
sigbridger_version |
Package Version of SigBridgeR |
This class is defined using the S7 object-oriented system and inherits from
SigBridgeRBase. It is marked as abstract, meaning it cannot be instantiated
directly. Concrete subclasses such as ScreenMethod and AnnotationMethod
provide specific method categories.
A Method S7 object (abstract; cannot be instantiated directly).
Other SigBridgeR-Classes:
ScreenMethod(),
SigBridgeRBase()
Collects the method-specific arguments of a benchmark configuration.
Each method registered in ScreenStrategy has a corresponding argument
named "<method>_param", which defaults to list().
MethodParamSet( Scissor_param = list(), scAB_param = list(), scPAS_param = list(), scPP_param = list(), DEGAS_param = list(), DEGASv2_param = list(), LP_SGL_param = list(), PIPET_param = list(), SCIPAC_param = list(), SIDISH_param = list(), TiRank_param = list(), PhenoMapR_param = list(), ... )MethodParamSet( Scissor_param = list(), scAB_param = list(), scPAS_param = list(), scPP_param = list(), DEGAS_param = list(), DEGASv2_param = list(), LP_SGL_param = list(), PIPET_param = list(), SCIPAC_param = list(), SIDISH_param = list(), TiRank_param = list(), PhenoMapR_param = list(), ... )
Scissor_param |
Extra arguments for method Scissor |
scAB_param |
Extra arguments for method scAB |
scPAS_param |
Extra arguments for method scPAS |
scPP_param |
Extra arguments for method scPP |
DEGAS_param |
Extra arguments for method DEGAS |
DEGASv2_param |
Extra arguments for method DEGASv2 |
LP_SGL_param |
Extra arguments for method LP_SGL |
PIPET_param |
Extra arguments for method PIPET |
SCIPAC_param |
Extra arguments for method SCIPAC |
SIDISH_param |
Extra arguments for method SIDISH |
TiRank_param |
Extra arguments for method TiRank |
PhenoMapR_param |
Extra arguments for method PhenoMapR |
... |
Currently unused |
A modified list of method-specific parameters.
Other ConfigSet:
BenchGSEAConfigSet(),
BenchGeneScoreConfigSet(),
BenchMemoryConfigSet()
MethodParamSet( Scissor_param = list(alpha = 0.05), scPAS_param = list(alpha = 0.05) )MethodParamSet( Scissor_param = list(alpha = 0.05), scPAS_param = list(alpha = 0.05) )
Performs automated cell type annotation for Seurat clusters by leveraging multiple large language models (LLMs) to interpret cluster-specific marker genes. The function supports both single-model annotation and multi-model consensus generation, with uncertainty quantification via agreement metrics.
Workflow:
Identifies top marker genes per cluster (via Seurat::FindAllMarkers()
or user-provided markers).
Queries specified LLMs with marker gene lists and tissue context.
For multiple models: computes consensus annotations and uncertainty
metrics (consensus proportion, entropy) via
mLLMCelltype::interactive_consensus_annotation().
For single model: uses direct annotation via
mLLMCelltype::annotate_cell_types().
Adds results as metadata columns to the Seurat object.
mLLMCelltypeAnnotate(sc, ...) ## Default S3 method: mLLMCelltypeAnnotate(sc, ...) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' mLLMCelltypeAnnotate(sc, ...) ## S3 method for class 'SingleCellExperiment' mLLMCelltypeAnnotate(sc, ...) ## S3 method for class 'Seurat' mLLMCelltypeAnnotate( sc, seurat_obj_markers = NULL, tissue_name = NULL, models = vector("character", 0L), api_keys = list(), top_gene_count = 10L, debug = FALSE, base_urls = NULL, return_reasoning = FALSE, controversy_threshold = 0.7, entropy_threshold = 1L, max_discussion_rounds = 3L, consensus_check_model = NULL, log_dir = "logs", cache_dir = NULL, use_cache = TRUE, clusters_to_analyze = NULL, force_rerun = FALSE, ... )mLLMCelltypeAnnotate(sc, ...) ## Default S3 method: mLLMCelltypeAnnotate(sc, ...) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' mLLMCelltypeAnnotate(sc, ...) ## S3 method for class 'SingleCellExperiment' mLLMCelltypeAnnotate(sc, ...) ## S3 method for class 'Seurat' mLLMCelltypeAnnotate( sc, seurat_obj_markers = NULL, tissue_name = NULL, models = vector("character", 0L), api_keys = list(), top_gene_count = 10L, debug = FALSE, base_urls = NULL, return_reasoning = FALSE, controversy_threshold = 0.7, entropy_threshold = 1L, max_discussion_rounds = 3L, consensus_check_model = NULL, log_dir = "logs", cache_dir = NULL, use_cache = TRUE, clusters_to_analyze = NULL, force_rerun = FALSE, ... )
sc |
A single-cell dataset with pre-computed clusters (stored in
|
... |
Additional arguments routed to downstream functions:
|
seurat_obj_markers |
Optional pre-computed marker gene table (output of
|
tissue_name |
Character. Biological context for annotation (e.g.,
tissue type or disease state), which helps LLMs interpret marker genes
appropriately. Default: |
models |
Character vector of LLM model identifiers. Supported formats:
For single-model mode ( |
api_keys |
Named vector of API keys with provider names as keys:
Example: |
top_gene_count |
Integer. Number of top marker genes per cluster passed
to the LLMs. Default: |
debug |
Logical. Whether to enable debug output from
|
base_urls |
Character vector or list of custom base URLs for the LLM
API endpoints (e.g., for proxies or local deployments). Default: |
return_reasoning |
Logical. Whether to return the reasoning text from
the single-model annotation. Default: |
controversy_threshold |
Numeric. Consensus proportion below which a
cluster is considered controversial and triggers further discussion.
Default: |
entropy_threshold |
Numeric. Entropy below which consensus is
considered reached. Default: |
max_discussion_rounds |
Integer. Maximum number of discussion rounds in
the consensus process. Default: |
consensus_check_model |
Character. Model used to check consensus during
the discussion. Default: |
log_dir |
Character. Directory for saving the consensus process logs.
Default: |
cache_dir |
Character. Directory for caching API responses.
Default: |
use_cache |
Logical. Whether to use cached API responses.
Default: |
clusters_to_analyze |
Character or integer vector. Subset of cluster
IDs to analyze; |
force_rerun |
Logical. Whether to ignore cached results and re-run the
annotation. Default: |
The input Seurat object with the following metadata columns added:
mllmcelltype_cell_type: Consensus cell type annotation per cell.
mllmcelltype_consensus_proportion: (Multi-model only) Proportion
of models agreeing on the assigned label (range: 0-1). Higher values
indicate stronger consensus.
mllmcelltype_entropy: (Multi-model only) Shannon entropy of model
predictions. Lower values indicate higher confidence (less disagreement
among models).
Note: Uncertainty metrics are only added in multi-model mode
(length(models) > 1).
SingleCellExperiment and ScreenMethodResult inputs are annotated as
Seurat objects and returned as such.
R packages: mLLMCelltype, Seurat
Valid API keys for the selected LLM providers (costs may apply)
Internet connectivity for LLM API calls
annotate_cell_types,
interactive_consensus_annotation
Other Single_Cell_Annotation_Method:
CellTypistAnnotate(),
DownloadCellTypistModels(),
ListCellTypistModels(),
RegisterAnnoMethod(),
SCAnnotateStrategy,
SingleRAnnotate()
## Not run: # Multi-model consensus annotation annotated <- mLLMCelltypeAnnotate( sc = pbmc_small, tissue_name = "Peripheral Blood Mononuclear Cells", models = c("gpt-4o", "claude-3-5-sonnet-20240620"), api_keys = list( openai = Sys.getenv("OPENAI_API_KEY"), anthropic = Sys.getenv("ANTHROPIC_API_KEY") ), top_gene_count = 15, min.pct = 0.25, logfc.threshold = 0.5 ) # User-provided markers markers_list <- list( "0" = c("CD3D", "CD3E", "CD2", "IL7R", "LTB"), "1" = c("CD14", "LYZ", "CST3", "MS4A7", "FCGR3A") ) # Example marker data frame markers_df <- data.frame( cluster = c(0, 0, 0, 1, 1, 1), gene = c("CD3D", "CD3E", "CD2", "CD14", "LYZ", "CST3"), avg_log2FC = c(2.5, 2.3, 2.1, 3.1, 2.8, 2.5), p_val_adj = c(0.001, 0.001, 0.002, 0.0001, 0.0002, 0.0005) ) # Single-model annotation (faster, no consensus metrics) annotated <- mLLMCelltypeAnnotate( sc = pbmc_small, models = "gpt-4o-mini", api_keys = list(openai = Sys.getenv("OPENAI_API_KEY")) ) # Inspect results table(annotated$mllmcelltype_cell_type) head(annotated$mllmcelltype_consensus_proportion) # Only present in multi-model mode ## End(Not run)## Not run: # Multi-model consensus annotation annotated <- mLLMCelltypeAnnotate( sc = pbmc_small, tissue_name = "Peripheral Blood Mononuclear Cells", models = c("gpt-4o", "claude-3-5-sonnet-20240620"), api_keys = list( openai = Sys.getenv("OPENAI_API_KEY"), anthropic = Sys.getenv("ANTHROPIC_API_KEY") ), top_gene_count = 15, min.pct = 0.25, logfc.threshold = 0.5 ) # User-provided markers markers_list <- list( "0" = c("CD3D", "CD3E", "CD2", "IL7R", "LTB"), "1" = c("CD14", "LYZ", "CST3", "MS4A7", "FCGR3A") ) # Example marker data frame markers_df <- data.frame( cluster = c(0, 0, 0, 1, 1, 1), gene = c("CD3D", "CD3E", "CD2", "CD14", "LYZ", "CST3"), avg_log2FC = c(2.5, 2.3, 2.1, 3.1, 2.8, 2.5), p_val_adj = c(0.001, 0.001, 0.002, 0.0001, 0.0002, 0.0005) ) # Single-model annotation (faster, no consensus metrics) annotated <- mLLMCelltypeAnnotate( sc = pbmc_small, models = "gpt-4o-mini", api_keys = list(openai = Sys.getenv("OPENAI_API_KEY")) ) # Inspect results table(annotated$mllmcelltype_cell_type) head(annotated$mllmcelltype_consensus_proportion) # Only present in multi-model mode ## End(Not run)
An internal utility function that converts regular expression patterns used for quality control in single-cell RNA-seq analysis into standardized column names for Seurat object metadata. This function handles both single patterns and combined patterns with logical OR operators.
Pattern2Colname(pat)Pattern2Colname(pat)
pat |
A character string containing a regular expression pattern or
multiple patterns combined with |
A character string with the standardized column name derived from the input pattern(s). The output follows these conventions: - Lowercase letters only - Special characters removed or replaced with underscores - Common patterns mapped to standardized abbreviations - Combined patterns sorted alphabetically and joined with underscores
Other single_cell_preprocess:
FilterTumorCell(),
FindRobustElbow(),
QCPatternDetect(),
RegisterSeuratMethod(),
SCAnnotate(),
SCIntegrate(),
SCPreProcess(),
SCPreProcessStrategy
## Not run: # Internal usage examples Pattern2Colname("^MT-") # Returns "mt" Pattern2Colname("^RP[LS]") # Returns "rp" Pattern2Colname("^[rt]rna") # Returns "rt_rna" Pattern2Colname("^MT-|^RP[LS]") # Returns "mt_rp" Pattern2Colname("^HB[AB]?") # Returns "hb_ab" Pattern2Colname("Custom_Pattern[0-9]+") # Returns "custom_pattern_0_9" ## End(Not run)## Not run: # Internal usage examples Pattern2Colname("^MT-") # Returns "mt" Pattern2Colname("^RP[LS]") # Returns "rp" Pattern2Colname("^[rt]rna") # Returns "rt_rna" Pattern2Colname("^MT-|^RP[LS]") # Returns "mt_rp" Pattern2Colname("^HB[AB]?") # Returns "hb_ab" Pattern2Colname("Custom_Pattern[0-9]+") # Returns "custom_pattern_0_9" ## End(Not run)
Efficiently transforms phenotype values based on user-defined conditional rules.
Similar to dplyr::case_when but optimized for performance on large datasets.
PhenoMap(data, ..., .default = NA)PhenoMap(data, ..., .default = NA)
data |
A vector, data frame, or data.table containing the phenotype data to transform. |
... |
Named or unnamed formulas of the form |
.default |
Value to use when no conditions match. Default: |
A data.table with the transformed column. If input is a vector, returns a vector.
Other input_preprocess:
DrawBulkPCA(),
PhenoPreProcess(),
SCPreProcess(),
SymbolConvert()
## Not run: # Example 1: Discretize a continuous phenotype scores <- rnorm(100, mean = 50, sd = 10) scores <- PhenoMap(scores, scores > 60 ~ "High", scores > 40 ~ "Medium", .default = "Low") # Example 2: Transform a column in a data frame df <- data.frame( age = c(25, 35, 45, 55, 65), gender = c("M", "F", "M", "F", "M") ) df <- PhenoMap(df, age < 30 ~ "Young", age < 50 ~ "Middle", .default = "Senior") # Example 3: Multiple conditions with complex logic df <- data.frame(value = c(5, 15, 25, 35, 45)) df <- PhenoMap( df, value < 10 ~ "Very Low", value < 20 ~ "Low", value < 30 ~ "Medium", value < 40 ~ "High", .default = "Very High" ) ## End(Not run)## Not run: # Example 1: Discretize a continuous phenotype scores <- rnorm(100, mean = 50, sd = 10) scores <- PhenoMap(scores, scores > 60 ~ "High", scores > 40 ~ "Medium", .default = "Low") # Example 2: Transform a column in a data frame df <- data.frame( age = c(25, 35, 45, 55, 65), gender = c("M", "F", "M", "F", "M") ) df <- PhenoMap(df, age < 30 ~ "Young", age < 50 ~ "Middle", .default = "Senior") # Example 3: Multiple conditions with complex logic df <- data.frame(value = c(5, 15, 25, 35, 45)) df <- PhenoMap( df, value < 10 ~ "Very Low", value < 20 ~ "Low", value < 30 ~ "Medium", value < 40 ~ "High", .default = "Very High" ) ## End(Not run)
Aligns and validates phenotype data with bulk RNA-seq expression matrix.
Supports three phenotype types (binary, continuous, survival) with automatic
sample matching, type validation, and optional conditional mapping via
PhenoMap.
PhenoPreProcess( bulk, phenotype, phenotype_class = c("binary", "continuous", "survival"), ..., select = NULL, verbose = getFuncOption("verbose") )PhenoPreProcess( bulk, phenotype, phenotype_class = c("binary", "continuous", "survival"), ..., select = NULL, verbose = getFuncOption("verbose") )
bulk |
A two-dimensional matrix or data frame of bulk RNA-seq expression data with genes as rows and samples as columns. Must have at least 2 samples. |
phenotype |
Phenotype data, either:
|
phenotype_class |
Character. Type of phenotype:
Partial matching is supported. |
... |
Conditional mapping rules passed to |
select |
Character. Column name(s) to select from |
verbose |
Logical. Whether to print diagnostic messages. Default: inherits
from |
Preprocessed phenotype data:
For binary/continuous: Named numeric vector with sample names as names
For survival: Data frame with two columns (time, status) and sample names as row names
Only samples present in both bulk and phenotype are retained.
Binary: Must have exactly 2 unique values (e.g., 0/1, TRUE/FALSE)
Continuous: Must have >2 unique values (to avoid confusion with binary)
Survival: Must have exactly 2 unique values in status column (typically 0 = censored, 1 = event)
Sample matching: Common samples identified via intersect(colnames(bulk), names/rownames(phenotype))
Survival column guessing: When phenotype_class = "survival"
and select = NULL, automatically detects columns containing "time"
and "status"/"censor" in their names (case-insensitive).
Type conversion: Logical values are converted to numeric (TRUE->1, FALSE->0)
Sample alignment: Returns only samples present in both bulk and phenotype
Other input_preprocess:
DrawBulkPCA(),
PhenoMap(),
SCPreProcess(),
SymbolConvert()
## Not run: # Example 1: Binary phenotype bulk_data <- matrix(rpois(100, 10), nrow = 20, ncol = 5) colnames(bulk_data) <- paste0("Sample", 1:5) pheno_binary <- c(Sample1 = 1, Sample2 = 0, Sample3 = 1, Sample4 = 0, Sample5 = 1) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_binary, phenotype_class = "binary" ) # Example 2: Continuous phenotype with discretization pheno_age <- c(Sample1 = 25, Sample2 = 35, Sample3 = 45, Sample4 = 55, Sample5 = 65) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_age, phenotype_class = "continuous", .x < 40 ~ "Young", .x >= 40 ~ "Old" ) # Example 3: Survival data with automatic column detection pheno_surv <- data.frame( time = c(12, 24, 18, 36, 30), status = c(1, 0, 1, 1, 0), row.names = paste0("Sample", 1:5) ) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_surv, phenotype_class = "survival" ) # Example 4: Survival data with explicit column names pheno_surv_custom <- data.frame( follow_up = c(12, 24, 18, 36, 30), event = c(1, 0, 1, 1, 0), row.names = paste0("Sample", 1:5) ) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_surv_custom, phenotype_class = "survival", select = c("follow_up", "event") ) ## End(Not run)## Not run: # Example 1: Binary phenotype bulk_data <- matrix(rpois(100, 10), nrow = 20, ncol = 5) colnames(bulk_data) <- paste0("Sample", 1:5) pheno_binary <- c(Sample1 = 1, Sample2 = 0, Sample3 = 1, Sample4 = 0, Sample5 = 1) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_binary, phenotype_class = "binary" ) # Example 2: Continuous phenotype with discretization pheno_age <- c(Sample1 = 25, Sample2 = 35, Sample3 = 45, Sample4 = 55, Sample5 = 65) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_age, phenotype_class = "continuous", .x < 40 ~ "Young", .x >= 40 ~ "Old" ) # Example 3: Survival data with automatic column detection pheno_surv <- data.frame( time = c(12, 24, 18, 36, 30), status = c(1, 0, 1, 1, 0), row.names = paste0("Sample", 1:5) ) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_surv, phenotype_class = "survival" ) # Example 4: Survival data with explicit column names pheno_surv_custom <- data.frame( follow_up = c(12, 24, 18, 36, 30), event = c(1, 0, 1, 1, 0), row.names = paste0("Sample", 1:5) ) result <- PhenoPreProcess( bulk = bulk_data, phenotype = pheno_surv_custom, phenotype_class = "survival", select = c("follow_up", "event") ) ## End(Not run)
+
x + y combines two screening results into a single Seurat object via
MergeResult(). Both operands may be ScreenMethodResult objects or Seurat
objects; a ScreenMethodResult is unwrapped to its scRNA_data slot before
merging.
## S3 method for class ''SigBridgeR::ScreenMethodResult'' x + y ## S3 method for class 'Seurat' x + y## S3 method for class ''SigBridgeR::ScreenMethodResult'' x + y ## S3 method for class 'Seurat' x + y
x |
A ScreenMethodResult or Seurat object as the main receiver. |
y |
A ScreenMethodResult or Seurat object as the main donor. |
A merged Seurat object.
Retrieve a property from SigBridgeR object
## S3 method for class ''SigBridgeR::SigBridgeRBase'' object$name ## S3 method for class ''SigBridgeR::SigBridgeRBase'' object[[name]]## S3 method for class ''SigBridgeR::SigBridgeRBase'' object$name ## S3 method for class ''SigBridgeR::SigBridgeRBase'' object[[name]]
object |
An object inheriting from SigBridgeRBase |
name |
The name of the parameter as a character. Partial matching is not performed. |
Filters cells based on nFeature_RNA and optional QC metrics (e.g. percent.mt, percent.rp),
defined in seurat_obj@misc$qc_colnames (See QCPatternDetect). Only metrics with non-constant, non-all-zero values are used.
QCFilter( seurat_obj, data_filter.thresh = list(assay = SeuratObject::DefaultAssay(seurat_obj), nFeature_thresh = c(200L, 6000L), nCount_thresh = c(500L, 50000L), percent.mt = 20L, percent.rp = 60L), verbose = TRUE, ... )QCFilter( seurat_obj, data_filter.thresh = list(assay = SeuratObject::DefaultAssay(seurat_obj), nFeature_thresh = c(200L, 6000L), nCount_thresh = c(500L, 50000L), percent.mt = 20L, percent.rp = 60L), verbose = TRUE, ... )
seurat_obj |
A |
data_filter.thresh |
A named list with thresholds. Default:
|
verbose |
Logical; whether to print progress messages via |
... |
No use |
A filtered Seurat object.
This function calculates the percentage of counts coming from features matching specified patterns (e.g., mitochondrial genes, ribosomal genes) and adds them as metadata columns to the Seurat object.
QCPatternDetect( obj, pattern = c("^MT-", "^mt-", "^RP[SL]", "^MT-|^RP[SL]"), verbose = TRUE, ... )QCPatternDetect( obj, pattern = c("^MT-", "^mt-", "^RP[SL]", "^MT-|^RP[SL]"), verbose = TRUE, ... )
obj |
A seurat object. |
pattern |
A character vector or list containing regex patterns to identify mitochondrial genes, ribosomal protein genes, or other unwanted genes, as well as combinations of these genes. Customized patterns are supported. |
verbose |
logical, whether to print progress messages |
... |
Additional arguments passed to |
The function automatically generates friendly column names based on the patterns:
"mt" for mitochondrial patterns
"rp" for ribosomal patterns
"rrna" for ribosomal RNA patterns
For combined patterns (using |), creates names like "mt_rp"
For other patterns, creates cleaned lowercase names
Other single_cell_preprocess:
FilterTumorCell(),
FindRobustElbow(),
Pattern2Colname(),
RegisterSeuratMethod(),
SCAnnotate(),
SCIntegrate(),
SCPreProcess(),
SCPreProcessStrategy
Registers screening, preprocessing, or annotation methods into their
respective strategy registries. Register() accepts named arguments where
the name becomes the registry key and the value (an S7 object or function)
is dispatched to the appropriate RegisterImpl method.
Register(..., overwrite = FALSE, verbose = getFuncOption("verbose"))Register(..., overwrite = FALSE, verbose = getFuncOption("verbose"))
... |
Named arguments where each name is the registry key and each
value is an S7 object (ScreenMethod or |
overwrite |
|
verbose |
|
Register() iterates over its named ... arguments, calling
RegisterImpl() for each. RegisterImpl is an S7 generic that dispatches
based on the class of the value:
ScreenMethod -> registered into ScreenStrategy.
AnnotationMethod -> registered into SCAnnotateStrategy.
function -> validated as a Seurat/SeuratObject function and
registered into SCPreProcessStrategy.
If the method name already exists in the target registry, the function
aborts unless overwrite = TRUE.
Invisibly TRUE on successful registration.
ScreenStrategy, SCAnnotateStrategy, SCPreProcessStrategy
## Not run: # Register a ScreenMethod method <- ScreenMethod( method_name = "Scissor", executor = DoScissor ) Register(Scissor = method) # Register a Seurat preprocessing function Register(h = Seurat::RunHarmony) # Register with overwrite Register(Scissor = method, overwrite = TRUE) ## End(Not run)## Not run: # Register a ScreenMethod method <- ScreenMethod( method_name = "Scissor", executor = DoScissor ) Register(Scissor = method) # Register a Seurat preprocessing function Register(h = Seurat::RunHarmony) # Register with overwrite Register(Scissor = method, overwrite = TRUE) ## End(Not run)
Registers one or more user-defined annotation functions into a shared registry
environment (e.g.,
SCAnnotateStrategy). Each method is stored with minimal
metadata (method_name and executor) to enable dynamic dispatch in
annotation pipelines.
This function supports extensible cell type annotation frameworks-ideal for integrating novel classifiers (e.g., custom SingleR wrappers, marker-based assigners, or deep learning models) while maintaining a uniform execution interface.
RegisterAnnoMethod( ..., registry = SCAnnotateStrategy, overwrite = FALSE, verbose = getFuncOption("verbose") )RegisterAnnoMethod( ..., registry = SCAnnotateStrategy, overwrite = FALSE, verbose = getFuncOption("verbose") )
... |
Named arguments where each value is a function implementing an
annotation method. The name becomes the method identifier (e.g.,
|
registry |
Target registry to store annotation methods.
Default: |
overwrite |
Logical. If |
verbose |
Logical. Whether to print a success message upon registration.
Default: inherits from package option |
Invisibly returns TRUE on successful registration.
Other Registering:
RegisterScreenMethod(),
RegisterSeuratMethod()
Other Single_Cell_Annotation_Method:
CellTypistAnnotate(),
DownloadCellTypistModels(),
ListCellTypistModels(),
SCAnnotateStrategy,
SingleRAnnotate(),
mLLMCelltypeAnnotate()
## Not run: # Register a custom annotation wrapper MyAnnotator <- function(sc, ...) { # Custom logic returning annotated Seurat/SCE object sc } RegisterAnnoMethod( custom_annot = MyAnnotator, registry = SCAnnotateStrategy ) # Attempting to re-register without `overwrite = TRUE` will fail # RegisterAnnoMethod(custom_annot = AnotherAnnotator) # Error! ## End(Not run)## Not run: # Register a custom annotation wrapper MyAnnotator <- function(sc, ...) { # Custom logic returning annotated Seurat/SCE object sc } RegisterAnnoMethod( custom_annot = MyAnnotator, registry = SCAnnotateStrategy ) # Attempting to re-register without `overwrite = TRUE` will fail # RegisterAnnoMethod(custom_annot = AnotherAnnotator) # Error! ## End(Not run)
Registers one or more user-defined screening functions into a shared registry
(i.e.,
ScreenStrategy), enabling dynamic dispatch based on phenotype type
(binary, survival, or continuous). Each method is stored with metadata including
supported phenotypes and an optional parameter remapping function.
This function supports community-driven extension of analysis pipelines-ideal for integrating novel single cell phenotypic screening methods while maintaining compatibility with downstream validation and execution frameworks.
RegisterScreenMethod( ..., supported_phenotypes = c("binary", "survival", "continuous"), parameter_mapper = NULL, registry = ScreenStrategy, overwrite = FALSE, verbose = getFuncOption("verbose") )RegisterScreenMethod( ..., supported_phenotypes = c("binary", "survival", "continuous"), parameter_mapper = NULL, registry = ScreenStrategy, overwrite = FALSE, verbose = getFuncOption("verbose") )
... |
Named arguments where each value is a function implementing a screening method.
The name becomes the method identifier (e.g., |
supported_phenotypes |
Character vector specifying which phenotype types the method supports.
Must be a subset of |
parameter_mapper |
A function that transforms the input parameter list before
passing it to the executor. Useful for changing parameters from interface function.
Receives a named list |
registry |
An environment used as a method registry (e.g., |
overwrite |
Logical. If |
verbose |
Logical. Whether to print a success message upon registration. Default: inherits from package option. |
Invisibly returns TRUE on successful registration.
Each registered method is stored as a list with four elements:
method_name: Character: the method key (e.g., "Scissor")
executor: Function: the actual screening implementation
phenotypes: Character vector: supported phenotype classes
mapper: Function: parameter transformation hook
Other Add_Screen_method:
ScreenStrategy,
TemplateScreenFunc(),
ValidateScreenFunc()
Other Registering:
RegisterAnnoMethod(),
RegisterSeuratMethod()
## Not run: # Example: Register a custom screen method for survival data DoMyScreen <- function(...) { # Implement your method here stop("Not implemented") } RegisterScreenMethod( # Key = function # jarl-ignore unreachable_code: example MyCox = DoMyScreen, # If `continuous` phenotype is not supported supported_phenotypes = c("survival", "binary"), parameter_mapper = function(params) { # If I prefer to use `quiet` instead of `verbose` params$quiet <- !params$verbose params } ) ## End(Not run)## Not run: # Example: Register a custom screen method for survival data DoMyScreen <- function(...) { # Implement your method here stop("Not implemented") } RegisterScreenMethod( # Key = function # jarl-ignore unreachable_code: example MyCox = DoMyScreen, # If `continuous` phenotype is not supported supported_phenotypes = c("survival", "binary"), parameter_mapper = function(params) { # If I prefer to use `quiet` instead of `verbose` params$quiet <- !params$verbose params } ) ## End(Not run)
Dynamically registers one or more new preprocessing strategies into a strategy
environment (i.e.,
SCPreProcessStrategy). Each strategy is stored under
a user-defined key and wraps a Seurat-compatible function to conform to the
standard interface: function(object, params).
Supports both direct function objects and character specifications of
package-qualified function names (e.g., h = "Seurat::RunHarmony").
This enables safe, lazy resolution of external dependencies and simplifies
pipeline configuration via strings.
RegisterSeuratMethod( ..., overwrite = FALSE, registry = SCPreProcessStrategy, verbose = getFuncOption("verbose") )RegisterSeuratMethod( ..., overwrite = FALSE, registry = SCPreProcessStrategy, verbose = getFuncOption("verbose") )
... |
Named arguments where each name is a strategy key (e.g.,
|
overwrite |
Logical. If |
registry |
Environment. The target registry to store strategies.
Default: |
verbose |
Logical. Whether to print registration messages.
Default: inherits from |
Invisibly returns TRUE on successful registration.
Other Registering:
RegisterAnnoMethod(),
RegisterScreenMethod()
Other single_cell_preprocess:
FilterTumorCell(),
FindRobustElbow(),
Pattern2Colname(),
QCPatternDetect(),
SCAnnotate(),
SCIntegrate(),
SCPreProcess(),
SCPreProcessStrategy
## Not run: # Register using a package-qualified name RegisterSeuratMethod( h = "Seurat::RunHarmony", registry = SCPreProcessStrategy ) # Attempting to re-register without `overwrite = TRUE` will fail # RegisterSeuratMethod(h = Seurat::RunHarmony) # Error! ## End(Not run)## Not run: # Register using a package-qualified name RegisterSeuratMethod( h = "Seurat::RunHarmony", registry = SCPreProcessStrategy ) # Attempting to re-register without `overwrite = TRUE` will fail # RegisterSeuratMethod(h = Seurat::RunHarmony) # Error! ## End(Not run)
A dispatch wrapper that routes cell type annotation requests to registered methods
stored in SCAnnotateStrategy. Provides a consistent API for applying
different annotation strategies (e.g., CellTypist, SingleR,
mLLMCelltype) to a Seurat object without needing to call each
method directly.
SCAnnotate(sc, ...) ## Default S3 method: SCAnnotate(sc, ...) ## S3 method for class 'Seurat' SCAnnotate(sc, method = c("CellTypist", "SingleR", "mLLMCelltype"), ...)SCAnnotate(sc, ...) ## Default S3 method: SCAnnotate(sc, ...) ## S3 method for class 'Seurat' SCAnnotate(sc, method = c("CellTypist", "SingleR", "mLLMCelltype"), ...)
sc |
A |
... |
Method-specific parameters passed to the underlying annotation function. Examples:
See individual method documentation for details. |
method |
Character. Annotation method to use. Must be one of the keys
registered in |
The input Seurat object enriched with method-specific annotation
metadata columns. Column names and content depend on the chosen method:
SingleR: SingleR_labels, SingleR_delta_next, SingleR_pruned_labels
CellTypist: celltypist_prediction, celltypist_probability, etc.
mLLMCelltype: mllmcelltype_cell_type, mllmcelltype_consensus_proportion, mllmcelltype_entropy
New annotation methods can be registered via RegisterAnnoMethod
or the unified Register interface. Once registered, they become
immediately available through this dispatcher.
Other single_cell_preprocess:
FilterTumorCell(),
FindRobustElbow(),
Pattern2Colname(),
QCPatternDetect(),
RegisterSeuratMethod(),
SCIntegrate(),
SCPreProcess(),
SCPreProcessStrategy
## Not run: # List available annotation methods names(SCAnnotateStrategy) # SingleR annotation with HPCA reference annotated <- SCAnnotate( sc = seurat_obj, method = "SingleR", ref = "HPCA" ) # CellTypist annotation with custom model annotated <- SCAnnotate( sc = seurat_obj, method = "CellTypist", model = "Immune_All_Low", download = TRUE ) # mLLMCelltype consensus annotation annotated <- SCAnnotate( sc = seurat_obj, method = "mLLMCelltype", tissue_name = "Lung Tumor", models = c("gpt-4o", "claude-3-5-sonnet-20240620"), api_keys = list( openai = Sys.getenv("OPENAI_API_KEY"), anthropic = Sys.getenv("ANTHROPIC_API_KEY") ) ) # Partial matching works annotated <- SCAnnotate(sc = seurat_obj, method = "single") # -> "SingleR" ## End(Not run)## Not run: # List available annotation methods names(SCAnnotateStrategy) # SingleR annotation with HPCA reference annotated <- SCAnnotate( sc = seurat_obj, method = "SingleR", ref = "HPCA" ) # CellTypist annotation with custom model annotated <- SCAnnotate( sc = seurat_obj, method = "CellTypist", model = "Immune_All_Low", download = TRUE ) # mLLMCelltype consensus annotation annotated <- SCAnnotate( sc = seurat_obj, method = "mLLMCelltype", tissue_name = "Lung Tumor", models = c("gpt-4o", "claude-3-5-sonnet-20240620"), api_keys = list( openai = Sys.getenv("OPENAI_API_KEY"), anthropic = Sys.getenv("ANTHROPIC_API_KEY") ) ) # Partial matching works annotated <- SCAnnotate(sc = seurat_obj, method = "single") # -> "SingleR" ## End(Not run)
An environment storing methods for annotating cell types.
SCAnnotateStrategy AVAILABLE_ANNOTATE_METHODSSCAnnotateStrategy AVAILABLE_ANNOTATE_METHODS
Storing structure - named list
key: method name
value: list
method_name: method name
executor: function implementation of the method
Other Single_Cell_Annotation_Method:
CellTypistAnnotate(),
DownloadCellTypistModels(),
ListCellTypistModels(),
RegisterAnnoMethod(),
SingleRAnnotate(),
mLLMCelltypeAnnotate()
A unified interface for standardized single-cell RNA-seq preprocessing.
It accepts raw counts (matrix/data.frame), AnnData (via
anndata or anndataR), or existing Seurat objects.
The analysis flow is fully customizable via a character string pipeline and a configuration list params.
SCPreProcess(sc, ...) ## Default S3 method: SCPreProcess( sc = NULL, ..., pipeline = "onsvpcetu", params = list(o = list(), n = list(), s = list(), v = list(), p = list(), e = list(), c = list(), t = list(), u = list()), quality_control = list(pattern = c("^MT-")), data_filter = list(nFeature_thresh = c(200L, 6000L), nCount_thresh = c(500L, 50000L), percent.mt = 20L, percent.rp = 60L), column2only_tumor = NULL ) ## S3 method for class 'R6' SCPreProcess( sc, ..., pipeline = "onsvpcetu", params = list(o = list(), n = list(), s = list(), v = list(), p = list(), e = list(), c = list(), t = list(), u = list()), quality_control = list(pattern = c("^MT-")), data_filter = list(nFeature_thresh = c(200L, 6000L), nCount_thresh = c(500L, 50000L), percent.mt = 20L, percent.rp = 60L), column2only_tumor = NULL ) ## S3 method for class 'Seurat' SCPreProcess(sc, column2only_tumor = NULL, ...)SCPreProcess(sc, ...) ## Default S3 method: SCPreProcess( sc = NULL, ..., pipeline = "onsvpcetu", params = list(o = list(), n = list(), s = list(), v = list(), p = list(), e = list(), c = list(), t = list(), u = list()), quality_control = list(pattern = c("^MT-")), data_filter = list(nFeature_thresh = c(200L, 6000L), nCount_thresh = c(500L, 50000L), percent.mt = 20L, percent.rp = 60L), column2only_tumor = NULL ) ## S3 method for class 'R6' SCPreProcess( sc, ..., pipeline = "onsvpcetu", params = list(o = list(), n = list(), s = list(), v = list(), p = list(), e = list(), c = list(), t = list(), u = list()), quality_control = list(pattern = c("^MT-")), data_filter = list(nFeature_thresh = c(200L, 6000L), nCount_thresh = c(500L, 50000L), percent.mt = 20L, percent.rp = 60L), column2only_tumor = NULL ) ## S3 method for class 'Seurat' SCPreProcess(sc, column2only_tumor = NULL, ...)
sc |
Input data. Can be:
|
... |
Additional arguments for backward compatibility (mapped to |
pipeline |
A character string defining the processing steps and order. Characters map to Seurat functions:
Default is |
params |
A named list of lists containing arguments for each pipeline step.
Keys match the pipeline characters (e.g., list( o = list(), # do not pass `counts` n = list(), # NormalizeData args s = list(), # ScaleData args v = list(), # FindVariableFeatures args c = list(), ... ) |
quality_control |
A list containing regex patterns for QC metric calculation. (See QCPatternDetect)
Default: |
data_filter |
A list of thresholds for cell filtering.
Default: |
column2only_tumor |
Optional character. Column name in metadata to filter for tumor cells
(matches "Tumor", "Cancer", "Malignant", etc.). If |
Pipeline Strategy:
The function parses the pipeline string and executes corresponding Seurat functions in order.
To use SCTransform, simply change the pipeline string (e.g., "orpetu") and provide parameters in params$r.
Quality Control & Filtering:
QC metrics are generated based on regex patterns in quality_control.
Cells are then filtered based on thresholds in data_filter.
Column names for filtering are auto-generated (e.g., pattern "^MT-" -> filter "percent.mt").
If confused about the column name, use SigBridgeR:::Pattern2Colname().
A processed Seurat object with reductions, clusters, and QC metrics.
Other single_cell_preprocess:
FilterTumorCell(),
FindRobustElbow(),
Pattern2Colname(),
QCPatternDetect(),
RegisterSeuratMethod(),
SCAnnotate(),
SCIntegrate(),
SCPreProcessStrategy
Other input_preprocess:
DrawBulkPCA(),
PhenoMap(),
PhenoPreProcess(),
SymbolConvert()
## Not run: # 1. Standard pipeline (LogNormalize -> Scale -> PCA -> UMAP) obj <- SCPreProcess( sc = counts_matrix, pipeline = "onsvpcetu", params = list(c = list(resolution = 0.8)) ) # 2. SCTransform pipeline obj_sct <- SCPreProcess( sc = counts_matrix, pipeline = "orpcu", # Create -> SCT -> PCA -> Clusters -> UMAP quality_control = list(pattern = c("^MT-", "^RP[LS]")), params = list( r = list(vars.to.regress = "percent.mt") ) ) # 3. Start from AnnData with tumor filtering adata_object <- anndataR::read_h5ad("data.h5ad") obj_ad <- SCPreProcess( sc = adata_object, column2only_tumor = "tissue" ) ## End(Not run)## Not run: # 1. Standard pipeline (LogNormalize -> Scale -> PCA -> UMAP) obj <- SCPreProcess( sc = counts_matrix, pipeline = "onsvpcetu", params = list(c = list(resolution = 0.8)) ) # 2. SCTransform pipeline obj_sct <- SCPreProcess( sc = counts_matrix, pipeline = "orpcu", # Create -> SCT -> PCA -> Clusters -> UMAP quality_control = list(pattern = c("^MT-", "^RP[LS]")), params = list( r = list(vars.to.regress = "percent.mt") ) ) # 3. Start from AnnData with tumor filtering adata_object <- anndataR::read_h5ad("data.h5ad") obj_ad <- SCPreProcess( sc = adata_object, column2only_tumor = "tissue" ) ## End(Not run)
An environment that maps single-letter codes to standardized Seurat preprocessing
operations. Each entry is a function of the form function(...)
that wraps a core Seurat step (e.g., normalization, PCA, clustering)
This registry enables compact, composable pipeline definitions (e.g., via character
strings like "onvps" for "Create -> Normalize -> VariableFeatures -> Scale -> PCA")
and supports both standard (NormalizeData) and SCTransform-based workflows.
SCPreProcessStrategySCPreProcessStrategy
o: Create Seurat object from count matrix (SeuratObject::CreateSeuratObject)
n: Normalize data (Seurat::NormalizeData)
v: Find variable features (Seurat::FindVariableFeatures)
s: Scale data (Seurat::ScaleData)
p: Run PCA (Seurat::RunPCA)
c: Find clusters (Seurat::FindClusters)
e: Find neighbors (Seurat::FindNeighbors)
t: Run t-SNE (Seurat::RunTSNE)
u: Run UMAP (Seurat::RunUMAP)
r: SCTransform (Seurat::SCTransform)
i: Integrate layers (Seurat::IntegrateLayers)
These functions are not intended for direct interactive use. They are
internal building blocks for workflow engines (i.e., SCPreProcess).
You can access any operation via SCPreProcessStrategy$letter,
but doing so bypasses pipeline validation and error handling.
To add more operations, use RegisterSeuratMethod()
Other single_cell_preprocess:
FilterTumorCell(),
FindRobustElbow(),
Pattern2Colname(),
QCPatternDetect(),
RegisterSeuratMethod(),
SCAnnotate(),
SCIntegrate(),
SCPreProcess()
Integrates matched bulk expression data and phenotype information to identify phenotype-associated cell populations in single-cell RNA-seq data using a registered screening method. Ensures consistency between bulk and phenotype data before analysis.
Screen( matched_bulk, sc_data, phenotype, label_type = NULL, phenotype_class = c("binary", "survival", "continuous"), screen_method = c("Scissor", "scPP", "scPAS", "scAB", "DEGAS", "LP_SGL", "PIPET", "SIDISH", "SCIPAC", "TiRank", "DEGASv2", "PhenoMapR"), ... )Screen( matched_bulk, sc_data, phenotype, label_type = NULL, phenotype_class = c("binary", "survival", "continuous"), screen_method = c("Scissor", "scPP", "scPAS", "scAB", "DEGAS", "LP_SGL", "PIPET", "SIDISH", "SCIPAC", "TiRank", "DEGASv2", "PhenoMapR"), ... )
matched_bulk |
Matrix or data frame of preprocessed bulk RNA-seq expression data (genes x samples). Column names must match names/IDs in phenotype. |
sc_data |
A Seurat object containing scRNA-seq data to be screened. |
phenotype |
Phenotype data, either:
|
label_type |
Character specifying phenotype label type, e.g. "SBS1" or "time". |
phenotype_class |
Type of phenotypic outcome. Must be consistent with input data:
|
screen_method |
Screening algorithm to use. Available options:
|
... |
Additional method-specific parameters. Scissor
scPP
scPAS
scAB
DEGAS
SIDISH
SCIPAC
PIPET
LP_SGL
DEGASv2
TiRank
PhenoMapR
|
A list containing:
scRNA_data: A Seurat object with phenotype-associated cells labelled in a meta.data column.
screen_result: Important information about the screened result related to the selected method.
Column names of matched_bulk and names or row names of phenotype must be identical.
Phenotype values must correspond to bulk samples, not directly to single cells.
Mismatches will trigger an error before analysis begins.
A built-in pre-run check is performed.
Associated functions:
Generates stacked bar plots showing the proportion of cells classified as Positive/Negative/Neutral by single-cell screening algorithms (Scissor, scPAS, scPP, or scAB) across different sample groups. Supports both single and multiple screen types visualization.
ScreenFractionPlot( screened_seurat, group_by = "Source", # x-axis label screen_type = NULL, # default: search all available screens show_null = FALSE, plot_color = NULL, # stack bar color of each status show_plot = FALSE, plot_title = "Screen Fraction", stack_width = 0.85, x_text_angle = 45, axis_linewidth = 0.8, x_lab = NULL, y_lab = "Fraction of Status", ncol = 2, # number of columns for facet wrap nrow = NULL, # number of rows for facet wrap verbose = SigBridgeRUtils::getFuncOption("verbose"), ... # ggplot2 theme arguments )ScreenFractionPlot( screened_seurat, group_by = "Source", # x-axis label screen_type = NULL, # default: search all available screens show_null = FALSE, plot_color = NULL, # stack bar color of each status show_plot = FALSE, plot_title = "Screen Fraction", stack_width = 0.85, x_text_angle = 45, axis_linewidth = 0.8, x_lab = NULL, y_lab = "Fraction of Status", ncol = 2, # number of columns for facet wrap nrow = NULL, # number of rows for facet wrap verbose = SigBridgeRUtils::getFuncOption("verbose"), ... # ggplot2 theme arguments )
screened_seurat |
A Seurat object containing screening results in metadata.
Must contain columns corresponding to |
group_by |
Metadata column name for grouping samples (default: "Source"). |
screen_type |
Screening algorithm(s) used. Can be a single value or vector. Must match metadata column(s) (case-sensitive, e.g., "scissor" for Scissor results). |
show_null |
Logical whether to show groups with zero cells (default: FALSE). |
plot_color |
Custom color palette (named vector format):
|
show_plot |
Logical to immediately display plot (default: TRUE). |
plot_title |
Plot title (default: "Screen Fraction"). When multiple screen types, can be a vector of titles or single title (will append screen type prefix). |
stack_width |
Bar width (default: 0.85). |
x_text_angle |
X-axis label angle (default: 45). |
axis_linewidth |
Axis line thickness (default: 0.8). |
x_lab |
X-axis label (default: NULL). |
y_lab |
Y-axis label (default: "Fraction of Status"). |
ncol |
Number of columns for facet wrap when multiple screen types (default: 2). |
nrow |
Number of rows for facet wrap when multiple screen types (default: NULL). |
verbose |
Logical, whether to print a message |
... |
Other arguments passed to ggplot2::theme() |
A list containing:
stats: A data frame (single screen) or list of data frames (multiple screens)
with screening statistics including:
Grouping variable counts
Raw cell counts
Percentage fractions
plot: A ggplot2 object (single screen) or list of ggplot2 objects (multiple screens)
combined_plot: A combined plot using patchwork (only for multiple screens)
Bars are ordered by descending Positive fraction
Y-axis shows percentage (0-100%)
Zero-fraction groups are automatically hidden unless show_null=TRUE
For multiple screen types, plots can be combined using patchwork
Other visualization_function:
ScreenUpset()
## Not run: # Single screen type usage res <- ScreenFractionPlot( screened_seurat = scissor_result, group_by = "PatientID", screen_type = "scissor" ) # Multiple screen types at once multi_res <- ScreenFractionPlot( screened_seurat = multi_screened_result, group_by = "TissueType", screen_type = c("scissor", "scPAS", "scPP", "scAB", "DEGAS"), ncol = 2 ) ## End(Not run)## Not run: # Single screen type usage res <- ScreenFractionPlot( screened_seurat = scissor_result, group_by = "PatientID", screen_type = "scissor" ) # Multiple screen types at once multi_res <- ScreenFractionPlot( screened_seurat = multi_screened_result, group_by = "TissueType", screen_type = c("scissor", "scPAS", "scPP", "scAB", "DEGAS"), ncol = 2 ) ## End(Not run)
ScreenMethod is the S7 class for phenotype-associated cell screening
methods. It extends Method with phenotype classification and mapper
function support, and enforces a standardized function signature for all
screening executors.
ScreenMethod( method_name, method_version, executor, phenotype_class, mapper = NULL, sigbridger_version = get_pkg_version() )ScreenMethod( method_name, method_version, executor, phenotype_class, mapper = NULL, sigbridger_version = get_pkg_version() )
method_name |
|
method_version |
|
executor |
|
phenotype_class |
|
mapper |
|
sigbridger_version |
Package Version of SigBridgeR |
This class inherits from Method and adds screening-specific properties.
It validates that the executor function accepts the required arguments:
matched_bulk, sc_data, phenotype, label_type, and
phenotype_class. This ensures a consistent interface across all screening
algorithms (e.g., Scissor, scPAS, scPP, TiRank).
A ScreenMethod S7 object.
Other SigBridgeR-Classes:
Method(),
SigBridgeRBase()
ScreenMethodCache bundles cached screening data with its configuration
and metadata. It serves as the primary container for reading from and
writing to the cache system.
ScreenMethodCache( cache_path, cache_config_path, cache_data, screen_method_config, sigbridger_version = get_pkg_version() )ScreenMethodCache( cache_path, cache_config_path, cache_data, screen_method_config, sigbridger_version = get_pkg_version() )
cache_path |
|
cache_config_path |
|
cache_data |
|
screen_method_config |
A |
sigbridger_version |
Package Version of SigBridgeR |
This class is defined using the S7 object-oriented system and inherits from
SigBridgeRBase. It wraps a ScreenMethodConfig together with cached data
objects, file paths, and a read-only SigBridgeR version stamp.
The class validator checks that:
cache_path is an existing directory.
The parent directory of cache_config_path exists.
cache_config_path ends with "cache_config.json".
A ScreenMethodCache S7 object.
@sigbridger_versioncharacter (read-only). The SigBridgeR package
version at the time the cache was created. Automatically set from
get_pkg_version() and cannot be modified by the user.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodConfig(),
ScreenMethodResult()
ScreenMethodConfig stores the configuration for a phenotype-associated
cell screening method. It is used both to define screening parameters and
as a cache result descriptor.
ScreenMethodConfig( method_name, param, method_version = NULL, phenotype_class = c("binary", "continuous", "survival"), label_type = character(0L), sigbridger_version = get_pkg_version() )ScreenMethodConfig( method_name, param, method_version = NULL, phenotype_class = c("binary", "continuous", "survival"), label_type = character(0L), sigbridger_version = get_pkg_version() )
method_name |
|
param |
|
method_version |
|
phenotype_class |
|
label_type |
|
sigbridger_version |
Package Version of SigBridgeR |
This class is defined using the S7 object-oriented system and inherits from
SigBridgeRBase. It validates that method_name is a registered screening
method in ScreenStrategy and that phenotype_class is one of the
supported types.
The class validator enforces:
param must be a non-empty named list.
phenotype_class must be one or more of "binary",
"continuous", "survival".
method_name must match a key in ScreenStrategy.
A ScreenMethodConfig S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodResult()
ScreenMethodResult stores the results of a phenotype-associated cell
screening analysis. It wraps a Seurat object containing the screened
single-cell data and supports attaching additional dynamic properties
(e.g., screening statistics, metadata) via ... in the constructor.
ScreenMethodResult(scRNA_data, ..., sigbridger_version = get_pkg_version())ScreenMethodResult(scRNA_data, ..., sigbridger_version = get_pkg_version())
scRNA_data |
A Seurat object containing the screening results. This is the core required property of the class. |
... |
Named arguments to set as additional S7 properties on the
result object (e.g., screening statistics, method-specific outputs). Stored
as a list in the |
sigbridger_version |
Package Version of SigBridgeR |
This class is defined using the S7 object-oriented system and inherits from
SigBridgeRBase. The core required property is scRNA_data, which must
be a Seurat object containing the screening
results.
Additional properties can be attached dynamically via the constructor's
... argument. Named arguments are set as S7 properties on the returned
object, allowing flexible result storage without subclassing.
The class validator enforces:
scRNA_data must be present on the object.
scRNA_data must be a Seurat object.
A ScreenMethodResult S7 object.
Other S7-Classes:
AnnotationMethod(),
BenchAccConfig(),
BenchConfig(),
BenchGSEAConfig(),
BenchGeneScoreConfig(),
BenchMemoryConfig(),
ScreenMethodCache(),
ScreenMethodConfig()
An environment storing methods for screening phenotype-associated cells.
ScreenStrategy AVAILABLE_SCREEN_METHODSScreenStrategy AVAILABLE_SCREEN_METHODS
Storing structure - named list
key: method name
value: list
method_name: method name
executor: function implementation of the method
phenotype_class: The phenotype types supported by this method
mapper: A function that transforms the parameters passed to the Screen function before forwarding them to the executor; both input and output must be of type list.
Other Add_Screen_method:
RegisterScreenMethod(),
TemplateScreenFunc(),
ValidateScreenFunc()
This function creates an UpSet plot to visualize intersections between different screening methods (e.g., scissor, scAB, scPAS, scPP) in a Seurat object metadata. It calculates all possible combinations of screening types and displays the number of cells positive for each combination.
ScreenUpset( screened_seurat, screen_type = NULL, order_by = c("freq", "degree"), show_plot = FALSE, n_intersections = 20L, bar_color = "#5189bb", combmatrix_point_color = "black", verbose = SigBridgeRUtils::getFuncOption("verbose"), ... )ScreenUpset( screened_seurat, screen_type = NULL, order_by = c("freq", "degree"), show_plot = FALSE, n_intersections = 20L, bar_color = "#5189bb", combmatrix_point_color = "black", verbose = SigBridgeRUtils::getFuncOption("verbose"), ... )
screened_seurat |
A Seurat object containing screening results in metadata. Must contain columns with screening types marked as "Positive". |
screen_type |
Character vector of screening types to analyze. Default: NULL, indicating that a self-search pattern will be used. |
order_by |
Character vector of columns to order the intersections by. Default: c("freq", "degree"). |
show_plot |
Whether to show the upset plot. Default: FALSE |
n_intersections |
Number of intersections to display in the plot. Default: 20. |
bar_color |
Color for the bars in the plot. Default: "#5189bb". |
combmatrix_point_color |
Color for points in the combination matrix. Default: "black". |
verbose |
Logical, whether to print a message |
... |
Additional arguments passed to |
The function performs the following steps:
Validates input parameters and checks if specified screening types exist in metadata
Generates all possible combinations of screening types (from 1 to the total number of types)
Creates a logical matrix of positive cells for efficient computation
Calculates cell counts for each intersection using vectorized operations
Creates an UpSet plot visualization with customizable appearance
A list containing two elements:
plot: A ggplot object displaying the UpSet plot
stats: A data frame with intersection statistics including:
intersection: Name of the intersection
sets: List of screening types in the intersection
count: Number of cells positive for all screening types in the intersection
Other visualization_function:
ScreenFractionPlot()
## Not run: # Basic usage with default parameters result <- ScreenUpset(screened_seurat = my_seurat_obj) # Customize screening types and appearance result <- ScreenUpset( screened_seurat = my_seurat_obj, screen_type = c("scissor", "scAB"), n_intersections = 15, title = "Custom Title", bar_color = "darkred" ) ## End(Not run)## Not run: # Basic usage with default parameters result <- ScreenUpset(screened_seurat = my_seurat_obj) # Customize screening types and appearance result <- ScreenUpset( screened_seurat = my_seurat_obj, screen_type = c("scissor", "scAB"), n_intersections = 15, title = "Custom Title", bar_color = "darkred" ) ## End(Not run)
These functions provide a centralized configuration system for the SigBridgeR package, allowing users to set and retrieve package-specific options with automatic naming conventions.
setFunOption sets one or more configuration options for the SigBridgeR package. Options are automatically prefixed with "SigBridgeR." if not already present, ensuring proper namespace isolation.
getFuncOption retrieves configuration options for the SigBridgeR package. The function automatically handles the "SigBridgeR." prefix, allowing users to reference options with or without the explicit prefix.
checkFuncOption validates configuration options for the SigBridgeR package. This function ensures that all options meet type and value requirements before they are set in the global options.
setFuncOption(...)setFuncOption(...)
... |
Named arguments representing option-value pairs. Options can be provided with or without the "SigBridgeR." prefix. If the prefix is missing, it will be automatically added. |
This function performs the following validations:
Must be single logical values (TRUE/FALSE)
Must be single integer values
Must be a single positive integer value
The function is automatically called by setFuncOption to ensure all configuration options are valid before they are set.
Invisibly returns NULL. The function is called for its side effects of setting package options.
The value of the specified option if it exists, otherwise the provided default value.
No return value. The function throws an error if the value doesn't meet the required specifications for the given option.
verbose: A logical value indicating whether to print verbose messages, defaults to TRUE
timeout: An integer specifying the timeout in seconds for parallel processing, defaults to '180L“
seed: An integer specifying the random seed for reproducible results, defaults to '123L“
nthreads: An integer specifying the number of threads for parallel processing, defaults to '1L“
# Set options with automatic prefixing setFuncOption(verbose = TRUE) # Retrieve options with automatic prefixing getFuncOption("verbose")# Set options with automatic prefixing setFuncOption(verbose = TRUE) # Retrieve options with automatic prefixing getFuncOption("verbose")
Unified interface to configure thread counts and acceleration features across
system-level (OpenMP/data.table/cheapr) and TensorFlow backends. Uses a hierarchical
configuration model where global threads serves as default for all
backends unless explicitly overridden.
Critical: TensorFlow configuration must be set before importing
TensorFlow via reticulate::import("tensorflow").
SetThreads( threads = getFuncOption("nthreads"), dt = threads, cheapr = threads, qs2 = threads, wgcna = max(threads, 2L), seurat = threads, openmp = NULL, tf_config = list(xla_flag = "--tf_xla_auto_jit=2 --tf_xla_cpu_global_jit", xla_device = NULL, inter_op = NULL, intra_op = c(1L, NULL)), verbose = getFuncOption("verbose"), ... )SetThreads( threads = getFuncOption("nthreads"), dt = threads, cheapr = threads, qs2 = threads, wgcna = max(threads, 2L), seurat = threads, openmp = NULL, tf_config = list(xla_flag = "--tf_xla_auto_jit=2 --tf_xla_cpu_global_jit", xla_device = NULL, inter_op = NULL, intra_op = c(1L, NULL)), verbose = getFuncOption("verbose"), ... )
threads |
Integer. Global thread count used as default for all backends.
Default: |
dt |
Integer. Thread count for data.table (default: inherited from |
cheapr |
Integer. Thread count for cheapr (default: inherited from |
qs2 |
Integer. Thread count for qs2 (default: inherited from |
wgcna |
Integer. Thread count for WGCNA (default: inherited from
|
seurat |
Integer. Thread count for Seurat (default: inherited from |
openmp |
Integer. Thread count for OpenMP (default: inherited from |
tf_config |
Named list for TensorFlow-specific configuration:
|
verbose |
Logical. Whether to print verbose output (default: inherited from function options). |
... |
Additional arguments for |
Invisible list with old/new values per backend.
## Not run: # Basic usage: auto-detect and configure SetThreads() # Explicit thread count for CPU-intensive workloads SetThreads(threads = 12L) # TensorFlow-optimized configuration for deep learning SetThreads( threads = 8L, tf_config = list( inter_op = 2L, intra_op = 8L ) ) # Import AFTER SetThreads() # Configure only data.table for memory-efficient workflows SetThreads(dt = 4L , verbose = FALSE) ## End(Not run)## Not run: # Basic usage: auto-detect and configure SetThreads() # Explicit thread count for CPU-intensive workloads SetThreads(threads = 12L) # TensorFlow-optimized configuration for deep learning SetThreads( threads = 8L, tf_config = list( inter_op = 2L, intra_op = 8L ) ) # Import AFTER SetThreads() # Configure only data.table for memory-efficient workflows SetThreads(dt = 4L , verbose = FALSE) ## End(Not run)
Sets up a Python environment with specified packages. This function can create new environments or reuse existing ones, supporting both Conda and venv environment types. It ensures all required dependencies are properly installed and verified.
Default method for unsupported environment types. Throws an informative error with supported environment types.
SetupPyEnv(env_type = c("conda", "venv"), ...)SetupPyEnv(env_type = c("conda", "venv"), ...)
env_type |
Character string specifying the type of Python environment to
create or use. One of: |
... |
Additional parameters passed to specific environment methods. |
This function provides a comprehensive solution for Python environment management in R projects, particularly for machine learning workflows requiring TensorFlow. Key features include:
Environment Creation: Automatically creates new environments or reuses existing ones with the same name
Package Management: Installs specified Python packages with version pinning support
Verification: Validates environment setup and package installations
Flexible Methods: Supports different backend methods for environment creation (reticulate vs system calls)
The function uses S3 method dispatch to handle different environment types, allowing for extensible support of additional environment managers in the future.
A data frame containing verification results for the environment setup, including installation status of all required packages. Invisibly returns the verification results.
reticulate::conda_create(), reticulate::virtualenv_create() for
underlying environment creation functions.
## Not run: # Setup a Conda environment with default parameters SetupPyEnv("conda") # Setup a venv environment SetupPyEnv("venv") ## End(Not run)## Not run: # Setup a Conda environment with default parameters SetupPyEnv("conda") # Setup a venv environment SetupPyEnv("venv") ## End(Not run)
These are S7 property definitions used within the SigBridgeRBase class
and its subclasses. They define the types, validators, and default values
for class attributes. These properties are exported for community developers
to extend and subclass SigBridgeRBase.
property_sigbridger_verison property_verison property_chr property_phenotype_class property_fn property_list property_mapper_fn property_py_env property_data_list property_seurat property_phenotype property_matrixproperty_sigbridger_verison property_verison property_chr property_phenotype_class property_fn property_list property_mapper_fn property_py_env property_data_list property_seurat property_phenotype property_matrix
An S7 property of class class_character.
An S7 property of class class_character.
An S7 property of class class_character.
An S7 property of class class_character.
An S7 property of class class_function.
An S7 property of class class_list.
An S7 property of class class_any.
An S7 property of class class_any.
An S7 property of class class_list.
An S7 property of class class_any.
An S7 property of class class_any.
An S7 property of class class_any.
A read-only character property that returns the current version of the
SigBridgeR package. Attempting to set this property will raise an error.
The version string is validated to contain at least one dot (.).
The default value is obtained from get_pkg_version().
A read-only character property that returns the current version of the
SigBridgeR package. Attempting to set this property will raise an error.
The version string is validated to contain at least one dot (.).
The default value is obtained from get_pkg_version().
A general-purpose character property with no additional validation. Can be used for any string-typed attribute in subclasses.
A character property that specifies the phenotype classification type(s).
Valid values are "binary", "continuous", and "survival".
Multiple values can be provided as a character vector.
Default: c("binary", "continuous", "survival").
A property that accepts a function value. Used to store callback or transformation functions in class attributes.
A named list property. The value must be a named list (not NULL or
NA) with unique names. Duplicate names are not allowed.
A property that accepts either a function or NULL. Used for storing
mapper/transformation functions that may be optionally specified.
If a value is provided, it must be a function; otherwise, NULL is
accepted to indicate no mapper is configured.
A property representing a Python environment configuration.
Accepts either a character string (e.g., a conda environment name or path)
or NULL (when no Python environment is specified).
A named list property for storing multiple data objects.
The list must be named (if not NULL) and names must be unique.
Unlike property_list, this property allows NULL, NA, and empty
lists (list()) as valid values, making it suitable for optional
data storage.
A property that requires a Seurat object.
The value must inherit from the "Seurat" class.
This property is used to store single-cell data in Seurat format for downstream analysis.
A property that accepts a phenotype data
A property that accepts a matrix.
S3 methods that make every SigBridgeRBase object – and therefore every
SigBridgeR object, such as ScreenMethod, ScreenMethodResult, and
InterceptStrategy – behave like a standard R object. They support the
base generics print(), length(), names(), names<-(), format(),
as.list(), and as.character().
Pretty-print a SigBridgeR object using the cli package.
The class name is displayed in bold blue. Slots are displayed as an unordered list, with slot names in regular blue and each value preceded by its type.
Returns the number of properties (slots) stored in a SigBridgeRBase object.
Returns the names of all properties (slots) stored in a SigBridgeRBase
object.
Returns the names of all properties (slots) stored in a SigBridgeRBase
object.
Format a SigBridgeRBase object as a compact character vector.
Converts a SigBridgeRBase object into a named list of its properties.
Coercion of SigBridgeRBase to character is intentionally unsupported.
Use format() to obtain a character representation instead.
## S3 method for class ''SigBridgeR::SigBridgeRBase'' print(x, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' summary(object, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' length(x) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' names(x) ## S3 replacement method for class ''SigBridgeR::SigBridgeRBase'' names(x) <- value ## S3 method for class ''SigBridgeR::SigBridgeRBase'' format(x, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' as.list(x, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' as.character(x, ...)## S3 method for class ''SigBridgeR::SigBridgeRBase'' print(x, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' summary(object, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' length(x) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' names(x) ## S3 replacement method for class ''SigBridgeR::SigBridgeRBase'' names(x) <- value ## S3 method for class ''SigBridgeR::SigBridgeRBase'' format(x, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' as.list(x, ...) ## S3 method for class ''SigBridgeR::SigBridgeRBase'' as.character(x, ...)
x |
A |
... |
Additional arguments passed to the method. Currently unused. |
object |
A |
value |
A character vector of property names. |
All SigBridgeR objects inherit from the abstract base class SigBridgeRBase and store their data in S7 properties. The methods documented on this page expose those properties through familiar base R interfaces:
print() displays a human-readable summary of the object. The class
name is shown in bold blue and each property is listed with its name,
value type, and value.
length() returns the number of properties stored in the object.
names() returns the names of the object's properties.
names<-() is restricted: properties are validated by their S7
definitions, so modifying them in place is not allowed. Reconstruct a
new object instead.
format() converts the object to a compact character vector, starting
with a header of the form <Class: SigBridgeR <version>>.
as.list() converts the object to a named list of its properties.
as.character() is intentionally unsupported: coercing a
SigBridgeRBase object to a character vector is not meaningful and
always throws an error. Use format() instead.
The class name is displayed in bold blue. Slots are displayed as an unordered list, with slot names in regular blue and each value preceded by its type.
The first line is displayed as <Class: name version> when the object has
method_name and method_version properties, for example
<ScreenMethod: SigBridgeR 4.0.0>. Each following line contains one property name
and its value on the same line. Property types are not shown.
Invisibly returns x.
Invisibly returns object.
An integer: the number of properties.
A character vector of property names.
A character vector of property names.
A character vector.
A named list of properties.
Throws an error; never returns.
SigBridgeRBase for the abstract base class on which these methods dispatch.
S7::props() for the underlying property accessor.
SigBridgeRBase is the abstract base class for all S7 classes in the
SigBridgeR package. It provides a unified foundation for S3 method
dispatch and ensures consistent behavior across all subclasses.
SigBridgeRBase(sigbridger_version = "4.0.0")SigBridgeRBase(sigbridger_version = "4.0.0")
sigbridger_version |
Package Version of SigBridgeR |
This class is defined using the S7 object-oriented system and is marked
as abstract, meaning it cannot be instantiated directly. All other
classes in the SigBridgeR package should inherit from SigBridgeRBase.
The primary purpose of this base class is to serve as a dispatch target for base R S3 generic functions, enabling polymorphic behavior across all SigBridgeR S7 objects through S3 method dispatch.
Other SigBridgeR-Classes:
Method(),
ScreenMethod()
Performs automated cell type annotation using the SingleR package. Supports
built-in references (e.g., Human Primary Cell Atlas) or user-provided
SingleCellExperiment objects. Integrates seamlessly with Seurat
objects by adding prediction results as metadata columns.
SingleRAnnotate(sc, ...) ## Default S3 method: SingleRAnnotate(sc, ...) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' SingleRAnnotate(sc, ...) ## S3 method for class 'Seurat' SingleRAnnotate(sc, ...) ## S3 method for class 'SingleCellExperiment' SingleRAnnotate( sc, verbose = getFuncOption("verbose"), ensembl = FALSE, cell.ont = c("all", "nonna", "none"), legacy = FALSE, ref = c("HPCA", "custom"), labels = NULL, ... )SingleRAnnotate(sc, ...) ## Default S3 method: SingleRAnnotate(sc, ...) ## S3 method for class ''SigBridgeR::ScreenMethodResult'' SingleRAnnotate(sc, ...) ## S3 method for class 'Seurat' SingleRAnnotate(sc, ...) ## S3 method for class 'SingleCellExperiment' SingleRAnnotate( sc, verbose = getFuncOption("verbose"), ensembl = FALSE, cell.ont = c("all", "nonna", "none"), legacy = FALSE, ref = c("HPCA", "custom"), labels = NULL, ... )
sc |
A single-cell dataset, either:
|
... |
Additional arguments passed to |
verbose |
Logical. Whether to print progress messages.
Default: inherits from package option |
ensembl |
Logical scalar indicating whether to convert row names to Ensembl IDs. Genes without a mapping to a non-duplicated Ensembl ID are discarded. |
cell.ont |
String specifying whether Cell Ontology terms should be included in the colData. If |
legacy |
Logical scalar indicating whether to pull data from ExperimentHub. By default, we use data from the gypsum backend. |
ref |
Reference data for annotation. One of:
Note: The placeholder option A numeric matrix of (usually normalized and log-transformed) expression values from a reference dataset, or a SummarizedExperiment object containing such a matrix; see |
labels |
A character vector of cell type labels corresponding to the columns of Alternatively, if ref is a list, labels should be a list of the same length. Each element should contain a character vector or factor specifying the labels for the columns of the corresponding element of ref. |
If input is a Seurat object: returns the same object with three new metadata columns:
SingleR_labels: Predicted cell type labels.
SingleR_delta_next: Confidence score (difference between top and second-best scores).
SingleR_pruned_labels: Labels after pruning low-confidence assignments.
If input is a SingleCellExperiment: returns the SingleR prediction result
If input is a ScreenMethodResult: returns the annotated Seurat object
from its scRNA_data slot, as above.
The celldex package is required when using ref = "HPCA".
All gene names must be consistent between test and reference datasets (e.g., Ensembl or symbol).
Other Single_Cell_Annotation_Method:
CellTypistAnnotate(),
DownloadCellTypistModels(),
ListCellTypistModels(),
RegisterAnnoMethod(),
SCAnnotateStrategy,
mLLMCelltypeAnnotate()
## Not run: # Using HPCA reference (requires celldex) annotated_seurat <- SingleRAnnotate(seurat_obj, ref = "HPCA") # Using custom reference library(celldex) ref_sce <- BlueprintEncodeData() annotated_sce <- SingleRAnnotate( sc = my_sce, ref = ref_sce, labels = ref_sce$label.main, de.n = 30 ) ## End(Not run)## Not run: # Using HPCA reference (requires celldex) annotated_seurat <- SingleRAnnotate(seurat_obj, ref = "HPCA") # Using custom reference library(celldex) ref_sce <- BlueprintEncodeData() annotated_sce <- SingleRAnnotate( sc = my_sce, ref = ref_sce, labels = ref_sce$label.main, de.n = 30 ) ## End(Not run)
Convert Ensembles version IDs and TCGA version IDs to genes. NA values (unmatched IDs) are replaced with the original unconverted IDs (Ensembl version IDs or TCGA version IDs).
SymbolConvert( data, genome_build = c("hg38", "hg19", "mm10", "mm9", "ce11", "T2T"), update_symbol = TRUE, update_symbol_method = c("auto", "scCustomize", "Seurat"), verbose = SigBridgeRUtils::getFuncOption("verbose"), unknown_format = lifecycle::deprecated(), ... )SymbolConvert( data, genome_build = c("hg38", "hg19", "mm10", "mm9", "ce11", "T2T"), update_symbol = TRUE, update_symbol_method = c("auto", "scCustomize", "Seurat"), verbose = SigBridgeRUtils::getFuncOption("verbose"), unknown_format = lifecycle::deprecated(), ... )
Data with rownames converted to gene symbols
Other input_preprocess:
DrawBulkPCA(),
PhenoMap(),
PhenoPreProcess(),
SCPreProcess()
Creates a scaffold for a new screening function that conforms to the expected
interface for bulk-scRNA integration workflows. The template includes standard
parameters (e.g., matched_bulk, sc_data, phenotype) and a return structure
compatible with downstream validation (e.g., ValidateScreenFunc). Optionally
includes roxygen2 documentation and supports writing to a new or existing .R file.
When filename = "current", the function attempts to append to the active
script in RStudio or Positron (requires rstudioapi).
TemplateScreenFunc( filename = NULL, func_name = "my_screen", append = TRUE, documentation = FALSE, open = rlang::is_interactive(), ... )TemplateScreenFunc( filename = NULL, func_name = "my_screen", append = TRUE, documentation = FALSE, open = rlang::is_interactive(), ... )
filename |
Character. Path to the output |
func_name |
Character. Name of the generated function. Must be a valid R identifier
(starts with letter, followed by letters, digits, |
append |
Logical. If |
documentation |
Logical. Whether to include a full roxygen2 documentation block above the function.
Default: |
open |
Logical. Whether to open the file in the RStudio/Positron editor after writing (if available).
Default: |
... |
Additional arguments (currently unused, reserved for future extension). |
Invisibly returns the path to the written file (filename).
Other Add_Screen_method:
RegisterScreenMethod(),
ScreenStrategy,
ValidateScreenFunc()
## Not run: # Create a new screen function with documentation TemplateScreenFunc( filename = "custom_screens.R", func_name = "MyCoxScreen", documentation = TRUE ) # Append to current script in RStudio TemplateScreenFunc(filename = "current", func_name = "QuickFilter") ## End(Not run)## Not run: # Create a new screen function with documentation TemplateScreenFunc( filename = "custom_screens.R", func_name = "MyCoxScreen", documentation = TRUE ) # Append to current script in RStudio TemplateScreenFunc(filename = "current", func_name = "QuickFilter") ## End(Not run)
Verifies if a user-provided function meets the interface requirements for the screening pipeline.
ValidateScreenFunc(func, ...)ValidateScreenFunc(func, ...)
func |
Function to validate. Must accept core parameters and return expected structure. |
... |
For future updates |
TRUE if all checks pass, otherwise terminates with diagnostic report
Other Add_Screen_method:
RegisterScreenMethod(),
ScreenStrategy,
TemplateScreenFunc()
## Not run: # Example compliant function my_screen <- function( sc_data, matched_bulk, phenotype, label_type, phenotype_class, verbose = FALSE, ... ) { if (verbose) { message("Running custom screen") } list( scRNA_data = sc_data, # Must be Seurat object results = data.frame(score = runif(10)) ) } ValidateScreenFunc(my_screen) ## End(Not run)## Not run: # Example compliant function my_screen <- function( sc_data, matched_bulk, phenotype, label_type, phenotype_class, verbose = FALSE, ... ) { if (verbose) { message("Running custom screen") } list( scRNA_data = sc_data, # Must be Seurat object results = data.frame(score = runif(10)) ) } ValidateScreenFunc(my_screen) ## End(Not run)
Aggregates classification votes from multiple voters using weighted scoring. Each voter assigns one of four labels ("Positive", "Negative", "Neutral", "Other") to each item, and votes are combined using user-specified weights.
WeightedVote( vote_data = data.frame(), weights = double(), ties.method = c("random", "first", "last") )WeightedVote( vote_data = data.frame(), weights = double(), ties.method = c("random", "first", "last") )
vote_data |
A data frame or matrix where:
Row names (if present) are preserved in the output. |
weights |
Named numeric vector specifying the weight for each voter.
Names must exactly match |
ties.method |
Character string specifying how to break ties. Must be one of "random", "first", or "last". |
Character vector of final aggregated labels, one per row in vote_data.
Each element is one of "Positive" or "Other" (the winner with
highest weighted score). If input has row names, they are preserved as names
in the output vector.
# Example 1: Simple majority voting vote_data <- data.frame( Expert1 = c("Positive", "Negative", "Neutral", "Positive"), Expert2 = c("Positive", "Neutral", "Other", "Negative"), Expert3 = c("Negative", "Positive", "Neutral", "Positive"), row.names = c("Cell1", "Cell2", "Cell3", "Cell4") ) weights <- c(Expert1 = 1, Expert2 = 1, Expert3 = 1) result <- WeightedVote(vote_data, weights)# Example 1: Simple majority voting vote_data <- data.frame( Expert1 = c("Positive", "Negative", "Neutral", "Positive"), Expert2 = c("Positive", "Neutral", "Other", "Negative"), Expert3 = c("Negative", "Positive", "Neutral", "Positive"), row.names = c("Cell1", "Cell2", "Cell3", "Cell4") ) weights <- c(Expert1 = 1, Expert2 = 1, Expert3 = 1) result <- WeightedVote(vote_data, weights)
Writes an R object to the cache directory. Uses qs2 for fast
serialization when available, falling back to rdata for general
objects. Small data frames and data.tables are saved as CSV via
data.table::fwrite() for easy inspection.
WriteCache(cache, ...)WriteCache(cache, ...)
cache |
A |
... |
Additional arguments passed to methods. For
For
|
The ScreenMethodCache method writes both the cache metadata (via
WriteCacheMeta()) and the cached data objects to disk. The
ScreenMethodConfig method only writes the metadata.
When format = "auto" (default), the format for each data object is
detected automatically:
If the object is a 2D structure (data.frame/matrix) with at most
max_rows rows and max_cols columns, CSV format is used.
If qs2 is installed and the object is a list, vector,
data.frame, or matrix, qdata format is used.
If qs2 is installed but the object is not qdata-compatible,
qs2 format is used.
Otherwise, rdata format is used as a fallback.
Invisible. Returns the absolute path(s) to the written cache file(s).
WriteCache is an S7 generic with methods available for the following
classes:
ANY
SigBridgeR::ScreenMethodCache
SigBridgeR::ScreenMethodConfig
Other cache_config:
CacheSetHere(),
CacheSysCall(),
CheckCache(),
ChooseCache(),
LoadCache(),
WriteCacheMeta()
## Not run: # Write using a ScreenMethodCache cache <- ScreenMethodCache( cache_path = "Scissor_res/survival_2025_01_01/", cache_config_path = "Scissor_res/survival_2025_01_01/cache_config.json", cache_data = list(result = my_matrix), screen_method_config = config ) WriteCache(cache) # Force CSV format for small data frames WriteCache(cache, format = "csv") ## End(Not run)## Not run: # Write using a ScreenMethodCache cache <- ScreenMethodCache( cache_path = "Scissor_res/survival_2025_01_01/", cache_config_path = "Scissor_res/survival_2025_01_01/cache_config.json", cache_data = list(result = my_matrix), screen_method_config = config ) WriteCache(cache) # Force CSV format for small data frames WriteCache(cache, format = "csv") ## End(Not run)
Writes metadata for SigBridgeR cache identification to a JSON file. The metadata includes general system information, cache configuration, and an optional user-provided description.
WriteCacheMeta(cache_config, ...)WriteCacheMeta(cache_config, ...)
cache_config |
A |
... |
Additional arguments passed to methods. For
For
|
This function creates a JSON metadata file containing:
general: File path, OS information, timestamp, R version, and
SigBridgeR version
config: Screen method, phenotype class, label type, and parameters
description: Additional user-provided description
The JSON file includes a header comment indicating it is required for cache identification and should not be modified.
Only for SigBridgeR version >= 3.7.0.
Invisible. Returns the metadata list that was written to the file.
WriteCacheMeta is an S7 generic with methods available for the following
classes:
ANY
SigBridgeR::ScreenMethodCache
SigBridgeR::ScreenMethodConfig
Other cache_config:
CacheSetHere(),
CacheSysCall(),
CheckCache(),
ChooseCache(),
LoadCache(),
WriteCache()
## Not run: # Write metadata for a ScreenMethodConfig config <- ScreenMethodConfig( method_name = "Scissor", param = list(alpha = 0.05) ) WriteCacheMeta(config, file = "cache/cache_config.json") # With an additional description WriteCacheMeta(config, file = "cache/cache_config.json", additional_description = "Scissor screening for survival phenotype" ) ## End(Not run)## Not run: # Write metadata for a ScreenMethodConfig config <- ScreenMethodConfig( method_name = "Scissor", param = list(alpha = 0.05) ) WriteCacheMeta(config, file = "cache/cache_config.json") # With an additional description WriteCacheMeta(config, file = "cache/cache_config.json", additional_description = "Scissor screening for survival phenotype" ) ## End(Not run)