| Title: | Personalized Drug Response Prediction from Single-Cell Transcriptomics |
|---|---|
| Description: | An R implementation of the PERCEPTION approach (Sinha et al., 2024) for predicting personalized drug response from single-cell tumor transcriptomics. It trains drug-response models on large-scale cell-line screens, predicts sensitivity at clone and patient level, and ships an interactive visualization suite plus a Shiny web application. |
| Authors: | Jia Ding [aut, cre] (ORCID: <https://orcid.org/0009-0002-2530-0897>), Yuxi Yang [ctb] (ORCID: <https://orcid.org/0009-0006-1329-1224>) |
| Maintainer: | Jia Ding <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.0 |
| Built: | 2026-11-16 17:01:37 UTC |
| Source: | https://github.com/WangLabCSU/PERCEPTIONx |
Add custom download mirrors
add_mirrors(urls, position = c("first", "last"))add_mirrors(urls, position = c("first", "last"))
urls |
Character vector of mirror URLs to add. |
position |
Character. Where to add: "first" or "last". Default: "first". |
Invisibly returns the updated mirror list.
## Not run: add_mirrors("https://my-mirror.com/https://github.com") add_mirrors(c("https://mirror1.com/https://github.com", "https://mirror2.com/https://github.com")) ## End(Not run)## Not run: add_mirrors("https://my-mirror.com/https://github.com") add_mirrors(c("https://mirror1.com/https://github.com", "https://mirror2.com/https://github.com")) ## End(Not run)
Performs Seurat clustering on a single-cell expression matrix and returns a mapping of each cell to its cluster (clone) ID. This matches the original PERCEPTIONx pipeline where Seurat clusters define transcriptional subclones.
annotate_clones( method = c("umap", "tsne"), expression_matrix, min_cells = 3L, min_features = 200L, nfeatures = 2000L, dims = 10L, resolution = 0.8, seed = 42L, progress_cb = NULL, cluster_algorithm = 1L, variable_selection = c("vst", "dispersion", "mvp") )annotate_clones( method = c("umap", "tsne"), expression_matrix, min_cells = 3L, min_features = 200L, nfeatures = 2000L, dims = 10L, resolution = 0.8, seed = 42L, progress_cb = NULL, cluster_algorithm = 1L, variable_selection = c("vst", "dispersion", "mvp") )
method |
Character. Dimensionality reduction method. One of |
expression_matrix |
Matrix. Gene expression matrix with genes as rows and cells as columns. Raw counts or normalized values are both accepted. |
min_cells |
Integer. Minimum cells per feature. Default = 3. |
min_features |
Integer. Minimum features per cell. Default = 200. |
nfeatures |
Integer. Number of variable features. Default = 2000. |
dims |
Integer. Number of PCA dimensions for clustering. Default = 10. |
resolution |
Numeric. Clustering resolution. Default = 0.8. |
seed |
Integer. Random seed for reproducibility. Default = 42. |
progress_cb |
Optional function called with the current Seurat stage
name (e.g. |
cluster_algorithm |
Integer. Community-detection algorithm passed to
|
variable_selection |
Character. Variable-feature selection method for
|
A data frame with columns: cell_id, clone_id, and
dim_1, dim_2 (2D embedding coordinates for visualization).
## Not run: cell_clone_map <- annotate_clones(patient_expression) cell_clone_map <- annotate_clones("tsne", patient_expression) ## End(Not run)## Not run: cell_clone_map <- annotate_clones(patient_expression) cell_clone_map <- annotate_clones("tsne", patient_expression) ## End(Not run)
Computes the number of cells per clone per patient, producing the
clone_counts data frame required by predict_patients().
build_clone_counts(cell_clone_map, patient_ids)build_clone_counts(cell_clone_map, patient_ids)
cell_clone_map |
Data frame with columns |
patient_ids |
Character vector. Patient ID for each cell, in the same order as rows in cell_clone_map. |
A data frame with first column patients and remaining columns
as clone IDs with cell counts as values.
The inverse of parse_clone_keys(): pastes patient and clone identifiers
into a single "patient@clone_id" key. The "@" separator is
the canonical clone-key format used throughout PERCEPTIONx.
build_clone_key(patient, clone_id)build_clone_key(patient, clone_id)
patient |
Character vector of patient IDs. |
clone_id |
Character vector of clone IDs. |
Character vector of "patient@clone_id" keys.
parse_clone_keys() for splitting keys back apart.
Core training function that builds a glmnet model using bulk expression, then evaluates on pseudo-bulk, bulk test, and single-cell test data. This is the direct port of build_on_BULK_v2 from step0B.
build_on_BULK_v2( infunc_drugName, infunc_cancerType = "PanCan", exclude_cancer = "PanCan", infunc_features, single_best = infunc_features[1L], k_features = 100L, infunc_alpha = 1L, model_type = "glmnet", num_folds = 3L, num_tree = 500L, seed = 1L, alpha_gradient = 0.05, lambda_gradient = 20L, lambda_range = c(1e-04, 1L), cv_method = "cv" )build_on_BULK_v2( infunc_drugName, infunc_cancerType = "PanCan", exclude_cancer = "PanCan", infunc_features, single_best = infunc_features[1L], k_features = 100L, infunc_alpha = 1L, model_type = "glmnet", num_folds = 3L, num_tree = 500L, seed = 1L, alpha_gradient = 0.05, lambda_gradient = 20L, lambda_range = c(1e-04, 1L), cv_method = "cv" )
infunc_drugName |
Character. Drug name. |
infunc_cancerType |
Character. Cancer type for training. Default = "PanCan". |
exclude_cancer |
Character. Cancer type to exclude. Default = "PanCan". |
infunc_features |
Character vector. Feature gene names (ranked). |
single_best |
Character. Name of the single best feature. Default = infunc_features[1]. |
k_features |
Integer. Number of top features to use. Default = 100. |
infunc_alpha |
Numeric. Alpha for glmnet (not used directly, tuning via alpha_gradient). Default = 1. |
model_type |
Character. Model type: "glmnet" or "rf". Default = "glmnet". |
num_folds |
Integer. Number of CV folds. Default = 3. |
num_tree |
Integer. Number of trees for random forest. Default = 500. |
seed |
Integer. Random seed for training. Default = 1. |
alpha_gradient |
Numeric. Step size for alpha grid in glmnet tuning. Default = 0.05. |
lambda_gradient |
Integer. Number of lambda values in glmnet tuning grid. Default = 20. |
lambda_range |
Numeric vector of length 2. Min and max lambda for tuning grid. Default = c(0.0001, 1). |
cv_method |
Character. Cross-validation method for caret::trainControl. Default = "cv". |
A list containing: model, single_best, model_performance_during_cv, performance_in_bulk, performance_in_pseudo_bulk, performance_in_scRNA, predVSgroundTruth.
For each patient, groups cells by clone_id and computes the mean expression of each gene within each clone. This reduces single-cell resolution to subclone resolution, matching the original PERCEPTION pipeline.
clone_mean_expression(expression_matrix, cell_clone_map, patient_ids = NULL)clone_mean_expression(expression_matrix, cell_clone_map, patient_ids = NULL)
expression_matrix |
Matrix or data frame. Gene expression matrix with genes as rows and cells as columns. |
cell_clone_map |
Data frame with columns |
patient_ids |
Character vector. Patient ID for each cell, same length as columns of expression_matrix. If NULL, all cells are assumed from one patient. |
A named list of matrices, one per patient. Each matrix has genes as rows and clone IDs as columns, with mean expression values.
Implements the IDA (Independent Drug Action) combination principle used in
PERCEPTION: each clone-level drug viability is first z-score scaled across
all clones, then the per-clone combined score is derived from the
drug-specific z-scores. The default rule min means "the most effective
drug in the combination drives the clone-level combined score" — the exact
rule hard-coded in the Shiny app's internal combo_clone_frame().
combine_drugs( pred, patient = NULL, clone_id = NULL, combine_rule = c("min", "mean", "max", "median"), na.rm = TRUE, include_single_z = FALSE )combine_drugs( pred, patient = NULL, clone_id = NULL, combine_rule = c("min", "mean", "max", "median"), na.rm = TRUE, include_single_z = FALSE )
pred |
Matrix, data.frame, or data.table of clone-level drug viability
predictions. Typically the output of |
patient |
Optional character vector of patient IDs, length equal to
|
clone_id |
Optional character vector of clone IDs, length equal to
|
combine_rule |
Character scalar, per-clone aggregation after z-scoring.
Must be one of |
na.rm |
Logical, passed through to the aggregator. Default |
include_single_z |
Logical. If |
This function is the missing glue between predict_drugs() and downstream
patient-level aggregation / visualisation. Its output feeds directly into
predict_patients() (as the app's predict_patients() already skips
re-standardising the comb_viability column) and plot_clone_viability().
A data.frame with columns:
Patient ID.
Clone ID.
Combined viability score (already z-scored across
clones, so predict_patients() will not standardise it again).
(optional, when include_single_z = TRUE) one
additional column per input drug, named like <drug>.z,
containing the per-drug z-scores before combination.
pred <- predict_drugs(models, rank_expr) # clones x drugs matrix clone_df <- combine_drugs(pred) # patient / clone_id / comb_viability pat <- predict_patients(clone_df, prepared_data) plot_clone_viability(clone_df, viability_var = "comb_viability")
The patient-level aggregated score will be identical to the one produced by the Shiny app for the same drugs / clones.
The default min rule amplifies noise when individual drug models are
very poor — the "least bad" model can still be quite bad, but min
picks it as the best combination driver. For exploratory analyses you can
pass combine_rule = "mean" or combine_rule = "max" and compare.
When only one drug is present in pred, the combined score is simply
that drug's z-score.
predict_drugs(), predict_patients(), plot_clone_viability(),
zscore_viability()
Computes and summarizes performance metrics across multiple drug models. Returns performance in cross-validation, bulk test, pseudo-bulk, and scRNA datasets.
compare_performance(model_list, threshold = 0.3, verbose = TRUE)compare_performance(model_list, threshold = 0.3, verbose = TRUE)
model_list |
A named list of trained model objects from train_models(). |
threshold |
Numeric. Minimum correlation threshold for "passing" models. Default = 0.3. |
verbose |
Logical. Whether to print summary statistics. Default = TRUE. |
A list containing:
Cross-validation performance (|correlation| = sqrt(R²); p-value not available) for each drug
Bulk test set performance for each drug
Pseudo-bulk performance for each drug
Single-cell RNA performance for each drug
Summary statistics of models passing threshold
## Not run: models <- train_models(drug_list = c("abemaciclib", "erlotinib")) perf <- compare_performance(models) ## End(Not run)## Not run: models <- train_models(drug_list = c("abemaciclib", "erlotinib")) perf <- compare_performance(models) ## End(Not run)
A generic function for fast correlation testing. Dispatches methods based on
the class of the first argument. This is a trimmed-down version of the base R
cor.test function, optimized for speed in large-scale computations.
cor.test_trimmed_v0(x, ...)cor.test_trimmed_v0(x, ...)
x |
First argument (typically a numeric vector). |
... |
Additional arguments passed to methods. |
A list containing the p-value and correlation estimate. The exact structure depends on the method used.
cor.test for the full version with confidence intervals.
Calculates weighted average of clone-level expression to produce a pseudo-bulk expression profile for a single patient. This is used for evaluating model performance on pseudo-bulk data, not for prediction.
each_patient_pseudo_bulk( x = 1L, comb_viability_df, Clone_Counts_per_patients, clone_Level_z_expression_df )each_patient_pseudo_bulk( x = 1L, comb_viability_df, Clone_Counts_per_patients, clone_Level_z_expression_df )
x |
Integer. Index of the patient. Default = 1. |
comb_viability_df |
Data frame. Retained for backward compatibility; no longer used (clone ids are read from the expression column names). |
Clone_Counts_per_patients |
Data frame. Patient-clone abundance data. |
clone_Level_z_expression_df |
Matrix. Clone-level expression data with columns named by patient-clone identifiers. |
Named numeric vector of pseudo-bulk expression values.
High-resolution plot export using the Cairo rendering engine for superior anti-aliasing and cross-platform font rendering.
export_plot_cairo( file, plot, format = "png", width = 7L, height = 5L, res = 600L, draw_fun = NULL )export_plot_cairo( file, plot, format = "png", width = 7L, height = 5L, res = 600L, draw_fun = NULL )
file |
Character. Output file path. |
plot |
A ggplot or grid object to export. |
format |
Character. One of |
width |
Numeric. Plot width in inches. Default = 7. |
height |
Numeric. Plot height in inches. Default = 5. |
res |
Numeric. Output resolution (DPI) for PNG. Default = 600, minimum 96. |
draw_fun |
Function. Optional custom draw function (e.g. |
Invisibly returns the file path. Called for its side effect of creating the file.
## Not run: p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() export_plot_cairo("plot.png", p) export_plot_cairo("plot.pdf", p, format = "pdf") ## End(Not run)## Not run: p <- ggplot2::ggplot(mtcars, ggplot2::aes(wt, mpg)) + ggplot2::geom_point() export_plot_cairo("plot.png", p) export_plot_cairo("plot.pdf", p, format = "pdf") ## End(Not run)
Performs False Discovery Rate (FDR) correction using the Benjamini-Hochberg method.
This is a wrapper around p.adjust with method = "fdr".
fdrcorr(test_list)fdrcorr(test_list)
test_list |
A numeric vector of p-values to be corrected. |
A numeric vector of FDR-adjusted p-values (q-values).
Computes Pearson correlation between each gene's expression and drug response, then ranks genes by absolute correlation. This matches the original feature_ranking_bulk function from step0B.
feature_ranking_bulk( infunc_drugName, infunc_cancerType = "PanCan", exclude_cancer = "PanCan", infunc_GOI, ncores = 4L )feature_ranking_bulk( infunc_drugName, infunc_cancerType = "PanCan", exclude_cancer = "PanCan", infunc_GOI, ncores = 4L )
infunc_drugName |
Character. Name of the drug. |
infunc_cancerType |
Character. Cancer type for training. Default = "PanCan". |
exclude_cancer |
Character. Cancer type to exclude. Default = "PanCan". |
infunc_GOI |
Character vector. Genes of Interest to rank. |
ncores |
Number of cores to use for parallelization. Default = 4. |
Matrix of ranked features with columns: p.value, estimate.cor (sorted by abs(cor) descending)
Identifies which cell lines should be used for training and which should be excluded (reserved for testing) based on cancer type and single-cell data availability.
get_cellLine_list( infunc_cancerType = "PanCan", infunc_drugName, exclude_cancer = "PanCan", infunc_response, force_add_cellLines = TRUE, force_add_cellLines_list = NA )get_cellLine_list( infunc_cancerType = "PanCan", infunc_drugName, exclude_cancer = "PanCan", infunc_response, force_add_cellLines = TRUE, force_add_cellLines_list = NA )
infunc_cancerType |
Character. Cancer type for training. Default = "PanCan". |
infunc_drugName |
Character. Name of the drug. |
exclude_cancer |
Character. Cancer type to exclude from training. Default = "PanCan". |
infunc_response |
Named numeric vector. Drug response data. |
force_add_cellLines |
Logical. Whether to force add additional cell lines. Default = TRUE. |
force_add_cellLines_list |
Character vector. Cell line IDs to force add. Default = NA. |
A list of length 2:
[1] common_cellLines: Cell lines to use for training
[2] cellLines2remove: Cell lines excluded (reserved for testing)
Retrieves the DepMap dataset from the package-level cache.
This is the recommended way to access DepMap data after loading
with load_depmap(read = TRUE).
get_depmap()get_depmap()
The DepMap list object. Errors if the data has not been loaded yet.
## Not run: load_depmap(read = TRUE) depmap <- get_depmap() ## End(Not run)## Not run: load_depmap(read = TRUE) depmap <- get_depmap() ## End(Not run)
Returns the current mirror list, including any user-added mirrors. User-added mirrors are tried first by default.
get_mirrors()get_mirrors()
Character vector of mirror URLs.
get_mirrors()get_mirrors()
Loads a saved model RDS file and returns only its performance portion. The file is deserialized fully first (an RDS is read as a whole), then the performance entries are extracted.
get_performance(filepath, drug_names = NULL)get_performance(filepath, drug_names = NULL)
filepath |
Character. Path to a single saved model RDS file. |
drug_names |
Character vector. Optional. Specific drug names to load. If NULL, loads all drugs in the file. |
A list containing performance metrics for each drug model.
## Not run: # Load performance from a single model file perf <- get_performance("models/PERCEPTIONx_models_PanCan_exPanCan_20240101_120000.RDS") # Or use compare_performance on the result models <- readRDS("models/PERCEPTIONx_models_PanCan_exPanCan_20240101_120000.RDS") perf <- compare_performance(models) ## End(Not run)## Not run: # Load performance from a single model file perf <- get_performance("models/PERCEPTIONx_models_PanCan_exPanCan_20240101_120000.RDS") # Or use compare_performance on the result models <- readRDS("models/PERCEPTIONx_models_PanCan_exPanCan_20240101_120000.RDS") perf <- compare_performance(models) ## End(Not run)
Extracts the drug response (AUC) for a given drug from the DepMap database. The function handles multiple screening batches by prioritizing MTS over HTS and selecting the batch with the fewest missing values.
get_response_matrix(infunc_drugName)get_response_matrix(infunc_drugName)
infunc_drugName |
Character string. Name of the drug (e.g., "erlotinib"). |
A named numeric vector of AUC values for all cell lines.
Filters model list to return only models that meet performance criteria. Useful for selecting significant drug models for downstream analysis.
get_significant_models( model_list, min_correlation = 0.3, max_pvalue = 0.05, dataset = "scRNA" )get_significant_models( model_list, min_correlation = 0.3, max_pvalue = 0.05, dataset = "scRNA" )
model_list |
A named list of trained model objects. |
min_correlation |
Numeric. Minimum correlation threshold. Default = 0.3. |
max_pvalue |
Numeric. Maximum p-value threshold. Default = 0.05. |
dataset |
Character. Which dataset to use for filtering: "scRNA" (default), "bulk", "pseudo_bulk", or "cv". |
A filtered list containing only models meeting the criteria.
## Not run: models <- train_models() significant_models <- get_significant_models(models, min_correlation = 0.3, max_pvalue = 0.05) ## End(Not run)## Not run: models <- train_models() significant_models <- get_significant_models(models, min_correlation = 0.3, max_pvalue = 0.05) ## End(Not run)
Tests whether the overlap between two gene lists is statistically significant. It answers the question: given a background set of genes (global), a reference gene set (base_list), and a test gene set (test_list), is the overlap between test_list and base_list more than expected by chance?
hypergeometric_test_for_twolists( test_list, base_list, global, lower.tail = FALSE )hypergeometric_test_for_twolists( test_list, base_list, global, lower.tail = FALSE )
test_list |
Character vector. The test gene list. |
base_list |
Character vector. The reference gene list. |
global |
Character vector. The background gene set. |
lower.tail |
Logical. If FALSE (default), calculates the probability of observing greater than or equal to the observed overlap (enrichment). If TRUE, calculates the probability of observing less than or equal to the observed overlap (depletion). |
Numeric p-value.
List current download mirrors
list_mirrors()list_mirrors()
Downloads the filtered DepMap RDS file for training models from GitHub Release. The file contains bulk expression, scRNA expression, drug response annotations, and cell line metadata required for PERCEPTIONx model training. Supports automatic mirror fallback for users in different regions.
load_depmap( dest = perception_default_depmap_dir(), read = FALSE, mirror = FALSE, mirror_url = NULL, timeout_seconds = 300L, retries = 1L, force = FALSE )load_depmap( dest = perception_default_depmap_dir(), read = FALSE, mirror = FALSE, mirror_url = NULL, timeout_seconds = 300L, retries = 1L, force = FALSE )
dest |
Directory to save the downloaded file. Default: the user cache
directory ( |
read |
Whether to read the data and assign to global environment as "DepMap". Default = FALSE. |
mirror |
Logical. If FALSE (default), download from GitHub directly.
If TRUE, use mirror sites from |
mirror_url |
Character. A specific mirror URL to use (e.g.,
|
timeout_seconds |
Numeric, timeout for each download attempt in seconds. Default = 300. |
retries |
Integer, number of retries for each mirror. Default = 1. |
force |
Logical. If TRUE, delete an existing cached file before downloading again (use after an interrupted/failed download left a corrupt file behind). Default = FALSE (keep and reuse the cache). |
Invisibly returns the DepMap object if read = TRUE, otherwise NULL.
## Not run: # Download from GitHub directly load_depmap(read = TRUE) # Use mirror sites load_depmap(read = TRUE, mirror = TRUE) # Force a fresh download (removes any cached copy first) load_depmap(read = TRUE, mirror = TRUE, force = TRUE) # Use a specific mirror load_depmap(read = TRUE, mirror_url = "https://gh-proxy.com/https://github.com") ## End(Not run)## Not run: # Download from GitHub directly load_depmap(read = TRUE) # Use mirror sites load_depmap(read = TRUE, mirror = TRUE) # Force a fresh download (removes any cached copy first) load_depmap(read = TRUE, mirror = TRUE, force = TRUE) # Use a specific mirror load_depmap(read = TRUE, mirror_url = "https://gh-proxy.com/https://github.com") ## End(Not run)
Downloads model files from GitHub Release if not cached locally. Supports automatic mirror fallback for users in different regions.
load_model( ..., dest = perception_default_model_dir(), read = FALSE, mirror = FALSE, mirror_url = NULL, timeout_seconds = 30L, retries = 0L, force = FALSE, all = FALSE )load_model( ..., dest = perception_default_model_dir(), read = FALSE, mirror = FALSE, mirror_url = NULL, timeout_seconds = 30L, retries = 0L, force = FALSE, all = FALSE )
... |
One or more drug names (e.g., "erlotinib", "gefitinib"). |
dest |
Directory to save downloaded models. Default: a cache-root
derived path (see |
read |
Whether to read and return the downloaded model(s) as a named list. Default = FALSE (download only). |
mirror |
Logical. If FALSE (default), download from GitHub directly.
If TRUE, use mirror sites from |
mirror_url |
Character. A specific mirror URL to use (e.g.,
|
timeout_seconds |
Numeric, timeout for each download attempt in seconds. Default = 30. |
retries |
Integer, number of retries for each mirror. Default = 0. |
force |
Logical. If TRUE, delete an existing cached model file before downloading it again (use after an interrupted/failed download left a corrupt file behind). Default = FALSE (keep and reuse the cache). |
all |
Logical. If TRUE, download all 44 pre-trained models (useful to
pre-cache the full model set on a deployment server). Overrides any
drug names given in |
If read = TRUE, a named list of model objects (names = drug names).
If read = FALSE, invisibly returns NULL (files are saved to disk only).
The returned list can be directly passed to predict_drugs(),
compare_performance(), or get_significant_models().
## Not run: # Download and load models from GitHub directly models <- load_model("erlotinib", "gefitinib", read = TRUE) # Use mirror sites models <- load_model("erlotinib", "gefitinib", read = TRUE, mirror = TRUE) # Use a specific mirror models <- load_model("erlotinib", read = TRUE, mirror_url = "https://gh-proxy.com/https://github.com") ## End(Not run)## Not run: # Download and load models from GitHub directly models <- load_model("erlotinib", "gefitinib", read = TRUE) # Use mirror sites models <- load_model("erlotinib", "gefitinib", read = TRUE, mirror = TRUE) # Use a specific mirror models <- load_model("erlotinib", read = TRUE, mirror_url = "https://gh-proxy.com/https://github.com") ## End(Not run)
Splits a character vector of clone identifiers (e.g. "PAT_001@0") into a
data frame with patient and clone_id columns.
parse_clone_keys(x)parse_clone_keys(x)
x |
Character vector of clone keys in |
A data frame with columns patient and clone_id.
build_clone_key() for the inverse operation.
The 44 pre-trained model drugs shipped with the package (used by load_model(all = TRUE) to pre-cache the full set on deployment servers). Single source of truth — train_models() defaults and the Shiny app's drug dropdown both read this list.
perception_all_drugsperception_all_drugs
Drug catalogue inside the DepMap data we provide. Extracted from secondary_screen_drugAnnotation$CommonName (PRISM secondary screen, sorted). The 44 pre-trained models (perception_all_drugs) are a subset of this list; every other drug here can be trained on the Train tab once DepMap is loaded.
perception_depmap_drugsperception_depmap_drugs
FDA-approved cancer drugs (Table S2 of Sinha et al., Nat Cancer 2024). 142 compounds, all of them present in perception_depmap_drugs; the 44 pre-trained models (perception_all_drugs) are a subset of this list.
perception_fda_approved_drugsperception_fda_approved_drugs
Visualizes the proportion of each clone across patients as a stacked bar plot. Useful for understanding tumor heterogeneity and clonal architecture.
plot_clone_distribution( clone_distribution, response_var = NULL, base_size = 15L, tooltip = TRUE, tooltip_col = NULL )plot_clone_distribution( clone_distribution, response_var = NULL, base_size = 15L, tooltip = TRUE, tooltip_col = NULL )
clone_distribution |
Data frame with columns: patients, clones, weights. |
response_var |
Character. Optional column name for response annotation. If provided, facets by response. Default = NULL. |
base_size |
Numeric. Base font size. Default = 15. |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, bar segments get hover tooltips (clone + proportion). |
tooltip_col |
Character. Optional existing column used as the tooltip text. Default = NULL (auto-builds a rich tooltip). |
A ggplot object.
## Not run: # After computing clone weights clone_dist <- data.frame( patients = c("P1", "P1", "P1", "P2", "P2", "P2"), clones = c("c1", "c2", "c3", "c1", "c2", "c3"), weights = c(0.3, 0.5, 0.2, 0.6, 0.3, 0.1) ) plot_clone_distribution(clone_dist) ## End(Not run)## Not run: # After computing clone weights clone_dist <- data.frame( patients = c("P1", "P1", "P1", "P2", "P2", "P2"), clones = c("c1", "c2", "c3", "c1", "c2", "c3"), weights = c(0.3, 0.5, 0.2, 0.6, 0.3, 0.1) ) plot_clone_distribution(clone_dist) ## End(Not run)
Single cells in the 2D embedding colored by clone identity – the spatial analogue of the paper's Extended Data Fig. 8a, showing at a glance which transcriptional subclones sit where.
plot_clone_umap( tsne_data, clone_col = "clone_id", title = NULL, color_label = "Clone", point_size = NULL, base_size = 11L, tooltip = TRUE, tooltip_col = NULL )plot_clone_umap( tsne_data, clone_col = "clone_id", title = NULL, color_label = "Clone", point_size = NULL, base_size = 11L, tooltip = TRUE, tooltip_col = NULL )
tsne_data |
Data frame with columns: X, Y, and the clone column. |
clone_col |
Character. Name of the column holding clone ids. Default = "clone_id". |
title |
Character. Plot title. Default = NULL. |
color_label |
Character. Legend label. Default = "Clone". |
point_size |
Numeric. Point size. If NULL (default), auto-adapts to the number of cells to avoid overplotting. |
base_size |
Numeric. Base font size. Default = 11. |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, points get hover tooltips (clone id). |
tooltip_col |
Character. Optional existing column used as the tooltip text. Default = NULL (auto-builds from the clone id). |
A ggplot object.
Visualizes predicted drug sensitivity for each clone within patients. Each clone is represented as a point with a stem (lollipop style). Useful for identifying resistant clones within heterogeneous tumors.
plot_clone_viability( clone_viability, viability_var = "comb_viability", weights_var = NULL, response_var = NULL, drug = NULL, base_size = 11L, y_limits = c(-3L, 1.2), viridis_scale = FALSE, tooltip = TRUE, tooltip_col = NULL )plot_clone_viability( clone_viability, viability_var = "comb_viability", weights_var = NULL, response_var = NULL, drug = NULL, base_size = 11L, y_limits = c(-3L, 1.2), viridis_scale = FALSE, tooltip = TRUE, tooltip_col = NULL )
clone_viability |
Data frame with columns: patient, clone_id, and the
viability column named by |
viability_var |
Character. Column name for viability values. Default = "comb_viability". |
weights_var |
Character. Optional column name for clone weights (point size). Default = NULL. |
response_var |
Character. Optional column for response annotation. Default = NULL. |
drug |
Character. Drug name, used as plot title. Default = NULL. |
base_size |
Numeric. Base font size. Default = 11. |
y_limits |
Numeric vector. Y-axis limits. Default = c(-3, 1.2). |
viridis_scale |
Logical. If TRUE, uses a viridis sequential scale (dark = low/sensitive, yellow = high/resistant). If FALSE (default), uses the diverging red-blue scale (blue = low/sensitive, white = neutral, red = high/resistant) with data-driven limits, so every value keeps a real color – nothing clips to grey/NA outside a fixed window. |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, points get hover tooltips (clone + viability + proportion). |
tooltip_col |
Character. Optional existing column used as the tooltip text. Default = NULL (auto-builds a rich tooltip). |
Facet strategy is adaptive:
<= 12 patients: single-row grid, strips on the bottom (45 deg).
> 12 patients: facet_wrap grid, one compact panel per patient.
A ggplot object.
## Not run: clone_kill <- data.frame( patient = c("P1", "P1", "P2", "P2"), clone_id = c("c1", "c2", "c1", "c2"), comb_viability = c(-0.5, 0.8, -1.2, 0.3) ) plot_clone_viability(clone_kill, viability_var = "comb_viability") ## End(Not run)## Not run: clone_kill <- data.frame( patient = c("P1", "P1", "P2", "P2"), clone_id = c("c1", "c2", "c1", "c2"), comb_viability = c(-0.5, 0.8, -1.2, 0.3) ) plot_clone_viability(clone_kill, viability_var = "comb_viability") ## End(Not run)
Visualizes the number of drugs achieving different correlation thresholds across bulk, pseudo-bulk, and single-cell datasets.
plot_model_performance( performance_list, threshold_range = NULL, base_size = 20L, highlight_threshold = 0.3, tooltip = TRUE )plot_model_performance( performance_list, threshold_range = NULL, base_size = 20L, highlight_threshold = 0.3, tooltip = TRUE )
performance_list |
Named list of model performance objects (from train_perception_models). |
threshold_range |
Numeric vector. Correlation thresholds to evaluate. Default = NULL (auto: from 0.1 up to at least 0.6, extended to the highest observed correlation so the curve always reaches 0). |
base_size |
Numeric. Base font size. Default = 20. |
highlight_threshold |
Numeric. Threshold to highlight with vertical line. Default = 0.3. |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, points get hover tooltips (dataset, threshold, drug count). |
A ggplot object.
## Not run: models <- train_perception_models(c("abemaciclib", "erlotinib"), ...) plot_model_performance(models) ## End(Not run)## Not run: models <- train_perception_models(c("abemaciclib", "erlotinib"), ...) plot_model_performance(models) ## End(Not run)
For each model and each validation dataset (bulk, pseudo-bulk, single-cell), the observed response is stratified into the top vs bottom 50\ (resistant vs sensitive – the PERCEPTION paper's convention, Extended Data Fig. 4C) and a ROC curve of the predicted viability is drawn, one curve per dataset, with the AUC annotated in the legend. Higher AUC = the model stratifies better. This is the most informative single-model summary after training.
plot_model_roc(performance_list, base_size = 13L)plot_model_roc(performance_list, base_size = 13L)
performance_list |
Named list of model objects from |
base_size |
Numeric. Base font size. Default = 13. |
A ggplot object: ROC curves per validation dataset, faceted by drug when more than one model is provided.
## Not run: models <- train_models(drug_list = "abemaciclib", ...) plot_model_roc(models) ## End(Not run)## Not run: models <- train_models(drug_list = "abemaciclib", ...) plot_model_roc(models) ## End(Not run)
Generates a comprehensive visualization panel for patient drug response prediction, including clone distribution, clone-level viability, response boxplot, and ROC curve. This is a convenience function that combines multiple plot functions.
plot_patient_response_panel( clone_distribution, clone_viability, exp_vs_pred, response_col = "response", viability_col = "comb_viability", predicted_col = "predicted_viability", weights_col = "weights", layout_matrix = NULL )plot_patient_response_panel( clone_distribution, clone_viability, exp_vs_pred, response_col = "response", viability_col = "comb_viability", predicted_col = "predicted_viability", weights_col = "weights", layout_matrix = NULL )
clone_distribution |
Data frame. Clone weights per patient. |
clone_viability |
Data frame. Viability scores per clone. |
exp_vs_pred |
Data frame. Predicted vs observed response. |
response_col |
Character. Response column name. Default = "response". |
viability_col |
Character. Viability column name. Default = "comb_viability". |
predicted_col |
Character. Predicted values column name. Default = "predicted_viability". |
weights_col |
Character. Weights column name. Default = "weights". |
layout_matrix |
Matrix. Layout for grid.arrange. Default = NULL (auto). |
A gtable object from grid.arrange.
## Not run: # After running prediction pipeline panel <- plot_patient_response_panel( clone_distribution = clone_dist_df, clone_viability = clone_kill_df, exp_vs_pred = response_df ) ggsave(panel, filename = "patient_response.pdf", height = 15, width = 10) ## End(Not run)## Not run: # After running prediction pipeline panel <- plot_patient_response_panel( clone_distribution = clone_dist_df, clone_viability = clone_kill_df, exp_vs_pred = response_df ) ggsave(panel, filename = "patient_response.pdf", height = 15, width = 10) ## End(Not run)
Draws one violin per metric, split by whether the cell was kept, with the per-patient thresholds drawn as horizontal lines. This is what makes the automatic QC auditable: a user does not need to understand the MAD rule to see whether their data were cut too aggressively.
plot_qc_report( qc_metrics, kept_cells, qc_report, base_size = 12, metric = c("all", "Detected genes", "Total counts", "Mitochondrial %"), ncol = 6L )plot_qc_report( qc_metrics, kept_cells, qc_report, base_size = 12, metric = c("all", "Detected genes", "Total counts", "Mitochondrial %"), ncol = 6L )
qc_metrics |
Data frame returned as |
kept_cells |
Character vector of cell IDs that passed QC. |
qc_report |
Data frame returned as |
base_size |
Numeric. Base font size. Default = 12. |
metric |
Character. |
ncol |
Integer. Number of facet columns in the per-patient layout. Default = 6. |
A ggplot object, faceted by metric.
Creates a combined violin + box + jitter plot comparing predicted viability between response groups (e.g., Responders vs Non-Responders) with a statistical significance bracket.
plot_response_boxplot( exp_vs_pred, response_var = "response", predicted_var = "predicted_viability", y_label = "Predicted Viability (z-score)", base_size = 15L, compare_method = "wilcox.test", alternative = "less", tooltip = TRUE )plot_response_boxplot( exp_vs_pred, response_var = "response", predicted_var = "predicted_viability", y_label = "Predicted Viability (z-score)", base_size = 15L, compare_method = "wilcox.test", alternative = "less", tooltip = TRUE )
exp_vs_pred |
Data frame with columns: response, predicted_viability. |
response_var |
Character. Column name for response labels. Default = "response". |
predicted_var |
Character. Column name for predicted values. Default = "predicted_viability". |
y_label |
Character. Y-axis label. Default = "Predicted Viability (z-score)". |
base_size |
Numeric. Base font size. Default = 15. |
compare_method |
Character. Statistical test method. One of
|
alternative |
Character. Alternative hypothesis direction. Default = "less". |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, jittered points get hover tooltips. |
A ggplot object.
## Not run: exp_pred <- data.frame( response = factor(c("R", "NR", "R", "NR")), predicted_viability = c(0.8, 0.2, 0.7, 0.3) ) plot_response_boxplot(exp_pred) ## End(Not run)## Not run: exp_pred <- data.frame( response = factor(c("R", "NR", "R", "NR")), predicted_viability = c(0.8, 0.2, 0.7, 0.3) ) plot_response_boxplot(exp_pred) ## End(Not run)
Generates a ROC curve from predicted vs observed response with AUC value annotation.
plot_roc_curve( response, predictor, smooth_curve = TRUE, base_size = 15L, auc_digits = 3L, title = NULL, tooltip = TRUE )plot_roc_curve( response, predictor, smooth_curve = TRUE, base_size = 15L, auc_digits = 3L, title = NULL, tooltip = TRUE )
response |
Factor or numeric. True response labels (e.g., "R"/"NR" or 0/1). |
predictor |
Numeric. Predicted values (e.g., viability scores). |
smooth_curve |
Logical. Whether to smooth the ROC curve. Default = TRUE. |
base_size |
Numeric. Base font size. Default = 15. |
auc_digits |
Integer. Number of digits for AUC display. Default = 3. |
title |
Character. Plot title. Default = NULL. |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, curve points get hover tooltips (FPR / TPR). |
A ggplot object.
## Not run: response <- factor(c("R", "NR", "R", "NR", "R")) predictor <- c(0.8, 0.2, 0.7, 0.3, 0.9) plot_roc_curve(response, predictor) ## End(Not run)## Not run: response <- factor(c("R", "NR", "R", "NR", "R")) predictor <- c(0.8, 0.2, 0.7, 0.3, 0.9) plot_roc_curve(response, predictor) ## End(Not run)
Performs Seurat clustering on an expression matrix and generates a 2D embedding visualization (UMAP or t-SNE). Useful for identifying subclones within patient tumor samples.
plot_seurat_clustering( method = c("umap", "tsne"), expression_matrix, min_cells = 3L, min_features = 200L, nfeatures = 2000L, dims = 10L, resolution = 0.8, seed = 1L )plot_seurat_clustering( method = c("umap", "tsne"), expression_matrix, min_cells = 3L, min_features = 200L, nfeatures = 2000L, dims = 10L, resolution = 0.8, seed = 1L )
method |
Character. Dimensionality reduction method. One of |
expression_matrix |
Matrix. Gene expression matrix (genes as rows, cells as columns). |
min_cells |
Integer. Minimum cells per feature. Default = 3. |
min_features |
Integer. Minimum features per cell. Default = 200. |
nfeatures |
Integer. Number of variable features. Default = 2000. |
dims |
Integer. Number of PCA dimensions for clustering. Default = 10. |
resolution |
Numeric. Clustering resolution. Default = 0.8. |
seed |
Integer. Random seed. Default = 1. |
A list containing:
seurat_object |
Seurat object with clustering results |
embedding_plot |
ggplot 2D embedding visualization |
cluster_ids |
Named vector of cluster IDs per cell |
## Not run: result <- plot_seurat_clustering(patient_expression) result$embedding_plot result$cluster_ids ## End(Not run)## Not run: result <- plot_seurat_clustering(patient_expression) result$embedding_plot result$cluster_ids ## End(Not run)
Creates a side-by-side comparison of biomarker expression and predicted viability in UMAP space. Useful for visualizing correlation between marker and response.
plot_tsne_biomarker_viability( tsne_data, biomarker_var = "biomarker_scaled", viability_var = "viability_scaled", biomarker_label = "Biomarker Exp", viability_label = "Drug Viability", nrow = 1L, base_size = 8L )plot_tsne_biomarker_viability( tsne_data, biomarker_var = "biomarker_scaled", viability_var = "viability_scaled", biomarker_label = "Biomarker Exp", viability_label = "Drug Viability", nrow = 1L, base_size = 8L )
tsne_data |
Data frame with X, Y coordinates and both biomarker/viability columns. |
biomarker_var |
Character. Column name for biomarker expression. Default = "biomarker_scaled". |
viability_var |
Character. Column name for viability values. Default = "viability_scaled". |
biomarker_label |
Character. Legend label for biomarker. Default = "Biomarker Exp". |
viability_label |
Character. Legend label for viability. Default = "Drug Viability". |
nrow |
Integer. Number of rows in arrangement. Default = 1. |
base_size |
Numeric. Base font size. Default = 8. |
A gtable object from grid.arrange.
## Not run: tsne_data <- data.frame( X = lung_tSNE$X, Y = lung_tSNE$Y, biomarker_scaled = range01(rank(MDM2_expression)), viability_scaled = range01(rank(-viability_pred)) ) plot_tsne_biomarker_viability(tsne_data) ## End(Not run)## Not run: tsne_data <- data.frame( X = lung_tSNE$X, Y = lung_tSNE$Y, biomarker_scaled = range01(rank(MDM2_expression)), viability_scaled = range01(rank(-viability_pred)) ) plot_tsne_biomarker_viability(tsne_data) ## End(Not run)
Visualizes single cells in UMAP space with color overlay representing either biomarker expression or predicted drug sensitivity.
plot_tsne_response( tsne_data, color_var = "viability_scaled", title = NULL, color_label = "Predicted Viability", point_size = NULL, colors = NULL, palette = c("viridis", "diverging"), midpoint = 0L, limits = NULL, base_size = 11L, tooltip = TRUE, tooltip_col = NULL )plot_tsne_response( tsne_data, color_var = "viability_scaled", title = NULL, color_label = "Predicted Viability", point_size = NULL, colors = NULL, palette = c("viridis", "diverging"), midpoint = 0L, limits = NULL, base_size = 11L, tooltip = TRUE, tooltip_col = NULL )
tsne_data |
Data frame with columns: X, Y (coordinates), and optional biomarker/viability columns. |
color_var |
Character. Name of the column to use for color mapping. Default = "viability_scaled". |
title |
Character. Plot title. Default = NULL. |
color_label |
Character. Legend label for color. Default = "Predicted Viability". |
point_size |
Numeric. Point size. If NULL (default), auto-adapts to the number of cells to avoid overplotting. |
colors |
Character vector. Custom gradient colors (low, mid, high) for the sequential palette. Default = NULL (uses built-in viridis). |
palette |
Character. One of |
midpoint |
Numeric. Center value for diverging palette. Default = 0. |
limits |
Numeric vector of length 2. Optional fixed scale limits
(e.g. |
base_size |
Numeric. Base font size for theme. Default = 11. |
tooltip |
Logical. If TRUE (default) and ggiraph is installed, points get hover tooltips (cell id if present, else the colored value). |
tooltip_col |
Character. Optional existing column used as the tooltip text (e.g. "cell_id"). Default = NULL (auto-builds from color_var). |
A ggplot object.
## Not run: # After predicting viability for single cells tsne_data <- data.frame( X = lung_tSNE$X, Y = lung_tSNE$Y, viability_scaled = range01(rank(-viability_pred)) ) plot_tsne_response(tsne_data, color_var = "viability_scaled") ## End(Not run)## Not run: # After predicting viability for single cells tsne_data <- data.frame( X = lung_tSNE$X, Y = lung_tSNE$Y, viability_scaled = range01(rank(-viability_pred)) ) plot_tsne_response(tsne_data, color_var = "viability_scaled") ## End(Not run)
Given a trained model (or list of models) and a rank-normalized expression matrix, predicts viability scores for each cell/sample across one or more drugs. This function merges the former viability_from_model (single drug) and viability_in_each_dataset (multi-drug) into a unified interface.
predict_drugs(model_list, expr)predict_drugs(model_list, expr)
model_list |
A named list of model objects (each with a |
expr |
Matrix, data frame, or data.table. Rank-normalized expression with genes as rows and cells/samples as columns. A data.table carries no row names, so its first column must hold the gene identifiers and the remaining columns the cells/samples. |
If a small fraction (<= 50\
expr (e.g. genes filtered out during scRNA QC), they are imputed
with the neutral rank value 0.5 and a warning is issued. If more than half
of the features are missing, prediction stops with an error.
A matrix with cells/samples as rows and drugs as columns, containing predicted viability scores. Lower values indicate higher drug sensitivity.
## Not run: # Single drug models <- load_model("erlotinib", read = TRUE) pred <- predict_drugs(models, expr_rnorm) # Multiple drugs models <- train_models(drug_list = c("abemaciclib", "erlotinib"), cancer_type = "PanCan", exclude_cancer = "PanCan", GOI = GOI) pred <- predict_drugs(models, expr_rnorm) ## End(Not run)## Not run: # Single drug models <- load_model("erlotinib", read = TRUE) pred <- predict_drugs(models, expr_rnorm) # Multiple drugs models <- train_models(drug_list = c("abemaciclib", "erlotinib"), cancer_type = "PanCan", exclude_cancer = "PanCan", GOI = GOI) pred <- predict_drugs(models, expr_rnorm) ## End(Not run)
Aggregates clone-level drug response predictions to patient-level using various weighting strategies based on clone abundance. This function merges the former each_patient_viability (single drug) and each_patient_viabilityv2 (multi-drug) into a unified interface.
predict_patients( clone_pred, prepared_data, clone_counts = NULL, mode = "weighted_max", zscore = TRUE )predict_patients( clone_pred, prepared_data, clone_counts = NULL, mode = "weighted_max", zscore = TRUE )
clone_pred |
Matrix from |
prepared_data |
List from |
clone_counts |
Optional. Data frame or data.table with patients as rows
and clone IDs as columns. Only needed if |
mode |
Character. Aggregation method:
|
zscore |
Logical. Whether to z-score scale drug columns across patients
before aggregation. Default = TRUE. Matches the original PERCEPTION pipeline.
An already-standardized |
A data frame with patients as rows and drugs as columns, containing aggregated viability scores.
## Not run: # Simple workflow: pass prepare_data() output directly prepared <- prepare_data(patient_scRNA) clone_pred <- predict_drugs(models, prepared$clone_expression) patient_pred <- predict_patients(clone_pred, prepared) # Legacy workflow: manually build clone_viability_matrix clone_viability_df <- data.frame( patient = patient_ids, clone_id = clone_ids, clone_pred ) patient_pred <- predict_patients(clone_viability_df, clone_counts) ## End(Not run)## Not run: # Simple workflow: pass prepare_data() output directly prepared <- prepare_data(patient_scRNA) clone_pred <- predict_drugs(models, prepared$clone_expression) patient_pred <- predict_patients(clone_pred, prepared) # Legacy workflow: manually build clone_viability_matrix clone_viability_df <- data.frame( patient = patient_ids, clone_id = clone_ids, clone_pred ) patient_pred <- predict_patients(clone_viability_df, clone_counts) ## End(Not run)
End-to-end preprocessing pipeline that takes raw single-cell expression data
and produces a rank-normalized subclone expression matrix and clone counts
table, ready for direct use with predict_drugs() and
predict_patients().
prepare_data( method = c("umap", "tsne"), expression_matrix = NULL, patient_mapping = NULL, cell_col = "cell_id", patient_col = "patient_id", parse_patient = FALSE, patient_sep = "_", patient_pos = 1L, genes_to_use = NULL, seurat_resolution = 0.8, seurat_dims = 10L, seurat_nfeatures = 2000L, seurat_min_cells = 3L, seurat_min_features = 200L, seurat_seed = 42L, skip_clustering = FALSE, progress_cb = NULL, data = NULL, clone_labels = NULL, assay = NULL, layer = NULL, clone_col = NULL )prepare_data( method = c("umap", "tsne"), expression_matrix = NULL, patient_mapping = NULL, cell_col = "cell_id", patient_col = "patient_id", parse_patient = FALSE, patient_sep = "_", patient_pos = 1L, genes_to_use = NULL, seurat_resolution = 0.8, seurat_dims = 10L, seurat_nfeatures = 2000L, seurat_min_cells = 3L, seurat_min_features = 200L, seurat_seed = 42L, skip_clustering = FALSE, progress_cb = NULL, data = NULL, clone_labels = NULL, assay = NULL, layer = NULL, clone_col = NULL )
method |
Character. Dimensionality reduction method passed to
|
expression_matrix |
Matrix. Gene expression matrix with genes as rows and cells as columns. |
patient_mapping |
List, data frame, or character vector. Patient-cell mapping in one of three formats:
If NULL and |
cell_col |
Character. Cell ID column name in patient_mapping data frame. Default = "cell_id". Only used when patient_mapping is a data frame. |
patient_col |
Character. Patient ID column name in patient_mapping data frame. Default = "patient_id". Only used when patient_mapping is a data frame. |
parse_patient |
Logical. If TRUE, parse patient ID from cell_col using separator. Default = FALSE. Auto-enabled if patient_sep or patient_pos is provided. Useful when cell names contain patient info (e.g., "P11_M_Barcode"). |
patient_sep |
Character. Separator to split cell_col for parsing patient ID. Default = "_". Providing this parameter auto-enables parse_patient. |
patient_pos |
Integer. Position of patient ID after splitting. Default = 1 (first element). Providing this parameter auto-enables parse_patient. |
genes_to_use |
Character vector. Genes to retain in the output matrix. If NULL, all genes in the expression matrix are used. |
seurat_resolution |
Numeric. Clustering resolution. Default = 0.8. |
seurat_dims |
Integer. PCA dimensions for clustering. Default = 10. |
seurat_nfeatures |
Integer. Variable features count. Default = 2000. |
seurat_min_cells |
Integer. Minimum cells per feature. Default = 3. |
seurat_min_features |
Integer. Minimum features per cell. Default = 200. Auto-adjusted to 10% of gene count if the expression matrix has fewer genes. |
seurat_seed |
Integer. Random seed. Default = 42. |
skip_clustering |
Logical. If TRUE, skip the Seurat clustering step and
treat every column of |
progress_cb |
Optional function called as |
data |
Optional |
clone_labels |
Optional data frame with |
assay |
Character. Assay to read when |
layer |
Character. Layer (Seurat v5) or slot (Seurat v4) to read.
Default = |
clone_col |
Character. Metadata column in |
The pipeline performs:
Seurat clustering to define transcriptional subclones
Cell-to-patient and cell-to-clone annotation
Clone-level mean expression computation
Rank normalization of clone expression
Clone abundance table construction
A named list with:
Matrix. Rank-normalized clone-level expression
(genes as rows, patient_clone as columns). Ready for predict_drugs().
Data frame. Clone abundance per patient. Ready for
predict_patients().
Data frame. Cell-to-clone mapping with columns cell_id, clone_id, patient, dim_1, dim_2.
Data frame. Template with patient and clone_id
columns, ready to merge with predict_drugs() output.
Data frame. 2D embedding coordinates per cell
(cell_id, dim_1, dim_2). Ready for plot_tsne_response().
Character. The method used ("umap" or
"tsne").
## Not run: # List format (same as Rmd) prepared <- prepare_data( expression_matrix = patient_scRNA, patient_mapping = cell_names_list, genes_to_use = GOI ) # Or data frame format (from metadata) metadata <- data.frame(cell_id = colnames(patient_scRNA), patient_id = patient_ids) prepared <- prepare_data(patient_scRNA, metadata) # Parse patient ID from cell names (e.g., "P11_M_Barcode" -> "P11") metadata <- data.frame(Cell = c("P11_M_Barcode1", "P12_M_Barcode2")) prepared <- prepare_data( patient_scRNA, metadata, cell_col = "Cell", # Custom column name parse_patient = TRUE, # Parse from Cell column patient_sep = "_", # Split by "_" patient_pos = 1 # Take first element ) # Result: Patient IDs = "P11", "P12" # Use directly with prediction functions clone_pred <- predict_drugs(models, prepared$clone_expression_rnorm) patient_pred <- predict_patients(clone_pred, prepared) # After preprocess_sc(): the labels alone are enough, because they already # carry the patient of every cell. The unfiltered matrix can be passed as # is; cells without a label are dropped. labels <- preprocess_sc(counts, cell_patients) prepared <- prepare_data( expression_matrix = counts, clone_labels = labels$cell_labels ) # Seurat object: patient IDs from metadata, or from a vector prepared <- prepare_data(data = so, patient_col = "patient_id") prepared <- prepare_data(data = so, patient_mapping = my_patients) # Clone labels as a vector, one per cell (same length as ncol(so)) prepared <- prepare_data(data = so, clone_col = my_clones) ## End(Not run)## Not run: # List format (same as Rmd) prepared <- prepare_data( expression_matrix = patient_scRNA, patient_mapping = cell_names_list, genes_to_use = GOI ) # Or data frame format (from metadata) metadata <- data.frame(cell_id = colnames(patient_scRNA), patient_id = patient_ids) prepared <- prepare_data(patient_scRNA, metadata) # Parse patient ID from cell names (e.g., "P11_M_Barcode" -> "P11") metadata <- data.frame(Cell = c("P11_M_Barcode1", "P12_M_Barcode2")) prepared <- prepare_data( patient_scRNA, metadata, cell_col = "Cell", # Custom column name parse_patient = TRUE, # Parse from Cell column patient_sep = "_", # Split by "_" patient_pos = 1 # Take first element ) # Result: Patient IDs = "P11", "P12" # Use directly with prediction functions clone_pred <- predict_drugs(models, prepared$clone_expression_rnorm) patient_pred <- predict_patients(clone_pred, prepared) # After preprocess_sc(): the labels alone are enough, because they already # carry the patient of every cell. The unfiltered matrix can be passed as # is; cells without a label are dropped. labels <- preprocess_sc(counts, cell_patients) prepared <- prepare_data( expression_matrix = counts, clone_labels = labels$cell_labels ) # Seurat object: patient IDs from metadata, or from a vector prepared <- prepare_data(data = so, patient_col = "patient_id") prepared <- prepare_data(data = so, patient_mapping = my_patients) # Clone labels as a vector, one per cell (same length as ncol(so)) prepared <- prepare_data(data = so, clone_col = my_clones) ## End(Not run)
End-to-end preprocessing for users who only have a raw count matrix: quality control, normalisation, variable-feature selection, PCA, and clustering, followed by a QC report. No tissue-specific thresholds are required; the QC fences adapt to each patient's own distribution.
preprocess_sc( counts, patient_labels, sample_labels = NULL, nmads = 5, min_genes = 200, max_mito = 25, max_genes = NULL, skip_qc = FALSE, remove_doublets = FALSE, exclude_markers = NULL, exclude_min_expr = 1, nfeatures = 2000, dims = 20, method = c("umap", "tsne"), resolution = 0.8, min_clone_cells = 10, integrate = c("auto", "none", "harmony"), cluster_scope = c("global", "patient"), seed = 42, progress_cb = NULL )preprocess_sc( counts, patient_labels, sample_labels = NULL, nmads = 5, min_genes = 200, max_mito = 25, max_genes = NULL, skip_qc = FALSE, remove_doublets = FALSE, exclude_markers = NULL, exclude_min_expr = 1, nfeatures = 2000, dims = 20, method = c("umap", "tsne"), resolution = 0.8, min_clone_cells = 10, integrate = c("auto", "none", "harmony"), cluster_scope = c("global", "patient"), seed = 42, progress_cb = NULL )
counts |
Matrix (genes as rows, cells as columns) or a |
patient_labels |
Character vector, one entry per cell, giving the patient
a cell belongs to. Names are matched to |
sample_labels |
Character vector, one entry per cell, giving the sample
or batch a cell belongs to. Required only when a patient has multiple
samples. Default = |
nmads |
Numeric. Width of the MAD-based QC fence, in median absolute deviations. Default = 5. Tumour tissue has genuinely higher mitochondrial content and larger cells than blood, so a 3-MAD fence removes real cells: against CellRanger's own calls on a real lung squamous carcinoma sample, 5 MAD recovers ~88% of its cells versus ~78% at 3 MAD, with precision unchanged. |
min_genes |
Integer. Minimum detected genes per cell. Default = 200. |
max_mito |
Numeric. Hard cap on the mitochondrial fraction (%). The effective threshold is the smaller of this and the MAD fence. Default = 25. |
max_genes |
Integer. Fixed upper bound on detected genes per cell. When
|
skip_qc |
Logical. When |
remove_doublets |
Logical. When |
exclude_markers |
Optional named list of gene vectors, e.g.
|
exclude_min_expr |
Numeric. Mean log-normalised expression a cell must reach in a marker set to be excluded. Default = 1. |
nfeatures |
Integer. Number of variable features used for PCA. Default = 2000. |
dims |
Integer. Number of principal components. Capped automatically for small datasets. Default = 20. |
method |
Character. 2D embedding for visualisation: |
resolution |
Numeric. Clustering resolution. Default = 0.8. |
min_clone_cells |
Integer. Clones with fewer cells are kept but marked
|
integrate |
Character. Sample integration strategy within a patient:
|
cluster_scope |
Character. |
seed |
Integer. Random seed. Default = 42. |
progress_cb |
Optional function called as |
Clustering is performed on a shared PCA embedding. By default
(cluster_scope = "global") every cell is clustered together, which is
what the original PERCEPTION method does: a clone is a transcriptional state
that can appear in several patients. With cluster_scope = "patient"
neighbours are searched inside each patient only, so a clone can never span
two patients – useful when clone labels are meant to be patient-specific.
For a single-patient dataset the two settings are identical.
When a patient has more than one sample (e.g. longitudinal biopsies) and
cluster_scope = "patient", harmony is applied inside that patient to
prevent one biological clone from being split in two by a technical batch
effect. harmony is an optional dependency: without it, the step is
skipped with a warning.
A list with:
Data frame with cell_id, clone_id,
clone_key (unique "patient@clone" key),
patient, cluster_size_class ("large" /
"small", a cell-count category and nothing more), and
dim_1/dim_2. This is the clone_labels argument
of prepare_data().
Data frame. Per-patient QC summary, including
n_marker_removed when exclude_markers was used and
n_doublet_removed when remove_doublets = TRUE.
Data frame. Per-cell QC metrics before filtering.
Data frame. Cells removed by exclude_markers
(columns cell_id, set, score); empty when no
marker filtering was requested.
Data frame. Cells removed by remove_doublets
(columns cell_id, patient, score); empty when
the step was not requested or no doublets were found.
Logical. Whether harmony was applied.
Character. Always "auto_cluster".
In the cell-level workflow, clone labels are operationally defined by transcriptomic clustering. Cells are grouped by transcriptional similarity within each patient, and the resulting cluster assignments are used as surrogate clone labels for downstream analysis. These labels do not necessarily represent genetically validated clonal populations and should not be interpreted as evidence of shared genomic ancestry. CNV- or genotype-based evidence is required to call true clones.
## Not run: labels <- preprocess_sc(counts, patient_labels = cell_patients) prepared <- prepare_data( expression_matrix = counts, clone_labels = labels$cell_labels ) ## End(Not run)## Not run: labels <- preprocess_sc(counts, patient_labels = cell_patients) prepared <- prepare_data( expression_matrix = counts, clone_labels = labels$cell_labels ) ## End(Not run)
Scales a numeric vector to the 0-1 range using the 5th and 95th percentiles as thresholds to handle outliers.
range01(x)range01(x)
x |
A numeric vector. |
A numeric vector scaled between 0 and 1.
Converts each column to ranks divided by column length, producing values in the range 0 to 1 (exclusive of 0, inclusive of 1). This is a crucial preprocessing step when using your own expression data with PERCEPTIONx.
rank_normalization_mat(mat)rank_normalization_mat(mat)
mat |
A numeric matrix. Rows = genes, columns = cells/samples. |
A rank-normalized matrix of the same dimensions, with values between 0 and 1.
PERCEPTIONx models are trained on DepMap expression data that has been rank-normalized. The model coefficients capture the relationship between relative gene expression ranks and drug response, not absolute expression values. Therefore, any new expression data fed into the model must undergo the same rank normalization to ensure compatibility.
For each column (cell/sample), every gene's expression value is replaced by its rank within that column, divided by the total number of genes:
where is the number of rows (genes) and ties are resolved by
averaging. This transforms each column into a uniform distribution over
, making the data robust to batch effects, library size
differences, and outliers.
If you provide your own expression data that has not been
rank-normalized, predictions will be unreliable. Always run
rank_normalization_mat() on your raw expression matrix before passing
it to predict_drugs().
raw_expr <- matrix(c(10, 200, 50, 30, 300, 80), nrow = 3, ncol = 2) rownames(raw_expr) <- c("GENE_A", "GENE_B", "GENE_C") norm_expr <- rank_normalization_mat(raw_expr)raw_expr <- matrix(c(10, 200, 50, 30, 300, 80), nrow = 3, ncol = 2) rownames(raw_expr) <- c("GENE_A", "GENE_B", "GENE_C") norm_expr <- rank_normalization_mat(raw_expr)
One reader for the inputs a user actually has: a CellRanger output folder, a
.h5 file, or the three files passed explicitly. The result is a sparse
genes x cells matrix with gene symbols as row names, which is what
preprocess_sc() and prepare_data() expect.
read_10x(path = NULL, mtx = NULL, barcodes = NULL, features = NULL)read_10x(path = NULL, mtx = NULL, barcodes = NULL, features = NULL)
path |
Directory holding |
mtx |
Path to |
barcodes |
Path to |
features |
Path to |
A dgCMatrix with genes as rows and cells as columns.
## Not run: counts <- read_10x("path/to/filtered_feature_bc_matrix") counts <- read_10x("path/to/filtered_feature_bc_matrix.h5") counts <- read_10x( mtx = "matrix.mtx.gz", barcodes = "barcodes.tsv.gz", features = "features.tsv.gz" ) ## End(Not run)## Not run: counts <- read_10x("path/to/filtered_feature_bc_matrix") counts <- read_10x("path/to/filtered_feature_bc_matrix.h5") counts <- read_10x( mtx = "matrix.mtx.gz", barcodes = "barcodes.tsv.gz", features = "features.tsv.gz" ) ## End(Not run)
Runs feature_ranking_bulk for a list of drugs.
run_parallel_feature_ranking_bulk( infunc_DrugsToUse, id_cancerType = "PanCan", infunc_exclude_cancer = "PanCan", infunc_GOI, ncores = 4L )run_parallel_feature_ranking_bulk( infunc_DrugsToUse, id_cancerType = "PanCan", infunc_exclude_cancer = "PanCan", infunc_GOI, ncores = 4L )
infunc_DrugsToUse |
Character vector. Drug names to rank features for. |
id_cancerType |
Character. Cancer type. Default = "PanCan". |
infunc_exclude_cancer |
Character. Cancer type to exclude. Default = "PanCan". |
infunc_GOI |
Character vector. Genes of Interest. |
ncores |
Integer. Kept for API compatibility; ignored (see NOTE above). |
NOTE: feature ranking is fully vectorized (~0.15 s per drug over 15k genes), so this deliberately runs SERIALLY. The old Windows PSOCK path serialized the 567 MB DepMap into every worker (clusterExport) and then still failed — workers are clean R sessions without the package's internal helpers — before silently falling back to serial; that cost ~10x for zero benefit.
A list of feature ranking results, one per drug.
Starts the interactive PERCEPTIONx dashboard for drug response prediction. The dashboard provides a graphical interface for data loading, model training, prediction, and visualization.
run_perception_app()run_perception_app()
Under a Shiny Server deployment the server executes this function and
expects a shiny app object back (a nested runApp() would
fail), so the function detects Shiny Server via the SHINY_PORT
environment variable it sets for every R worker (the same signal the shiny
package itself uses internally) and returns the app object instead of
starting its own server. This lets the same one-liner work both locally and
inside apps/<name>/app.R.
A Shiny app object. When run interactively (no SHINY_PORT
environment variable set) the app is also launched in the user's browser.
## Not run: library(PERCEPTIONx) run_perception_app() ## End(Not run)## Not run: library(PERCEPTIONx) run_perception_app() ## End(Not run)
This function runs the complete PERCEPTIONx training pipeline for a list of drugs. It performs feature ranking, model training with hyperparameter tuning across different k_features values, and selects the best model per drug based on single-cell test performance.
train_models( drug_list = NULL, cancer_type = "PanCan", exclude_cancer = "PanCan", GOI = NULL, k_features_values = NULL, ncores = 4L, output_dir = "./models", model_type = "glmnet", num_folds = 3L, num_tree = 500L, seed = 1L, alpha_gradient = 0.05, lambda_gradient = 20L, lambda_range = c(1e-04, 1L), cv_method = "cv", progress_cb = NULL )train_models( drug_list = NULL, cancer_type = "PanCan", exclude_cancer = "PanCan", GOI = NULL, k_features_values = NULL, ncores = 4L, output_dir = "./models", model_type = "glmnet", num_folds = 3L, num_tree = 500L, seed = 1L, alpha_gradient = 0.05, lambda_gradient = 20L, lambda_range = c(1e-04, 1L), cv_method = "cv", progress_cb = NULL )
drug_list |
Character vector. Names of drugs to train models for. If NULL, uses the 44 FDA-approved drugs from the paper. |
cancer_type |
Character. Cancer type for training. Default = "PanCan". |
exclude_cancer |
Character. Cancer type to exclude from training. Default = "PanCan". |
GOI |
Character vector. Genes of Interest to use as features. |
k_features_values |
Numeric vector. Feature counts to test during tuning. If NULL, automatically calculated from expression_rnorm dimensions. |
ncores |
Integer. Number of CPU cores for parallel feature ranking. Default = 4. |
output_dir |
Character. Directory to save trained model RDS file. Default = "./models". |
model_type |
Character. Model type: "glmnet" or "rf". Default = "glmnet". |
num_folds |
Integer. Number of CV folds. Default = 3. |
num_tree |
Integer. Number of trees for random forest. Default = 500. |
seed |
Integer. Random seed for training. Default = 1. |
alpha_gradient |
Numeric. Step size for alpha grid in glmnet tuning. Default = 0.05. |
lambda_gradient |
Integer. Number of lambda values in glmnet tuning grid. Default = 20. |
lambda_range |
Numeric vector of length 2. Min and max lambda for tuning grid. Default = c(0.0001, 1). |
cv_method |
Character. Cross-validation method. Default = "cv". |
progress_cb |
Function. Optional progress callback called as
|
A named list of trained model objects, one per drug. Also saved as a single RDS file.
## Not run: load_depmap(read = TRUE) available_genes <- intersect(rownames(DepMap$expression_20Q4), rownames(DepMap$scRNA_complete)) set.seed(123) GOI_100 <- sample(available_genes, 100) train_models("abemaciclib", "PanCan", "PanCan", GOI_100, ncores = 1) ## End(Not run)## Not run: load_depmap(read = TRUE) available_genes <- intersect(rownames(DepMap$expression_20Q4), rownames(DepMap$scRNA_complete)) set.seed(123) GOI_100 <- sample(available_genes, 100) train_models("abemaciclib", "PanCan", "PanCan", GOI_100, ncores = 1) ## End(Not run)
Applies base R scale() to each drug column across all patients,
centering to mean 0 and standard deviation 1. This ensures comparability
of predicted viability scores between different drugs before patient-level
aggregation. Matches the original PERCEPTION pipeline.
zscore_viability(clone_viability_df, cols = NULL)zscore_viability(clone_viability_df, cols = NULL)
clone_viability_df |
Data frame. Must have columns 'patient' and 'clone_id', plus one or more drug columns with predicted viability values. |
cols |
Character vector of column names to scale. Default |
A data frame with the same structure, but drug columns z-score scaled.