From 0150a1ea946f2a5b6fbb64c6290c50fcbbb6607e Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Wed, 4 Nov 2026 07:38:02 -0500 Subject: [PATCH 1/4] - bump version to 0.3.1 - adopt cli/lifecycle tooling - import cli as messager --- .Rbuildignore | 3 + DESCRIPTION | 12 +- NAMESPACE | 136 +-- R/PERCEPTIONx-package.R | 93 ++ R/annotate.R | 428 +++++--- R/app.R | 29 +- R/depmap_meta.R | 51 +- R/drugs.R | 2009 ++++++++---------------------------- R/evaluate.R | 217 ++-- R/load.R | 328 ++++-- R/paths.R | 26 +- R/plot.R | 1868 +++++++++++++++++++++++---------- R/predict.R | 319 +++--- R/stats.R | 109 +- R/train.R | 628 +++++++---- R/utils.R | 21 +- R/utils_cortest.R | 101 +- air.toml | 0 inst/WORDLIST | 100 ++ jarl.toml | 20 + man/PERCEPTIONx-package.Rd | 38 + tests/spelling.R | 3 + 22 files changed, 3542 insertions(+), 2997 deletions(-) create mode 100644 R/PERCEPTIONx-package.R create mode 100644 air.toml create mode 100644 inst/WORDLIST create mode 100644 jarl.toml create mode 100644 man/PERCEPTIONx-package.Rd create mode 100644 tests/spelling.R diff --git a/.Rbuildignore b/.Rbuildignore index 09ec6d3..56ffddb 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -16,3 +16,6 @@ ^docs$ ^pkgdown$ ^models$ +^[.]?air[.]toml$ +^\.vscode$ +^jarl\.toml$ diff --git a/DESCRIPTION b/DESCRIPTION index 367705b..57a52f9 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,6 +1,6 @@ Package: PERCEPTIONx Title: Personalized Drug Response Prediction from Single-Cell Transcriptomics -Version: 0.3.0 +Version: 0.3.1 Authors@R: person("Jia", "Ding", , "jiading682@qq.com", role = c("aut", "cre"), comment = c(ORCID = "0009-0002-2530-0897")) @@ -14,7 +14,6 @@ Encoding: UTF-8 Depends: R (>= 4.1.0) Roxygen: list(markdown = TRUE) -RoxygenNote: 8.0.0 VignetteBuilder: knitr Imports: ggplot2, @@ -28,7 +27,9 @@ Imports: uwot, shiny, ggiraph, - parallel + parallel, + cli, + lifecycle URL: https://wanglabcsu.github.io/PERCEPTIONx, https://github.com/WangLabCSU/PERCEPTIONx BugReports: https://github.com/WangLabCSU/PERCEPTIONx/issues Suggests: @@ -42,5 +43,8 @@ Suggests: waiter, thematic, readxl, - callr + callr, + spelling Config/testthat/edition: 3 +Language: en-US +Config/roxygen2/version: 8.1.0 diff --git a/NAMESPACE b/NAMESPACE index 5c5d4cd..97ebbb5 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -48,70 +48,78 @@ export(run_perception_app) export(train_models) export(zscore_viability) importFrom(caret,predict.train) -importFrom(ggplot2,aes) -importFrom(ggplot2,annotate) -importFrom(ggplot2,coord_cartesian) -importFrom(ggplot2,coord_equal) -importFrom(ggplot2,element_blank) -importFrom(ggplot2,element_line) -importFrom(ggplot2,element_rect) -importFrom(ggplot2,element_text) -importFrom(ggplot2,facet_grid) -importFrom(ggplot2,facet_wrap) -importFrom(ggplot2,geom_abline) -importFrom(ggplot2,geom_bar) -importFrom(ggplot2,geom_boxplot) -importFrom(ggplot2,geom_hline) -importFrom(ggplot2,geom_jitter) -importFrom(ggplot2,geom_line) -importFrom(ggplot2,geom_point) -importFrom(ggplot2,geom_rect) -importFrom(ggplot2,geom_segment) -importFrom(ggplot2,geom_text) -importFrom(ggplot2,geom_violin) -importFrom(ggplot2,geom_vline) -importFrom(ggplot2,ggplot) -importFrom(ggplot2,ggtitle) -importFrom(ggplot2,guide_colourbar) -importFrom(ggplot2,guide_legend) -importFrom(ggplot2,guides) -importFrom(ggplot2,labs) -importFrom(ggplot2,margin) -importFrom(ggplot2,rel) -importFrom(ggplot2,scale_color_manual) -importFrom(ggplot2,scale_colour_gradient2) -importFrom(ggplot2,scale_colour_gradientn) -importFrom(ggplot2,scale_colour_manual) -importFrom(ggplot2,scale_fill_manual) -importFrom(ggplot2,scale_size) -importFrom(ggplot2,scale_x_discrete) -importFrom(ggplot2,theme) -importFrom(ggplot2,theme_bw) -importFrom(ggplot2,theme_void) -importFrom(ggplot2,unit) -importFrom(ggplot2,vars) +importFrom(ggplot2, + aes, + annotate, + coord_cartesian, + coord_equal, + element_blank, + element_line, + element_rect, + element_text, + facet_grid, + facet_wrap, + geom_abline, + geom_bar, + geom_boxplot, + geom_hline, + geom_jitter, + geom_line, + geom_point, + geom_rect, + geom_segment, + geom_text, + geom_violin, + geom_vline, + ggplot, + ggtitle, + guide_colourbar, + guide_legend, + guides, + labs, + margin, + rel, + scale_color_manual, + scale_colour_gradient2, + scale_colour_gradientn, + scale_colour_manual, + scale_fill_manual, + scale_size, + scale_x_discrete, + theme, + theme_bw, + theme_void, + unit, + vars +) importFrom(glmnet,glmnet) -importFrom(pROC,auc) -importFrom(pROC,ggroc) -importFrom(pROC,roc) -importFrom(pROC,smooth) +importFrom(pROC, + auc, + ggroc, + roc, + smooth +) importFrom(randomForest,randomForest) importFrom(rlang,.data) -importFrom(stats,aggregate) -importFrom(stats,complete.cases) -importFrom(stats,cor) -importFrom(stats,cor.test) -importFrom(stats,median) -importFrom(stats,na.omit) -importFrom(stats,p.adjust) -importFrom(stats,phyper) -importFrom(stats,pnorm) -importFrom(stats,predict) -importFrom(stats,pt) -importFrom(stats,reformulate) -importFrom(stats,setNames) -importFrom(stats,t.test) -importFrom(stats,wilcox.test) -importFrom(utils,combn) -importFrom(utils,download.file) -importFrom(utils,head) +importFrom(stats, + aggregate, + complete.cases, + cor, + cor.test, + median, + na.omit, + p.adjust, + phyper, + pnorm, + predict, + pt, + reformulate, + setNames, + t.test, + wilcox.test +) +importFrom(utils, + combn, + download.file, + head +) diff --git a/R/PERCEPTIONx-package.R b/R/PERCEPTIONx-package.R new file mode 100644 index 0000000..287ccb8 --- /dev/null +++ b/R/PERCEPTIONx-package.R @@ -0,0 +1,93 @@ +# nocov start + +#' @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. +#' +#' @section License: +#' MIT + file LICENSE +#' +#' @docType package +#' @name PERCEPTIONx-package +#' @aliases PERCEPTIONx +#' @keywords internal +#' +"_PACKAGE" + + +.onAttach <- function(libname, pkgname) { + if (startup_message_allowed()) { + pkg_version <- utils::packageVersion(pkgname) + end <- Sys.time() + elapsed <- cli_timestamp_formatter(as.numeric(end - .time_record$start)) + cli::cli_alert_success(sprintf( + "{.pkg {pkgname}} v{pkg_version} loaded {cli::col_grey('[%s]')}", + elapsed + )) + } +} + +.onLoad <- function(libname, pkgname) { + if (startup_message_allowed()) { + .time_record$start <- Sys.time() + } + + invisible() +} + +.time_record <- new.env() + +cli_timestamp_formatter <- function(x) { + stopifnot( + length(x) == 1L, + is.numeric(x), + !is.na(x), + x >= 0L + ) + + if (x < 1L) { + sprintf("%d ms", as.integer(x * 1000L)) + } else if (x < 60L) { + sprintf("%d s", as.integer(x)) + } else if (x < 3600L) { + sprintf("%d min %d s", floor(x / 60L), as.integer(x %% 60L)) + } else { + sprintf( + "%d h %02d min %d s", + floor(x / 3600L), + floor((x %% 3600L) / 60L), + as.integer(x %% 60L) + ) + } +} + +startup_message_allowed <- function() { + allowed <- FALSE + + withRestarts( + { + signalCondition(structure( + list(message = ".__startup_probe__."), + class = c( + "packageStartupProbe", + "packageStartupMessage", + "condition" + ) + )) + allowed <- TRUE + }, + muffleMessage = function() NULL + ) + + allowed +} + +## usethis namespace: start +## usethis namespace: end +NULL + +# nocov end diff --git a/R/annotate.R b/R/annotate.R index 37c1841..f31a2c4 100644 --- a/R/annotate.R +++ b/R/annotate.R @@ -16,30 +16,47 @@ NULL # clusters -> UMAP/t-SNE, with PCA dimensions capped to what the (possibly # small) dataset can support. Used by both annotate_clones() and # plot_seurat_clustering() so they stay in sync and share the same safeguards. -run_seurat_pipeline <- function(expression_matrix, method, - min_cells, min_features, nfeatures, - dims, resolution, seed, progress_cb = NULL, - cluster_algorithm = 1, - variable_selection = c("vst", "dispersion", "mvp")) { +run_seurat_pipeline <- function( + expression_matrix, + method, + min_cells, + min_features, + nfeatures, + dims, + resolution, + seed, + progress_cb = NULL, + cluster_algorithm = 1, + variable_selection = c("vst", "dispersion", "mvp") +) { + lifecycle::deprecate_soft("0.3.1", "run_seurat_pipeline()") notify <- function(phase) { if (is.function(progress_cb)) progress_cb(phase) } - variable_selection <- match.arg(variable_selection) + variable_selection <- rlang::arg_match(variable_selection) set.seed(seed) notify("normalizing") - so <- Seurat::CreateSeuratObject(counts = expression_matrix, - project = "PERCEPTIONx", - min.cells = min_cells, - min.features = min_features) - so <- Seurat::NormalizeData(so, normalization.method = "LogNormalize", - scale.factor = 10000) + so <- Seurat::CreateSeuratObject( + counts = expression_matrix, + project = "PERCEPTIONx", + min.cells = min_cells, + min.features = min_features + ) + so <- Seurat::NormalizeData( + so, + normalization.method = "LogNormalize", + scale.factor = 10000 + ) notify("variable-features") # vst is the most accurate but by far the slowest variable-feature method # on large matrices; dispersion/mvp trade a little feature quality for a # big speedup. The Seurat pipeline below works with any of them. - so <- Seurat::FindVariableFeatures(so, selection.method = variable_selection, - nfeatures = nfeatures) + so <- Seurat::FindVariableFeatures( + so, + selection.method = variable_selection, + nfeatures = nfeatures + ) notify("scaling") so <- Seurat::ScaleData(so, features = Seurat::VariableFeatures(object = so)) @@ -47,16 +64,22 @@ run_seurat_pipeline <- function(expression_matrix, method, # number actually available so small datasets do not error out. max_pcs <- min(ncol(so), length(Seurat::VariableFeatures(object = so))) - 1 actual_dims <- min(dims, max_pcs) - if (actual_dims < 1) actual_dims <- 1 + if (actual_dims < 1) { + actual_dims <- 1 + } if (actual_dims < dims) { - message(" Adjusting PCA dims from ", dims, " to ", actual_dims, - " due to limited cells/features") + cli::cli_progress_step( + "Adjusting PCA dims from {dims} to {actual_dims} due to limited cells/features" + ) } notify("pca") - so <- Seurat::RunPCA(so, features = Seurat::VariableFeatures(object = so), - npcs = actual_dims) + so <- Seurat::RunPCA( + so, + features = Seurat::VariableFeatures(object = so), + npcs = actual_dims + ) notify("neighbors") so <- Seurat::FindNeighbors(so, dims = seq_len(actual_dims)) # verbose = FALSE: FindClusters prints "Modularity Optimizer" progress to @@ -65,8 +88,12 @@ run_seurat_pipeline <- function(expression_matrix, method, # is slightly faster on VERY large graphs but pulls in the 'leidenbase' # package — not worth the dependency at PERCEPTIONx's typical cell counts. notify("clustering") - so <- Seurat::FindClusters(so, resolution = resolution, - algorithm = cluster_algorithm, verbose = FALSE) + so <- Seurat::FindClusters( + so, + resolution = resolution, + algorithm = cluster_algorithm, + verbose = FALSE + ) notify(if (method == "umap") "umap" else "tsne") if (method == "umap") { @@ -79,24 +106,48 @@ run_seurat_pipeline <- function(expression_matrix, method, # still-valid settings (15/200/10 -> ~2.5x faster, measured). The result # is attached as a normal "umap" reduction, so Embeddings(so, "umap") # and everything downstream work unchanged. - pca_emb <- Seurat::Embeddings(so, "pca")[, seq_len(actual_dims), drop = FALSE] - n_threads <- max(1L, min(4L, as.integer(parallel::detectCores()), na.rm = TRUE)) + pca_emb <- Seurat::Embeddings(so, "pca")[, + seq_len(actual_dims), + drop = FALSE + ] + n_threads <- max( + 1L, + min(4L, as.integer(parallel::detectCores()), na.rm = TRUE) + ) # uwot requires n_neighbors < number of points; cap it for tiny datasets # so a small test matrix (<= 15 cells) does not crash with an Annoy # index error. n_neighbors <- min(15, max(2L, nrow(pca_emb) - 1L)) coords <- uwot::umap( - X = pca_emb, n_neighbors = n_neighbors, n_components = 2, n_epochs = 200, - n_trees = 10, metric = "cosine", learning_rate = 1, min_dist = 0.3, - spread = 1, set_op_mix_ratio = 1, local_connectivity = 1, - repulsion_strength = 1, negative_sample_rate = 5, - n_threads = n_threads, verbose = FALSE) + X = pca_emb, + n_neighbors = n_neighbors, + n_components = 2, + n_epochs = 200, + n_trees = 10, + metric = "cosine", + learning_rate = 1, + min_dist = 0.3, + spread = 1, + set_op_mix_ratio = 1, + local_connectivity = 1, + repulsion_strength = 1, + negative_sample_rate = 5, + n_threads = n_threads, + verbose = FALSE + ) rownames(coords) <- colnames(so) colnames(coords) <- c("UMAP_1", "UMAP_2") so[["umap"]] <- Seurat::CreateDimReducObject( - embeddings = coords, key = "UMAP_", assay = Seurat::DefaultAssay(so)) + embeddings = coords, + key = "UMAP_", + assay = Seurat::DefaultAssay(so) + ) } else { - so <- Seurat::RunTSNE(so, dims = seq_len(actual_dims), check_duplicates = FALSE) + so <- Seurat::RunTSNE( + so, + dims = seq_len(actual_dims), + check_duplicates = FALSE + ) } so @@ -142,30 +193,38 @@ run_seurat_pipeline <- function(expression_matrix, method, #' } #' #' @export -annotate_clones <- function(method = c("umap", "tsne"), - expression_matrix, - min_cells = 3, - min_features = 200, - nfeatures = 2000, - dims = 10, - resolution = 0.8, - seed = 42, - progress_cb = NULL, - cluster_algorithm = 1, - variable_selection = c("vst", "dispersion", "mvp")) { - - method <- match.arg(method) - variable_selection <- match.arg(variable_selection) - - if (!requireNamespace("Seurat", quietly = TRUE)) { - stop("Package 'Seurat' is required for clone annotation. ", - "Install with: install.packages('Seurat')") - } - - so <- run_seurat_pipeline(expression_matrix, method, - min_cells, min_features, nfeatures, - dims, resolution, seed, progress_cb, - cluster_algorithm, variable_selection) +annotate_clones <- function( + method = c("umap", "tsne"), + expression_matrix, + min_cells = 3, + min_features = 200, + nfeatures = 2000, + dims = 10, + resolution = 0.8, + seed = 42, + progress_cb = NULL, + cluster_algorithm = 1, + variable_selection = c("vst", "dispersion", "mvp") +) { + method <- rlang::arg_match(method) + variable_selection <- rlang::arg_match(variable_selection) + + rlang::check_installed("Seurat", "for clone annotation.") + + # TODO: deprecated this function + so <- run_seurat_pipeline( + expression_matrix, + method, + min_cells, + min_features, + nfeatures, + dims, + resolution, + seed, + progress_cb, + cluster_algorithm, + variable_selection + ) cluster_ids <- Seurat::Idents(so) emb <- Seurat::Embeddings(so, reduction = method) @@ -193,13 +252,14 @@ annotate_clones <- function(method = c("umap", "tsne"), #' as clone IDs with cell counts as values. #' @export build_clone_counts <- function(cell_clone_map, patient_ids) { - if (!all(c("cell_id", "clone_id") %in% colnames(cell_clone_map))) { - stop("cell_clone_map must have columns 'cell_id' and 'clone_id'.") + rlang::abort("cell_clone_map must have columns 'cell_id' and 'clone_id'.") } if (length(patient_ids) != nrow(cell_clone_map)) { - stop("Length of patient_ids must match number of rows in cell_clone_map.") + rlang::abort( + "Length of patient_ids must match number of rows in cell_clone_map." + ) } map_df <- data.frame( @@ -335,30 +395,31 @@ build_clone_counts <- function(cell_clone_map, patient_ids) { #' \code{"mapping"}). Used to show live progress in the Shiny app. #' #' @export -prepare_data <- function(method = c("umap", "tsne"), - expression_matrix, - patient_mapping = NULL, - cell_col = "cell_id", - patient_col = "patient_id", - parse_patient = FALSE, - patient_sep = "_", - patient_pos = 1, - genes_to_use = NULL, - seurat_resolution = 0.8, - seurat_dims = 10, - seurat_nfeatures = 2000, - seurat_min_cells = 3, - seurat_min_features = 200, - seurat_seed = 42, - skip_clustering = FALSE, - progress_cb = NULL) { - - method <- match.arg(method) +prepare_data <- function( + method = c("umap", "tsne"), + expression_matrix, + patient_mapping = NULL, + cell_col = "cell_id", + patient_col = "patient_id", + parse_patient = FALSE, + patient_sep = "_", + patient_pos = 1, + genes_to_use = NULL, + seurat_resolution = 0.8, + seurat_dims = 10, + seurat_nfeatures = 2000, + seurat_min_cells = 3, + seurat_min_features = 200, + seurat_seed = 42, + skip_clustering = FALSE, + progress_cb = NULL +) { + method <- rlang::arg_match(method) notify_stage <- function(phase, i, n) { if (is.function(progress_cb)) progress_cb(phase, i, n, "") } - message("=== PERCEPTIONx Patient Data Preparation ===") - message(" Reduction method: ", toupper(method)) + cli::cli_h2("PERCEPTIONx Patient Data Preparation") + cli::cli_ul("Reduction method: {.val {toupper(method)}}") # --- Auto-enable parse_patient if patient_sep or patient_pos is provided --- if (!parse_patient) { @@ -366,9 +427,15 @@ prepare_data <- function(method = c("umap", "tsne"), # Default: patient_sep="_", patient_pos=1 # If user explicitly changed either, auto-enable parsing caller_args <- as.list(match.call()) - if ("patient_sep" %in% names(caller_args) || "patient_pos" %in% names(caller_args)) { + if ( + "patient_sep" %in% + names(caller_args) || + "patient_pos" %in% names(caller_args) + ) { parse_patient <- TRUE - message(" Auto-enabling parse_patient (patient_sep or patient_pos provided)") + cli::cli_alert_info( + "Auto-enabling parse_patient (patient_sep or patient_pos provided)" + ) } } @@ -381,28 +448,45 @@ prepare_data <- function(method = c("umap", "tsne"), # (inst/shiny/app/R/mod_data.R); doing it here as well makes the documented # behaviour available to scripted users who call prepare_data() directly. # The abundance column is consumed here and not passed downstream. - count_col <- intersect(c("count", "cells", "n_cells", "n_cells_per_clone", "abundance"), - tolower(colnames(patient_mapping))) + count_col <- intersect( + c("count", "cells", "n_cells", "n_cells_per_clone", "abundance"), + tolower(colnames(patient_mapping)) + ) if (length(count_col) > 0) { - cnt_col <- colnames(patient_mapping)[tolower(colnames(patient_mapping)) == count_col[1]][1] + cnt_col <- colnames(patient_mapping)[ + tolower(colnames(patient_mapping)) == count_col[1] + ][1] cnt <- suppressWarnings(as.numeric(patient_mapping[[cnt_col]])) cnt[is.na(cnt) | cnt < 1] <- 1L - patient_mapping <- patient_mapping[rep(seq_len(nrow(patient_mapping)), cnt), , drop = FALSE] + patient_mapping <- patient_mapping[ + rep(seq_len(nrow(patient_mapping)), cnt), + , + drop = FALSE + ] patient_mapping[[cnt_col]] <- NULL rownames(patient_mapping) <- NULL - message(" Expanded mapping by '", cnt_col, "' to ", nrow(patient_mapping), - " rows (true clone abundance).") + cli::cli_progress_step( + "Expanded mapping by '{cnt_col}' to {nrow(patient_mapping)} rows (true clone abundance)" + ) } if (!cell_col %in% colnames(patient_mapping)) { - stop("patient_mapping data frame must have a column named '", cell_col, "'") + cli::cli_abort( + "patient_mapping data frame must have a column named '{cell_col}'" + ) } # Parse patient ID from cell_col if requested if (parse_patient) { - message(" Parsing patient IDs from '", cell_col, "' column using separator '", patient_sep, "'") + cli::cli_progress_step( + "Parsing patient IDs from '{cell_col}' column using separator '{patient_sep}'" + ) cell_names <- patient_mapping[[cell_col]] - parsed_parts <- strsplit(as.character(cell_names), patient_sep, fixed = TRUE) + parsed_parts <- strsplit( + as.character(cell_names), + patient_sep, + fixed = TRUE + ) # Extract patient ID at specified position patient_ids_parsed <- sapply(parsed_parts, function(x) { @@ -414,23 +498,39 @@ prepare_data <- function(method = c("umap", "tsne"), }) # Check for parsing failures - if (any(is.na(patient_ids_parsed))) { - warning(sum(is.na(patient_ids_parsed)), " cells could not be parsed for patient ID") + if (anyNA(patient_ids_parsed)) { + cli::cli_warn( + "{sum(is.na(patient_ids_parsed))} cells could not be parsed for patient ID" + ) } # Add parsed patient IDs to the data frame patient_mapping$patient_id_parsed <- patient_ids_parsed - sample_cell_names <- split(patient_mapping[[cell_col]], patient_mapping$patient_id_parsed) - message(" Parsed ", length(unique(patient_ids_parsed)), " unique patient IDs") + sample_cell_names <- split( + patient_mapping[[cell_col]], + patient_mapping$patient_id_parsed + ) + cli::cli_progress_step( + "Parsed {length(unique(patient_ids_parsed))} unique patient IDs" + ) } else { # Use existing patient_col if (!patient_col %in% colnames(patient_mapping)) { - stop("patient_mapping data frame must have a column named '", patient_col, - "'\n Or use parse_patient=TRUE to extract patient ID from cell names") + cli::cli_abort( + c( + "patient_mapping data frame must have a column named '{patient_col}'", + "i" = "Use parse_patient = TRUE to extract patient ID from cell names" + ) + ) } - sample_cell_names <- split(patient_mapping[[cell_col]], patient_mapping[[patient_col]]) + sample_cell_names <- split( + patient_mapping[[cell_col]], + patient_mapping[[patient_col]] + ) } - message(" Converted metadata data frame to list format: ", length(sample_cell_names), " patients") + cli::cli_progress_step( + "Converted metadata data frame to list format: {length(sample_cell_names)} patients" + ) } else { sample_cell_names <- patient_mapping } @@ -438,11 +538,14 @@ prepare_data <- function(method = c("umap", "tsne"), # --- Step 1: Define clones (Seurat clustering OR clone-level input) --- if (isTRUE(skip_clustering)) { notify_stage("clones", 1L, 5L) - message("[1/5] Skipping Seurat clustering -- each column is treated as one clone...") + cli::cli_progress_step( + "[1/5] Skipping Seurat clustering -- each column is treated as one clone..." + ) cn <- colnames(expression_matrix) if (is.null(cn)) { - stop("expression_matrix must have column names when skip_clustering = TRUE ", - "(each column is expected to be one clone).") + cli::cli_abort( + "expression_matrix must have column names when skip_clustering = TRUE (each column is expected to be one clone)." + ) } # Clone-level input with a cell-count-resolved mapping: if the patient # mapping repeats clone ids (one row per real cell, e.g. "Kydar01_c1" @@ -456,37 +559,52 @@ prepare_data <- function(method = c("umap", "tsne"), } else if (is.character(sample_cell_names)) { sample_cell_ids <- sample_cell_names } - if (!is.null(sample_cell_ids) && anyDuplicated(sample_cell_ids) > 0 && - all(cn %in% sample_cell_ids)) { - cell_clone_map <- data.frame(cell_id = sample_cell_ids, - clone_id = sample_cell_ids, - stringsAsFactors = FALSE) - cell_clone_map <- cell_clone_map[cell_clone_map$cell_id %in% cn, , drop = FALSE] - message(" Using cell-count-resolved mapping: ", nrow(cell_clone_map), - " cells across ", length(unique(cell_clone_map$cell_id)), " clones.") + if ( + !is.null(sample_cell_ids) && + anyDuplicated(sample_cell_ids) > 0 && + all(cn %in% sample_cell_ids) + ) { + cell_clone_map <- data.frame( + cell_id = sample_cell_ids, + clone_id = sample_cell_ids, + stringsAsFactors = FALSE + ) + cell_clone_map <- cell_clone_map[ + cell_clone_map$cell_id %in% cn, + , + drop = FALSE + ] + cli::cli_progress_step( + "Using cell-count-resolved mapping: {nrow(cell_clone_map)} cells across {length(unique(cell_clone_map$cell_id))} clones" + ) } else { # Keep the full column name as the unique clone identity (e.g. "Kydar01_c1"). # This is universal: clone names are whatever the user's data uses. Patient # separation is guaranteed downstream via "patient@@clone" keys. - cell_clone_map <- data.frame(cell_id = cn, clone_id = cn, - stringsAsFactors = FALSE) - message(" Using ", length(cn), " provided clone columns.") + cell_clone_map <- data.frame( + cell_id = cn, + clone_id = cn, + stringsAsFactors = FALSE + ) + cli::cli_progress_step("Using {length(cn)} provided clone columns") } } else { notify_stage("seurat", 1L, 5L) - message("[1/5] Clustering cells via Seurat...") + cli::cli_progress_step("[1/5] Clustering cells via Seurat...") # Auto-adjust min_features and nfeatures if gene count is small n_genes <- nrow(expression_matrix) if (n_genes < seurat_min_features) { seurat_min_features <- max(1, floor(n_genes * 0.1)) - message(" Adjusting min_features to ", seurat_min_features, - " (only ", n_genes, " genes in expression matrix)") + cli::cli_progress_step( + "Adjusting min_features to {seurat_min_features} (only {n_genes} genes in expression matrix)" + ) } if (n_genes < seurat_nfeatures) { seurat_nfeatures <- max(10, n_genes) - message(" Adjusting nfeatures to ", seurat_nfeatures, - " (only ", n_genes, " genes available)") + cli::cli_progress_step( + "Adjusting nfeatures to {seurat_nfeatures} (only {n_genes} genes available)" + ) } cell_clone_map <- annotate_clones( @@ -502,13 +620,14 @@ prepare_data <- function(method = c("umap", "tsne"), # through the same channel so the UI can show live stage text. progress_cb = function(step) notify_stage(paste0("seurat-", step), 1L, 5L) ) - message(" Found ", length(unique(cell_clone_map$clone_id)), " clones across ", - nrow(cell_clone_map), " cells.") + cli::cli_progress_step( + "Found {length(unique(cell_clone_map$clone_id))} clones across {nrow(cell_clone_map)} cells" + ) } # --- Step 2: Build patient IDs --- notify_stage("mapping", 2L, 5L) - message("[2/5] Mapping cells to patients...") + cli::cli_progress_step("[2/5] Mapping cells to patients...") if (is.null(sample_cell_names)) { patient_ids <- rep("patient1", ncol(expression_matrix)) names(patient_ids) <- colnames(expression_matrix) @@ -523,18 +642,22 @@ prepare_data <- function(method = c("umap", "tsne"), # Remove cells with no patient assignment unassigned <- is.na(patient_ids) if (any(unassigned)) { - warning(sum(unassigned), " cells could not be assigned to any patient. Removing them.") + cli::cli_warn( + "{sum(unassigned)} cells could not be assigned to any patient. Removing them." + ) keep_cells <- names(patient_ids)[!unassigned] expression_matrix <- expression_matrix[, keep_cells, drop = FALSE] patient_ids <- patient_ids[!unassigned] cell_clone_map <- cell_clone_map[cell_clone_map$cell_id %in% keep_cells, ] } } - message(" Found ", length(unique(patient_ids)), " patients.") + cli::cli_progress_step("Found {length(unique(patient_ids))} patients") # Add patient column to cell_clone_map - cell_clone_map$patient <- patient_ids[match(cell_clone_map$cell_id, - names(patient_ids))] + cell_clone_map$patient <- patient_ids[match( + cell_clone_map$cell_id, + names(patient_ids) + )] # In clone-level mode, refine the clone label to the per-patient category # (e.g. "Kydar01_c1" -> "c1") using the KNOWN patient id, so clone keys @@ -542,17 +665,23 @@ prepare_data <- function(method = c("umap", "tsne"), # when the cell name actually starts with its patient id; any other naming # scheme keeps the full name, so the behavior is universal. if (isTRUE(skip_clustering)) { - cell_clone_map$clone_id <- vapply(seq_len(nrow(cell_clone_map)), function(i) { - cell <- cell_clone_map$cell_id[i] - pat <- cell_clone_map$patient[i] - if (is.na(pat) || !startsWith(cell, pat)) return(cell) - rest <- sub("^[\\._-]", "", substring(cell, nchar(pat) + 1)) - if (nchar(rest) == 0) cell else rest - }, character(1)) + cell_clone_map$clone_id <- vapply( + seq_len(nrow(cell_clone_map)), + function(i) { + cell <- cell_clone_map$cell_id[i] + pat <- cell_clone_map$patient[i] + if (is.na(pat) || !startsWith(cell, pat)) { + return(cell) + } + rest <- sub("^[\\._-]", "", substring(cell, nchar(pat) + 1)) + if (nchar(rest) == 0) cell else rest + }, + character(1) + ) } # --- Step 3: Compute clone-level mean expression --- - message("[3/5] Computing clone-level mean expression...") + cli::cli_progress_step("[3/5] Computing clone-level mean expression...") clone_expr_list <- clone_mean_expression( expression_matrix = expression_matrix, cell_clone_map = cell_clone_map[, c("cell_id", "clone_id")], @@ -560,24 +689,30 @@ prepare_data <- function(method = c("umap", "tsne"), ) if (length(clone_expr_list) == 0) { - stop("No clone expression matrices were produced. Check cell-clone mapping.") + cli::cli_abort( + "No clone expression matrices were produced. Check cell-clone mapping." + ) } # Merge all patients into one matrix clone_expr_merged <- do.call(cbind, clone_expr_list) - message(" Produced ", ncol(clone_expr_merged), " clone columns across ", - length(clone_expr_list), " patients.") + cli::cli_progress_step( + "Produced {ncol(clone_expr_merged)} clone columns across {length(clone_expr_list)} patients" + ) # --- Step 4: Filter genes and rank normalize --- - message("[4/5] Rank-normalizing clone expression...") + cli::cli_progress_step("[4/5] Rank-normalizing clone expression...") if (!is.null(genes_to_use)) { available_genes <- intersect(genes_to_use, rownames(clone_expr_merged)) if (length(available_genes) == 0) { - stop("None of the provided genes_to_use were found in the expression matrix.") + rlang::abort( + "None of the provided genes_to_use were found in the expression matrix." + ) } if (length(available_genes) < length(genes_to_use)) { - warning("Only ", length(available_genes), " / ", length(genes_to_use), - " genes_to_use found in expression matrix.") + cli::cli_warn( + "Only {length(available_genes)} / {length(genes_to_use)} genes_to_use found in expression matrix." + ) } clone_expr_merged <- clone_expr_merged[available_genes, , drop = FALSE] } @@ -586,7 +721,7 @@ prepare_data <- function(method = c("umap", "tsne"), # --- Step 5: Build clone counts table --- notify_stage("clone-counts", 5L, 5L) - message("[5/5] Building clone abundance table...") + cli::cli_progress_step("[5/5] Building clone abundance table...") clone_counts <- build_clone_counts( cell_clone_map = cell_clone_map, patient_ids = cell_clone_map$patient @@ -596,18 +731,21 @@ prepare_data <- function(method = c("umap", "tsne"), # Row order matches clone_expression_rnorm column order clone_viability_template <- parse_clone_keys(colnames(clone_expression_rnorm)) - message("\n=== Preparation complete ===") - message(" Genes: ", nrow(clone_expression_rnorm)) - message(" Clones: ", ncol(clone_expression_rnorm)) - message(" Patients: ", nrow(clone_counts)) + cli::cli_h2("Preparation complete") + cli::cli_ul("Genes: {.val {nrow(clone_expression_rnorm)}}") + cli::cli_ul("Clones: {.val {ncol(clone_expression_rnorm)}}") + cli::cli_ul("Patients: {.val {nrow(clone_counts)}}") return(list( clone_expression_rnorm = clone_expression_rnorm, clone_counts = clone_counts, cell_clone_map = cell_clone_map, clone_viability_template = clone_viability_template, - umap_coords = if (isTRUE(skip_clustering)) NULL else - cell_clone_map[, c("cell_id", "dim_1", "dim_2")], + umap_coords = if (isTRUE(skip_clustering)) { + NULL + } else { + cell_clone_map[, c("cell_id", "dim_1", "dim_2")] + }, reduction_method = if (isTRUE(skip_clustering)) "none" else method )) } diff --git a/R/app.R b/R/app.R index 65a61ca..6f17e3a 100644 --- a/R/app.R +++ b/R/app.R @@ -25,23 +25,19 @@ run_perception_app <- function() { appDir <- system.file("shiny", "app", package = "PERCEPTIONx") if (appDir == "") { - stop("Could not find PERCEPTIONx dashboard. Try re-installing the package with: install.packages('PERCEPTIONx', repos = NULL, type = 'source')", - call. = FALSE) + cli::cli_abort(c( + x = "Could not find PERCEPTIONx dashboard. ", + i = "Try re-installing the package with: `install.packages('PERCEPTIONx', repos = NULL, type = 'source')`" + )) } # The dashboard hard-depends on these packages. They are in Suggests (not # Imports) to keep the core pipeline lean, so check them here and fail fast # with an actionable message instead of a cryptic library() error. - app_deps <- c("bslib", "DT", "plotly", "waiter", "thematic", "callr") - missing <- app_deps[!vapply(app_deps, requireNamespace, logical(1), quietly = TRUE)] - if (length(missing) > 0) { - stop("The PERCEPTIONx dashboard requires these packages, which are not installed: ", - paste(missing, collapse = ", "), - "\nInstall them with: install.packages(c(", - paste(shQuote(missing), collapse = ", "), "))", - call. = FALSE) - } - + rlang::check_installed( + c("bslib", "DT", "plotly", "waiter", "thematic", "callr"), + reason = "for PERCEPTIONx dashboard" + ) # Set max upload size to 1 GB (for DepMap ~567MB + models) options(shiny.maxRequestSize = 1024 * 1024^2) @@ -71,10 +67,13 @@ run_perception_app <- function() { env <- new.env(parent = globalenv()) exprs <- parse(app_file) obj <- NULL - for (e in exprs) obj <- eval(e, envir = env) + for (e in exprs) { + obj <- eval(e, envir = env) + } if (!inherits(obj, "shiny.appobj")) { - stop("Failed to build the PERCEPTIONx app object (app.R did not yield a shinyApp).", - call. = FALSE) + rlang::abort( + "Failed to build the PERCEPTIONx app object (app.R did not yield a shinyApp)." + ) } obj } diff --git a/R/depmap_meta.R b/R/depmap_meta.R index 256137d..534a431 100644 --- a/R/depmap_meta.R +++ b/R/depmap_meta.R @@ -15,7 +15,9 @@ #' \code{lineages}, \code{components}. #' @noRd extract_depmap_meta <- function(depmap_path, cache_file = NULL) { - if (!is.null(cache_file) && file.exists(cache_file) && file.exists(depmap_path)) { + if ( + !is.null(cache_file) && file.exists(cache_file) && file.exists(depmap_path) + ) { # Only trust a cache that is newer than the source DepMap.RDS itself: # if the RDS was replaced (re-download / different version) the cached # genes/drugs would be silently stale. A corrupt cache falls through to @@ -29,24 +31,38 @@ extract_depmap_meta <- function(depmap_path, cache_file = NULL) { } DepMap <- readRDS(depmap_path) if (!is.list(DepMap)) { - stop("The file is not a list. Expected a DepMap.RDS from the PERCEPTIONx release (or an object with the same structure).") + cli::cli_abort(c( + x = "The file is not a {.cls list}.", + i = "Expected a DepMap.RDS from the PERCEPTIONx release (or an object with the same structure)." + )) } - required_fields <- c("secondary_prism", "secondary_screen_drugAnnotation", - "expression_rnorm", "scRNA_complete", "scRNA_subset_rnorm", - "CPM_scRNA_CCLE_rnorm", "annotation_20Q4", - "metadata_CPM_scRNA", "expression_20Q4") + required_fields <- c( + "secondary_prism", + "secondary_screen_drugAnnotation", + "expression_rnorm", + "scRNA_complete", + "scRNA_subset_rnorm", + "CPM_scRNA_CCLE_rnorm", + "annotation_20Q4", + "metadata_CPM_scRNA", + "expression_20Q4" + ) missing_fields <- setdiff(required_fields, names(DepMap)) if (length(missing_fields) > 0) { - stop("The RDS is missing required components: ", - paste(missing_fields, collapse = ", "), - ". Re-save it with these components, or use the built-in 'Download & Load' (known-good).") + cli::cli_abort(c( + "The RDS is missing required components: {.field {missing_fields}}.", + "i" = "Re-save it with these components, or use the built-in 'Download & Load' (known-good)." + )) } nms <- names(DepMap) components <- lapply(nms, function(nm) { obj <- DepMap[[nm]] if (is.matrix(obj) || is.data.frame(obj)) { - list(nrow = nrow(obj), ncol = ncol(obj), - cols_preview = head(colnames(obj), 12)) + list( + nrow = nrow(obj), + ncol = ncol(obj), + cols_preview = head(colnames(obj), 12) + ) } else { list(nrow = NA_integer_, ncol = NA_integer_, cols_preview = character(0)) } @@ -56,12 +72,17 @@ extract_depmap_meta <- function(depmap_path, cache_file = NULL) { lineages <- lineages[!is.na(lineages) & nzchar(lineages)] meta <- list( loaded = TRUE, - genes = rownames(DepMap$expression_rnorm), - drugs = unique(as.character(DepMap$secondary_screen_drugAnnotation$CommonName)), + genes = rownames(DepMap$expression_rnorm), + drugs = unique(as.character( + DepMap$secondary_screen_drugAnnotation$CommonName + )), lineages = lineages, components = components ) - if (!is.null(cache_file)) saveRDS(meta, cache_file) - rm(DepMap); gc() + if (!is.null(cache_file)) { + saveRDS(meta, cache_file) + } + rm(DepMap) + gc() meta } diff --git a/R/drugs.R b/R/drugs.R index 8bf8ad2..2cecd46 100644 --- a/R/drugs.R +++ b/R/drugs.R @@ -1,1603 +1,416 @@ -# 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. +#' 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. +#' +#' @export +# fmt:table perception_depmap_drugs <- c( - "1-azakenpaullone", - "1-naphthyl-PP1", - "1-phenylbiguanide", - "10-deacetylbaccatin", - "10-hydroxycamptothecin", - "12-O-tetradecanoylphorbol-13-acetate", - "2'-MeCCPA", - "2-methoxyestradiol", - "2,3-DCPE", - "3'-fluorobenzylspiperone", - "3-amino-benzamide", - "3-deazaneplanocin-A", - "4-(4-fluorobenzoyl)-1-(4-phenylbutyl)-piperidine", - "4-chlorophenylguanidine", - "4-hydroxy-phenazone", - "4-iodo-6-phenylpyrimidine", - "4-methylgenistein", - "4-methylhistamine", - "4-pyrimidinecarbonitrile", - "4E1RCat", - "5-fluorouracil", - "5-hydroxymethyl-tolterodine", - "7-aminocephalosporanic-acid", - "7-hydroxystaurosporine", - "7-nitroindazole", - "8-bromo-cGMP", - "8-hydroxy-PIPAT", - "9-aminoacridine", - "A-674563", - "A-803467", - "A61603", - "abemaciclib", - "abiraterone", - "abiraterone-acetate", - "ABT-702", - "ABT-737", - "ABT-751", - "AC-264613", - "ACDPP", - "acesulfame-potassium", - "acetazolamide", - "acetophenazine", - "acetylcysteine", - "acetylsalicylsalicylic-acid", - "acipimox", - "acivicin", - "ACY-1215", - "adapalene", - "adaprev", - "adarotene", - "adefovir-dipivoxil", - "ADL5859", - "AEE788", - "AEG3482", - "afatinib", - "afobazole", - "AG-14361", - "ajmaline", - "albendazole", - "alectinib", - "alexidine", - "alfacalcidol", - "alisertib", - "almorexant", - "alogliptin", - "alpelisib", - "altretamine", - "alvespimycin", - "alvocidib", - "AM-251", - "AM-404", - "AM-580", - "ambazone", - "amfenac", - "AMG-208", - "AMG-232", - "AMG458", - "AMG900", - "aminoglutethimide", - "aminopurvalanol-a", - "amisulpride", - "ammonium-lactate", - "amonafide", - "amoxicillin", - "amprolium", - "amsacrine", - "anagrelide", - "anastrozole", - "anguidine", - "anisomycin", - "AP1903", - "AP26113", - "apatinib", - "aphidicolin", - "AR-12", - "AR-42", - "arctigenin", - "arcyriaflavin-a", - "aripiprazole", - "ARRY-334543", - "artemisinin", - "artesunate", - "AS-1949490", - "AS-703026", - "aspirin", - "AST-1306", - "astemizole", - "asymmetrical-dimethylarginine", - "AT-7519", - "AT-9283", - "AT13387", - "AT7867", - "atenolol-(-)", - "atenolol-(+/-)", - "atipamezole", - "atiprimod", - "atorvastatin", - "aurora-a-inhibitor-i", - "AV-412", - "avanafil", - "AVL-292", - "AVN-944", - "axitinib", - "AZ-628", - "AZ20", - "AZ3146", - "AZ960", - "azacitidine", - "azalomycin-b", - "azathioprine", - "AZD1480", - "AZD2014", - "AZD2461", - "AZD2858", - "AZD3463", - "AZD4547", - "AZD5363", - "AZD5438", - "AZD6482", - "AZD7762", - "AZD8055", - "AZD8330", - "AZD8931", - "AZD9668", - "azilsartan", - "azithromycin", - "azodicarbonamide", - "azomycin-(2-nitroimidazole)", - "aztreonam", - "bafetinib", - "baicalein", - "baicalin", - "balapiravir", - "BAM7", - "BAN-ORL-24", - "barasertib", - "barasertib-HQPA", - "bardoxolone", - "bardoxolone-methyl", - "baricitinib", - "batimastat", - "BAY-11-7082", - "BAY-11-7085", - "BAY-87-2243", - "BAY-K-8644-(s)-(-)", - "beclomethasone-dipropionate", - "bekanamycin", - "belinostat", - "bendamustine", - "bendroflumethiazide", - "benfotiamine", - "bentazepam", - "benzethonium", - "benzocaine", - "benzydamine", - "benzyldimethylhexadecylammonium", - "bephenium-hydroxynaphthoate", - "berberine", - "beta-lapachone", - "beta-naphthol", - "betamethasone", - "betamethasone-dipropionate", - "betulinic-acid", - "bexarotene", - "BF2.649", - "BGT226", - "BI-2536", - "BI-78D3", - "BI-D1870", - "BIBR-1532", - "BIBU-1361", - "BIBX-1382", - "bicalutamide", - "bifemelane", - "BIIB021", - "bindarit", - "birinapant", - "bis(maltolato)oxovanadium(IV)", - "bisacodyl", - "bisindolylmaleimide-ix", - "bitopertin", - "BIX-01294", - "BIX-02188", - "blebbistatin-(-)", - "BMS-265246", - "BMS-345541", - "BMS-387032", - "BMS-599626", - "BMS-626529", - "BMS-690514", - "BMS-707035", - "BMS-754807", - "BMS-986020", - "BNC105", - "BNTX", - "bortezomib", - "bosentan", - "bosutinib", - "brefeldin-a", - "brequinar", - "brigatinib", - "brilliant-green", - "brivaracetam", - "bromosporine", - "broxaldine", - "broxyquinoline", - "bruceantin", - "BTS-54505", - "bucladesine", - "bumetanide", - "buparlisib", - "buphenine", - "busulfan", - "butamben", - "buthionine-sulfoximine", - "butylscopolamine-bromide", - "BVD-523", - "BVT-948", - "BW-180C", - "BX-912", - "cabazitaxel", - "cabozantinib", - "caffeic-acid", - "caffeic-acid-phenethyl-ester", - "calcitriol", - "camptothecin", - "camylofine-chlorhydrate", - "candesartan", - "canertinib", - "canrenone", - "capecitabine", - "capsaicin", - "captamine", - "carbachol", - "carboplatin", - "carboxyamidotriazole", - "carboxypyridine-disulfide", - "carfilzomib", - "cariporide", - "carmofur", - "carmustine", - "carvedilol", - "CB-10-277", - "CCG-50014", - "CCMI", - "CCT128930", - "CCT129202", - "CCT137690", - "CD-437", - "cebranopadol", - "cediranib", - "cefdinir", - "cefditoren-pivoxil", - "cefpiramide", - "CEP-32496", - "CEP-33779", - "CEP-37440", - "cephalomannine", - "cetrimonium", - "cetylpyridinium", - "CGM097", - "CGP-37849", - "CGP-52411", - "CGP-54626", - "CGS-15943", - "CGS-20625", - "CH5132799", - "chicago-sky-blue-6b", - "chidamide", - "CHIR-124", - "CHIR-98014", - "CHIR-99021", - "chlorambucil", - "chloramphenicol-palmitate", - "chlorhexidine", - "chlorindanol", - "chlormidazole", - "chlorogenic-acid", - "chloropyramine", - "chloroxine", - "chlorpropamide", - "chlorpyrifos", - "chlorquinaldol", - "cholecalciferol", - "chromocarb", - "CI-844", - "cibenzoline", - "ciclesonide", - "ciclopirox", - "CID-5458317", - "cidofovir", - "cilostamide", - "cimetidine", - "cinacalcet", - "cinalukast", - "cinnarazine", - "cinromide", - "ciprofibrate", - "cisplatin", - "CL-218872", - "cladribine", - "clebopride", - "clenbuterol", - "clindamycin-phosphate", - "clobetasol-propionate", - "clobutinol", - "clocortolone-pivalate", - "clofarabine", - "clofazimine", - "clofibrate", - "clofoctol", - "clomifene", - "clonazepam", - "clopamide", - "clotrimazole", - "CMPD-1", - "CNX-2006", - "CNX-774", - "cobicistat", - "cobimetinib", - "colchicine", - "colforsin-daproate", - "colfosceril-palmitate", - "colistin-b-sulfate", - "combretastatin-A-4", - "costunolide", - "CP-673451", - "CP-724714", - "CP-945,598", - "CPI-1189", - "CPP", - "CR8-(R)", - "creatine", - "crenolanib", - "crizotinib", - "crizotinib-(S)", - "cromakalim", - "crystal-violet", - "CS-110266", - "CUDC-101", - "CUDC-907", - "curcumin", - "CX-4945", - "CX-5461", - "CYC116", - "cyclocytidine", - "cycloheximide", - "cyclophosphamide", - "cyclosporin-a", - "cyclosporine", - "cyclovalone", - "cyclovirobuxin-d", - "cyproheptadine", - "cyproterone-acetate", - "cyromazine", - "CYT-997", - "cyt387", - "cytarabine", - "cytochalasin-b", - "cytochlor", - "D-4476", - "D-64131", - "D-7193", - "D-Serine", - "dabrafenib", - "dacarbazine", - "dacinostat", - "daclatasvir", - "dacomitinib", - "dalcetrapib", - "danazol", - "danusertib", - "dapivirine", - "darapladib", - "darifenacin", - "dasatinib", - "daunorubicin", - "DCEBIO", - "decitabine", - "defactinib", - "deferasirox", - "deflazacort", - "deforolimus", - "dehydrocholate-acid", - "delanzomib", - "demecarium", - "deoxycorticosterone-acetate", - "dequalinium", - "desonide", - "desoxycortone", - "dexamethasone-acetate", - "dexrazoxane", - "dianhydrogalactitol", - "diaveridine", - "diazooxonorleucine", - "dichlorisone-acetate", - "dichloroacetate", - "dichlorvos", - "diclazuril", - "dicycloverine", - "dienogest", - "difluprednate", - "digitoxigenin", - "digitoxin", - "digoxigenin", - "digoxin", - "dihydroartemisinin", - "dihydroergocristine", - "dihydromyricetin", - "dimethisoquin", - "dinaciclib", - "dioscin", - "diphemanil", - "diphenyleneiodonium", - "dirithromycin", - "disulfiram", - "DMH1", - "docetaxel", - "dofetilide", - "dolastatin-10", - "dolutegravir", - "domiphen", - "domperidone", - "dorzolamide", - "dovitinib", - "doxercalciferol", - "doxifluridine", - "doxorubicin", - "doxycycline", - "DPI-201106", - "dronedarone", - "drospirenone", - "DU-728", - "DVD-111", - "E7449", - "ebastine", - "ecamsule-triethanolamine", - "echinomycin", - "efonidipine-monoethanolate", - "elacridar", - "elesclomol", - "eltrombopag", - "embelin", - "EMD-53998", - "emetine", - "endo-IWR-1", - "ENMD-2076", - "enocitabine", - "enoximone", - "entinostat", - "enzalutamide", - "epiandrosterone", - "epinastine", - "epinephrine", - "epirubicin", - "eplerenone", - "epothilone-a", - "epothilone-b", - "epothilone-d", - "eprinomectin", - "eprobemide", - "eprosartan", - "eptifibatide", - "EPZ-5676", - "equol", - "ER-27319", - "erastin", - "ercalcitriol", - "erdafitinib", - "erlotinib", - "erteberel", - "erythritol", - "estradiol", - "estradiol-benzoate", - "estradiol-cypionate", - "estramustine", - "estramustine-phosphate", - "estrone", - "ethacridine-lactate-monohydrate", - "ethinyl-estradiol", - "etofylline-clofibrate", - "etomoxir", - "etoposide", - "etoposide-phosphate", - "ETP-46464", - "evacetrapib", - "everolimus", - "evodiamine", - "EVP4593", - "exatecan-mesylate", - "exemestane", - "famciclovir", - "famotidine", - "favipiravir", - "fdcyd", - "felbamate", - "fenaclon", - "fenbendazole", - "fendiline", - "fenofibrate", - "fenoprofen", - "fenretinide", - "FERb-033", - "fexinidazole", - "FG-4592", - "filanesib", - "filgotinib", - "finafloxacin", - "FK-3311", - "FK-866", - "FK-888", - "fleroxacin", - "FLI-06", - "florfenicol", - "floxuridine", - "flubendazole", - "fludarabine", - "fludarabine-phosphate", - "fludroxycortide", - "flufenamic-acid", - "flumatinib", - "flumethasone", - "flumethasone-pivalate", - "fluocinolone-acetonide", - "fluorometholone", - "fluoromethylcholine", - "fluroxene", - "flutamide", - "fluticasone-propionate", - "fluvastatin", - "foretinib", - "formestane", - "forodesine", - "forskolin", - "fosbretabulin", - "foscarnet", - "FPH1-(BRD-6125)", - "FR-122047", - "FR-139317", - "frentizole", - "ftorafur", - "fudosteine", - "fulvestrant", - "G-1", - "galeterone", - "gambogic-acid", - "gamma-aminobutyric-acid", - "ganetespib", - "gastrodin", - "GDC-0068", - "GDC-0152", - "GDC-0349", - "GDC-0879", - "GDC-0941", - "GDC-0980", - "gefitinib", - "gemcitabine", - "genipin", - "genz-644282", - "gestrinone", - "GGTI-298", - "gidazepam", - "gilteritinib", - "gimeracil", - "ginkgolide-a", - "givinostat", - "golgicide-a", - "golvatinib", - "gossypol", - "GS-39783", - "GS-9973", - "GSK-3-inhibitor-IX", - "GSK-J4", - "GSK1070916", - "GSK1292263", - "GSK1838705A", - "GSK1904529A", - "GSK2110183", - "GSK2126458", - "GSK256066", - "GSK2656157", - "GSK2830371", - "GSK429286A", - "GSK461364", - "GSK650394", - "GSK923295", - "GTP-14564", - "guanidine", - "GW-3965", - "GW-405833", - "GW-441756", - "GW-501516", - "GW-583340", - "GW-788388", - "GW-842166", - "GW-843682X", - "GZD824", - "HA14-1", - "halcinonide", - "halobetasol-propionate", - "halofantrine", - "halofuginone", - "harringtonine", - "hesperadin", - "hexachlorophene", - "hexaminolevulinate", - "hexylresorcinol", - "HMN-214", - "homoharringtonine", - "homoquinolinic-acid", - "homosalate", - "hydrocortisone", - "hydroxytacrine-maleate-(r,s)", - "hydroxyurea", - "hyodeoxycholic-acid", - "hyoscyamine", - "hypericin", - "hypoestoxide", - "I-BET-762", - "I-BET151", - "ibrutinib", - "ibutilide", - "ICG-001", - "ICI-162846", - "icotinib", - "idarubicin", - "idasanutlin", - "idazoxan", - "idelalisib", - "idoxuridine", - "IDRA-21", - "idronoxil", - "IEM1754", - "ifosfamide", - "IKK-16", - "IKK-2-inhibitor-V", - "ilomastat", - "imatinib", - "imidapril", - "imiloxan", - "imiquimod", - "INC-280", - "indibulin", - "indiplon", - "indirubin", - "indisulam", - "indoprofen", - "ingenol-mebutate", - "INH1", - "inosine", - "iobenguane", - "iodipamide", - "iododexetimide", - "IOWH032", - "iproniazid", - "ipsapirone", - "irinotecan", - "isoetharine", - "isofloxythepin", - "isoflupredone-acetate", - "isometheptene-mucate", - "isopropyl-myristate", - "isoxsuprine", - "ispinesib", - "istradefylline", - "itraconazole", - "ivermectin", - "ixabepilone", - "ixazomib", - "ixazomib-citrate", - "JIB04", - "JK-184", - "JNJ-16259685", - "JNJ-26481585", - "JNJ-7706621", - "josamycin", - "JQ1-(+)", - "JTC-801", - "JTE-607", - "JZL-184", - "K-858", - "K-Ras(G12C)-inhibitor-6", - "k-strophanthidin", - "KD-023", - "KD025", - "kenpaullone", - "ketoconazole", - "ketoprofen", - "KF-38789", - "KI-16425", - "KI-8751", - "kifunensine", - "KP-1212", - "KPT-185", - "KPT-276", - "ku-0063794", - "KW-2449", - "KW-2478", - "KX2-391", - "KY02111", - "kynurenic-acid", - "L-798,106", - "lacitol", - "lafutidine", - "lanatoside-c", - "lanoconazole", - "lapatinib", - "lappaconite", - "lasalocid", - "latanoprost", - "latrepirdine", - "LB42708", - "LCL-161", - "LDN-212854", - "LDN-57444", - "LE-135", - "lenalidomide", - "lenvatinib", - "lerisetron", - "lestaurtinib", - "letrozole", - "leucovorin", - "levobunolol", - "levocarnitine", - "levocetirizine", - "levonorgestrel", - "LGX818", - "licochalcone-a", - "lidamidine", - "lidocaine", - "linalool", - "linifanib", - "linsitinib", - "litronesib", - "lomefloxacin", - "lomitapide", - "lonafarnib", - "lorazepam", - "lorlatinib", - "lovastatin", - "loxistatin-acid", - "lucitanib", - "lurasidone", - "LY2090314", - "LY2109761", - "LY2183240", - "LY2334737", - "LY2603618", - "LY2606368", - "LY2608204", - "LY2784544", - "LY2801653", - "LY2874455", - "LY3023414", - "LY303511", - "LY364947", - "LY456236", - "M-344", - "maprotiline", - "marimastat", - "masitinib", - "maxacalcitol", - "maytansinol-isobutyrate", - "mebendazole", - "mechlorethamine", - "meclizine", - "mefexamide", - "meglitinide", - "MEK1-2-inhibitor", - "MEK162", - "melengestrol-acetate", - "meloxicam", - "melphalan", - "menadione", - "mephenytoin", - "mepivacaine", - "mercaptopurine", - "mericitabine", - "merimepodib", - "mesna", - "mesoridazine", - "metaraminol", - "metatinib", - "methacycline", - "methiazole", - "methocarbamol", - "methotrexate", - "methoxyflurane", - "methscopolamine", - "methyldopa", - "methylphenidate", - "methylprednisolone", - "metoprolol", - "metoxibutropate", - "metronidazole", - "metyrapone", - "mevastatin", - "mexeneone", - "mexiletine", - "MG-132", - "MGCD-265", - "mibampator", - "mibefradil", - "midodrine", - "midostaurin", - "mifepristone", - "minocycline", - "mitomycin-c", - "mitoxantrone", - "MK-0773", - "MK-0812", - "MK-1775", - "MK-2206", - "MK-2461", - "MK-3207", - "MK-5108", - "MK-8245", - "MK-8745", - "ML133", - "MLN-8054", - "MLN0128", - "MNS-(3,4-Methylenedioxy-nitrostyrene)", - "mocetinostat", - "monensin", - "monobenzone", - "morin", - "motesanib", - "mozavaptan", - "MPI-0479605", - "MRS-1220", - "MTPG", - "mubritinib", - "mycophenolate-mofetil", - "mycophenolic-acid", - "N-acetylmannosamine", - "nadide", - "nadifloxacin", - "nafcillin", - "naftidrofuryl", - "naftifine", - "naloxone", - "naltrexone", - "NAN-190", - "nanchangmycin", - "napabucasin", - "naproxen", - "narasin", - "narlaprevir", - "navarixin", - "navitoclax", - "nefiracetam", - "nelarabine", - "nemonapride", - "nemorubicin", - "neratinib", - "nexturastat-a", - "NH125", - "niacin", - "niclosamide", - "nicorandil", - "nicotine", - "nilotinib", - "nilutamide", - "nimorazole", - "nintedanib", - "niraparib", - "niridazole", - "nisoxetine", - "nitarsone", - "nithiamide", - "nitisinone", - "nitrocaramiphen", - "nizatidine", - "nizofenone", - "NMS-1286937", - "NMS-873", - "NMS-E973", - "nobiletin", - "nocodazole", - "nomegestrol-acetate", - "nonoxynol-9", - "norepinephrine", - "norethindrone", - "norethindrone-acetate", - "noretynodrel", - "norfloxacin", - "norgestrel", - "novobiocin", - "NSC-23766", - "NSC-319726", - "NSC-3852", - "NSC-632839", - "NSC-663284", - "NSC-697923", - "NU6027", - "nutlin-3", - "NVP-AEW541", - "NVP-AUY922", - "NVP-BEZ235", - "NVP-BHG712", - "NVP-BVU972", - "NVP-TAE226", - "NVP-TAE684", - "obatoclax", - "obidoxime", - "octenidine", - "octopamine", - "odanacatib", - "olaparib", - "OLDA", - "oleanolic-acid", - "oleoylethanolamide", - "oligomycin-a", - "oltipraz", - "omeprazole", - "ONC201", - "oncrasin-1", - "ONX-0914", - "oprozomib", - "orantinib", - "oridonin", - "ornithine", - "orotic-acid", - "oseltamivir-phosphate", - "OSI-027", - "OSI-420", - "OSI-930", - "osimertinib", - "OTS167", - "OTX015", - "ouabain", - "oxaliplatin", - "oxazepam", - "oxcarbazepine", - "oxibendazole", - "oxiperomide", - "oxiracetam", - "oxonic-acid", - "oxprenolol", - "oxymatrine", - "oxymetazoline", - "oxyphencyclimine", - "oxyquinoline", - "P22077", - "P276-00", - "P5091", - "PAC-1", - "paclitaxel", - "pacritinib", - "palbociclib", - "paliperidone", - "palmatine-chloride", - "palmitoylethanolamide", - "palomid-529", - "panobinostat", - "papaverine", - "parachlorophenol", - "parbendazole", - "pardoprunox", - "paricalcitol", - "parthenolide", - "parthenolide-(-)", - "pazopanib", - "PCI-24781", - "PD-0325901", - "PD-153035", - "PD-168393", - "PD-173074", - "PD-184352", - "PD-198306", - "PD-318088", - "PD-407824", - "PD-98059", - "pelitinib", - "penfluridol", - "penicillamine-(D)", - "pentagastrin", - "pentamidine", - "pentostatin", - "pepstatin", - "peruvoside", - "PETCM", - "pevonedistat", - "PF-03758309", - "PF-03814735", - "PF-04136309", - "PF-04217903", - "PF-04457845", - "PF-04691502", - "PF-05212384", - "PF-3845", - "PF-477736", - "PF-4981517", - "PF-562271", - "PF-573228", - "PFI-1", - "PFK-015", - "PHA-665752", - "PHA-680632", - "PHA-767491", - "PHA-793887", - "PHA-848125", - "phenazone", - "phenelzine", - "pheniramine", - "phenylbutazone", - "phenylmercuric-acetate", - "phlorizin", - "PI-103", - "PI-828", - "PI3K-IN-2", - "pibenzimol", - "picolinic-acid", - "PIK-75", - "pilaralisib", - "pilocarpine", - "pindolol", - "piperacetazine", - "piperazine", - "piperine", - "pirenperone", - "piretanide", - "piroxicam", - "pitavastatin", - "PJ-34", - "PKI-179", - "plinabulin", - "PLX-4720", - "podophyllotoxin", - "polydatin", - "pomalidomide", - "ponatinib", - "posaconazole", - "poziotinib", - "PP-1", - "PP-121", - "PP-2", - "PP242", - "PPT", - "PQ-401", - "PR-619", - "practolol", - "pralatrexate", - "pranidipine", - "prazosin", - "prednisolone", - "prednisolone-acetate", - "prednisolone-hemisuccinate", - "prednisolone-tebutate", - "primaquine", - "proflavine-hemisulfate", - "propoxycaine", - "propranolol", - "proscillaridin-a", - "protirelin", - "PRT062070", - "PRT062607", - "PSB-1115", - "PSI-7976", - "PTC-209", - "pterostilbene", - "PU-H71", - "puromycin", - "pyrimethamine", - "pyrithione-zinc", - "pyritinol", - "pyroxamide", - "quinethazone", - "quinidine", - "quizartinib", - "R306465", - "R406", - "R547", - "rabeprazole", - "racecadotril", - "raclopride", - "radezolid", - "RAF265", - "raloxifene", - "raltitrexed", - "ramatroban", - "ramifenazone", - "ranitidine", - "refametinib", - "regorafenib", - "remoxipride", - "repaglinide", - "repsox", - "resatorvid", - "resiquimod", - "resminostat", - "RG108", - "RG2833", - "RGFP966", - "rheochrysidin", - "RI-1", - "ribavirin", - "ribitol", - "ribociclib", - "riboflavin", - "rifampin", - "rigosertib", - "riluzole", - "rimexolone", - "riociguat", - "RITA", - "ritodrine", - "RKI-1447", - "RN-1734", - "Ro-04-5595", - "Ro-10-5824", - "Ro-106-9920", - "Ro-4987655", - "Ro-90-7501", - "Ro-9187", - "rociletinib", - "romidepsin", - "roquinimex", - "RS-16566", - "RS-17053", - "RS-504393", - "RS-67506", - "RU-58841", - "rubitecan", - "rucinol", - "rutin", - "ruxolitinib", - "ryuvidine", - "S-methylcysteine", - "S26948", - "salidroside", - "salinomycin", - "salvianolic-acid-B", - "salvinorin-a", - "sangivamycin", - "SAR131675", - "saracatinib", - "sarafloxacin", - "satraplatin", - "saxagliptin", - "SB-200646", - "SB-205384", - "SB-216641", - "SB-218078", - "SB-218795", - "SB-225002", - "SB-228357", - "SB-2343", - "SB-239063", - "SB-242235", - "SB-366791", - "SB-431542", - "SB-505124", - "SB-525334", - "SB-590885", - "SB-657510", - "SB-743921", - "SB-939", - "SC-12267", - "SC-144", - "SCH-58261", - "SCH-900776", - "sclareol", - "scriptaid", - "SCS", - "SDZ-WAG-994", - "se-methylselenocysteine", - "secnidazole", - "securinine", - "selamectin", - "selinexor", - "selumetinib", - "semaxanib", - "serdemetan", - "sertindole", - "sevelamer", - "sevoflurane", - "SGI-1027", - "SGI-1776", - "SIB-1757", - "SID-7969543", - "simvastatin", - "sirolimus", - "skepinone-l", - "SKF-96365", - "SKI-II", - "SMI-4a", - "SN-38", - "SNS-314", - "SNX-2112", - "SNX-5422", - "sobetirome", - "sodium-glucoheptonate", - "sodium-stibogluconate", - "sodium-tanshinone-ii-a-sulfonate", - "sonidegib", - "sorafenib", - "sparfloxacin", - "spermidine", - "spermine", - "spiradoline", - "spironolactone", - "SR-27897", - "SR-33805", - "SR-57227A", - "SRT1720", - "STA-5326", - "stattic", - "stemregenin-1", - "STF-118804", - "streptozotocin", - "SU014813", - "SU3327", - "sufentanil", - "sulconazole", - "sulfabenzamide", - "sulfamethazine", - "sulfanilamide", - "sulfasalazine", - "sulmazole", - "sunitinib", - "suxibuzone", - "tacalcitol", - "tacedinaline", - "tacrolimus", - "tagatose", - "TAK-285", - "TAK-632", - "TAK-715", - "TAK-733", - "TAK-901", - "talazoparib", - "talmapimod", - "taltirelin", - "taltobulin", - "TAME", - "tamibarotene", - "tamoxifen", - "tanaproget", - "tandutinib", - "tanespimycin", - "tanshinone-i", - "TAS-103", - "taselisib", - "tasisulam", - "taurine", - "tazemetostat", - "TC1", - "tecastemizole", - "tedizolid", - "tedizolid-phosphate", - "telatinib", - "telotristat-ethyl", - "temazepam", - "temocapril", - "temoporfin", - "temozolomide", - "temsirolimus", - "teniposide", - "tenovin-6", - "tepoxalin", - "teprenone", - "terbutaline", - "terconazole", - "terfenadine", - "teriflunomide", - "teroxirone", - "tetrahydropapaverine", - "tetrahydrouridine", - "tetramethylthiuram-monosulfide", - "tetrandrine", - "tezacaftor", - "TG-02", - "TG-100572", - "TG-100713", - "TG-101209", - "TG-101348", - "TG100-115", - "TH-302", - "theophylline", - "thiamine", - "thiocolchicoside", - "thioguanine", - "thiomersal", - "thioproperazine", - "thiostrepton", - "thiram", - "thonzonium", - "tiagabine", - "tideglusib", - "tiletamine", - "tilmicosin", - "tiludronate", - "tioguanine", - "tiotidine", - "tioxolone", - "tipifarnib", - "tipiracil", - "tipranavir", - "tirapazamine", - "tivantinib", - "tivozanib", - "TMC-353121", - "TMS", - "tofogliflozin", - "topotecan", - "torasemide", - "torcetrapib", - "toremifene", - "torin-1", - "torin-2", - "tosedostat", - "tozasertib", - "TPCA-1", - "trametinib", - "tranilast", - "trans-4-Hydroxycrotonic-acid", - "trapidil", - "tremorine", - "trequinsin", - "triamcinolone", - "triamcinolone-acetonide", - "triamterene", - "triapine", - "trichostatin-a", - "triciribine", - "triclabendazole", - "trifluridine", - "trimebutine", - "triptolide", - "trolox", - "trometamol", - "tropisetron", - "trovafloxacin", - "tryptanthrin", - "TU-2100", - "tucatinib", - "TW-37", - "TWS-119", - "tyloxapol", - "tyrphostin-A9", - "tyrphostin-AG-1296", - "tyrphostin-AG-1478", - "tyrphostin-AG-494", - "tyrphostin-AG-99", - "U-0126", - "U-18666A", - "ubenimex", - "UH-232-(+)", - "UK-383367", - "ulipristal", - "UNBS-5162", - "UNC0631", - "UNC2250", - "uprosertib", - "uracil", - "uric-acid", - "uridine", - "usniacin-(+)", - "valnemulin", - "valrubicin", - "vandetanib", - "vanoxerine", - "vatalanib", - "VE-821", - "VE-822", - "vemurafenib", - "venetoclax", - "VER-49009", - "verubulin", - "vidarabine", - "vinblastine", - "vincamine", - "vincristine", - "vindesine", - "vinflunine", - "vinorelbine", - "vismodegib", - "VLX600", - "volasertib", - "voreloxin", - "vorinostat", - "voxtalisib", - "VS-4718", - "VTP-27999", - "VU0238429", - "VU0361737", - "VU0364770", - "VX-702", - "VX-765", - "warfarin", - "WAY-170523", - "WAY-600", - "WHI-P154", - "WP1066", - "WP1130", - "WYE-125132", - "WYE-354", - "WZ-3146", - "WZ-4002", - "WZ8040", - "xanomeline", - "XBD173", - "xilobam", - "XL-647", - "XL388", - "XL888", - "xylazine", - "Y-27632", - "Y-320", - "Y-39983", - "YM-155", - "YM-201636", - "YM-976", - "YO-01027", - "zaldaride", - "zaleplon", - "zardaverine", - "ziprasidone", - "ZK-93423", - "ZK-93426", - "ZK811752", - "ZLN005", - "ZM-306416", - "ZM-447439", - "zolantidine", - "zolmitriptan", - "ZSTK-474" + "1-azakenpaullone" , "1-naphthyl-PP1" , "1-phenylbiguanide" , "10-deacetylbaccatin" , + "10-hydroxycamptothecin" , "12-O-tetradecanoylphorbol-13-acetate" , "2'-MeCCPA" , "2-methoxyestradiol" , + "2,3-DCPE" , "3'-fluorobenzylspiperone" , "3-amino-benzamide" , "3-deazaneplanocin-A" , + "4-(4-fluorobenzoyl)-1-(4-phenylbutyl)-piperidine" , "4-chlorophenylguanidine" , "4-hydroxy-phenazone" , "4-iodo-6-phenylpyrimidine" , + "4-methylgenistein" , "4-methylhistamine" , "4-pyrimidinecarbonitrile" , "4E1RCat" , + "5-fluorouracil" , "5-hydroxymethyl-tolterodine" , "7-aminocephalosporanic-acid" , "7-hydroxystaurosporine" , + "7-nitroindazole" , "8-bromo-cGMP" , "8-hydroxy-PIPAT" , "9-aminoacridine" , + "A-674563" , "A-803467" , "A61603" , "abemaciclib" , + "abiraterone" , "abiraterone-acetate" , "ABT-702" , "ABT-737" , + "ABT-751" , "AC-264613" , "ACDPP" , "acesulfame-potassium" , + "acetazolamide" , "acetophenazine" , "acetylcysteine" , "acetylsalicylsalicylic-acid" , + "acipimox" , "acivicin" , "ACY-1215" , "adapalene" , + "adaprev" , "adarotene" , "adefovir-dipivoxil" , "ADL5859" , + "AEE788" , "AEG3482" , "afatinib" , "afobazole" , + "AG-14361" , "ajmaline" , "albendazole" , "alectinib" , + "alexidine" , "alfacalcidol" , "alisertib" , "almorexant" , + "alogliptin" , "alpelisib" , "altretamine" , "alvespimycin" , + "alvocidib" , "AM-251" , "AM-404" , "AM-580" , + "ambazone" , "amfenac" , "AMG-208" , "AMG-232" , + "AMG458" , "AMG900" , "aminoglutethimide" , "aminopurvalanol-a" , + "amisulpride" , "ammonium-lactate" , "amonafide" , "amoxicillin" , + "amprolium" , "amsacrine" , "anagrelide" , "anastrozole" , + "anguidine" , "anisomycin" , "AP1903" , "AP26113" , + "apatinib" , "aphidicolin" , "AR-12" , "AR-42" , + "arctigenin" , "arcyriaflavin-a" , "aripiprazole" , "ARRY-334543" , + "artemisinin" , "artesunate" , "AS-1949490" , "AS-703026" , + "aspirin" , "AST-1306" , "astemizole" , "asymmetrical-dimethylarginine" , + "AT-7519" , "AT-9283" , "AT13387" , "AT7867" , + "atenolol-(-)" , "atenolol-(+/-)" , "atipamezole" , "atiprimod" , + "atorvastatin" , "aurora-a-inhibitor-i" , "AV-412" , "avanafil" , + "AVL-292" , "AVN-944" , "axitinib" , "AZ-628" , + "AZ20" , "AZ3146" , "AZ960" , "azacitidine" , + "azalomycin-b" , "azathioprine" , "AZD1480" , "AZD2014" , + "AZD2461" , "AZD2858" , "AZD3463" , "AZD4547" , + "AZD5363" , "AZD5438" , "AZD6482" , "AZD7762" , + "AZD8055" , "AZD8330" , "AZD8931" , "AZD9668" , + "azilsartan" , "azithromycin" , "azodicarbonamide" , "azomycin-(2-nitroimidazole)" , + "aztreonam" , "bafetinib" , "baicalein" , "baicalin" , + "balapiravir" , "BAM7" , "BAN-ORL-24" , "barasertib" , + "barasertib-HQPA" , "bardoxolone" , "bardoxolone-methyl" , "baricitinib" , + "batimastat" , "BAY-11-7082" , "BAY-11-7085" , "BAY-87-2243" , + "BAY-K-8644-(s)-(-)" , "beclomethasone-dipropionate" , "bekanamycin" , "belinostat" , + "bendamustine" , "bendroflumethiazide" , "benfotiamine" , "bentazepam" , + "benzethonium" , "benzocaine" , "benzydamine" , "benzyldimethylhexadecylammonium" , + "bephenium-hydroxynaphthoate" , "berberine" , "beta-lapachone" , "beta-naphthol" , + "betamethasone" , "betamethasone-dipropionate" , "betulinic-acid" , "bexarotene" , + "BF2.649" , "BGT226" , "BI-2536" , "BI-78D3" , + "BI-D1870" , "BIBR-1532" , "BIBU-1361" , "BIBX-1382" , + "bicalutamide" , "bifemelane" , "BIIB021" , "bindarit" , + "birinapant" , "bis(maltolato)oxovanadium(IV)" , "bisacodyl" , "bisindolylmaleimide-ix" , + "bitopertin" , "BIX-01294" , "BIX-02188" , "blebbistatin-(-)" , + "BMS-265246" , "BMS-345541" , "BMS-387032" , "BMS-599626" , + "BMS-626529" , "BMS-690514" , "BMS-707035" , "BMS-754807" , + "BMS-986020" , "BNC105" , "BNTX" , "bortezomib" , + "bosentan" , "bosutinib" , "brefeldin-a" , "brequinar" , + "brigatinib" , "brilliant-green" , "brivaracetam" , "bromosporine" , + "broxaldine" , "broxyquinoline" , "bruceantin" , "BTS-54505" , + "bucladesine" , "bumetanide" , "buparlisib" , "buphenine" , + "busulfan" , "butamben" , "buthionine-sulfoximine" , "butylscopolamine-bromide" , + "BVD-523" , "BVT-948" , "BW-180C" , "BX-912" , + "cabazitaxel" , "cabozantinib" , "caffeic-acid" , "caffeic-acid-phenethyl-ester" , + "calcitriol" , "camptothecin" , "camylofine-chlorhydrate" , "candesartan" , + "canertinib" , "canrenone" , "capecitabine" , "capsaicin" , + "captamine" , "carbachol" , "carboplatin" , "carboxyamidotriazole" , + "carboxypyridine-disulfide" , "carfilzomib" , "cariporide" , "carmofur" , + "carmustine" , "carvedilol" , "CB-10-277" , "CCG-50014" , + "CCMI" , "CCT128930" , "CCT129202" , "CCT137690" , + "CD-437" , "cebranopadol" , "cediranib" , "cefdinir" , + "cefditoren-pivoxil" , "cefpiramide" , "CEP-32496" , "CEP-33779" , + "CEP-37440" , "cephalomannine" , "cetrimonium" , "cetylpyridinium" , + "CGM097" , "CGP-37849" , "CGP-52411" , "CGP-54626" , + "CGS-15943" , "CGS-20625" , "CH5132799" , "chicago-sky-blue-6b" , + "chidamide" , "CHIR-124" , "CHIR-98014" , "CHIR-99021" , + "chlorambucil" , "chloramphenicol-palmitate" , "chlorhexidine" , "chlorindanol" , + "chlormidazole" , "chlorogenic-acid" , "chloropyramine" , "chloroxine" , + "chlorpropamide" , "chlorpyrifos" , "chlorquinaldol" , "cholecalciferol" , + "chromocarb" , "CI-844" , "cibenzoline" , "ciclesonide" , + "ciclopirox" , "CID-5458317" , "cidofovir" , "cilostamide" , + "cimetidine" , "cinacalcet" , "cinalukast" , "cinnarazine" , + "cinromide" , "ciprofibrate" , "cisplatin" , "CL-218872" , + "cladribine" , "clebopride" , "clenbuterol" , "clindamycin-phosphate" , + "clobetasol-propionate" , "clobutinol" , "clocortolone-pivalate" , "clofarabine" , + "clofazimine" , "clofibrate" , "clofoctol" , "clomifene" , + "clonazepam" , "clopamide" , "clotrimazole" , "CMPD-1" , + "CNX-2006" , "CNX-774" , "cobicistat" , "cobimetinib" , + "colchicine" , "colforsin-daproate" , "colfosceril-palmitate" , "colistin-b-sulfate" , + "combretastatin-A-4" , "costunolide" , "CP-673451" , "CP-724714" , + "CP-945,598" , "CPI-1189" , "CPP" , "CR8-(R)" , + "creatine" , "crenolanib" , "crizotinib" , "crizotinib-(S)" , + "cromakalim" , "crystal-violet" , "CS-110266" , "CUDC-101" , + "CUDC-907" , "curcumin" , "CX-4945" , "CX-5461" , + "CYC116" , "cyclocytidine" , "cycloheximide" , "cyclophosphamide" , + "cyclosporin-a" , "cyclosporine" , "cyclovalone" , "cyclovirobuxin-d" , + "cyproheptadine" , "cyproterone-acetate" , "cyromazine" , "CYT-997" , + "cyt387" , "cytarabine" , "cytochalasin-b" , "cytochlor" , + "D-4476" , "D-64131" , "D-7193" , "D-Serine" , + "dabrafenib" , "dacarbazine" , "dacinostat" , "daclatasvir" , + "dacomitinib" , "dalcetrapib" , "danazol" , "danusertib" , + "dapivirine" , "darapladib" , "darifenacin" , "dasatinib" , + "daunorubicin" , "DCEBIO" , "decitabine" , "defactinib" , + "deferasirox" , "deflazacort" , "deforolimus" , "dehydrocholate-acid" , + "delanzomib" , "demecarium" , "deoxycorticosterone-acetate" , "dequalinium" , + "desonide" , "desoxycortone" , "dexamethasone-acetate" , "dexrazoxane" , + "dianhydrogalactitol" , "diaveridine" , "diazooxonorleucine" , "dichlorisone-acetate" , + "dichloroacetate" , "dichlorvos" , "diclazuril" , "dicycloverine" , + "dienogest" , "difluprednate" , "digitoxigenin" , "digitoxin" , + "digoxigenin" , "digoxin" , "dihydroartemisinin" , "dihydroergocristine" , + "dihydromyricetin" , "dimethisoquin" , "dinaciclib" , "dioscin" , + "diphemanil" , "diphenyleneiodonium" , "dirithromycin" , "disulfiram" , + "DMH1" , "docetaxel" , "dofetilide" , "dolastatin-10" , + "dolutegravir" , "domiphen" , "domperidone" , "dorzolamide" , + "dovitinib" , "doxercalciferol" , "doxifluridine" , "doxorubicin" , + "doxycycline" , "DPI-201106" , "dronedarone" , "drospirenone" , + "DU-728" , "DVD-111" , "E7449" , "ebastine" , + "ecamsule-triethanolamine" , "echinomycin" , "efonidipine-monoethanolate" , "elacridar" , + "elesclomol" , "eltrombopag" , "embelin" , "EMD-53998" , + "emetine" , "endo-IWR-1" , "ENMD-2076" , "enocitabine" , + "enoximone" , "entinostat" , "enzalutamide" , "epiandrosterone" , + "epinastine" , "epinephrine" , "epirubicin" , "eplerenone" , + "epothilone-a" , "epothilone-b" , "epothilone-d" , "eprinomectin" , + "eprobemide" , "eprosartan" , "eptifibatide" , "EPZ-5676" , + "equol" , "ER-27319" , "erastin" , "ercalcitriol" , + "erdafitinib" , "erlotinib" , "erteberel" , "erythritol" , + "estradiol" , "estradiol-benzoate" , "estradiol-cypionate" , "estramustine" , + "estramustine-phosphate" , "estrone" , "ethacridine-lactate-monohydrate" , "ethinyl-estradiol" , + "etofylline-clofibrate" , "etomoxir" , "etoposide" , "etoposide-phosphate" , + "ETP-46464" , "evacetrapib" , "everolimus" , "evodiamine" , + "EVP4593" , "exatecan-mesylate" , "exemestane" , "famciclovir" , + "famotidine" , "favipiravir" , "fdcyd" , "felbamate" , + "fenaclon" , "fenbendazole" , "fendiline" , "fenofibrate" , + "fenoprofen" , "fenretinide" , "FERb-033" , "fexinidazole" , + "FG-4592" , "filanesib" , "filgotinib" , "finafloxacin" , + "FK-3311" , "FK-866" , "FK-888" , "fleroxacin" , + "FLI-06" , "florfenicol" , "floxuridine" , "flubendazole" , + "fludarabine" , "fludarabine-phosphate" , "fludroxycortide" , "flufenamic-acid" , + "flumatinib" , "flumethasone" , "flumethasone-pivalate" , "fluocinolone-acetonide" , + "fluorometholone" , "fluoromethylcholine" , "fluroxene" , "flutamide" , + "fluticasone-propionate" , "fluvastatin" , "foretinib" , "formestane" , + "forodesine" , "forskolin" , "fosbretabulin" , "foscarnet" , + "FPH1-(BRD-6125)" , "FR-122047" , "FR-139317" , "frentizole" , + "ftorafur" , "fudosteine" , "fulvestrant" , "G-1" , + "galeterone" , "gambogic-acid" , "gamma-aminobutyric-acid" , "ganetespib" , + "gastrodin" , "GDC-0068" , "GDC-0152" , "GDC-0349" , + "GDC-0879" , "GDC-0941" , "GDC-0980" , "gefitinib" , + "gemcitabine" , "genipin" , "genz-644282" , "gestrinone" , + "GGTI-298" , "gidazepam" , "gilteritinib" , "gimeracil" , + "ginkgolide-a" , "givinostat" , "golgicide-a" , "golvatinib" , + "gossypol" , "GS-39783" , "GS-9973" , "GSK-3-inhibitor-IX" , + "GSK-J4" , "GSK1070916" , "GSK1292263" , "GSK1838705A" , + "GSK1904529A" , "GSK2110183" , "GSK2126458" , "GSK256066" , + "GSK2656157" , "GSK2830371" , "GSK429286A" , "GSK461364" , + "GSK650394" , "GSK923295" , "GTP-14564" , "guanidine" , + "GW-3965" , "GW-405833" , "GW-441756" , "GW-501516" , + "GW-583340" , "GW-788388" , "GW-842166" , "GW-843682X" , + "GZD824" , "HA14-1" , "halcinonide" , "halobetasol-propionate" , + "halofantrine" , "halofuginone" , "harringtonine" , "hesperadin" , + "hexachlorophene" , "hexaminolevulinate" , "hexylresorcinol" , "HMN-214" , + "homoharringtonine" , "homoquinolinic-acid" , "homosalate" , "hydrocortisone" , + "hydroxytacrine-maleate-(r,s)" , "hydroxyurea" , "hyodeoxycholic-acid" , "hyoscyamine" , + "hypericin" , "hypoestoxide" , "I-BET-762" , "I-BET151" , + "ibrutinib" , "ibutilide" , "ICG-001" , "ICI-162846" , + "icotinib" , "idarubicin" , "idasanutlin" , "idazoxan" , + "idelalisib" , "idoxuridine" , "IDRA-21" , "idronoxil" , + "IEM1754" , "ifosfamide" , "IKK-16" , "IKK-2-inhibitor-V" , + "ilomastat" , "imatinib" , "imidapril" , "imiloxan" , + "imiquimod" , "INC-280" , "indibulin" , "indiplon" , + "indirubin" , "indisulam" , "indoprofen" , "ingenol-mebutate" , + "INH1" , "inosine" , "iobenguane" , "iodipamide" , + "iododexetimide" , "IOWH032" , "iproniazid" , "ipsapirone" , + "irinotecan" , "isoetharine" , "isofloxythepin" , "isoflupredone-acetate" , + "isometheptene-mucate" , "isopropyl-myristate" , "isoxsuprine" , "ispinesib" , + "istradefylline" , "itraconazole" , "ivermectin" , "ixabepilone" , + "ixazomib" , "ixazomib-citrate" , "JIB04" , "JK-184" , + "JNJ-16259685" , "JNJ-26481585" , "JNJ-7706621" , "josamycin" , + "JQ1-(+)" , "JTC-801" , "JTE-607" , "JZL-184" , + "K-858" , "K-Ras(G12C)-inhibitor-6" , "k-strophanthidin" , "KD-023" , + "KD025" , "kenpaullone" , "ketoconazole" , "ketoprofen" , + "KF-38789" , "KI-16425" , "KI-8751" , "kifunensine" , + "KP-1212" , "KPT-185" , "KPT-276" , "ku-0063794" , + "KW-2449" , "KW-2478" , "KX2-391" , "KY02111" , + "kynurenic-acid" , "L-798,106" , "lacitol" , "lafutidine" , + "lanatoside-c" , "lanoconazole" , "lapatinib" , "lappaconite" , + "lasalocid" , "latanoprost" , "latrepirdine" , "LB42708" , + "LCL-161" , "LDN-212854" , "LDN-57444" , "LE-135" , + "lenalidomide" , "lenvatinib" , "lerisetron" , "lestaurtinib" , + "letrozole" , "leucovorin" , "levobunolol" , "levocarnitine" , + "levocetirizine" , "levonorgestrel" , "LGX818" , "licochalcone-a" , + "lidamidine" , "lidocaine" , "linalool" , "linifanib" , + "linsitinib" , "litronesib" , "lomefloxacin" , "lomitapide" , + "lonafarnib" , "lorazepam" , "lorlatinib" , "lovastatin" , + "loxistatin-acid" , "lucitanib" , "lurasidone" , "LY2090314" , + "LY2109761" , "LY2183240" , "LY2334737" , "LY2603618" , + "LY2606368" , "LY2608204" , "LY2784544" , "LY2801653" , + "LY2874455" , "LY3023414" , "LY303511" , "LY364947" , + "LY456236" , "M-344" , "maprotiline" , "marimastat" , + "masitinib" , "maxacalcitol" , "maytansinol-isobutyrate" , "mebendazole" , + "mechlorethamine" , "meclizine" , "mefexamide" , "meglitinide" , + "MEK1-2-inhibitor" , "MEK162" , "melengestrol-acetate" , "meloxicam" , + "melphalan" , "menadione" , "mephenytoin" , "mepivacaine" , + "mercaptopurine" , "mericitabine" , "merimepodib" , "mesna" , + "mesoridazine" , "metaraminol" , "metatinib" , "methacycline" , + "methiazole" , "methocarbamol" , "methotrexate" , "methoxyflurane" , + "methscopolamine" , "methyldopa" , "methylphenidate" , "methylprednisolone" , + "metoprolol" , "metoxibutropate" , "metronidazole" , "metyrapone" , + "mevastatin" , "mexeneone" , "mexiletine" , "MG-132" , + "MGCD-265" , "mibampator" , "mibefradil" , "midodrine" , + "midostaurin" , "mifepristone" , "minocycline" , "mitomycin-c" , + "mitoxantrone" , "MK-0773" , "MK-0812" , "MK-1775" , + "MK-2206" , "MK-2461" , "MK-3207" , "MK-5108" , + "MK-8245" , "MK-8745" , "ML133" , "MLN-8054" , + "MLN0128" , "MNS-(3,4-Methylenedioxy-nitrostyrene)" , "mocetinostat" , "monensin" , + "monobenzone" , "morin" , "motesanib" , "mozavaptan" , + "MPI-0479605" , "MRS-1220" , "MTPG" , "mubritinib" , + "mycophenolate-mofetil" , "mycophenolic-acid" , "N-acetylmannosamine" , "nadide" , + "nadifloxacin" , "nafcillin" , "naftidrofuryl" , "naftifine" , + "naloxone" , "naltrexone" , "NAN-190" , "nanchangmycin" , + "napabucasin" , "naproxen" , "narasin" , "narlaprevir" , + "navarixin" , "navitoclax" , "nefiracetam" , "nelarabine" , + "nemonapride" , "nemorubicin" , "neratinib" , "nexturastat-a" , + "NH125" , "niacin" , "niclosamide" , "nicorandil" , + "nicotine" , "nilotinib" , "nilutamide" , "nimorazole" , + "nintedanib" , "niraparib" , "niridazole" , "nisoxetine" , + "nitarsone" , "nithiamide" , "nitisinone" , "nitrocaramiphen" , + "nizatidine" , "nizofenone" , "NMS-1286937" , "NMS-873" , + "NMS-E973" , "nobiletin" , "nocodazole" , "nomegestrol-acetate" , + "nonoxynol-9" , "norepinephrine" , "norethindrone" , "norethindrone-acetate" , + "noretynodrel" , "norfloxacin" , "norgestrel" , "novobiocin" , + "NSC-23766" , "NSC-319726" , "NSC-3852" , "NSC-632839" , + "NSC-663284" , "NSC-697923" , "NU6027" , "nutlin-3" , + "NVP-AEW541" , "NVP-AUY922" , "NVP-BEZ235" , "NVP-BHG712" , + "NVP-BVU972" , "NVP-TAE226" , "NVP-TAE684" , "obatoclax" , + "obidoxime" , "octenidine" , "octopamine" , "odanacatib" , + "olaparib" , "OLDA" , "oleanolic-acid" , "oleoylethanolamide" , + "oligomycin-a" , "oltipraz" , "omeprazole" , "ONC201" , + "oncrasin-1" , "ONX-0914" , "oprozomib" , "orantinib" , + "oridonin" , "ornithine" , "orotic-acid" , "oseltamivir-phosphate" , + "OSI-027" , "OSI-420" , "OSI-930" , "osimertinib" , + "OTS167" , "OTX015" , "ouabain" , "oxaliplatin" , + "oxazepam" , "oxcarbazepine" , "oxibendazole" , "oxiperomide" , + "oxiracetam" , "oxonic-acid" , "oxprenolol" , "oxymatrine" , + "oxymetazoline" , "oxyphencyclimine" , "oxyquinoline" , "P22077" , + "P276-00" , "P5091" , "PAC-1" , "paclitaxel" , + "pacritinib" , "palbociclib" , "paliperidone" , "palmatine-chloride" , + "palmitoylethanolamide" , "palomid-529" , "panobinostat" , "papaverine" , + "parachlorophenol" , "parbendazole" , "pardoprunox" , "paricalcitol" , + "parthenolide" , "parthenolide-(-)" , "pazopanib" , "PCI-24781" , + "PD-0325901" , "PD-153035" , "PD-168393" , "PD-173074" , + "PD-184352" , "PD-198306" , "PD-318088" , "PD-407824" , + "PD-98059" , "pelitinib" , "penfluridol" , "penicillamine-(D)" , + "pentagastrin" , "pentamidine" , "pentostatin" , "pepstatin" , + "peruvoside" , "PETCM" , "pevonedistat" , "PF-03758309" , + "PF-03814735" , "PF-04136309" , "PF-04217903" , "PF-04457845" , + "PF-04691502" , "PF-05212384" , "PF-3845" , "PF-477736" , + "PF-4981517" , "PF-562271" , "PF-573228" , "PFI-1" , + "PFK-015" , "PHA-665752" , "PHA-680632" , "PHA-767491" , + "PHA-793887" , "PHA-848125" , "phenazone" , "phenelzine" , + "pheniramine" , "phenylbutazone" , "phenylmercuric-acetate" , "phlorizin" , + "PI-103" , "PI-828" , "PI3K-IN-2" , "pibenzimol" , + "picolinic-acid" , "PIK-75" , "pilaralisib" , "pilocarpine" , + "pindolol" , "piperacetazine" , "piperazine" , "piperine" , + "pirenperone" , "piretanide" , "piroxicam" , "pitavastatin" , + "PJ-34" , "PKI-179" , "plinabulin" , "PLX-4720" , + "podophyllotoxin" , "polydatin" , "pomalidomide" , "ponatinib" , + "posaconazole" , "poziotinib" , "PP-1" , "PP-121" , + "PP-2" , "PP242" , "PPT" , "PQ-401" , + "PR-619" , "practolol" , "pralatrexate" , "pranidipine" , + "prazosin" , "prednisolone" , "prednisolone-acetate" , "prednisolone-hemisuccinate" , + "prednisolone-tebutate" , "primaquine" , "proflavine-hemisulfate" , "propoxycaine" , + "propranolol" , "proscillaridin-a" , "protirelin" , "PRT062070" , + "PRT062607" , "PSB-1115" , "PSI-7976" , "PTC-209" , + "pterostilbene" , "PU-H71" , "puromycin" , "pyrimethamine" , + "pyrithione-zinc" , "pyritinol" , "pyroxamide" , "quinethazone" , + "quinidine" , "quizartinib" , "R306465" , "R406" , + "R547" , "rabeprazole" , "racecadotril" , "raclopride" , + "radezolid" , "RAF265" , "raloxifene" , "raltitrexed" , + "ramatroban" , "ramifenazone" , "ranitidine" , "refametinib" , + "regorafenib" , "remoxipride" , "repaglinide" , "repsox" , + "resatorvid" , "resiquimod" , "resminostat" , "RG108" , + "RG2833" , "RGFP966" , "rheochrysidin" , "RI-1" , + "ribavirin" , "ribitol" , "ribociclib" , "riboflavin" , + "rifampin" , "rigosertib" , "riluzole" , "rimexolone" , + "riociguat" , "RITA" , "ritodrine" , "RKI-1447" , + "RN-1734" , "Ro-04-5595" , "Ro-10-5824" , "Ro-106-9920" , + "Ro-4987655" , "Ro-90-7501" , "Ro-9187" , "rociletinib" , + "romidepsin" , "roquinimex" , "RS-16566" , "RS-17053" , + "RS-504393" , "RS-67506" , "RU-58841" , "rubitecan" , + "rucinol" , "rutin" , "ruxolitinib" , "ryuvidine" , + "S-methylcysteine" , "S26948" , "salidroside" , "salinomycin" , + "salvianolic-acid-B" , "salvinorin-a" , "sangivamycin" , "SAR131675" , + "saracatinib" , "sarafloxacin" , "satraplatin" , "saxagliptin" , + "SB-200646" , "SB-205384" , "SB-216641" , "SB-218078" , + "SB-218795" , "SB-225002" , "SB-228357" , "SB-2343" , + "SB-239063" , "SB-242235" , "SB-366791" , "SB-431542" , + "SB-505124" , "SB-525334" , "SB-590885" , "SB-657510" , + "SB-743921" , "SB-939" , "SC-12267" , "SC-144" , + "SCH-58261" , "SCH-900776" , "sclareol" , "scriptaid" , + "SCS" , "SDZ-WAG-994" , "se-methylselenocysteine" , "secnidazole" , + "securinine" , "selamectin" , "selinexor" , "selumetinib" , + "semaxanib" , "serdemetan" , "sertindole" , "sevelamer" , + "sevoflurane" , "SGI-1027" , "SGI-1776" , "SIB-1757" , + "SID-7969543" , "simvastatin" , "sirolimus" , "skepinone-l" , + "SKF-96365" , "SKI-II" , "SMI-4a" , "SN-38" , + "SNS-314" , "SNX-2112" , "SNX-5422" , "sobetirome" , + "sodium-glucoheptonate" , "sodium-stibogluconate" , "sodium-tanshinone-ii-a-sulfonate" , "sonidegib" , + "sorafenib" , "sparfloxacin" , "spermidine" , "spermine" , + "spiradoline" , "spironolactone" , "SR-27897" , "SR-33805" , + "SR-57227A" , "SRT1720" , "STA-5326" , "stattic" , + "stemregenin-1" , "STF-118804" , "streptozotocin" , "SU014813" , + "SU3327" , "sufentanil" , "sulconazole" , "sulfabenzamide" , + "sulfamethazine" , "sulfanilamide" , "sulfasalazine" , "sulmazole" , + "sunitinib" , "suxibuzone" , "tacalcitol" , "tacedinaline" , + "tacrolimus" , "tagatose" , "TAK-285" , "TAK-632" , + "TAK-715" , "TAK-733" , "TAK-901" , "talazoparib" , + "talmapimod" , "taltirelin" , "taltobulin" , "TAME" , + "tamibarotene" , "tamoxifen" , "tanaproget" , "tandutinib" , + "tanespimycin" , "tanshinone-i" , "TAS-103" , "taselisib" , + "tasisulam" , "taurine" , "tazemetostat" , "TC1" , + "tecastemizole" , "tedizolid" , "tedizolid-phosphate" , "telatinib" , + "telotristat-ethyl" , "temazepam" , "temocapril" , "temoporfin" , + "temozolomide" , "temsirolimus" , "teniposide" , "tenovin-6" , + "tepoxalin" , "teprenone" , "terbutaline" , "terconazole" , + "terfenadine" , "teriflunomide" , "teroxirone" , "tetrahydropapaverine" , + "tetrahydrouridine" , "tetramethylthiuram-monosulfide" , "tetrandrine" , "tezacaftor" , + "TG-02" , "TG-100572" , "TG-100713" , "TG-101209" , + "TG-101348" , "TG100-115" , "TH-302" , "theophylline" , + "thiamine" , "thiocolchicoside" , "thioguanine" , "thiomersal" , + "thioproperazine" , "thiostrepton" , "thiram" , "thonzonium" , + "tiagabine" , "tideglusib" , "tiletamine" , "tilmicosin" , + "tiludronate" , "tioguanine" , "tiotidine" , "tioxolone" , + "tipifarnib" , "tipiracil" , "tipranavir" , "tirapazamine" , + "tivantinib" , "tivozanib" , "TMC-353121" , "TMS" , + "tofogliflozin" , "topotecan" , "torasemide" , "torcetrapib" , + "toremifene" , "torin-1" , "torin-2" , "tosedostat" , + "tozasertib" , "TPCA-1" , "trametinib" , "tranilast" , + "trans-4-Hydroxycrotonic-acid" , "trapidil" , "tremorine" , "trequinsin" , + "triamcinolone" , "triamcinolone-acetonide" , "triamterene" , "triapine" , + "trichostatin-a" , "triciribine" , "triclabendazole" , "trifluridine" , + "trimebutine" , "triptolide" , "trolox" , "trometamol" , + "tropisetron" , "trovafloxacin" , "tryptanthrin" , "TU-2100" , + "tucatinib" , "TW-37" , "TWS-119" , "tyloxapol" , + "tyrphostin-A9" , "tyrphostin-AG-1296" , "tyrphostin-AG-1478" , "tyrphostin-AG-494" , + "tyrphostin-AG-99" , "U-0126" , "U-18666A" , "ubenimex" , + "UH-232-(+)" , "UK-383367" , "ulipristal" , "UNBS-5162" , + "UNC0631" , "UNC2250" , "uprosertib" , "uracil" , + "uric-acid" , "uridine" , "usniacin-(+)" , "valnemulin" , + "valrubicin" , "vandetanib" , "vanoxerine" , "vatalanib" , + "VE-821" , "VE-822" , "vemurafenib" , "venetoclax" , + "VER-49009" , "verubulin" , "vidarabine" , "vinblastine" , + "vincamine" , "vincristine" , "vindesine" , "vinflunine" , + "vinorelbine" , "vismodegib" , "VLX600" , "volasertib" , + "voreloxin" , "vorinostat" , "voxtalisib" , "VS-4718" , + "VTP-27999" , "VU0238429" , "VU0361737" , "VU0364770" , + "VX-702" , "VX-765" , "warfarin" , "WAY-170523" , + "WAY-600" , "WHI-P154" , "WP1066" , "WP1130" , + "WYE-125132" , "WYE-354" , "WZ-3146" , "WZ-4002" , + "WZ8040" , "xanomeline" , "XBD173" , "xilobam" , + "XL-647" , "XL388" , "XL888" , "xylazine" , + "Y-27632" , "Y-320" , "Y-39983" , "YM-155" , + "YM-201636" , "YM-976" , "YO-01027" , "zaldaride" , + "zaleplon" , "zardaverine" , "ziprasidone" , "ZK-93423" , + "ZK-93426" , "ZK811752" , "ZLN005" , "ZM-306416" , + "ZM-447439" , "zolantidine" , "zolmitriptan" , "ZSTK-474" ) -# 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. +#' 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. +#' @export +# fmt:table perception_fda_approved_drugs <- c( - "5-fluorouracil", - "abemaciclib", - "abiraterone", - "abiraterone-acetate", - "afatinib", - "alectinib", - "altretamine", - "aminoglutethimide", - "amsacrine", - "anagrelide", - "anastrozole", - "axitinib", - "azacitidine", - "belinostat", - "bendamustine", - "bexarotene", - "bicalutamide", - "bortezomib", - "bosutinib", - "brigatinib", - "busulfan", - "cabazitaxel", - "cabozantinib", - "capecitabine", - "carboplatin", - "carfilzomib", - "carmofur", - "carmustine", - "chlorambucil", - "cimetidine", - "cinacalcet", - "cisplatin", - "cladribine", - "clofarabine", - "cobimetinib", - "crizotinib", - "cyclophosphamide", - "cyproterone-acetate", - "cytarabine", - "dabrafenib", - "dacarbazine", - "dasatinib", - "daunorubicin", - "decitabine", - "docetaxel", - "doxifluridine", - "doxorubicin", - "enzalutamide", - "epirubicin", - "erlotinib", - "estramustine", - "estramustine-phosphate", - "etoposide", - "etoposide-phosphate", - "everolimus", - "exemestane", - "floxuridine", - "fludarabine", - "fludarabine-phosphate", - "flutamide", - "formestane", - "ftorafur", - "fulvestrant", - "gefitinib", - "gemcitabine", - "gimeracil", - "homoharringtonine", - "hydroxyurea", - "ibrutinib", - "icotinib", - "idarubicin", - "idelalisib", - "ifosfamide", - "imatinib", - "imiquimod", - "iobenguane", - "irinotecan", - "ixabepilone", - "ixazomib", - "ixazomib-citrate", - "lapatinib", - "lenalidomide", - "lenvatinib", - "letrozole", - "leucovorin", - "mechlorethamine", - "melphalan", - "mercaptopurine", - "methotrexate", - "midostaurin", - "mitomycin-c", - "mitoxantrone", - "nelarabine", - "nilotinib", - "nilutamide", - "nimorazole", - "niraparib", - "olaparib", - "osimertinib", - "oxaliplatin", - "paclitaxel", - "palbociclib", - "panobinostat", - "pazopanib", - "pentostatin", - "pomalidomide", - "ponatinib", - "pralatrexate", - "raloxifene", - "raltitrexed", - "regorafenib", - "ribociclib", - "romidepsin", - "ruxolitinib", - "sn-38", - "sonidegib", - "sorafenib", - "streptozotocin", - "sunitinib", - "tamibarotene", - "tamoxifen", - "temoporfin", - "temozolomide", - "temsirolimus", - "teniposide", - "thioguanine", - "tipiracil", - "topotecan", - "toremifene", - "trametinib", - "ubenimex", - "valrubicin", - "vandetanib", - "vemurafenib", - "venetoclax", - "vinblastine", - "vincristine", - "vindesine", - "vinflunine", - "vinorelbine", - "vismodegib", - "vorinostat" + "5-fluorouracil" , "abemaciclib" , "abiraterone" , "abiraterone-acetate" , + "afatinib" , "alectinib" , "altretamine" , "aminoglutethimide" , + "amsacrine" , "anagrelide" , "anastrozole" , "axitinib" , + "azacitidine" , "belinostat" , "bendamustine" , "bexarotene" , + "bicalutamide" , "bortezomib" , "bosutinib" , "brigatinib" , + "busulfan" , "cabazitaxel" , "cabozantinib" , "capecitabine" , + "carboplatin" , "carfilzomib" , "carmofur" , "carmustine" , + "chlorambucil" , "cimetidine" , "cinacalcet" , "cisplatin" , + "cladribine" , "clofarabine" , "cobimetinib" , "crizotinib" , + "cyclophosphamide" , "cyproterone-acetate" , "cytarabine" , "dabrafenib" , + "dacarbazine" , "dasatinib" , "daunorubicin" , "decitabine" , + "docetaxel" , "doxifluridine" , "doxorubicin" , "enzalutamide" , + "epirubicin" , "erlotinib" , "estramustine" , "estramustine-phosphate" , + "etoposide" , "etoposide-phosphate" , "everolimus" , "exemestane" , + "floxuridine" , "fludarabine" , "fludarabine-phosphate" , "flutamide" , + "formestane" , "ftorafur" , "fulvestrant" , "gefitinib" , + "gemcitabine" , "gimeracil" , "homoharringtonine" , "hydroxyurea" , + "ibrutinib" , "icotinib" , "idarubicin" , "idelalisib" , + "ifosfamide" , "imatinib" , "imiquimod" , "iobenguane" , + "irinotecan" , "ixabepilone" , "ixazomib" , "ixazomib-citrate" , + "lapatinib" , "lenalidomide" , "lenvatinib" , "letrozole" , + "leucovorin" , "mechlorethamine" , "melphalan" , "mercaptopurine" , + "methotrexate" , "midostaurin" , "mitomycin-c" , "mitoxantrone" , + "nelarabine" , "nilotinib" , "nilutamide" , "nimorazole" , + "niraparib" , "olaparib" , "osimertinib" , "oxaliplatin" , + "paclitaxel" , "palbociclib" , "panobinostat" , "pazopanib" , + "pentostatin" , "pomalidomide" , "ponatinib" , "pralatrexate" , + "raloxifene" , "raltitrexed" , "regorafenib" , "ribociclib" , + "romidepsin" , "ruxolitinib" , "sn-38" , "sonidegib" , + "sorafenib" , "streptozotocin" , "sunitinib" , "tamibarotene" , + "tamoxifen" , "temoporfin" , "temozolomide" , "temsirolimus" , + "teniposide" , "thioguanine" , "tipiracil" , "topotecan" , + "toremifene" , "trametinib" , "ubenimex" , "valrubicin" , + "vandetanib" , "vemurafenib" , "venetoclax" , "vinblastine" , + "vincristine" , "vindesine" , "vinflunine" , "vinorelbine" , + "vismodegib" , "vorinostat" ) diff --git a/R/evaluate.R b/R/evaluate.R index 5376e33..5a2dfff 100644 --- a/R/evaluate.R +++ b/R/evaluate.R @@ -16,19 +16,31 @@ NULL # * positional c(pvalue, correlation) (fallback) # Returns c(pvalue = NA, correlation = NA) when nothing usable is found. perf_to_vector <- function(perf) { - if (is.null(perf)) return(c(pvalue = NA, correlation = NA)) + if (is.null(perf)) { + return(c(pvalue = NA, correlation = NA)) + } if (is.data.frame(perf)) { - cor <- if ("estimate.cor" %in% names(perf)) perf$estimate.cor[1] else - if ("correlation" %in% names(perf)) perf$correlation[1] else NA - p <- if ("p.value" %in% names(perf)) perf$p.value[1] else NA + cor <- if ("estimate.cor" %in% names(perf)) { + perf$estimate.cor[1] + } else if ("correlation" %in% names(perf)) { + perf$correlation[1] + } else { + NA + } + p <- if ("p.value" %in% names(perf)) perf$p.value[1] else NA return(c(pvalue = unname(p), correlation = unname(cor))) } if (is.numeric(perf) && !is.null(names(perf))) { - cor <- if ("estimate.cor" %in% names(perf)) perf["estimate.cor"] else - if ("correlation" %in% names(perf)) perf["correlation"] else NA - p <- if ("p.value" %in% names(perf)) perf["p.value"] else NA + cor <- if ("estimate.cor" %in% names(perf)) { + perf["estimate.cor"] + } else if ("correlation" %in% names(perf)) { + perf["correlation"] + } else { + NA + } + p <- if ("p.value" %in% names(perf)) perf["p.value"] else NA return(c(pvalue = unname(p), correlation = unname(cor))) } @@ -66,35 +78,54 @@ perf_to_vector <- function(perf) { #' #' @export compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { - # Validate input if (!is.list(model_list) || length(model_list) == 0) { - stop("model_list must be a non-empty list of trained models.") + cli::cli_abort("model_list must be a non-empty list of trained models.") } # Extract performance metrics from each model # R package uses named elements, not positional indices like original code - perf_cv <- do.call(rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) return(c(pvalue = NA, correlation = NA)) - # CV stores sqrt(R²) = |correlation| only (no p-value available). - c(pvalue = NA, correlation = as.numeric(x$model_performance_during_cv)[1]) - })) + perf_cv <- do.call( + rbind, + lapply(model_list, function(x) { + if (is.null(x) || (length(x) == 1 && is.na(x))) { + return(c(pvalue = NA, correlation = NA)) + } + # CV stores sqrt(R²) = |correlation| only (no p-value available). + c(pvalue = NA, correlation = as.numeric(x$model_performance_during_cv)[1]) + }) + ) - perf_bulk <- do.call(rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) return(c(pvalue = NA, correlation = NA)) - perf_to_vector(x$performance_in_bulk) - })) + perf_bulk <- do.call( + rbind, + lapply(model_list, function(x) { + if (is.null(x) || (length(x) == 1 && is.na(x))) { + return(c(pvalue = NA, correlation = NA)) + } + perf_to_vector(x$performance_in_bulk) + }) + ) - perf_pseudo_bulk <- do.call(rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) return(c(pvalue = NA, correlation = NA)) - perf_to_vector(x$performance_in_pseudo_bulk) - })) + perf_pseudo_bulk <- do.call( + rbind, + lapply(model_list, function(x) { + if (is.null(x) || (length(x) == 1 && is.na(x))) { + return(c(pvalue = NA, correlation = NA)) + } + perf_to_vector(x$performance_in_pseudo_bulk) + }) + ) - perf_scRNA <- do.call(rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) return(c(pvalue = NA, correlation = NA)) - perf_to_vector(x$performance_in_scRNA) - })) + perf_scRNA <- do.call( + rbind, + lapply(model_list, function(x) { + if (is.null(x) || (length(x) == 1 && is.na(x))) { + return(c(pvalue = NA, correlation = NA)) + } + perf_to_vector(x$performance_in_scRNA) + }) + ) # Set column names and row names colnames(perf_cv) <- c("pvalue", "correlation") @@ -122,28 +153,35 @@ compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { mean_corrs <- sapply(performance_results, function(x) { mean(x[, "correlation"], na.rm = TRUE) }) - passing_drugs <- names(model_list)[which(perf_scRNA[, "correlation"] > threshold)] + passing_drugs <- names(model_list)[which( + perf_scRNA[, "correlation"] > threshold + )] # Print summary statistics if verbose if (verbose) { - message("\n=== Model Performance Summary ===") - message("Threshold: correlation >", threshold) - - message("\nModels passing threshold:") - message(" CV (|cor|): ", passing_counts["perf_cv"], " / ", length(model_list)) - message(" Bulk test: ", passing_counts["perf_bulk"], " / ", length(model_list)) - message(" Pseudo-bulk: ", passing_counts["perf_pseudo_bulk"], " / ", length(model_list)) - message(" scRNA: ", passing_counts["perf_scRNA"], " / ", length(model_list)) + cli::cli_alert_info( + "Model performance summary (threshold: correlation > {threshold})" + ) - message("\nMean correlations:") - message(" CV (|cor|): ", round(mean_corrs["perf_cv"], 3)) - message(" Bulk test: ", round(mean_corrs["perf_bulk"], 3)) - message(" Pseudo-bulk: ", round(mean_corrs["perf_pseudo_bulk"], 3)) - message(" scRNA: ", round(mean_corrs["perf_scRNA"], 3)) + cli::cli_alert_info("Models passing threshold:") + cli::cli_ul(c( + "CV (|cor|): {passing_counts['perf_cv']} / {length(model_list)}", + "Bulk test: {passing_counts['perf_bulk']} / {length(model_list)}", + "Pseudo-bulk: {passing_counts['perf_pseudo_bulk']} / {length(model_list)}", + "scRNA: {passing_counts['perf_scRNA']} / {length(model_list)}" + )) + + cli::cli_alert_info("Mean correlations:") + cli::cli_ul(c( + "CV (|cor|): {round(mean_corrs['perf_cv'], 3)}", + "Bulk test: {round(mean_corrs['perf_bulk'], 3)}", + "Pseudo-bulk: {round(mean_corrs['perf_pseudo_bulk'], 3)}", + "scRNA: {round(mean_corrs['perf_scRNA'], 3)}" + )) if (length(passing_drugs) > 0) { - message("\nDrugs passing threshold in scRNA:") - message(" ", paste(passing_drugs, collapse = ", ")) + cli::cli_alert_info("Drugs passing threshold in scRNA:") + cli::cli_ul(passing_drugs) } } @@ -185,10 +223,9 @@ compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { #' #' @export get_performance <- function(filepath, drug_names = NULL) { - # Validate filepath if (!file.exists(filepath)) { - stop("File not found: ", filepath) + cli::cli_abort("File not found: {.path {filepath}}") } # Load the model file @@ -196,14 +233,16 @@ get_performance <- function(filepath, drug_names = NULL) { # Check if it's a list of models if (!is.list(model_data)) { - stop("Loaded data is not a list of models.") + cli::cli_abort("Loaded data is not a list of models.") } # Filter by drug names if specified if (!is.null(drug_names)) { available_drugs <- intersect(drug_names, names(model_data)) if (length(available_drugs) == 0) { - stop("None of the specified drug_names found in the model file.") + cli::cli_abort( + "None of the specified {.arg drug_names} found in the model file." + ) } model_data <- model_data[available_drugs] } @@ -250,41 +289,53 @@ get_performance <- function(filepath, drug_names = NULL) { #' } #' #' @export -get_significant_models <- function(model_list, - min_correlation = 0.3, - max_pvalue = 0.05, - dataset = "scRNA") { - +get_significant_models <- function( + model_list, + min_correlation = 0.3, + max_pvalue = 0.05, + dataset = "scRNA" +) { # Validate dataset parameter valid_datasets <- c("scRNA", "bulk", "pseudo_bulk", "cv") if (!dataset %in% valid_datasets) { - stop("dataset must be one of: ", paste(valid_datasets, collapse = ", ")) + cli::cli_abort("{.arg dataset} must be one of: {.val {valid_datasets}}") } # Get the appropriate performance element name - perf_element <- switch(dataset, - "scRNA" = "performance_in_scRNA", - "bulk" = "performance_in_bulk", - "pseudo_bulk" = "performance_in_pseudo_bulk", - "cv" = "model_performance_during_cv") + perf_element <- switch( + dataset, + "scRNA" = "performance_in_scRNA", + "bulk" = "performance_in_bulk", + "pseudo_bulk" = "performance_in_pseudo_bulk", + "cv" = "model_performance_during_cv" + ) # Filter models. "cv" stores sqrt(R²)=|correlation| with no p-value; the other # datasets carry a named vector or data.frame with (p-value, correlation). - significant_models <- model_list[vapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) return(FALSE) - - if (dataset == "cv") { - cv <- x$model_performance_during_cv - return(is.numeric(cv) && length(cv) >= 1 && isTRUE(cv[1] > min_correlation)) - } - - perf <- perf_to_vector(x[[perf_element]]) - isTRUE(perf[["correlation"]] > min_correlation) && - isTRUE(perf[["pvalue"]] < max_pvalue) - }, logical(1))] - - message("Found ", length(significant_models), " models meeting criteria (cor > ", - min_correlation, ", p < ", max_pvalue, " in ", dataset, ")") + significant_models <- model_list[vapply( + model_list, + function(x) { + if (is.null(x) || (length(x) == 1 && is.na(x))) { + return(FALSE) + } + + if (dataset == "cv") { + cv <- x$model_performance_during_cv + return( + is.numeric(cv) && length(cv) >= 1 && isTRUE(cv[1] > min_correlation) + ) + } + + perf <- perf_to_vector(x[[perf_element]]) + isTRUE(perf[["correlation"]] > min_correlation) && + isTRUE(perf[["pvalue"]] < max_pvalue) + }, + logical(1) + )] + + cli::cli_alert_info( + "Found {length(significant_models)} models meeting criteria (cor > {min_correlation}, p < {max_pvalue} in {dataset})." + ) return(significant_models) } @@ -305,11 +356,12 @@ get_significant_models <- function(model_list, #' @return Named numeric vector of pseudo-bulk expression values. #' #' @export -each_patient_pseudo_bulk <- function(x = 1, - comb_viability_df, - Clone_Counts_per_patients, - clone_Level_z_expression_df) { - +each_patient_pseudo_bulk <- function( + x = 1, + comb_viability_df, + Clone_Counts_per_patients, + clone_Level_z_expression_df +) { patient <- Clone_Counts_per_patients$patients[x] # Expression columns are named "Patient@@Clone". Select this patient's clones @@ -320,12 +372,17 @@ each_patient_pseudo_bulk <- function(x = 1, cols <- which(parsed$patient == patient) col_clone_ids <- parsed$clone_id[cols] - total_cells <- sum(unlist(Clone_Counts_per_patients[x, col_clone_ids]), na.rm = TRUE) + total_cells <- sum( + unlist(Clone_Counts_per_patients[x, col_clone_ids]), + na.rm = TRUE + ) if (!is.finite(total_cells) || total_cells == 0 || length(cols) == 0) { # No cells / no clones for this patient: return all-NA pseudo-bulk. return(rep(NA_real_, nrow(clone_Level_z_expression_df))) } - clone_weights <- unlist(Clone_Counts_per_patients[x, col_clone_ids] / total_cells) + clone_weights <- unlist( + Clone_Counts_per_patients[x, col_clone_ids] / total_cells + ) sub <- clone_Level_z_expression_df[, cols, drop = FALSE] @@ -335,4 +392,4 @@ each_patient_pseudo_bulk <- function(x = 1, pseudo_bulk <- sub[, 1] } pseudo_bulk -} \ No newline at end of file +} diff --git a/R/load.R b/R/load.R index 13987bb..b32903c 100644 --- a/R/load.R +++ b/R/load.R @@ -37,7 +37,9 @@ get_depmap <- function() { if (exists("DepMap", envir = .GlobalEnv)) { return(get("DepMap", envir = .GlobalEnv)) } - stop("DepMap data not loaded. Run load_depmap(read = TRUE) first.") + cli::cli_abort( + "DepMap data not loaded. Run load_depmap(read = TRUE) first." + ) } # DepMap is accessed via get_depmap() - declare to suppress R CMD check note @@ -59,11 +61,15 @@ utils::globalVariables("DepMap") #' @return TRUE if successful, FALSE otherwise #' @keywords internal #' @noRd -download_with_mirrors <- function(urls, destfile, quiet = FALSE, - speed_threshold = 10, - timeout_seconds = 30, - retries = 0, - expected_size = NULL) { +download_with_mirrors <- function( + urls, + destfile, + quiet = FALSE, + speed_threshold = 10, + timeout_seconds = 30, + retries = 0, + expected_size = NULL +) { # Save and restore R timeout setting old_timeout <- getOption("timeout") on.exit(options(timeout = old_timeout), add = TRUE) @@ -96,36 +102,61 @@ download_with_mirrors <- function(urls, destfile, quiet = FALSE, extra_base <- "-L --fail --ssl-no-revoke" for (i in seq_along(urls)) { - if (!quiet) message("Trying mirror ", i, "/", length(urls)) + if (!quiet) { + cli::cli_alert_info("Trying mirror {i}/{length(urls)}") + } for (attempt in 0:retries) { - if (attempt > 0 && !quiet) message(" Retry attempt ", attempt) + if (attempt > 0 && !quiet) { + cli::cli_alert_info("Retry attempt {attempt}") + } start_time <- Sys.time() success <- FALSE timeout_occurred <- FALSE incomplete <- FALSE - tryCatch({ - suppressWarnings({ - curl_extra <- if (attempt > 0) paste(extra_base, "-C -") else extra_base - download.file(urls[i], destfile, mode = "wb", quiet = quiet, - method = download_method, extra = curl_extra) - }) - success <- TRUE - }, error = function(e) { - if (grepl("Timeout|timed out|reached elapsed time", e$message, ignore.case = TRUE)) { - timeout_occurred <<- TRUE - if (!quiet && attempt == retries) { - message(" Mirror ", i, " timed out after ", timeout_seconds, " seconds") - } - } else { - if (!quiet && attempt == retries) { - message(" Mirror ", i, " failed: ", e$message) + tryCatch( + { + suppressWarnings({ + curl_extra <- if (attempt > 0) { + paste(extra_base, "-C -") + } else { + extra_base + } + download.file( + urls[i], + destfile, + mode = "wb", + quiet = quiet, + method = download_method, + extra = curl_extra + ) + }) + success <- TRUE + }, + error = function(e) { + if ( + grepl( + "Timeout|timed out|reached elapsed time", + e$message, + ignore.case = TRUE + ) + ) { + timeout_occurred <<- TRUE + if (!quiet && attempt == retries) { + cli::cli_alert_warning( + "Mirror {i} timed out after {timeout_seconds} seconds." + ) + } + } else { + if (!quiet && attempt == retries) { + cli::cli_alert_warning("Mirror {i} failed: {e$message}") + } } + if (file.exists(destfile)) file.remove(destfile) } - if (file.exists(destfile)) file.remove(destfile) - }) + ) # A "successful" transfer can still be truncated by a flaky connection # or a misbehaving proxy: verify the size against the known release @@ -135,9 +166,11 @@ download_with_mirrors <- function(urls, destfile, quiet = FALSE, sz <- file.size(destfile) if (!is.null(expected_size) && is.finite(sz) && sz < expected_size) { incomplete <- TRUE - if (!quiet) message(sprintf( - " Incomplete download: %d of %d bytes (%.1f%%), discarding and retrying", - sz, expected_size, 100 * sz / expected_size)) + if (!quiet) { + cli::cli_alert_warning( + "Incomplete download: {sz} of {expected_size} bytes ({round(100 * sz / expected_size, 1)}%), discarding and retrying." + ) + } file.remove(destfile) success <- FALSE } @@ -150,18 +183,22 @@ download_with_mirrors <- function(urls, destfile, quiet = FALSE, speed_kb_s <- (file.size(destfile) / 1024) / elapsed if (!quiet) { - message(sprintf("Downloaded %.2f MB in %.1f sec (%.0f KB/s)", - file_size_mb, elapsed, speed_kb_s)) + cli::cli_alert_success( + "Downloaded {round(file_size_mb, 2)} MB in {round(elapsed, 1)} sec ({round(speed_kb_s)} KB/s)." + ) } if (is.finite(speed_kb_s) && speed_kb_s < speed_threshold) { - message(sprintf(" Warning: mirror %d is slow (%.0f KB/s < %.0f KB/s threshold). Consider a different mirror.", - i, speed_kb_s, speed_threshold)) + cli::cli_alert_warning( + "Mirror {i} is slow ({round(speed_kb_s)} KB/s < {round(speed_threshold)} KB/s threshold). Consider a different mirror." + ) } return(TRUE) } if ((timeout_occurred || incomplete) && attempt < retries) { - if (!quiet) message(" Retrying mirror ", i, "...") + if (!quiet) { + cli::cli_alert_info("Retrying mirror {i}...") + } next } } @@ -170,7 +207,6 @@ download_with_mirrors <- function(urls, destfile, quiet = FALSE, } - #' Get current download mirrors #' #' Returns the current mirror list, including any user-added mirrors. @@ -205,7 +241,6 @@ get_default_perception_mirrors <- function() { } - #' Add custom download mirrors #' #' @param urls Character vector of mirror URLs to add. @@ -221,13 +256,16 @@ get_default_perception_mirrors <- function() { #' "https://mirror2.com/https://github.com")) #' } add_mirrors <- function(urls, position = c("first", "last")) { - position <- match.arg(position) + position <- rlang::arg_match(position) if (!all(grepl("^https?://", urls))) { - stop("All URLs must start with http:// or https://") + cli::cli_abort("All URLs must start with {.url http://} or {.url https://}") } - current_mirrors <- getOption("PERCEPTIONx.download_mirrors", get_default_perception_mirrors()) + current_mirrors <- getOption( + "PERCEPTIONx.download_mirrors", + get_default_perception_mirrors() + ) urls <- sub("/$", "", urls) # Remove duplicates (both against current and within input) @@ -235,21 +273,22 @@ add_mirrors <- function(urls, position = c("first", "last")) { urls <- urls[!urls %in% current_mirrors] if (length(urls) == 0) { - message("All mirrors already exist") + cli::cli_alert_info("All mirrors already exist.") return(invisible(current_mirrors)) } - new_mirrors <- switch(position, - "first" = c(urls, current_mirrors), - "last" = c(current_mirrors, urls)) + new_mirrors <- switch( + position, + "first" = c(urls, current_mirrors), + "last" = c(current_mirrors, urls) + ) options(PERCEPTIONx.download_mirrors = new_mirrors) - message("Added ", length(urls), " mirror(s)") + cli::cli_alert_success("Added {length(urls)} mirror(s).") invisible(new_mirrors) } - #' List current download mirrors #' #' @export @@ -262,32 +301,65 @@ list_mirrors <- function() { } - #' Reset mirrors to default #' #' @export reset_mirrors <- function() { options(PERCEPTIONx.download_mirrors = NULL) - message("Mirrors reset to default") + cli::cli_alert_success("Mirrors reset to default.") invisible(get_default_perception_mirrors()) } - # 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_drugs <- c( - "abemaciclib", "afatinib", "axitinib", "azacitidine", "cladribine", - "clofarabine", "cobimetinib", "dabrafenib", "dasatinib", "daunorubicin", - "decitabine", "docetaxel", "doxorubicin", "epirubicin", "erlotinib", - "etoposide", "gefitinib", "gemcitabine", "homoharringtonine", "ibrutinib", - "icotinib", "ixabepilone", "lapatinib", "lenvatinib", "midostaurin", - "niraparib", "osimertinib", "paclitaxel", "palbociclib", "ponatinib", - "romidepsin", "sunitinib", "temsirolimus", "teniposide", "thioguanine", - "topotecan", "trametinib", "vandetanib", "vemurafenib", "vinblastine", - "vincristine", "vindesine", "vinflunine", "vinorelbine" + "abemaciclib", + "afatinib", + "axitinib", + "azacitidine", + "cladribine", + "clofarabine", + "cobimetinib", + "dabrafenib", + "dasatinib", + "daunorubicin", + "decitabine", + "docetaxel", + "doxorubicin", + "epirubicin", + "erlotinib", + "etoposide", + "gefitinib", + "gemcitabine", + "homoharringtonine", + "ibrutinib", + "icotinib", + "ixabepilone", + "lapatinib", + "lenvatinib", + "midostaurin", + "niraparib", + "osimertinib", + "paclitaxel", + "palbociclib", + "ponatinib", + "romidepsin", + "sunitinib", + "temsirolimus", + "teniposide", + "thioguanine", + "topotecan", + "trametinib", + "vandetanib", + "vemurafenib", + "vinblastine", + "vincristine", + "vindesine", + "vinflunine", + "vinorelbine" ) #' Load pre-built model of provided drugs @@ -332,20 +404,31 @@ perception_all_drugs <- c( #' models <- load_model("erlotinib", read = TRUE, #' mirror_url = "https://gh-proxy.com/https://github.com") #' } -load_model <- function(..., dest = perception_default_model_dir(), read = FALSE, mirror = FALSE, - mirror_url = NULL, timeout_seconds = 30, retries = 0, force = FALSE, - all = FALSE) { +load_model <- function( + ..., + dest = perception_default_model_dir(), + read = FALSE, + mirror = FALSE, + mirror_url = NULL, + timeout_seconds = 30, + retries = 0, + force = FALSE, + all = FALSE +) { drugs <- tolower(c(...)) if (all) { if (length(drugs) > 0) { - warning("all = TRUE overrides the drug names given in ...; downloading all 44 models.", - call. = FALSE) + warning( + "all = TRUE overrides the drug names given in ...; downloading all 44 models.", + call. = FALSE + ) } drugs <- perception_all_drugs } if (length(drugs) == 0) { - stop("Drug list is empty. Pass drug names or set all = TRUE to download all 44 pre-trained models.", - call. = FALSE) + cli::cli_abort( + "Drug list is empty. Pass drug names or set {.code all = TRUE} to download all 44 pre-trained models." + ) } if (!dir.exists(dest)) { @@ -368,28 +451,40 @@ load_model <- function(..., dest = perception_default_model_dir(), read = FALSE, # force: drop a stale/corrupt cached file so the download always restarts if (force && file.exists(file_path)) { file.remove(file_path) - message("force = TRUE: removed cached ", drug, ".RDS, re-downloading...") + cli::cli_alert_info( + "Force = TRUE: removed cached {.file {drug}.RDS}, re-downloading..." + ) } if (!file.exists(file_path)) { - urls <- paste0(base_urls, "/WangLabCSU/PERCEPTIONx/releases/download/models-v1/", drug, ".RDS") - message("Downloading model for: ", drug) - - if(!download_with_mirrors(urls, file_path, quiet = FALSE, - timeout_seconds = timeout_seconds, - retries = retries)){ - stop("Failed to download model for: ", drug) + urls <- paste0( + base_urls, + "/WangLabCSU/PERCEPTIONx/releases/download/models-v1/", + drug, + ".RDS" + ) + cli::cli_progress_step("Downloading model for: {.val {drug}}") + + if ( + !download_with_mirrors( + urls, + file_path, + quiet = FALSE, + timeout_seconds = timeout_seconds, + retries = retries + ) + ) { + cli::cli_abort("Failed to download model for: {.val {drug}}") } - message("-> Successfully downloaded: ", drug, ".RDS") - + cli::cli_alert_success("Successfully downloaded: {.file {drug}.RDS}") } else { - message("Found cached model: ", drug) + cli::cli_alert_info("Found cached model: {.val {drug}}") } if (read) { result[[drug]] <- readRDS(file_path) - message("-> Successfully loaded: ", drug) + cli::cli_alert_success("Successfully loaded: {.val {drug}}") } } @@ -401,7 +496,6 @@ load_model <- function(..., dest = perception_default_model_dir(), read = FALSE, } - #' Download filtered DepMap data #' #' Downloads the filtered DepMap RDS file for training models from GitHub Release. @@ -441,8 +535,15 @@ load_model <- function(..., dest = perception_default_model_dir(), read = FALSE, #' # Use a specific mirror #' load_depmap(read = TRUE, mirror_url = "https://gh-proxy.com/https://github.com") #' } -load_depmap <- function(dest = perception_default_depmap_dir(), read = FALSE, mirror = FALSE, mirror_url = NULL, - timeout_seconds = 300, retries = 1, force = FALSE) { +load_depmap <- function( + dest = perception_default_depmap_dir(), + read = FALSE, + mirror = FALSE, + mirror_url = NULL, + timeout_seconds = 300, + retries = 1, + force = FALSE +) { if (!dir.exists(dest)) { dir.create(dest, recursive = TRUE) } @@ -452,17 +553,23 @@ load_depmap <- function(dest = perception_default_depmap_dir(), read = FALSE, mi # force: drop a stale/corrupt cached file so the download always restarts if (force && file.exists(destfile)) { file.remove(destfile) - message("force = TRUE: removed cached DepMap.RDS, re-downloading...") + cli::cli_alert_info( + "Force = TRUE: removed cached {.file DepMap.RDS}, re-downloading..." + ) } # A partial file from an interrupted download must never be treated as a # cache hit (it would fail at readRDS). Re-download when the on-disk file is # smaller than the official release asset. - if (!file.exists(destfile) || - is.finite(file.size(destfile)) && file.size(destfile) < .depmap_release_size) { + if ( + !file.exists(destfile) || + is.finite(file.size(destfile)) && + file.size(destfile) < .depmap_release_size + ) { if (file.exists(destfile)) { - message(sprintf("Existing DepMap.RDS is incomplete (%d bytes < expected %d), re-downloading...", - file.size(destfile), .depmap_release_size)) + cli::cli_alert_warning( + "Existing {.file DepMap.RDS} is incomplete ({format(file.size(destfile), big.mark = ',')} bytes < expected {format(.depmap_release_size, big.mark = ',')}), re-downloading..." + ) file.remove(destfile) } base_urls <- if (!is.null(mirror_url)) { @@ -472,34 +579,51 @@ load_depmap <- function(dest = perception_default_depmap_dir(), read = FALSE, mi } else { "https://github.com" } - urls <- paste0(base_urls, "/WangLabCSU/PERCEPTIONx/releases/download/depmap/DepMap.RDS") - - message("Downloading DepMap.RDS (~567 MB). This may take several minutes...") - - if (!download_with_mirrors(urls, destfile, quiet = FALSE, - timeout_seconds = timeout_seconds, - retries = retries, - expected_size = .depmap_release_size)) { - message("\nAutomatic download failed. Please try manual download:") - message(" 1. Download from: https://github.com/WangLabCSU/PERCEPTIONx/releases/tag/depmap") - message(" 2. Save the file to: ", destfile) - message(" 3. Then run load_depmap(read = TRUE) again") - stop("Manual download required", call. = FALSE) + urls <- paste0( + base_urls, + "/WangLabCSU/PERCEPTIONx/releases/download/depmap/DepMap.RDS" + ) + + cli::cli_progress_step( + "Downloading DepMap.RDS (~567 MB). This may take several minutes..." + ) + + if ( + !download_with_mirrors( + urls, + destfile, + quiet = FALSE, + timeout_seconds = timeout_seconds, + retries = retries, + expected_size = .depmap_release_size + ) + ) { + cli::cli_alert_warning( + "Automatic download failed. Please try manual download:" + ) + cli::cli_ul(c( + "Download from: {.url https://github.com/WangLabCSU/PERCEPTIONx/releases/tag/depmap}", + "Save the file to: {.path {destfile}}", + "Then run {.code load_depmap(read = TRUE)} again" + )) + cli::cli_abort("Manual download required.") } - message("Successfully downloaded DepMap.RDS") + cli::cli_alert_success("Successfully downloaded DepMap.RDS.") } else { - message("File already exists: ", destfile) + cli::cli_alert_info("File already exists: {.path {destfile}}") } if (read) { - message("Reading DepMap.RDS...") + cli::cli_progress_step("Reading DepMap.RDS...") DepMap <- readRDS(destfile) assign("DepMap", DepMap, envir = .depmap_env) # Also assign to .GlobalEnv for backward compatibility with existing scripts # that reference DepMap directly do.call("assign", list("DepMap", DepMap, envir = .GlobalEnv)) - message("Assigned 'DepMap' to package cache and global environment.") - message("Use get_depmap() or DepMap to access the data.") + cli::cli_alert_success( + "Assigned {.val DepMap} to package cache and global environment." + ) + cli::cli_alert_info("Use {.code get_depmap()} or {.code DepMap} to access the data.") return(invisible(DepMap)) } diff --git a/R/paths.R b/R/paths.R index dad8585..11b6998 100644 --- a/R/paths.R +++ b/R/paths.R @@ -26,8 +26,10 @@ perception_cache_root <- function() { root <- getOption("PERCEPTIONx.cache_root") if (is.null(root) || !nzchar(root)) { - root <- Sys.getenv("PERCEPTIONX_CACHE_ROOT", - Sys.getenv("PERCEPTIONx_CACHE_ROOT", "")) + root <- Sys.getenv( + "PERCEPTIONX_CACHE_ROOT", + Sys.getenv("PERCEPTIONx_CACHE_ROOT", "") + ) } if (!is.null(root) && nzchar(root)) root else NULL } @@ -36,12 +38,18 @@ perception_cache_root <- function() { perception_depmap_cache_dir <- function() { d <- getOption("PERCEPTIONx.depmap_cache_dir") if (is.null(d) || !nzchar(d)) { - d <- Sys.getenv("PERCEPTIONX_DEPMAP_CACHE_DIR", - Sys.getenv("PERCEPTIONx_DEPMAP_CACHE_DIR", "")) + d <- Sys.getenv( + "PERCEPTIONX_DEPMAP_CACHE_DIR", + Sys.getenv("PERCEPTIONx_DEPMAP_CACHE_DIR", "") + ) + } + if (!is.null(d) && nzchar(d)) { + return(d) } - if (!is.null(d) && nzchar(d)) return(d) root <- perception_cache_root() - if (!is.null(root)) return(file.path(root, "depmap")) + if (!is.null(root)) { + return(file.path(root, "depmap")) + } tools::R_user_dir("PERCEPTIONx", "data") } @@ -66,5 +74,9 @@ perception_default_model_dir <- function() { # Shared master jobs directory: cache_root-derived, else tempdir()/perception_jobs. perception_jobs_dir <- function() { root <- perception_cache_root() - if (is.null(root)) file.path(tempdir(), "perception_jobs") else file.path(root, "jobs") + if (is.null(root)) { + file.path(tempdir(), "perception_jobs") + } else { + file.path(root, "jobs") + } } diff --git a/R/plot.R b/R/plot.R index 4388212..e46a8cc 100644 --- a/R/plot.R +++ b/R/plot.R @@ -17,13 +17,33 @@ NULL # Column names used in aes() - declare as global variables to suppress R CMD check notes -utils::globalVariables(c("X", "Y", "clones", "weights", "patients", - "clone_id", "Predictability", "drugsCount", "dataused", - "pred_viab", "expression", - "tooltip_text", "data_id", "fpr", "tpr", - "x", "y", "label", "yintercept", - "size_val", "drugProp", "Dataset", "y_mid", - "Label", "AUC")) +utils::globalVariables(c( + "X", + "Y", + "clones", + "weights", + "patients", + "clone_id", + "Predictability", + "drugsCount", + "dataused", + "pred_viab", + "expression", + "tooltip_text", + "data_id", + "fpr", + "tpr", + "x", + "y", + "label", + "yintercept", + "size_val", + "drugProp", + "Dataset", + "y_mid", + "Label", + "AUC" +)) # --------------------------------------------------------------------------- # Design system @@ -34,26 +54,45 @@ utils::globalVariables(c("X", "Y", "clones", "weights", "patients", theme_perception <- function(base_size = 11, base_family = "") { ggplot2::theme_bw(base_size = base_size, base_family = base_family) + ggplot2::theme( - panel.background = element_rect(fill = "white", color = NA), - plot.background = element_rect(fill = "white", color = NA), - panel.border = element_rect(color = "#dfe3ee", linewidth = 0.5), - panel.grid.major = element_line(color = "#eef0f6", linewidth = 0.4), - panel.grid.minor = element_blank(), - axis.ticks = element_line(color = "#b6becd"), - axis.title = element_text(face = "bold", color = "#1e2a4a"), - axis.text = element_text(color = "#3d4a63"), - plot.title = element_text(face = "bold", color = "#1e2a4a", hjust = 0, - margin = margin(b = 4)), - plot.subtitle = element_text(color = "#5a6a8a", hjust = 0, - margin = margin(b = 8)), - legend.background = element_rect(fill = "white", color = NA), - legend.key = element_rect(fill = "white", color = NA), + panel.background = element_rect(fill = "white", color = NA), + plot.background = element_rect(fill = "white", color = NA), + panel.border = element_rect(color = "#dfe3ee", linewidth = 0.5), + panel.grid.major = element_line(color = "#eef0f6", linewidth = 0.4), + panel.grid.minor = element_blank(), + axis.ticks = element_line(color = "#b6becd"), + axis.title = element_text(face = "bold", color = "#1e2a4a"), + axis.text = element_text(color = "#3d4a63"), + plot.title = element_text( + face = "bold", + color = "#1e2a4a", + hjust = 0, + margin = margin(b = 4) + ), + plot.subtitle = element_text( + color = "#5a6a8a", + hjust = 0, + margin = margin(b = 8) + ), + legend.background = element_rect(fill = "white", color = NA), + legend.key = element_rect(fill = "white", color = NA), legend.box.background = element_rect(fill = "white", color = NA), - legend.title = element_text(face = "bold", color = "#1e2a4a", size = rel(0.85)), - legend.text = element_text(color = "#3d4a63", size = rel(0.8)), - strip.background = element_rect(fill = "#f6f8fc", color = "#dfe3ee", linewidth = 0.5), - strip.text = element_text(face = "bold", color = "#1e2a4a", size = rel(0.85)), - plot.margin = margin(t = 6, r = 8, b = 6, l = 6) + legend.title = element_text( + face = "bold", + color = "#1e2a4a", + size = rel(0.85) + ), + legend.text = element_text(color = "#3d4a63", size = rel(0.8)), + strip.background = element_rect( + fill = "#f6f8fc", + color = "#dfe3ee", + linewidth = 0.5 + ), + strip.text = element_text( + face = "bold", + color = "#1e2a4a", + size = rel(0.85) + ), + plot.margin = margin(t = 6, r = 8, b = 6, l = 6) ) } @@ -62,9 +101,21 @@ theme_perception <- function(base_size = 11, base_family = "") { # yellow -> green -> teal -> indigo -> slate), kept at moderate saturation # so neighboring clones stay distinguishable without clashing. clone_palette_base <- c( - "#c1dc55ff", "#20bb3dff", "#28a5dfff", "#2c6a9dff", "#5C6BC0", - "#764BA2", "#AB47BC", "#c977d2ff", "#910013ff", "#d42e2bff", - "#FF7043", "#FFCA28", "#18861dff", "#23acbeff", "#7e645bff" + "#c1dc55ff", + "#20bb3dff", + "#28a5dfff", + "#2c6a9dff", + "#5C6BC0", + "#764BA2", + "#AB47BC", + "#c977d2ff", + "#910013ff", + "#d42e2bff", + "#FF7043", + "#FFCA28", + "#18861dff", + "#23acbeff", + "#7e645bff" ) clone_palette <- function(n) { if (n <= length(clone_palette_base)) { @@ -88,14 +139,33 @@ sequential_colors <- c("#440154", "#3B528B", "#21908C", "#5DC863", "#FDE725") # or "c1, c2, ..., c10" instead of the lexicographic "1, 10, 12, 2, ...". natural_levels <- function(x) { lv <- unique(as.character(x)) - parts <- strsplit(lv, "(?<=[^0-9])(?=[0-9])|(?<=[0-9])(?=[^0-9])", perl = TRUE) - pref <- vapply(parts, function(p) { - if (length(p) == 1L && grepl("^[0-9]+$", p)) "" else paste(p[c(TRUE, FALSE)], collapse = "") - }, character(1)) - num <- vapply(parts, function(p) { - if (length(p) == 1L && grepl("^[0-9]+$", p)) as.integer(p) - else suppressWarnings(as.integer(paste(p[c(FALSE, TRUE)], collapse = ""))) - }, integer(1)) + parts <- strsplit( + lv, + "(?<=[^0-9])(?=[0-9])|(?<=[0-9])(?=[^0-9])", + perl = TRUE + ) + pref <- vapply( + parts, + function(p) { + if (length(p) == 1L && grepl("^[0-9]+$", p)) { + "" + } else { + paste(p[c(TRUE, FALSE)], collapse = "") + } + }, + character(1) + ) + num <- vapply( + parts, + function(p) { + if (length(p) == 1L && grepl("^[0-9]+$", p)) { + as.integer(p) + } else { + suppressWarnings(as.integer(paste(p[c(FALSE, TRUE)], collapse = ""))) + } + }, + integer(1) + ) num[is.na(num)] <- 0L lv[order(pref, num)] } @@ -146,79 +216,114 @@ natural_levels <- function(x) { #' } #' #' @export -plot_tsne_response <- function(tsne_data, - color_var = "viability_scaled", - title = NULL, - color_label = "Predicted Viability", - point_size = NULL, - colors = NULL, - palette = c("viridis", "diverging"), - midpoint = 0, - limits = NULL, - base_size = 11, - tooltip = TRUE, - tooltip_col = NULL) { - +plot_tsne_response <- function( + tsne_data, + color_var = "viability_scaled", + title = NULL, + color_label = "Predicted Viability", + point_size = NULL, + colors = NULL, + palette = c("viridis", "diverging"), + midpoint = 0, + limits = NULL, + base_size = 11, + tooltip = TRUE, + tooltip_col = NULL +) { if (!all(c("X", "Y", color_var) %in% colnames(tsne_data))) { - stop("tsne_data must contain columns: X, Y, and ", color_var) + cli::cli_abort( + "tsne_data must contain columns: {.field X}, {.field Y}, and {.field {color_var}}" + ) } if (!is.numeric(tsne_data[[color_var]])) { - stop(color_var, " must be a numeric column for continuous color mapping") + cli::cli_abort( + "{.field {color_var}} must be a numeric column for continuous color mapping" + ) } - palette <- match.arg(palette) + palette <- rlang::arg_match(palette) n_points <- nrow(tsne_data) # Adaptive point size / alpha to prevent overplotting on large scRNA data. if (is.null(point_size)) { - point_size <- if (n_points > 50000) 0.4 - else if (n_points > 20000) 0.5 - else if (n_points > 8000) 0.6 - else 0.8 + point_size <- if (n_points > 50000) { + 0.4 + } else if (n_points > 20000) { + 0.5 + } else if (n_points > 8000) { + 0.6 + } else { + 0.8 + } + } + point_alpha <- if (n_points > 50000) { + 0.35 + } else if (n_points > 20000) { + 0.5 + } else if (n_points > 8000) { + 0.65 + } else { + 0.8 } - point_alpha <- if (n_points > 50000) 0.35 - else if (n_points > 20000) 0.5 - else if (n_points > 8000) 0.65 - else 0.8 # Downsample extremely large datasets for smooth interactive rendering. if (n_points > 50000) { set.seed(42) keep <- sample.int(n_points, 50000) tsne_data <- tsne_data[keep, , drop = FALSE] - message("plot_tsne_response: downsampled to 50,000 points for rendering (n = ", n_points, ")") + cli::cli_alert_info( + "Downsampled to 50,000 points for rendering (n = {n_points})." + ) } # Tooltip for ggiraph interactivity. tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) if (!is.null(tooltip_col) && tooltip_col %in% colnames(tsne_data)) { - tsne_data$tooltip_text <- sprintf("%s\n%s: %.3f", - tsne_data[[tooltip_col]], color_label, - tsne_data[[color_var]]) + tsne_data$tooltip_text <- sprintf( + "%s\n%s: %.3f", + tsne_data[[tooltip_col]], + color_label, + tsne_data[[color_var]] + ) } else { - tsne_data$tooltip_text <- sprintf("%s: %.3f", color_label, - tsne_data[[color_var]]) + tsne_data$tooltip_text <- sprintf( + "%s: %.3f", + color_label, + tsne_data[[color_var]] + ) } tsne_data$data_id <- paste0("cell_", seq_len(nrow(tsne_data))) p <- ggplot(tsne_data, aes(x = X, y = Y, color = .data[[color_var]])) + - { if (tt_ok) ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), - size = point_size, alpha = point_alpha) - else geom_point(size = point_size, alpha = point_alpha) } + + { + if (tt_ok) { + ggiraph::geom_point_interactive( + aes(tooltip = tooltip_text, data_id = data_id), + size = point_size, + alpha = point_alpha + ) + } else { + geom_point(size = point_size, alpha = point_alpha) + } + } + theme_perception(base_size = base_size) + labs(color = color_label, x = "", y = "") + - theme(legend.position = "top", - legend.key.height = unit(0.9, "lines"), - legend.key.width = unit(2.6, "lines")) + theme( + legend.position = "top", + legend.key.height = unit(0.9, "lines"), + legend.key.width = unit(2.6, "lines") + ) if (palette == "diverging") { - p <- p + scale_colour_gradient2(low = diverging_colors[1], - mid = diverging_colors[2], - high = diverging_colors[3], - midpoint = midpoint, - limits = limits) + p <- p + + scale_colour_gradient2( + low = diverging_colors[1], + mid = diverging_colors[2], + high = diverging_colors[3], + midpoint = midpoint, + limits = limits + ) } else { cols <- if (is.null(colors)) sequential_colors else colors # Pass limits through: with a fixed 0-1 scale (e.g. gene expression), @@ -260,45 +365,63 @@ plot_tsne_response <- function(tsne_data, #' @return A ggplot object. #' #' @export -plot_clone_umap <- function(tsne_data, - clone_col = "clone_id", - title = NULL, - color_label = "Clone", - point_size = NULL, - base_size = 11, - tooltip = TRUE, - tooltip_col = NULL) { - +plot_clone_umap <- function( + tsne_data, + clone_col = "clone_id", + title = NULL, + color_label = "Clone", + point_size = NULL, + base_size = 11, + tooltip = TRUE, + tooltip_col = NULL +) { if (!all(c("X", "Y", clone_col) %in% colnames(tsne_data))) { - stop("tsne_data must contain columns: X, Y, and ", clone_col) + cli::cli_abort( + "tsne_data must contain columns: {.field X}, {.field Y}, and {.field {clone_col}}" + ) } n_points <- nrow(tsne_data) # Adaptive point size / alpha to prevent overplotting on large scRNA data. if (is.null(point_size)) { - point_size <- if (n_points > 50000) 0.4 - else if (n_points > 20000) 0.5 - else if (n_points > 8000) 0.6 - else 0.8 + point_size <- if (n_points > 50000) { + 0.4 + } else if (n_points > 20000) { + 0.5 + } else if (n_points > 8000) { + 0.6 + } else { + 0.8 + } + } + point_alpha <- if (n_points > 50000) { + 0.35 + } else if (n_points > 20000) { + 0.5 + } else if (n_points > 8000) { + 0.65 + } else { + 0.8 } - point_alpha <- if (n_points > 50000) 0.35 - else if (n_points > 20000) 0.5 - else if (n_points > 8000) 0.65 - else 0.8 # Downsample extremely large datasets for smooth interactive rendering. if (n_points > 50000) { set.seed(42) keep <- sample.int(n_points, 50000) tsne_data <- tsne_data[keep, , drop = FALSE] - message("plot_clone_umap: downsampled to 50,000 points for rendering (n = ", n_points, ")") + cli::cli_alert_info( + "Downsampled to 50,000 points for rendering (n = {n_points})." + ) } # Stable, naturally ordered factor levels (1, 2, ..., 10 or c1, c2, ...) so # legend order and color mapping stay consistent across plots. clone_levels <- natural_levels(tsne_data[[clone_col]]) - tsne_data[[clone_col]] <- factor(tsne_data[[clone_col]], levels = clone_levels) + tsne_data[[clone_col]] <- factor( + tsne_data[[clone_col]], + levels = clone_levels + ) # Tooltip for ggiraph interactivity. tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) @@ -310,22 +433,38 @@ plot_clone_umap <- function(tsne_data, tsne_data$data_id <- paste0("cell_", seq_len(nrow(tsne_data))) p <- ggplot(tsne_data, aes(x = X, y = Y, color = .data[[clone_col]])) + - { if (tt_ok) ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), - size = point_size, alpha = point_alpha) - else geom_point(size = point_size, alpha = point_alpha) } + - scale_colour_manual(values = clone_palette(length(clone_levels)), - drop = FALSE) + + { + if (tt_ok) { + ggiraph::geom_point_interactive( + aes(tooltip = tooltip_text, data_id = data_id), + size = point_size, + alpha = point_alpha + ) + } else { + geom_point(size = point_size, alpha = point_alpha) + } + } + + scale_colour_manual( + values = clone_palette(length(clone_levels)), + drop = FALSE + ) + theme_perception(base_size = base_size) + labs(color = color_label, x = "", y = "") + # Compact legend: force 2 rows so a 15-clone palette (8+7) does not wrap # into 3+ rows and compress the plot canvas. - guides(color = guide_legend(nrow = 2, keywidth = unit(0.7, "lines"), - keyheight = unit(0.7, "lines"), - override.aes = list(size = 2.5))) + - theme(legend.position = "top", - legend.key.height = unit(0.7, "lines"), - legend.key.width = unit(0.7, "lines")) + guides( + color = guide_legend( + nrow = 2, + keywidth = unit(0.7, "lines"), + keyheight = unit(0.7, "lines"), + override.aes = list(size = 2.5) + ) + ) + + theme( + legend.position = "top", + legend.key.height = unit(0.7, "lines"), + legend.key.width = unit(0.7, "lines") + ) if (!is.null(title)) { p <- p + ggtitle(title) @@ -366,41 +505,65 @@ plot_clone_umap <- function(tsne_data, #' } #' #' @export -plot_clone_distribution <- function(clone_distribution, - response_var = NULL, - base_size = 15, - tooltip = TRUE, - tooltip_col = NULL) { - +plot_clone_distribution <- function( + clone_distribution, + response_var = NULL, + base_size = 15, + tooltip = TRUE, + tooltip_col = NULL +) { required_cols <- c("patients", "clones", "weights") if (!all(required_cols %in% colnames(clone_distribution))) { - stop("clone_distribution must contain columns: ", paste(required_cols, collapse = ", ")) + cli::cli_abort( + "clone_distribution must contain columns: {.field {required_cols}}" + ) } # Pre-convert the response column to an R/NR factor BEFORE building the ggplot # object (ggplot captures data at build time, so the factor must exist first; # this avoids the %+% data-update operator entirely). - if (!is.null(response_var) && response_var %in% colnames(clone_distribution)) { + if ( + !is.null(response_var) && response_var %in% colnames(clone_distribution) + ) { resp_vec <- clone_distribution[[response_var]] if (all(toupper(resp_vec[!is.na(resp_vec)]) %in% c("R", "NR"))) { - clone_distribution[[response_var]] <- factor(resp_vec, levels = c("R", "NR")) + clone_distribution[[response_var]] <- factor( + resp_vec, + levels = c("R", "NR") + ) } } # Order patients naturally (e.g. AZ_01, AZ_02, ..., LT_S01, ...): group by # letter prefix, then sort by trailing number. All patient labels are shown. pat_levels <- unique(clone_distribution$patients) - pat_parts <- strsplit(pat_levels, "(?<=[^0-9])(?=[0-9])|(?<=[0-9])(?=[^0-9])", perl = TRUE) - key_pref <- vapply(pat_parts, function(p) paste(p[c(TRUE, FALSE)], collapse = ""), character(1)) - key_num <- suppressWarnings(vapply(pat_parts, function(p) as.integer(paste(p[c(FALSE, TRUE)], collapse = "")), integer(1))) + pat_parts <- strsplit( + pat_levels, + "(?<=[^0-9])(?=[0-9])|(?<=[0-9])(?=[^0-9])", + perl = TRUE + ) + key_pref <- vapply( + pat_parts, + function(p) paste(p[c(TRUE, FALSE)], collapse = ""), + character(1) + ) + key_num <- suppressWarnings(vapply( + pat_parts, + function(p) as.integer(paste(p[c(FALSE, TRUE)], collapse = "")), + integer(1) + )) key_num[is.na(key_num)] <- 0L - clone_distribution$patients <- factor(clone_distribution$patients, - levels = pat_levels[order(key_pref, key_num)]) + clone_distribution$patients <- factor( + clone_distribution$patients, + levels = pat_levels[order(key_pref, key_num)] + ) # Same natural ordering for the clone labels, otherwise the legend sorts # them lexicographically ("1", "10", "12", "2", ...). See natural_levels(). - clone_distribution$clones <- factor(clone_distribution$clones, - levels = natural_levels(clone_distribution$clones)) + clone_distribution$clones <- factor( + clone_distribution$clones, + levels = natural_levels(clone_distribution$clones) + ) n_clones <- length(unique(clone_distribution$clones)) n_patients <- length(unique(clone_distribution$patients)) @@ -414,7 +577,9 @@ plot_clone_distribution <- function(clone_distribution, # Tooltip for ggiraph interactivity (hover shows clone + proportion). tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) - if (is.null(tooltip_col) || !(tooltip_col %in% colnames(clone_distribution))) { + if ( + is.null(tooltip_col) || !(tooltip_col %in% colnames(clone_distribution)) + ) { clone_distribution$tooltip_text <- sprintf( "Patient: %s\nClone: %s\nProportion: %.2f", clone_distribution$patients, @@ -422,37 +587,73 @@ plot_clone_distribution <- function(clone_distribution, clone_distribution$weights ) } - tt_col <- if (!is.null(tooltip_col) && tooltip_col %in% colnames(clone_distribution)) { + tt_col <- if ( + !is.null(tooltip_col) && tooltip_col %in% colnames(clone_distribution) + ) { tooltip_col } else { "tooltip_text" } - p <- ggplot(clone_distribution, aes(fill = clones, y = weights, x = patients)) + - { if (tt_ok) ggiraph::geom_bar_interactive( - aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), - position = "stack", stat = "identity", width = 0.75, - color = "white", linewidth = 0.15) - else geom_bar(position = "stack", stat = "identity", width = 0.75, - color = "white", linewidth = 0.15) } + + p <- ggplot( + clone_distribution, + aes(fill = clones, y = weights, x = patients) + ) + + { + if (tt_ok) { + ggiraph::geom_bar_interactive( + aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), + position = "stack", + stat = "identity", + width = 0.75, + color = "white", + linewidth = 0.15 + ) + } else { + geom_bar( + position = "stack", + stat = "identity", + width = 0.75, + color = "white", + linewidth = 0.15 + ) + } + } + scale_fill_manual(values = clone_palette(n_clones)) + theme_perception(base_size = base_size) + - theme(axis.text.x = element_text(angle = x_angle, hjust = x_hjust, vjust = x_vjust, - size = rel(0.8), margin = margin(t = 4)), - legend.position = "bottom", - legend.text = element_text(size = rel(0.7)), - legend.key.height = unit(0.7, "lines"), - strip.placement = "outside", - strip.text = element_text(angle = 0, hjust = 0.5, vjust = 0.5, - size = rel(0.8))) + + theme( + axis.text.x = element_text( + angle = x_angle, + hjust = x_hjust, + vjust = x_vjust, + size = rel(0.8), + margin = margin(t = 4) + ), + legend.position = "bottom", + legend.text = element_text(size = rel(0.7)), + legend.key.height = unit(0.7, "lines"), + strip.placement = "outside", + strip.text = element_text( + angle = 0, + hjust = 0.5, + vjust = 0.5, + size = rel(0.8) + ) + ) + labs(y = "Clone Proportion", x = "Patients", fill = "Clone") # Facet by response group (R/NR) -- Y axis kept fixed (0-1) so proportions # are directly comparable across facets; only X is free. - if (!is.null(response_var) && response_var %in% colnames(clone_distribution)) { + if ( + !is.null(response_var) && response_var %in% colnames(clone_distribution) + ) { p <- p + - facet_grid(cols = vars(.data[[response_var]]), shrink = TRUE, - scales = "free_x", space = "free_x") + facet_grid( + cols = vars(.data[[response_var]]), + shrink = TRUE, + scales = "free_x", + space = "free_x" + ) } return(p) @@ -465,9 +666,14 @@ plot_clone_distribution <- function(clone_distribution, # p-value display: always show the number (scientific notation when very # small) instead of an abbreviated "< 0.001". fmt_pval <- function(p) { - if (is.na(p) || !is.finite(p)) return("NA") - if (p < 0.001) format(p, scientific = TRUE, digits = 2) - else sprintf("%.3f", p) + if (is.na(p) || !is.finite(p)) { + return("NA") + } + if (p < 0.001) { + format(p, scientific = TRUE, digits = 2) + } else { + sprintf("%.3f", p) + } } # Short facet tag for a response label: R/NR for responder/resistant @@ -475,11 +681,27 @@ fmt_pval <- function(p) { # points) so multi-group response data keeps its own grouping. resp_short_tag <- function(rv) { u <- toupper(trimws(as.character(rv))) - if (u %in% c("R", "RESPONDER", "SENSITIVE", "RESPONSE", "RESPONSIVE")) "R" - else if (u %in% c("NR", "NON-RESPONDER", "NONRESPONDER", "NON RESPONDER", - "NON-RESPONSIVE", "NONRESPONSIVE", "RESISTANT", "RESISTANCE", - "PROGRESSOR", "PROGRESSION")) "NR" - else u + if (u %in% c("R", "RESPONDER", "SENSITIVE", "RESPONSE", "RESPONSIVE")) { + "R" + } else if ( + u %in% + c( + "NR", + "NON-RESPONDER", + "NONRESPONDER", + "NON RESPONDER", + "NON-RESPONSIVE", + "NONRESPONSIVE", + "RESISTANT", + "RESISTANCE", + "PROGRESSOR", + "PROGRESSION" + ) + ) { + "NR" + } else { + u + } } #' Plot clone-level viability (lollipop plot) @@ -530,19 +752,24 @@ resp_short_tag <- function(rv) { #' } #' #' @export -plot_clone_viability <- function(clone_viability, - viability_var = "comb_viability", - weights_var = NULL, - response_var = NULL, - drug = NULL, - base_size = 11, - y_limits = c(-3, 1.2), - viridis_scale = FALSE, - tooltip = TRUE, - tooltip_col = NULL) { - - if (!all(c("patient", "clone_id", viability_var) %in% colnames(clone_viability))) { - stop("clone_viability must contain columns: patient, clone_id, and ", viability_var) +plot_clone_viability <- function( + clone_viability, + viability_var = "comb_viability", + weights_var = NULL, + response_var = NULL, + drug = NULL, + base_size = 11, + y_limits = c(-3, 1.2), + viridis_scale = FALSE, + tooltip = TRUE, + tooltip_col = NULL +) { + if ( + !all(c("patient", "clone_id", viability_var) %in% colnames(clone_viability)) + ) { + cli::cli_abort( + "clone_viability must contain columns: {.field patient}, {.field clone_id}, and {.field {viability_var}}" + ) } # --- Prepare facet labels --- @@ -554,18 +781,29 @@ plot_clone_viability <- function(clone_viability, patient_order <- unique(clone_viability$patient[ order(clone_viability[[response_var]], decreasing = TRUE) ]) - clone_viability$patient <- factor(clone_viability$patient, levels = patient_order) - clone_viability$facet_label <- vapply(as.character(clone_viability$patient), function(pat) { - rv <- as.character(resp_map[pat, response_var]) - tag <- resp_short_tag(rv) - paste0(tag, " ", pat) - }, character(1)) + clone_viability$patient <- factor( + clone_viability$patient, + levels = patient_order + ) + clone_viability$facet_label <- vapply( + as.character(clone_viability$patient), + function(pat) { + rv <- as.character(resp_map[pat, response_var]) + tag <- resp_short_tag(rv) + paste0(tag, " ", pat) + }, + character(1) + ) # Two-line variant used by facet_wrap (top strip, no rotation) - clone_viability$facet_label_wrap <- vapply(as.character(clone_viability$patient), function(pat) { - rv <- as.character(resp_map[pat, response_var]) - tag <- resp_short_tag(rv) - paste0(tag, "\n", pat) - }, character(1)) + clone_viability$facet_label_wrap <- vapply( + as.character(clone_viability$patient), + function(pat) { + rv <- as.character(resp_map[pat, response_var]) + tag <- resp_short_tag(rv) + paste0(tag, "\n", pat) + }, + character(1) + ) } else { clone_viability$facet_label <- as.character(clone_viability$patient) clone_viability$facet_label_wrap <- as.character(clone_viability$patient) @@ -573,50 +811,68 @@ plot_clone_viability <- function(clone_viability, # Preserve patient ordering via factor levels on facet_label if (!is.null(response_var) && response_var %in% colnames(clone_viability)) { - clone_viability$facet_label <- factor(clone_viability$facet_label, - levels = unique(clone_viability$facet_label[ - order(clone_viability$patient) - ])) - clone_viability$facet_label_wrap <- factor(clone_viability$facet_label_wrap, - levels = unique(clone_viability$facet_label_wrap[ - order(clone_viability$patient) - ])) + clone_viability$facet_label <- factor( + clone_viability$facet_label, + levels = unique(clone_viability$facet_label[ + order(clone_viability$patient) + ]) + ) + clone_viability$facet_label_wrap <- factor( + clone_viability$facet_label_wrap, + levels = unique(clone_viability$facet_label_wrap[ + order(clone_viability$patient) + ]) + ) } # --- Sort clones within each patient by proportion (descending) --- if (!is.null(weights_var) && weights_var %in% colnames(clone_viability)) { - clone_viability <- clone_viability[order(clone_viability$facet_label, - -clone_viability[[weights_var]]), ] + clone_viability <- clone_viability[ + order(clone_viability$facet_label, -clone_viability[[weights_var]]), + ] } # Build aes mapping. NOTE: `size` (clone proportion) is mapped ONLY on # geom_point -- a global size mapping would be inherited by the line layers # (geom_segment/geom_hline), which triggers the ggplot2 "size for lines is # deprecated" warning. - has_weights <- !is.null(weights_var) && weights_var %in% colnames(clone_viability) + has_weights <- !is.null(weights_var) && + weights_var %in% colnames(clone_viability) if (has_weights) { # Point size = clone proportion on its NATURAL 0..1 scale: relative sizes # stay true (0.8 > 0.4), and the largest circle is bounded only by the # size range (scale_size below), not by clamping the value. clone_viability$size_val <- clone_viability[[weights_var]] } - aes_mapping <- aes(y = .data[[viability_var]], x = clone_id, - color = .data[[viability_var]]) + aes_mapping <- aes( + y = .data[[viability_var]], + x = clone_id, + color = .data[[viability_var]] + ) # Tooltip for ggiraph interactivity (hover shows clone, viability, proportion). tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) if (is.null(tooltip_col) || !(tooltip_col %in% colnames(clone_viability))) { clone_viability$tooltip_text <- if (has_weights) { - sprintf("Clone: %s\nPatient: %s\nViability: %.2f\nProportion: %.2f", - clone_viability$clone_id, clone_viability$facet_label, - clone_viability[[viability_var]], clone_viability[[weights_var]]) + sprintf( + "Clone: %s\nPatient: %s\nViability: %.2f\nProportion: %.2f", + clone_viability$clone_id, + clone_viability$facet_label, + clone_viability[[viability_var]], + clone_viability[[weights_var]] + ) } else { - sprintf("Clone: %s\nPatient: %s\nViability: %.2f", - clone_viability$clone_id, clone_viability$facet_label, - clone_viability[[viability_var]]) + sprintf( + "Clone: %s\nPatient: %s\nViability: %.2f", + clone_viability$clone_id, + clone_viability$facet_label, + clone_viability[[viability_var]] + ) } } - tt_col <- if (!is.null(tooltip_col) && tooltip_col %in% colnames(clone_viability)) { + tt_col <- if ( + !is.null(tooltip_col) && tooltip_col %in% colnames(clone_viability) + ) { tooltip_col } else { "tooltip_text" @@ -635,32 +891,62 @@ plot_clone_viability <- function(clone_viability, # hline data (one per facet) so ggplotly can locate the facet column facet_var <- if (wrap_mode) "facet_label_wrap" else "facet_label" - hline_data <- clone_viability[!duplicated(clone_viability[[facet_var]]), facet_var, drop = FALSE] + hline_data <- clone_viability[ + !duplicated(clone_viability[[facet_var]]), + facet_var, + drop = FALSE + ] hline_data$yintercept <- 0 p <- ggplot(clone_viability, aes_mapping) + - geom_hline(data = hline_data, mapping = aes(yintercept = yintercept), - color = "grey60", linewidth = 0.3) + - geom_segment(aes(x = clone_id, xend = clone_id, y = 0, yend = .data[[viability_var]]), - color = "grey40", linewidth = 0.35) + - { if (tt_ok && has_weights) ggiraph::geom_point_interactive( - aes(size = size_val, tooltip = .data[[tt_col]], - data_id = .data[[tt_col]]), alpha = 0.85) - else if (tt_ok) ggiraph::geom_point_interactive( - aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), alpha = 0.85) - else if (has_weights) geom_point(aes(size = size_val), alpha = 0.85) - else geom_point(alpha = 0.85) } + + geom_hline( + data = hline_data, + mapping = aes(yintercept = yintercept), + color = "grey60", + linewidth = 0.3 + ) + + geom_segment( + aes(x = clone_id, xend = clone_id, y = 0, yend = .data[[viability_var]]), + color = "grey40", + linewidth = 0.35 + ) + + { + if (tt_ok && has_weights) { + ggiraph::geom_point_interactive( + aes( + size = size_val, + tooltip = .data[[tt_col]], + data_id = .data[[tt_col]] + ), + alpha = 0.85 + ) + } else if (tt_ok) { + ggiraph::geom_point_interactive( + aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), + alpha = 0.85 + ) + } else if (has_weights) { + geom_point(aes(size = size_val), alpha = 0.85) + } else { + geom_point(alpha = 0.85) + } + } + coord_cartesian(ylim = c(y_bottom, y_top)) + theme_perception(base_size = base_size) + - labs(x = "Clones", y = "Predicted Viability (z-score)", - color = "Predicted Viability", - size = if (has_weights) "Proportion in Tumor" else NULL, - caption = "Higher = more resistant - lower = more sensitive (stronger drug killing). Z-scores are standardized across all patients, so clones are comparable across patients.") + - theme(legend.position = "top", - legend.box = "horizontal", - legend.box.spacing = unit(8, "pt"), - legend.key.size = unit(13, "pt"), - axis.title.y = element_text(margin = margin(r = 6))) + labs( + x = "Clones", + y = "Predicted Viability (z-score)", + color = "Predicted Viability", + size = if (has_weights) "Proportion in Tumor" else NULL, + caption = "Higher = more resistant - lower = more sensitive (stronger drug killing). Z-scores are standardized across all patients, so clones are comparable across patients." + ) + + theme( + legend.position = "top", + legend.box = "horizontal", + legend.box.spacing = unit(8, "pt"), + legend.key.size = unit(13, "pt"), + axis.title.y = element_text(margin = margin(r = 6)) + ) # Color scale: red-blue diverging by default (blue = low/sensitive, white = # neutral, red = high/resistant), the same ramp as the Gene Expression / @@ -669,21 +955,27 @@ plot_clone_viability <- function(clone_viability, # instead of being clipped to grey/NA. The viridis sequential ramp remains # available via viridis_scale = TRUE. if (viridis_scale) { - p <- p + scale_colour_gradientn( - colours = sequential_colors, - breaks = function(limits) pretty(limits, n = 4) - ) + p <- p + + scale_colour_gradientn( + colours = sequential_colors, + breaks = function(limits) pretty(limits, n = 4) + ) } else { - p <- p + scale_colour_gradient2(low = diverging_colors[1], - mid = diverging_colors[2], - high = diverging_colors[3], - midpoint = 0, - breaks = function(limits) pretty(limits, n = 4)) + p <- p + + scale_colour_gradient2( + low = diverging_colors[1], + mid = diverging_colors[2], + high = diverging_colors[3], + midpoint = 0, + breaks = function(limits) pretty(limits, n = 4) + ) } if (has_weights) { max_w <- max(clone_viability[[weights_var]], na.rm = TRUE) - if (!is.finite(max_w) || max_w <= 0) max_w <- 1 + if (!is.finite(max_w) || max_w <= 0) { + max_w <- 1 + } # Point size = true proportion on its NATURAL 0..1 scale: a 0.8 clone is # always visibly larger than a 0.4 clone (no clamping). The upper range is # kept modest (3 instead of 5) so high-abundance clones do not dominate the @@ -691,32 +983,63 @@ plot_clone_viability <- function(clone_viability, # real circles. Tune here if the lollipop balls look too big/small. size_breaks <- pretty(c(0, max_w), n = 3) size_breaks <- size_breaks[size_breaks >= 0 & size_breaks <= max_w] - if (length(size_breaks) < 2) size_breaks <- c(0, max_w) - p <- p + scale_size(range = c(1, 3), - limits = c(0, max_w), - breaks = size_breaks) + if (length(size_breaks) < 2) { + size_breaks <- c(0, max_w) + } + p <- p + + scale_size(range = c(1, 3), limits = c(0, max_w), breaks = size_breaks) } else { p <- p + guides(size = "none") } if (wrap_mode) { ncol <- min(6, max(2, ceiling(sqrt(n_patients) * 1.4))) - p <- p + facet_wrap(reformulate(facet_var), scales = "free_x", - ncol = ncol, drop = TRUE, strip.position = "top") + - theme(strip.text = element_text(angle = 0, hjust = 0.5, vjust = 0.5, - size = rel(0.62), lineheight = 0.9), - axis.text.x = element_text(angle = 0, hjust = 0.5, vjust = 0.5, - size = rel(0.55)), - panel.spacing = unit(0.3, "lines")) + p <- p + + facet_wrap( + reformulate(facet_var), + scales = "free_x", + ncol = ncol, + drop = TRUE, + strip.position = "top" + ) + + theme( + strip.text = element_text( + angle = 0, + hjust = 0.5, + vjust = 0.5, + size = rel(0.62), + lineheight = 0.9 + ), + axis.text.x = element_text( + angle = 0, + hjust = 0.5, + vjust = 0.5, + size = rel(0.55) + ), + panel.spacing = unit(0.3, "lines") + ) } else { - p <- p + facet_grid(reformulate(facet_var, "."), - scales = "free_x", shrink = TRUE, - drop = TRUE, space = "free_x", switch = "x", - as.table = TRUE) + - theme(strip.text = element_text(angle = 45, hjust = 0, vjust = 0.5, - size = rel(0.75), lineheight = 0.9, - margin = margin(t = 2, b = 2, l = 4, r = 4, unit = "pt")), - panel.spacing = unit(0.15, "lines")) + p <- p + + facet_grid( + reformulate(facet_var, "."), + scales = "free_x", + shrink = TRUE, + drop = TRUE, + space = "free_x", + switch = "x", + as.table = TRUE + ) + + theme( + strip.text = element_text( + angle = 45, + hjust = 0, + vjust = 0.5, + size = rel(0.75), + lineheight = 0.9, + margin = margin(t = 2, b = 2, l = 4, r = 4, unit = "pt") + ), + panel.spacing = unit(0.15, "lines") + ) } if (!is.null(drug) && nchar(drug) > 0) { @@ -753,21 +1076,27 @@ plot_clone_viability <- function(clone_viability, #' } #' #' @export -plot_roc_curve <- function(response, - predictor, - smooth_curve = TRUE, - base_size = 15, - auc_digits = 3, - title = NULL, - tooltip = TRUE) { - +plot_roc_curve <- function( + response, + predictor, + smooth_curve = TRUE, + base_size = 15, + auc_digits = 3, + title = NULL, + tooltip = TRUE +) { if (!requireNamespace("pROC", quietly = TRUE)) { - stop("Package 'pROC' is required for ROC curve plotting. Install with: install.packages('pROC')") + cli::cli_abort(c( + "Package {.pkg pROC} is required for ROC curve plotting.", + "i" = "Install with {.run install.packages('pROC')}." + )) } # Single-class response cannot build a ROC curve -- return an informative placeholder if (length(unique(response[!is.na(response)])) < 2) { - stop("ROC curve requires at least two response classes (e.g. both R and NR).") + cli::cli_abort( + "ROC curve requires at least two response classes (e.g. both R and NR)." + ) } rocobj <- pROC::roc(response = response, predictor = predictor) @@ -777,7 +1106,11 @@ plot_roc_curve <- function(response, rocobj_smooth <- tryCatch( pROC::smooth(rocobj), error = function(e) { - warning("ROC curve not smoothable: ", e$message, ". Using unsmoothed curve.") + warning( + "ROC curve not smoothable: ", + e$message, + ". Using unsmoothed curve." + ) NULL } ) @@ -795,27 +1128,43 @@ plot_roc_curve <- function(response, # are kept as-is — their steps are already continuous. if (smooth_ok) { sp <- as.data.frame( - pROC::coords(rocobj, x = "all", ret = c("specificity", "sensitivity"), - transpose = FALSE) + pROC::coords( + rocobj, + x = "all", + ret = c("specificity", "sensitivity"), + transpose = FALSE + ) ) sp$fpr <- 1 - sp$specificity sp <- sp[order(sp$fpr), ] sp <- sp[!duplicated(sp$fpr), ] if (nrow(sp) > 2) { - dens <- stats::approx(sp$fpr, sp$sensitivity, xout = seq(0, 1, length.out = 200)) + dens <- stats::approx( + sp$fpr, + sp$sensitivity, + xout = seq(0, 1, length.out = 200) + ) curve_df <- data.frame(specificity = 1 - dens$x, sensitivity = dens$y) } else { curve_df <- sp } } else { curve_df <- as.data.frame( - pROC::coords(rocobj, x = "all", ret = c("specificity", "sensitivity"), - transpose = FALSE) + pROC::coords( + rocobj, + x = "all", + ret = c("specificity", "sensitivity"), + transpose = FALSE + ) ) } curve_df$fpr <- 1 - curve_df$specificity curve_df$tpr <- curve_df$sensitivity - curve_df$tooltip_text <- sprintf("FPR: %.3f\nTPR: %.3f", curve_df$fpr, curve_df$tpr) + curve_df$tooltip_text <- sprintf( + "FPR: %.3f\nTPR: %.3f", + curve_df$fpr, + curve_df$tpr + ) curve_df$data_id <- paste0("roc_", seq_len(nrow(curve_df))) tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) @@ -828,11 +1177,20 @@ plot_roc_curve <- function(response, if (tt_ok) { p <- ggplot(curve_df, aes(x = fpr, y = tpr)) if (can_line) { - p <- p + ggiraph::geom_line_interactive(aes(tooltip = tooltip_text, data_id = data_id), - linewidth = 1.1, color = "#2E86AB") + p <- p + + ggiraph::geom_line_interactive( + aes(tooltip = tooltip_text, data_id = data_id), + linewidth = 1.1, + color = "#2E86AB" + ) } - p <- p + ggiraph::geom_point_interactive(aes(tooltip = tooltip_text, data_id = data_id), - size = 1.4, color = "#2E86AB", alpha = 0.7) + p <- p + + ggiraph::geom_point_interactive( + aes(tooltip = tooltip_text, data_id = data_id), + size = 1.4, + color = "#2E86AB", + alpha = 0.7 + ) } else { p <- ggplot(curve_df, aes(x = fpr, y = tpr)) if (can_line) { @@ -846,15 +1204,38 @@ plot_roc_curve <- function(response, labs(x = "1 - Specificity (FPR)", y = "Sensitivity (TPR)") + coord_equal() + # Random-chance diagonal from (0,0) to (1,1) - annotate("segment", x = 0, xend = 1, y = 0, yend = 1, - color = "grey60", linewidth = 0.5, linetype = "dashed") + + annotate( + "segment", + x = 0, + xend = 1, + y = 0, + yend = 1, + color = "grey60", + linewidth = 0.5, + linetype = "dashed" + ) + # AUC badge in a rounded, semi-transparent box (bottom-right corner, # inside the region below the curve). - annotate("rect", xmin = 0.60, xmax = 0.98, ymin = 0.05, ymax = 0.20, - fill = "white", alpha = 0.85, color = "#dfe3ee", linewidth = 0.3) + - annotate("text", x = 0.79, y = 0.125, - label = paste0("AUC = ", round(rocobj$auc, auc_digits)), - size = base_size * 0.28, color = "#1e2a4a", fontface = "bold") + annotate( + "rect", + xmin = 0.60, + xmax = 0.98, + ymin = 0.05, + ymax = 0.20, + fill = "white", + alpha = 0.85, + color = "#dfe3ee", + linewidth = 0.3 + ) + + annotate( + "text", + x = 0.79, + y = 0.125, + label = paste0("AUC = ", round(rocobj$auc, auc_digits)), + size = base_size * 0.28, + color = "#1e2a4a", + fontface = "bold" + ) if (!is.null(title)) { p <- p + ggtitle(title) @@ -896,17 +1277,20 @@ plot_roc_curve <- function(response, #' } #' #' @export -plot_response_boxplot <- function(exp_vs_pred, - response_var = "response", - predicted_var = "predicted_viability", - y_label = "Predicted Viability (z-score)", - base_size = 15, - compare_method = "wilcox.test", - alternative = "less", - tooltip = TRUE) { - +plot_response_boxplot <- function( + exp_vs_pred, + response_var = "response", + predicted_var = "predicted_viability", + y_label = "Predicted Viability (z-score)", + base_size = 15, + compare_method = "wilcox.test", + alternative = "less", + tooltip = TRUE +) { if (!all(c(response_var, predicted_var) %in% colnames(exp_vs_pred))) { - stop("exp_vs_pred must contain columns: ", response_var, " and ", predicted_var) + cli::cli_abort( + "exp_vs_pred must contain columns: {.field {response_var}} and {.field {predicted_var}}" + ) } # Ensure response is a factor preserving R/NR order (R first, as passed in). @@ -914,8 +1298,10 @@ plot_response_boxplot <- function(exp_vs_pred, # significantly LOWER than NR -- i.e. responders are more sensitive. resp_vec <- exp_vs_pred[[response_var]] if (is.factor(resp_vec)) { - resp_vec <- factor(resp_vec) # drop unused levels, keep order - } else if (all(toupper(as.character(resp_vec[!is.na(resp_vec)])) %in% c("R", "NR"))) { + resp_vec <- factor(resp_vec) # drop unused levels, keep order + } else if ( + all(toupper(as.character(resp_vec[!is.na(resp_vec)])) %in% c("R", "NR")) + ) { resp_vec <- factor(resp_vec, levels = c("R", "NR")) } else { resp_vec <- factor(resp_vec) @@ -927,21 +1313,32 @@ plot_response_boxplot <- function(exp_vs_pred, # 6-color palette, generate evenly-spaced hues (ggplot2's default scheme), # so any number of response groups is supported. n_lv <- length(levels(exp_vs_pred[[response_var]])) - fixed_pal <- c("#C13232", "#2E86AB", "#E8A13A", "#5A8A6A", "#8A5AC1", "#4A8FB8") + fixed_pal <- c( + "#C13232", + "#2E86AB", + "#E8A13A", + "#5A8A6A", + "#8A5AC1", + "#4A8FB8" + ) if (n_lv <= length(fixed_pal)) { grp_colors <- fixed_pal[seq_len(n_lv)] } else { grp_colors <- grDevices::hcl( h = seq(15, 375, length.out = n_lv + 1)[seq_len(n_lv)], - c = 100, l = 65) + c = 100, + l = 65 + ) } names(grp_colors) <- levels(exp_vs_pred[[response_var]]) # Tooltip for ggiraph interactivity (hover shows group + predicted value). tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) - exp_vs_pred$tooltip_text <- sprintf("%s: %.3f", - exp_vs_pred[[response_var]], - exp_vs_pred[[predicted_var]]) + exp_vs_pred$tooltip_text <- sprintf( + "%s: %.3f", + exp_vs_pred[[response_var]], + exp_vs_pred[[predicted_var]] + ) exp_vs_pred$data_id <- paste0("box_", seq_len(nrow(exp_vs_pred))) # Layer order & styling are deliberate (simplified, non-overlapping): @@ -950,16 +1347,45 @@ plot_response_boxplot <- function(exp_vs_pred, # violin's silhouette, # 3) jitter = raw points, spread across the violin width so the dots # visually match the density shape. - p <- ggplot(exp_vs_pred, aes(x = .data[[response_var]], y = .data[[predicted_var]])) + - geom_violin(aes(fill = .data[[response_var]]), alpha = 0.25, - width = 0.80, color = "grey40", linewidth = 0.35) + - geom_boxplot(width = 0.14, outlier.shape = NA, fill = NA, - color = "grey30", linewidth = 0.45) + - { if (tt_ok) ggiraph::geom_jitter_interactive( - aes(color = .data[[response_var]], tooltip = tooltip_text, data_id = data_id), - width = 0.18, size = 1.5, alpha = 0.55) - else geom_jitter(aes(color = .data[[response_var]]), - width = 0.18, size = 1.5, alpha = 0.55) } + + p <- ggplot( + exp_vs_pred, + aes(x = .data[[response_var]], y = .data[[predicted_var]]) + ) + + geom_violin( + aes(fill = .data[[response_var]]), + alpha = 0.25, + width = 0.80, + color = "grey40", + linewidth = 0.35 + ) + + geom_boxplot( + width = 0.14, + outlier.shape = NA, + fill = NA, + color = "grey30", + linewidth = 0.45 + ) + + { + if (tt_ok) { + ggiraph::geom_jitter_interactive( + aes( + color = .data[[response_var]], + tooltip = tooltip_text, + data_id = data_id + ), + width = 0.18, + size = 1.5, + alpha = 0.55 + ) + } else { + geom_jitter( + aes(color = .data[[response_var]]), + width = 0.18, + size = 1.5, + alpha = 0.55 + ) + } + } + theme_perception(base_size = base_size) + labs(y = y_label, x = "") + theme(legend.position = "none") + @@ -978,43 +1404,90 @@ plot_response_boxplot <- function(exp_vs_pred, grp1 <- exp_vs_pred[[predicted_var]][exp_vs_pred[[response_var]] == lvls[1]] grp2 <- exp_vs_pred[[predicted_var]][exp_vs_pred[[response_var]] == lvls[2]] if (length(grp1) > 1 && length(grp2) > 1) { - test_fun <- if (tolower(compare_method) == "t.test") t.test else wilcox.test - wt <- tryCatch(test_fun(grp1, grp2, alternative = alternative), - error = function(e) NULL) + test_fun <- if (tolower(compare_method) == "t.test") { + t.test + } else { + wilcox.test + } + wt <- tryCatch( + test_fun(grp1, grp2, alternative = alternative), + error = function(e) NULL + ) if (!is.null(wt)) { p_label <- sprintf("p = %s", fmt_pval(wt$p.value)) y_max <- max(exp_vs_pred[[predicted_var]], na.rm = TRUE) if (is.finite(y_max)) { - y_pos <- y_max + (y_max - min(exp_vs_pred[[predicted_var]], na.rm = TRUE)) * 0.10 + y_pos <- y_max + + (y_max - min(exp_vs_pred[[predicted_var]], na.rm = TRUE)) * 0.10 p <- p + - annotate("segment", x = 1, xend = 1, y = y_pos * 0.985, yend = y_pos, - color = "#1e2a4a", linewidth = 0.4) + - annotate("segment", x = 2, xend = 2, y = y_pos * 0.985, yend = y_pos, - color = "#1e2a4a", linewidth = 0.4) + - annotate("segment", x = 1, xend = 2, y = y_pos, yend = y_pos, - color = "#1e2a4a", linewidth = 0.4) + - annotate("text", x = 1.5, y = y_pos * 1.03, label = p_label, - size = base_size * 0.3, hjust = 0.5, fontface = "italic", - color = "#1e2a4a") + + annotate( + "segment", + x = 1, + xend = 1, + y = y_pos * 0.985, + yend = y_pos, + color = "#1e2a4a", + linewidth = 0.4 + ) + + annotate( + "segment", + x = 2, + xend = 2, + y = y_pos * 0.985, + yend = y_pos, + color = "#1e2a4a", + linewidth = 0.4 + ) + + annotate( + "segment", + x = 1, + xend = 2, + y = y_pos, + yend = y_pos, + color = "#1e2a4a", + linewidth = 0.4 + ) + + annotate( + "text", + x = 1.5, + y = y_pos * 1.03, + label = p_label, + size = base_size * 0.3, + hjust = 0.5, + fontface = "italic", + color = "#1e2a4a" + ) + coord_cartesian(ylim = c(NA, y_pos * 1.06)) } } } } else if (n_lv > 2) { - test_data <- exp_vs_pred[!is.na(exp_vs_pred[[response_var]]) & - !is.na(exp_vs_pred[[predicted_var]]), ] - if (nrow(test_data) >= 6 && length(unique(test_data[[response_var]])) >= 2) { + test_data <- exp_vs_pred[ + !is.na(exp_vs_pred[[response_var]]) & + !is.na(exp_vs_pred[[predicted_var]]), + ] + if ( + nrow(test_data) >= 6 && length(unique(test_data[[response_var]])) >= 2 + ) { lvls <- levels(exp_vs_pred[[response_var]]) if (n_lv <= 4) { # Pairwise Wilcoxon rank-sum tests (two-sided: no directional hypothesis # among arbitrary groups like PD/RD/TN), BH-adjusted across all pairs. combos <- combn(seq_along(lvls), 2, simplify = FALSE) res_list <- lapply(combos, function(ij) { - g1 <- test_data[[predicted_var]][test_data[[response_var]] == lvls[ij[1]]] - g2 <- test_data[[predicted_var]][test_data[[response_var]] == lvls[ij[2]]] - if (length(g1) < 2 || length(g2) < 2) return(NULL) + g1 <- test_data[[predicted_var]][ + test_data[[response_var]] == lvls[ij[1]] + ] + g2 <- test_data[[predicted_var]][ + test_data[[response_var]] == lvls[ij[2]] + ] + if (length(g1) < 2 || length(g2) < 2) { + return(NULL) + } wt <- tryCatch(wilcox.test(g1, g2), error = function(e) NULL) - if (is.null(wt)) return(NULL) + if (is.null(wt)) { + return(NULL) + } data.frame(i = ij[1], j = ij[2], p = wt$p.value) }) res_df <- do.call(rbind, res_list) @@ -1026,30 +1499,66 @@ plot_response_boxplot <- function(exp_vs_pred, span <- y_max - y_min for (k in seq_len(nrow(res_df))) { y_pos <- y_max + span * (0.06 + 0.07 * k) - x1 <- res_df$i[k]; x2 <- res_df$j[k] + x1 <- res_df$i[k] + x2 <- res_df$j[k] p_label <- sprintf("adj. p = %s", fmt_pval(res_df$p_adj[k])) p <- p + - annotate("segment", x = x1, xend = x1, - y = y_pos - span * 0.012, yend = y_pos, - color = "#1e2a4a", linewidth = 0.4) + - annotate("segment", x = x2, xend = x2, - y = y_pos - span * 0.012, yend = y_pos, - color = "#1e2a4a", linewidth = 0.4) + - annotate("segment", x = x1, xend = x2, y = y_pos, yend = y_pos, - color = "#1e2a4a", linewidth = 0.4) + - annotate("text", x = (x1 + x2) / 2, y = y_pos + span * 0.025, - label = p_label, size = base_size * 0.28, hjust = 0.5, - fontface = "italic", color = "#1e2a4a") + annotate( + "segment", + x = x1, + xend = x1, + y = y_pos - span * 0.012, + yend = y_pos, + color = "#1e2a4a", + linewidth = 0.4 + ) + + annotate( + "segment", + x = x2, + xend = x2, + y = y_pos - span * 0.012, + yend = y_pos, + color = "#1e2a4a", + linewidth = 0.4 + ) + + annotate( + "segment", + x = x1, + xend = x2, + y = y_pos, + yend = y_pos, + color = "#1e2a4a", + linewidth = 0.4 + ) + + annotate( + "text", + x = (x1 + x2) / 2, + y = y_pos + span * 0.025, + label = p_label, + size = base_size * 0.28, + hjust = 0.5, + fontface = "italic", + color = "#1e2a4a" + ) } p <- p + - labs(caption = "Pairwise Wilcoxon rank-sum tests (two-sided), BH-adjusted p-values") + - coord_cartesian(ylim = c(NA, y_max + span * (0.06 + 0.07 * (nrow(res_df) + 1)))) + labs( + caption = "Pairwise Wilcoxon rank-sum tests (two-sided), BH-adjusted p-values" + ) + + coord_cartesian( + ylim = c(NA, y_max + span * (0.06 + 0.07 * (nrow(res_df) + 1))) + ) } } } else { # Many groups -- a single global omnibus test (too many brackets to read). - kw <- tryCatch(stats::kruskal.test(test_data[[predicted_var]], test_data[[response_var]]), - error = function(e) NULL) + kw <- tryCatch( + stats::kruskal.test( + test_data[[predicted_var]], + test_data[[response_var]] + ), + error = function(e) NULL + ) if (!is.null(kw) && !is.na(kw$p.value)) { p_label <- sprintf("Kruskal-Wallis p = %s", fmt_pval(kw$p.value)) y_max <- max(test_data[[predicted_var]], na.rm = TRUE) @@ -1057,9 +1566,16 @@ plot_response_boxplot <- function(exp_vs_pred, if (is.finite(y_max) && is.finite(y_min)) { y_pos <- y_max + (y_max - y_min) * 0.08 p <- p + - annotate("text", x = (1 + n_lv) / 2, y = y_pos, label = p_label, - size = base_size * 0.3, hjust = 0.5, fontface = "italic", - color = "#1e2a4a") + + annotate( + "text", + x = (1 + n_lv) / 2, + y = y_pos, + label = p_label, + size = base_size * 0.3, + hjust = 0.5, + fontface = "italic", + color = "#1e2a4a" + ) + coord_cartesian(ylim = c(NA, y_pos * 1.10)) } } @@ -1098,43 +1614,71 @@ plot_response_boxplot <- function(exp_vs_pred, #' } #' #' @export -plot_model_performance <- function(performance_list, - threshold_range = NULL, - base_size = 20, - highlight_threshold = 0.3, - tooltip = TRUE) { - +plot_model_performance <- function( + performance_list, + threshold_range = NULL, + base_size = 20, + highlight_threshold = 0.3, + tooltip = TRUE +) { # Extract performance metrics with safety: skip entries lacking the expected list extract_col <- function(lst, what, col) { vals <- lapply(lst, function(x) { el <- x[[what]] - if (is.null(el)) return(NULL) + if (is.null(el)) { + return(NULL) + } # Training output is a named vector (unlist(cor.test(...))), while the # built-in demo models use a one-row data.frame -- support both. if (is.data.frame(el)) { - if (!(col %in% colnames(el))) return(NULL) + if (!(col %in% colnames(el))) { + return(NULL) + } el[[col]][1] } else { - if (is.null(names(el)) || !(col %in% names(el))) return(NULL) + if (is.null(names(el)) || !(col %in% names(el))) { + return(NULL) + } el[[col]] } }) vals <- vals[!sapply(vals, is.null)] - if (length(vals) == 0) stop("No performance metrics found in performance_list (missing ", what, ").") + if (length(vals) == 0) { + cli::cli_abort( + "No performance metrics found in performance_list (missing {.field {what}})." + ) + } unlist(vals) } - cor_scRNA <- extract_col(performance_list, "performance_in_scRNA", "estimate.cor") - cor_bulk <- extract_col(performance_list, "performance_in_bulk", "estimate.cor") - cor_pseudo <- extract_col(performance_list, "performance_in_pseudo_bulk", "estimate.cor") + cor_scRNA <- extract_col( + performance_list, + "performance_in_scRNA", + "estimate.cor" + ) + cor_bulk <- extract_col( + performance_list, + "performance_in_bulk", + "estimate.cor" + ) + cor_pseudo <- extract_col( + performance_list, + "performance_in_pseudo_bulk", + "estimate.cor" + ) # Threshold grid: by default extend past 0.6 whenever any model's correlation # exceeds it, so the curve keeps dropping to 0 instead of being cut off # mid-air. Round the upper end up to 2 decimals. if (is.null(threshold_range)) { all_cors <- c(cor_scRNA, cor_bulk, cor_pseudo) - hi <- suppressWarnings(max(0.6, ceiling(max(all_cors, na.rm = TRUE) * 100) / 100)) - if (!is.finite(hi) || hi <= 0.1) hi <- 0.6 + hi <- suppressWarnings(max( + 0.6, + ceiling(max(all_cors, na.rm = TRUE) * 100) / 100 + )) + if (!is.finite(hi) || hi <= 0.1) { + hi <- 0.6 + } threshold_range <- seq(0.1, hi, 0.01) } @@ -1144,48 +1688,83 @@ plot_model_performance <- function(performance_list, df2plot <- rbind( data.frame( - drugProp = sapply(threshold_range, function(x) sum(cor_scRNA > x) / n_models), + drugProp = sapply(threshold_range, function(x) { + sum(cor_scRNA > x) / n_models + }), dataused = "scRNA-seq", Predictability = threshold_range ), data.frame( - drugProp = sapply(threshold_range, function(x) sum(cor_bulk > x) / n_models), + drugProp = sapply(threshold_range, function(x) { + sum(cor_bulk > x) / n_models + }), dataused = "bulk", Predictability = threshold_range ), data.frame( - drugProp = sapply(threshold_range, function(x) sum(cor_pseudo > x) / n_models), + drugProp = sapply(threshold_range, function(x) { + sum(cor_pseudo > x) / n_models + }), dataused = "pseudo-bulk", Predictability = threshold_range ) ) - df2plot$dataused <- factor(df2plot$dataused, - levels = c("scRNA-seq", "pseudo-bulk", "bulk")) + df2plot$dataused <- factor( + df2plot$dataused, + levels = c("scRNA-seq", "pseudo-bulk", "bulk") + ) - dataset_colors <- c("scRNA-seq" = "#2E86AB", "pseudo-bulk" = "#27AE60", - "bulk" = "#E67E22") + dataset_colors <- c( + "scRNA-seq" = "#2E86AB", + "pseudo-bulk" = "#27AE60", + "bulk" = "#E67E22" + ) # Tooltip for ggiraph interactivity. tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) - df2plot$tooltip_text <- sprintf("Dataset: %s\nThreshold: %.2f\nProportion: %.2f", - df2plot$dataused, df2plot$Predictability, - df2plot$drugProp) + df2plot$tooltip_text <- sprintf( + "Dataset: %s\nThreshold: %.2f\nProportion: %.2f", + df2plot$dataused, + df2plot$Predictability, + df2plot$drugProp + ) df2plot$data_id <- paste0("perf_", seq_len(nrow(df2plot))) - p <- ggplot(df2plot, aes(x = Predictability, y = drugProp, color = dataused)) + - geom_vline(xintercept = highlight_threshold, linetype = "dashed", - color = "#C13232", alpha = 0.5, linewidth = 0.4) + + p <- ggplot( + df2plot, + aes(x = Predictability, y = drugProp, color = dataused) + ) + + geom_vline( + xintercept = highlight_threshold, + linetype = "dashed", + color = "#C13232", + alpha = 0.5, + linewidth = 0.4 + ) + geom_line(linewidth = 0.9) + - { if (tt_ok) ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), size = 1.8, alpha = 0.85) - else geom_point(size = 1.8, alpha = 0.85) } + + { + if (tt_ok) { + ggiraph::geom_point_interactive( + aes(tooltip = tooltip_text, data_id = data_id), + size = 1.8, + alpha = 0.85 + ) + } else { + geom_point(size = 1.8, alpha = 0.85) + } + } + scale_color_manual(values = dataset_colors) + theme_perception(base_size = base_size) + - labs(y = "Proportion of Drugs", color = "Validation Dataset", - x = "Predictability (Pearson Correlation)") + - theme(legend.position = "top", - legend.box = "horizontal", - legend.box.spacing = unit(8, "pt")) + labs( + y = "Proportion of Drugs", + color = "Validation Dataset", + x = "Predictability (Pearson Correlation)" + ) + + theme( + legend.position = "top", + legend.box = "horizontal", + legend.box.spacing = unit(8, "pt") + ) return(p) } @@ -1220,15 +1799,20 @@ plot_model_performance <- function(performance_list, #' @export plot_model_roc <- function(performance_list, base_size = 13) { if (!requireNamespace("pROC", quietly = TRUE)) { - stop("Package 'pROC' is required for ROC computation. Install with: install.packages('pROC')") + cli::cli_abort(c( + "Package {.pkg pROC} is required for ROC computation.", + "i" = "Install with {.run install.packages('pROC')}." + )) } if (is.null(names(performance_list))) { performance_list <- setNames(list(performance_list), "model") } - ds_map <- c(pred_gt_bulk = "bulk", - pred_gt_mscRNA = "pseudo-bulk", - pred_gt_scRNA = "single-cell") + ds_map <- c( + pred_gt_bulk = "bulk", + pred_gt_mscRNA = "pseudo-bulk", + pred_gt_scRNA = "single-cell" + ) # Per-drug collection. A drug is only dropped when NONE of its three # validation datasets can produce a curve; the reason is recorded (with @@ -1237,29 +1821,45 @@ plot_model_roc <- function(performance_list, base_size = 13) { curve_rows <- lapply(names(performance_list), function(d) { m <- performance_list[[d]] if (is.null(m$predVSgroundTruth)) { - dropped_reasons[[d]] <<- "no prediction-vs-observed data stored in the model" + dropped_reasons[[ + d + ]] <<- "no prediction-vs-observed data stored in the model" return(NULL) } ds_out <- lapply(names(ds_map), function(k) { df <- m$predVSgroundTruth[[k]] if (is.null(df) || nrow(df) < 6) { - return(list(rows = NULL, - why = sprintf("%s: %d rows (<6 needed)", k, - if (is.null(df)) 0L else nrow(df)))) + return(list( + rows = NULL, + why = sprintf( + "%s: %d rows (<6 needed)", + k, + if (is.null(df)) 0L else nrow(df) + ) + )) } if (!"Observed" %in% colnames(df)) { - return(list(rows = NULL, why = sprintf("%s: missing 'Observed' column", k))) + return(list( + rows = NULL, + why = sprintf("%s: missing 'Observed' column", k) + )) } pred_col <- setdiff(colnames(df), "Observed")[1] if (is.na(pred_col)) { return(list(rows = NULL, why = sprintf("%s: no prediction column", k))) } - obs <- as.numeric(df[["Observed"]]) + obs <- as.numeric(df[["Observed"]]) pred <- as.numeric(df[[pred_col]]) keep <- !is.na(obs) & !is.na(pred) if (sum(keep) < 4) { - return(list(rows = NULL, - why = sprintf("%s: only %d valid observed-vs-predicted pairs", k, sum(keep)))) + return(list( + rows = NULL, + why = sprintf( + "%s: only %d valid observed-vs-predicted pairs", + k, + sum(keep) + ) + )) } # Top vs bottom 50% BY RANK (the paper's convention, Extended Data # Fig. 4C). ties.method="first" breaks ties by position: a value-based @@ -1268,28 +1868,55 @@ plot_model_roc <- function(performance_list, base_size = 13) { # into a single class and makes the ROC impossible. First-tie ranks are # always 1..n, so the median split always yields two balanced classes. if (length(unique(obs[keep])) < 2) { - return(list(rows = NULL, - why = sprintf("%s: all %d observed values are identical (no distinct split)", k, sum(keep)))) + return(list( + rows = NULL, + why = sprintf( + "%s: all %d observed values are identical (no distinct split)", + k, + sum(keep) + ) + )) } rnk <- rank(obs[keep], ties.method = "first") lab <- ifelse(rnk > stats::median(rnk), "Resistant", "Sensitive") rocobj <- tryCatch( - pROC::roc(factor(lab, levels = c("Sensitive", "Resistant")), - pred[keep], quiet = TRUE), - error = function(e) NULL) + pROC::roc( + factor(lab, levels = c("Sensitive", "Resistant")), + pred[keep], + quiet = TRUE + ), + error = function(e) NULL + ) if (is.null(rocobj)) { - return(list(rows = NULL, why = sprintf("%s: ROC computation failed", k))) + return(list( + rows = NULL, + why = sprintf("%s: ROC computation failed", k) + )) } a <- as.numeric(pROC::auc(rocobj)) - co <- as.data.frame(pROC::coords(rocobj, x = "all", - ret = c("specificity", "sensitivity"), - transpose = FALSE)) - list(rows = data.frame(fpr = 1 - co$specificity, tpr = co$sensitivity, - Dataset = unname(ds_map[[k]]), Drug = d, AUC = a, - stringsAsFactors = FALSE), - why = NULL) + co <- as.data.frame(pROC::coords( + rocobj, + x = "all", + ret = c("specificity", "sensitivity"), + transpose = FALSE + )) + list( + rows = data.frame( + fpr = 1 - co$specificity, + tpr = co$sensitivity, + Dataset = unname(ds_map[[k]]), + Drug = d, + AUC = a, + stringsAsFactors = FALSE + ), + why = NULL + ) }) - reasons <- vapply(ds_out, function(x) if (is.null(x$why)) "" else x$why, character(1)) + reasons <- vapply( + ds_out, + function(x) if (is.null(x$why)) "" else x$why, + character(1) + ) reasons <- reasons[nzchar(reasons)] ok_rows <- do.call(rbind, lapply(ds_out, function(x) x$rows)) if (is.null(ok_rows)) { @@ -1304,21 +1931,38 @@ plot_model_roc <- function(performance_list, base_size = 13) { dropped_drugs <- names(curve_rows)[vapply(curve_rows, is.null, logical(1))] curve_rows <- curve_rows[!vapply(curve_rows, is.null, logical(1))] if (length(curve_rows) == 0) { - stop("No prediction-vs-observed data available to compute validation ROC.") + cli::cli_abort( + "No prediction-vs-observed data available to compute validation ROC." + ) } df <- do.call(rbind, curve_rows) - df$Dataset <- factor(df$Dataset, levels = c("bulk", "pseudo-bulk", "single-cell")) + df$Dataset <- factor( + df$Dataset, + levels = c("bulk", "pseudo-bulk", "single-cell") + ) - auc_lab <- do.call(rbind, lapply( - split(df, interaction(df$Drug, df$Dataset, drop = TRUE)), function(sub) { - data.frame(Drug = unique(sub$Drug), Dataset = unique(sub$Dataset), - AUC = unique(sub$AUC), stringsAsFactors = FALSE) - })) + auc_lab <- do.call( + rbind, + lapply( + split(df, interaction(df$Drug, df$Dataset, drop = TRUE)), + function(sub) { + data.frame( + Drug = unique(sub$Drug), + Dataset = unique(sub$Dataset), + AUC = unique(sub$AUC), + stringsAsFactors = FALSE + ) + } + ) + ) rownames(auc_lab) <- NULL - dataset_colors <- c("bulk" = "#E67E22", "pseudo-bulk" = "#27AE60", - "single-cell" = "#2E86AB") - ds_levels <- c("bulk", "pseudo-bulk", "single-cell") + dataset_colors <- c( + "bulk" = "#E67E22", + "pseudo-bulk" = "#27AE60", + "single-cell" = "#2E86AB" + ) + ds_levels <- c("bulk", "pseudo-bulk", "single-cell") # 2-column layout (5+ drugs) gives narrow panels: the full dataset names # collide with the AUC values there. Use compact but still readable labels -- @@ -1326,92 +1970,157 @@ plot_model_roc <- function(performance_list, base_size = 13) { n_drugs_total <- length(unique(df$Drug)) short_mode <- n_drugs_total > 4 if (short_mode) { - ds_labels <- c("bulk" = "Bulk", "pseudo-bulk" = "Pseudo", "single-cell" = "SC") + ds_labels <- c( + "bulk" = "Bulk", + "pseudo-bulk" = "Pseudo", + "single-cell" = "SC" + ) label_size <- base_size * 0.23 value_size <- base_size * 0.26 } else { - ds_labels <- c("bulk" = "Bulk", "pseudo-bulk" = "Pseudo-bulk", - "single-cell" = "Single-cell") + ds_labels <- c( + "bulk" = "Bulk", + "pseudo-bulk" = "Pseudo-bulk", + "single-cell" = "Single-cell" + ) label_size <- base_size * 0.28 value_size <- base_size * 0.30 } # ---- AUC card geometry parameters (data coordinates, with coord_cartesian) ---- - n_ds <- length(ds_levels) - box_x0 <- 0.60; box_x1 <- 1.16 + n_ds <- length(ds_levels) + box_x0 <- 0.60 + box_x1 <- 1.16 header_h <- 0.055 - row_h <- 0.085 - pad_bot <- 0.02 - box_y1 <- 0.33 - box_y0 <- box_y1 - header_h - n_ds * row_h - pad_bot + row_h <- 0.085 + pad_bot <- 0.02 + box_y1 <- 0.33 + box_y0 <- box_y1 - header_h - n_ds * row_h - pad_bot - swatch_x <- box_x0 + 0.07 # square marker center (plotly-safe color block) - label_x <- box_x0 + 0.20 # all three labels left-aligned at this column - value_x <- box_x1 - 0.14 # values right-aligned, comfortable inside the box + swatch_x <- box_x0 + 0.07 # square marker center (plotly-safe color block) + label_x <- box_x0 + 0.20 # all three labels left-aligned at this column + value_x <- box_x1 - 0.14 # values right-aligned, comfortable inside the box box_bg <- data.frame(Drug = unique(df$Drug), stringsAsFactors = FALSE) - auc_box <- do.call(rbind, lapply(unique(df$Drug), function(drg) { - do.call(rbind, lapply(seq_along(ds_levels), function(i) { - ds <- ds_levels[i] - y_mid <- box_y1 - header_h - (i - 0.5) * row_h - sub <- auc_lab[auc_lab$Drug == drg & auc_lab$Dataset == ds, ] - data.frame(Drug = drg, Dataset = ds, y_mid = y_mid, - Label = ds_labels[[ds]], - AUC = if (nrow(sub)) sub$AUC[1] else NA_real_, - stringsAsFactors = FALSE) - })) - })) + auc_box <- do.call( + rbind, + lapply(unique(df$Drug), function(drg) { + do.call( + rbind, + lapply(seq_along(ds_levels), function(i) { + ds <- ds_levels[i] + y_mid <- box_y1 - header_h - (i - 0.5) * row_h + sub <- auc_lab[auc_lab$Drug == drg & auc_lab$Dataset == ds, ] + data.frame( + Drug = drg, + Dataset = ds, + y_mid = y_mid, + Label = ds_labels[[ds]], + AUC = if (nrow(sub)) sub$AUC[1] else NA_real_, + stringsAsFactors = FALSE + ) + }) + ) + }) + ) p <- ggplot(df, aes(x = fpr, y = tpr, color = Dataset)) + - geom_abline(slope = 1, intercept = 0, linetype = "dashed", - color = "grey55", linewidth = 0.35) + + geom_abline( + slope = 1, + intercept = 0, + linetype = "dashed", + color = "grey55", + linewidth = 0.35 + ) + geom_line(linewidth = 0.9) + # shadow layer -- constants passed directly (not aes()) so ggplot2 does not # warn about recycling scalar aesthetics across the per-drug rows. - geom_rect(data = box_bg, - xmin = box_x0 + 0.006, xmax = box_x1 + 0.006, - ymin = box_y0 - 0.006, ymax = box_y1 - 0.006, - fill = "grey70", color = NA, alpha = 0.30, - inherit.aes = FALSE) + + geom_rect( + data = box_bg, + xmin = box_x0 + 0.006, + xmax = box_x1 + 0.006, + ymin = box_y0 - 0.006, + ymax = box_y1 - 0.006, + fill = "grey70", + color = NA, + alpha = 0.30, + inherit.aes = FALSE + ) + # card background - geom_rect(data = box_bg, - xmin = box_x0, xmax = box_x1, ymin = box_y0, ymax = box_y1, - fill = "white", color = "#d7dbe4", linewidth = 0.4, - inherit.aes = FALSE) + + geom_rect( + data = box_bg, + xmin = box_x0, + xmax = box_x1, + ymin = box_y0, + ymax = box_y1, + fill = "white", + color = "#d7dbe4", + linewidth = 0.4, + inherit.aes = FALSE + ) + # title "AUC" + separator line - geom_text(data = box_bg, - x = (box_x0 + box_x1) / 2, y = box_y1 - header_h / 2, - label = "AUC", - inherit.aes = FALSE, size = base_size * 0.28, - fontface = "bold", color = "grey35") + - geom_segment(data = box_bg, - x = box_x0 + 0.02, xend = box_x1 - 0.02, - y = box_y1 - header_h, yend = box_y1 - header_h, - inherit.aes = FALSE, color = "grey85", linewidth = 0.3) + + geom_text( + data = box_bg, + x = (box_x0 + box_x1) / 2, + y = box_y1 - header_h / 2, + label = "AUC", + inherit.aes = FALSE, + size = base_size * 0.28, + fontface = "bold", + color = "grey35" + ) + + geom_segment( + data = box_bg, + x = box_x0 + 0.02, + xend = box_x1 - 0.02, + y = box_y1 - header_h, + yend = box_y1 - header_h, + inherit.aes = FALSE, + color = "grey85", + linewidth = 0.3 + ) + # each row: colored square marker + left-aligned dataset name + right- # aligned value. Marker uses geom_point (renders reliably in plotly, unlike # a fill-mapped geom_rect which can spread under the text). - geom_point(data = auc_box, - aes(x = swatch_x, y = y_mid, color = Dataset), - shape = 15, size = 3.2, inherit.aes = FALSE, - show.legend = FALSE) + - geom_text(data = auc_box, - aes(x = label_x, y = y_mid, label = Label), - inherit.aes = FALSE, hjust = 0, size = label_size, - color = "grey25") + - geom_text(data = auc_box, - aes(x = value_x, y = y_mid, label = sprintf("%.2f", AUC)), - inherit.aes = FALSE, hjust = 1, size = value_size, - fontface = "bold", color = "grey20") + + geom_point( + data = auc_box, + aes(x = swatch_x, y = y_mid, color = Dataset), + shape = 15, + size = 3.2, + inherit.aes = FALSE, + show.legend = FALSE + ) + + geom_text( + data = auc_box, + aes(x = label_x, y = y_mid, label = Label), + inherit.aes = FALSE, + hjust = 0, + size = label_size, + color = "grey25" + ) + + geom_text( + data = auc_box, + aes(x = value_x, y = y_mid, label = sprintf("%.2f", AUC)), + inherit.aes = FALSE, + hjust = 1, + size = value_size, + fontface = "bold", + color = "grey20" + ) + scale_color_manual(values = dataset_colors) + coord_cartesian(xlim = c(0, 1.2), ylim = c(0, 1)) + theme_perception(base_size = base_size) + - labs(x = "1 - Specificity (FPR)", y = "Sensitivity (TPR)", - color = "Validation Dataset") + - theme(legend.position = "top", - legend.box = "horizontal", - legend.box.spacing = unit(8, "pt")) + labs( + x = "1 - Specificity (FPR)", + y = "Sensitivity (TPR)", + color = "Validation Dataset" + ) + + theme( + legend.position = "top", + legend.box = "horizontal", + legend.box.spacing = unit(8, "pt") + ) # Multiple drugs: stack one panel per drug (full width) instead of squeezing # them into a single row -- narrow panels overlap the AUC box, strip labels @@ -1421,16 +2130,18 @@ plot_model_roc <- function(performance_list, base_size = 13) { n_drugs <- length(unique(df$Drug)) if (n_drugs > 1) { roc_ncol <- if (n_drugs <= 4) 1 else 2 - p <- p + facet_wrap(~ Drug, ncol = roc_ncol, strip.position = "top") + p <- p + facet_wrap(~Drug, ncol = roc_ncol, strip.position = "top") } # Surface drugs that could not produce a ROC so the app can warn the user # (otherwise a missing panel looks like a rendering bug). if (length(dropped_drugs) > 0) { why <- dropped_reasons[dropped_drugs] - warning("Validation ROC skipped for: ", - paste(names(why), paste0("(", why, ")"), collapse = "; "), - ". Data-dependent: held-out cell lines lack sufficient, varied drug responses.") + warning( + "Validation ROC skipped for: ", + paste(names(why), paste0("(", why, ")"), collapse = "; "), + ". Data-dependent: held-out cell lines lack sufficient, varied drug responses." + ) attr(p, "dropped_drugs") <- dropped_drugs attr(p, "dropped_reasons") <- why } @@ -1470,26 +2181,37 @@ plot_model_roc <- function(performance_list, base_size = 13) { #' } #' #' @export -plot_seurat_clustering <- function(method = c("umap", "tsne"), - expression_matrix, - min_cells = 3, - min_features = 200, - nfeatures = 2000, - dims = 10, - resolution = 0.8, - seed = 1) { - - method <- match.arg(method) +plot_seurat_clustering <- function( + method = c("umap", "tsne"), + expression_matrix, + min_cells = 3, + min_features = 200, + nfeatures = 2000, + dims = 10, + resolution = 0.8, + seed = 1 +) { + method <- rlang::arg_match(method) if (!requireNamespace("Seurat", quietly = TRUE)) { - stop("Package 'Seurat' is required. Install with: install.packages('Seurat')") + cli::cli_abort(c( + "Package {.pkg Seurat} is required.", + "i" = "Install with {.run install.packages('Seurat')}." + )) } # Shared pipeline (also used by annotate_clones) includes the PCA-dimension # safeguard for small datasets. - so <- run_seurat_pipeline(expression_matrix, method, - min_cells, min_features, nfeatures, - dims, resolution, seed) + so <- run_seurat_pipeline( + expression_matrix, + method, + min_cells, + min_features, + nfeatures, + dims, + resolution, + seed + ) return(list( seurat_object = so, @@ -1531,43 +2253,70 @@ plot_seurat_clustering <- function(method = c("umap", "tsne"), #' } #' #' @export -plot_patient_response_panel <- function(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 <- function( + clone_distribution, + clone_viability, + exp_vs_pred, + response_col = "response", + viability_col = "comb_viability", + predicted_col = "predicted_viability", + weights_col = "weights", + layout_matrix = NULL +) { if (!requireNamespace("gridExtra", quietly = TRUE)) { - stop("Package 'gridExtra' is required. Install with: install.packages('gridExtra')") + cli::cli_abort(c( + "Package {.pkg gridExtra} is required.", + "i" = "Install with {.run install.packages('gridExtra')}." + )) } # Panel 1: Clone distribution p1 <- plot_clone_distribution(clone_distribution, response_var = response_col) # Panel 2: Clone-level viability (uses viability_col from clone_viability data) - p2 <- plot_clone_viability(clone_viability, viability_var = viability_col, - weights_var = weights_col, response_var = response_col) + p2 <- plot_clone_viability( + clone_viability, + viability_var = viability_col, + weights_var = weights_col, + response_var = response_col + ) # Panel 3: Response boxplot (uses predicted_col from exp_vs_pred data) - p3 <- plot_response_boxplot(exp_vs_pred, response_var = response_col, - predicted_var = predicted_col) + p3 <- plot_response_boxplot( + exp_vs_pred, + response_var = response_col, + predicted_var = predicted_col + ) # Panel 4: ROC curve -- auto-disable smoothing for small samples + safety net - n_pts <- sum(!is.na(exp_vs_pred[[response_col]]) & !is.na(exp_vs_pred[[predicted_col]])) - p4 <- tryCatch({ - plot_roc_curve(response = exp_vs_pred[[response_col]], - predictor = exp_vs_pred[[predicted_col]], - smooth_curve = n_pts >= 10) - }, error = function(e) { - # Last-resort fallback: render an empty placeholder ggplot with error message - ggplot(data.frame(x = 0, y = 0, label = paste("ROC unavailable:", e$message))) + - geom_text(aes(x, y, label = label), hjust = 0.5, vjust = 0.5, size = 3) + - theme_void() + - labs(title = "ROC Curve (unavailable)") - }) + n_pts <- sum( + !is.na(exp_vs_pred[[response_col]]) & !is.na(exp_vs_pred[[predicted_col]]) + ) + p4 <- tryCatch( + { + plot_roc_curve( + response = exp_vs_pred[[response_col]], + predictor = exp_vs_pred[[predicted_col]], + smooth_curve = n_pts >= 10 + ) + }, + error = function(e) { + # Last-resort fallback: render an empty placeholder ggplot with error message + ggplot(data.frame( + x = 0, + y = 0, + label = paste("ROC unavailable:", e$message) + )) + + geom_text( + aes(x, y, label = label), + hjust = 0.5, + vjust = 0.5, + size = 3 + ) + + theme_void() + + labs(title = "ROC Curve (unavailable)") + } + ) # Arrange panels if (is.null(layout_matrix)) { @@ -1579,7 +2328,13 @@ plot_patient_response_panel <- function(clone_distribution, ) } - panel <- gridExtra::grid.arrange(p1, p2, p3, p4, layout_matrix = layout_matrix) + panel <- gridExtra::grid.arrange( + p1, + p2, + p3, + p4, + layout_matrix = layout_matrix + ) return(panel) } @@ -1615,24 +2370,36 @@ plot_patient_response_panel <- function(clone_distribution, #' } #' #' @export -plot_tsne_biomarker_viability <- function(tsne_data, - biomarker_var = "biomarker_scaled", - viability_var = "viability_scaled", - biomarker_label = "Biomarker Exp", - viability_label = "Drug Viability", - nrow = 1, - base_size = 8) { - +plot_tsne_biomarker_viability <- function( + tsne_data, + biomarker_var = "biomarker_scaled", + viability_var = "viability_scaled", + biomarker_label = "Biomarker Exp", + viability_label = "Drug Viability", + nrow = 1, + base_size = 8 +) { if (!requireNamespace("gridExtra", quietly = TRUE)) { - stop("Package 'gridExtra' is required. Install with: install.packages('gridExtra')") + cli::cli_abort(c( + "Package {.pkg gridExtra} is required.", + "i" = "Install with {.run install.packages('gridExtra')}." + )) } - p1 <- plot_tsne_response(tsne_data, color_var = biomarker_var, - color_label = biomarker_label, base_size = base_size, - colors = c("#e0e0e0", "#c13232")) - p2 <- plot_tsne_response(tsne_data, color_var = viability_var, - color_label = viability_label, base_size = base_size, - palette = "viridis") + p1 <- plot_tsne_response( + tsne_data, + color_var = biomarker_var, + color_label = biomarker_label, + base_size = base_size, + colors = c("#e0e0e0", "#c13232") + ) + p2 <- plot_tsne_response( + tsne_data, + color_var = viability_var, + color_label = viability_label, + base_size = base_size, + palette = "viridis" + ) combined <- gridExtra::grid.arrange(p1, p2, nrow = nrow) @@ -1668,18 +2435,35 @@ plot_tsne_biomarker_viability <- function(tsne_data, #' } #' #' @export -export_plot_cairo <- function(file, plot, format = "png", - width = 7, height = 5, res = 600, - draw_fun = NULL) { +export_plot_cairo <- function( + file, + plot, + format = "png", + width = 7, + height = 5, + res = 600, + draw_fun = NULL +) { format <- tolower(format) has_cairo <- capabilities("cairo") if (format == "png") { if (has_cairo) { - grDevices::png(file, width = width, height = height, - units = "in", res = max(res, 96), type = "cairo") + grDevices::png( + file, + width = width, + height = height, + units = "in", + res = max(res, 96), + type = "cairo" + ) } else { - grDevices::png(file, width = width, height = height, - units = "in", res = max(res, 96)) + grDevices::png( + file, + width = width, + height = height, + units = "in", + res = max(res, 96) + ) } } else if (format == "svg") { grDevices::svg(file, width = width, height = height, antialias = "default") diff --git a/R/predict.R b/R/predict.R index 5862aea..4b03849 100644 --- a/R/predict.R +++ b/R/predict.R @@ -50,23 +50,27 @@ NULL #' #' @export predict_drugs <- function(model_list, expr) { - # Normalize input: wrap a single model object (one with a $model element) # into a named list so the rest of the function treats both cases uniformly. if (!is.null(model_list$model)) { drug_name <- attr(model_list, "drug_name") - if (is.null(drug_name)) drug_name <- "drug1" + if (is.null(drug_name)) { + drug_name <- "drug1" + } model_list <- setNames(list(model_list), drug_name) } if (!is.list(model_list) || is.null(names(model_list))) { - stop("model_list must be a named list of model objects (each with $model element), ", - "or a single model object.") + cli::cli_abort( + "model_list must be a named list of model objects (each with a {.field model} element), or a single model object." + ) } # Validate expression matrix if (!is.matrix(expr) && !is.data.frame(expr)) { - stop("expr must be a matrix or data frame with genes as rows and samples as columns.") + cli::cli_abort( + "expr must be a matrix or data frame with genes as rows and samples as columns." + ) } # Predict for each drug @@ -94,7 +98,7 @@ predict_drugs <- function(model_list, expr) { viab_raw <- viab_raw[!sapply(viab_raw, is.null)] if (length(viab_raw) == 0) { - stop("All model predictions failed.") + cli::cli_abort("All model predictions failed.") } do.call(cbind, viab_raw) @@ -116,10 +120,10 @@ predict_drugs <- function(model_list, expr) { #' #' @keywords internal viability_from_model_internal <- function(drug_name, model, dataset) { - if (is.null(model$coefnames) || length(model$coefnames) == 0) { - stop("Model for drug '", drug_name, "' has no feature names ($coefnames is NULL/empty). ", - "Cannot subset the expression matrix for prediction.") + cli::cli_abort( + "Model for drug {.val {drug_name}} has no feature names ({.field coefnames} is NULL/empty). Cannot subset the expression matrix for prediction." + ) } # Step 1: Try exact match of model features to expression matrix rows @@ -146,19 +150,29 @@ viability_from_model_internal <- function(drug_name, model, dataset) { if (length(missing_features) > 0) { frac_missing <- length(missing_features) / length(model$coefnames) if (frac_missing > 0.5) { - stop(sprintf( - "Model features not found in expression matrix for drug '%s': %d / %d features missing (%.0f%%).\nThis usually means gene name formats differ between training and prediction data, or the wrong expression matrix was provided.", - drug_name, length(missing_features), length(model$coefnames), 100 * frac_missing)) + cli::cli_abort( + c( + "Model features not found in expression matrix for drug {.val {drug_name}}: {length(missing_features)} / {length(model$coefnames)} features missing ({round(100 * frac_missing)}%).", + "i" = "This usually means gene name formats differ between training and prediction data, or the wrong expression matrix was provided." + ) + ) } # Impute the remaining features with the neutral rank-normalized value (0.5, # the median rank). This keeps predictions unbiased when a handful of genes # were filtered out during scRNA QC / gene-set coverage differences. warning(sprintf( "Imputing %d / %d missing model features for drug '%s' with the median rank value (0.5): %s", - length(missing_features), length(model$coefnames), drug_name, - paste(head(missing_features, 10), collapse = ", "))) - impute_mat <- matrix(0.5, nrow = length(missing_features), ncol = ncol(dataset), - dimnames = list(missing_features, colnames(dataset))) + length(missing_features), + length(model$coefnames), + drug_name, + paste(head(missing_features, 10), collapse = ", ") + )) + impute_mat <- matrix( + 0.5, + nrow = length(missing_features), + ncol = ncol(dataset), + dimnames = list(missing_features, colnames(dataset)) + ) dataset <- rbind(as.matrix(dataset), impute_mat) feature_match <- match(model$coefnames, rownames(dataset)) } @@ -226,14 +240,22 @@ viability_from_model_internal <- function(drug_name, model, dataset) { #' } #' #' @export -predict_patients <- function(clone_pred, prepared_data, clone_counts = NULL, - mode = "weighted_max", zscore = TRUE) { - +predict_patients <- function( + clone_pred, + prepared_data, + clone_counts = NULL, + mode = "weighted_max", + zscore = TRUE +) { # Determine input mode: simple (prepared_data is a list) vs legacy (prepared_data is clone_counts) # Accept both clone_viability_template and clone_viability_df_template for backward compatibility # Also accept any list with clone_counts + any template-like element - template_names <- c("clone_viability_template", "clone_viability_df_template", - "template", "viability_template") + template_names <- c( + "clone_viability_template", + "clone_viability_df_template", + "template", + "viability_template" + ) has_counts <- "clone_counts" %in% names(prepared_data) if (is.list(prepared_data) && !is.data.frame(prepared_data) && has_counts) { @@ -242,13 +264,19 @@ predict_patients <- function(clone_pred, prepared_data, clone_counts = NULL, if (is.na(template_name)) { # No template found but has counts - try to build template from clone_pred rownames - message(" [predict_patients] No template found, building from clone_pred rownames...") + cli::cli_alert_info( + "No template found, building from {.field clone_pred} rownames..." + ) clone_col_names <- rownames(clone_pred) if (length(clone_col_names) > 0 && all(grepl("@@", clone_col_names))) { clone_template <- parse_clone_keys(clone_col_names) } else { - stop("Cannot build template: clone_pred rownames do not follow Patient@@Clone format.\n", - " clone_pred rownames: ", paste(head(rownames(clone_pred), 5), collapse = ", ")) + cli::cli_abort( + c( + "Cannot build template: clone_pred rownames do not follow the {.val Patient@@Clone} format.", + "x" = "clone_pred rownames: {paste(head(rownames(clone_pred), 5), collapse = ', ')}" + ) + ) } } else { clone_template <- prepared_data[[template_name]] @@ -266,35 +294,45 @@ predict_patients <- function(clone_pred, prepared_data, clone_counts = NULL, clone_viability_matrix <- clone_pred clone_counts <- prepared_data } else { - stop("prepared_data must be either:\n", - " 1. A list from prepare_data() (with clone_counts)\n", - " 2. A data frame of clone_counts (legacy mode, requires clone_pred to be clone_viability_matrix)\n", - "\nDiagnostic info:\n", - " class(prepared_data): ", class(prepared_data)[1], "\n", - " is.list: ", is.list(prepared_data), "\n", - " is.data.frame: ", is.data.frame(prepared_data), "\n", - " names(prepared_data): ", paste(names(prepared_data), collapse = ", "), "\n", - " has clone_counts: ", has_counts, "\n") + cli::cli_abort( + c( + "prepared_data must be either:", + "*" = "A list from prepare_data() (with clone_counts)", + "*" = "A data frame of clone_counts (legacy mode, requires clone_pred to be clone_viability_matrix)", + "i" = "class(prepared_data): {class(prepared_data)[1]}", + "i" = "is.list: {is.list(prepared_data)}", + "i" = "is.data.frame: {is.data.frame(prepared_data)}", + "i" = "names(prepared_data): {paste(names(prepared_data), collapse = ', ')}", + "i" = "has clone_counts: {has_counts}" + ) + ) } # Validate inputs if (!"patient" %in% colnames(clone_viability_matrix)) { - stop("clone_viability_matrix must have a 'patient' column.") + cli::cli_abort("clone_viability_matrix must have a {.field patient} column.") } if (!"clone_id" %in% colnames(clone_viability_matrix)) { - stop("clone_viability_matrix must have a 'clone_id' column.") + cli::cli_abort( + "clone_viability_matrix must have a {.field clone_id} column." + ) } if (!"patients" %in% colnames(clone_counts)) { - stop("clone_counts must have a 'patients' column.") + cli::cli_abort("clone_counts must have a {.field patients} column.") } valid_modes <- c("weighted_average", "min", "max", "weighted_max", "average") if (!mode %in% valid_modes) { - stop("mode must be one of: ", paste(valid_modes, collapse = ", ")) + cli::cli_abort( + "{.arg mode} must be one of: {.val {valid_modes}}" + ) } # Identify drug columns (all columns except patient and clone_id) - drug_cols <- setdiff(colnames(clone_viability_matrix), c("patient", "clone_id")) + drug_cols <- setdiff( + colnames(clone_viability_matrix), + c("patient", "clone_id") + ) n_drugs <- length(drug_cols) # Z-score scale drug columns across patients before aggregation. @@ -307,67 +345,83 @@ predict_patients <- function(clone_pred, prepared_data, clone_counts = NULL, if (zscore) { scale_cols <- setdiff(drug_cols, "comb_viability") if (length(scale_cols) > 0) { - clone_viability_matrix <- zscore_viability(clone_viability_matrix, - cols = scale_cols) + clone_viability_matrix <- zscore_viability( + clone_viability_matrix, + cols = scale_cols + ) } } # Aggregate for each patient - patient_results <- do.call(rbind, lapply(1:nrow(clone_counts), function(x) { - patient_id <- clone_counts$patients[x] - - # Get clone data for this patient - patient_clones <- clone_viability_matrix[ - clone_viability_matrix$patient == patient_id, ] - - if (nrow(patient_clones) == 0) { - # No clone data for this patient - return(setNames(rep(NA, n_drugs), drug_cols)) - } - - # Compute clone weights. Abundance columns are keyed "patient@@clone" (see - # build_clone_counts); fall back to the bare clone id so objects prepared by - # earlier versions keep working. - clone_ids <- patient_clones$clone_id - clone_keys <- paste(patient_id, clone_ids, sep = "@@") - use_keys <- if (all(clone_keys %in% colnames(clone_counts))) clone_keys else clone_ids - total_cells <- sum(clone_counts[x, use_keys], na.rm = TRUE) - if (!is.finite(total_cells) || total_cells == 0) { - return(setNames(rep(NA, n_drugs), drug_cols)) - } - clone_weights <- unlist(clone_counts[x, use_keys] / total_cells) + patient_results <- do.call( + rbind, + lapply(1:nrow(clone_counts), function(x) { + patient_id <- clone_counts$patients[x] + + # Get clone data for this patient + patient_clones <- clone_viability_matrix[ + clone_viability_matrix$patient == patient_id, + ] + + if (nrow(patient_clones) == 0) { + # No clone data for this patient + return(setNames(rep(NA, n_drugs), drug_cols)) + } - # Aggregate based on mode - if (n_drugs == 1) { - # Single drug: use comb_viability column if present, otherwise use drug column - if ("comb_viability" %in% colnames(patient_clones)) { - viability_values <- patient_clones$comb_viability + # Compute clone weights. Abundance columns are keyed "patient@@clone" (see + # build_clone_counts); fall back to the bare clone id so objects prepared by + # earlier versions keep working. + clone_ids <- patient_clones$clone_id + clone_keys <- paste(patient_id, clone_ids, sep = "@@") + use_keys <- if (all(clone_keys %in% colnames(clone_counts))) { + clone_keys } else { - viability_values <- patient_clones[[drug_cols]] + clone_ids } - - result <- switch(mode, - "weighted_average" = sum(viability_values * clone_weights), - "min" = min(viability_values), - "max" = max(viability_values), - "weighted_max" = max(viability_values * clone_weights), - "average" = mean(viability_values) - ) - return(setNames(result, drug_cols)) - } else { - # Multiple drugs: apply aggregation across all drug columns - drug_matrix <- as.matrix(patient_clones[, drug_cols, drop = FALSE]) - - result <- switch(mode, - "weighted_average" = apply(drug_matrix, 2, function(col) sum(col * clone_weights)), - "min" = apply(drug_matrix, 2, function(col) min(col)), - "max" = apply(drug_matrix, 2, function(col) max(col)), - "weighted_max" = apply(drug_matrix, 2, function(col) max(col * clone_weights)), - "average" = apply(drug_matrix, 2, function(col) mean(col)) - ) - return(result) - } - })) + total_cells <- sum(clone_counts[x, use_keys], na.rm = TRUE) + if (!is.finite(total_cells) || total_cells == 0) { + return(setNames(rep(NA, n_drugs), drug_cols)) + } + clone_weights <- unlist(clone_counts[x, use_keys] / total_cells) + + # Aggregate based on mode + if (n_drugs == 1) { + # Single drug: use comb_viability column if present, otherwise use drug column + if ("comb_viability" %in% colnames(patient_clones)) { + viability_values <- patient_clones$comb_viability + } else { + viability_values <- patient_clones[[drug_cols]] + } + + result <- switch( + mode, + "weighted_average" = sum(viability_values * clone_weights), + "min" = min(viability_values), + "max" = max(viability_values), + "weighted_max" = max(viability_values * clone_weights), + "average" = mean(viability_values) + ) + return(setNames(result, drug_cols)) + } else { + # Multiple drugs: apply aggregation across all drug columns + drug_matrix <- as.matrix(patient_clones[, drug_cols, drop = FALSE]) + + result <- switch( + mode, + "weighted_average" = apply(drug_matrix, 2, function(col) { + sum(col * clone_weights) + }), + "min" = apply(drug_matrix, 2, function(col) min(col)), + "max" = apply(drug_matrix, 2, function(col) max(col)), + "weighted_max" = apply(drug_matrix, 2, function(col) { + max(col * clone_weights) + }), + "average" = apply(drug_matrix, 2, function(col) mean(col)) + ) + return(result) + } + }) + ) # Add patient names as row names rownames(patient_results) <- clone_counts$patients @@ -445,14 +499,15 @@ predict_patients <- function(clone_pred, prepared_data, clone_counts = NULL, #' @seealso [predict_drugs()], [predict_patients()], [plot_clone_viability()], #' [zscore_viability()] #' @export -combine_drugs <- function(pred, - patient = NULL, - clone_id = NULL, - combine_rule = c("min", "mean", "max", "median"), - na.rm = TRUE, - include_single_z = FALSE) { - - combine_rule <- match.arg(combine_rule) +combine_drugs <- function( + pred, + patient = NULL, + clone_id = NULL, + combine_rule = c("min", "mean", "max", "median"), + na.rm = TRUE, + include_single_z = FALSE +) { + combine_rule <- rlang::arg_match(combine_rule) # --- 1. Normalise input to a numeric matrix with row names ---------------- if (is.data.frame(pred)) { @@ -461,8 +516,9 @@ combine_drugs <- function(pred, drop_cols <- intersect(df_cols, c("patient", "clone_id", "comb_viability")) pred_mat <- as.matrix(pred[, setdiff(df_cols, drop_cols), drop = FALSE]) if (ncol(pred_mat) == 0) { - stop("No drug columns found in pred. A data.frame input must contain ", - "drug columns in addition to 'patient' / 'clone_id'.") + cli::cli_abort( + "No drug columns found in pred. A data.frame input must contain drug columns in addition to {.field patient} / {.field clone_id}." + ) } if (is.null(patient) && "patient" %in% df_cols) { patient <- as.character(pred$patient) @@ -471,56 +527,76 @@ combine_drugs <- function(pred, clone_id <- as.character(pred$clone_id) } } else if (!is.matrix(pred)) { - stop("pred must be a matrix or data.frame (from predict_drugs()).") + cli::cli_abort( + "pred must be a matrix or data.frame (from {.fn predict_drugs})." + ) } else { pred_mat <- pred } pred_mat <- as.matrix(pred_mat) storage.mode(pred_mat) <- "double" - if (ncol(pred_mat) < 1) stop("pred has zero drug columns.") + if (ncol(pred_mat) < 1) { + cli::cli_abort("pred has zero drug columns.") + } # --- 2. Resolve patient / clone_id --------------------------------------- if (is.null(patient) || is.null(clone_id)) { rn <- rownames(pred_mat) if (is.null(rn) || any(!grepl("@@", rn))) { - stop("pred row names must be canonical PERCEPTION clone keys ", - "(\"patient@@clone_id\"), OR supply both 'patient' and 'clone_id'.") + cli::cli_abort( + c( + "pred row names must be canonical PERCEPTION clone keys ({.val patient@@clone_id}),", + "i" = "or supply both {.arg patient} and {.arg clone_id}." + ) + ) } keys <- parse_clone_keys(rn) - if (is.null(patient)) patient <- keys$patient + if (is.null(patient)) { + patient <- keys$patient + } if (is.null(clone_id)) clone_id <- keys$clone_id } if (length(patient) != nrow(pred_mat) || length(clone_id) != nrow(pred_mat)) { - stop("patient and clone_id lengths (", length(patient), "/", length(clone_id), - ") must equal nrow(pred) (", nrow(pred_mat), ").") + cli::cli_abort( + "{.arg patient} and {.arg clone_id} lengths ({length(patient)}/{length(clone_id)}) must equal {.code nrow(pred)} ({nrow(pred_mat)})." + ) } # --- 3. Z-score each drug column across all clones ------------------------ z_mat <- pred_mat for (j in seq_len(ncol(pred_mat))) { col <- pred_mat[, j] - s <- stats::sd(col, na.rm = TRUE) - z_mat[, j] <- if (is.na(s) || s == 0) rep(0, length(col)) else + s <- stats::sd(col, na.rm = TRUE) + z_mat[, j] <- if (is.na(s) || s == 0) { + rep(0, length(col)) + } else { as.numeric(scale(col)) + } } # --- 4. Per-clone combination --------------------------------------------- - agg <- switch(combine_rule, - "min" = function(x, ...) apply(x, 1, min, na.rm = na.rm), - "mean" = function(x, ...) rowMeans(x, na.rm = na.rm), - "max" = function(x, ...) apply(x, 1, max, na.rm = na.rm), - "median" = function(x, ...) apply(x, 1, stats::median, na.rm = na.rm)) + agg <- switch( + combine_rule, + "min" = function(x, ...) apply(x, 1, min, na.rm = na.rm), + "mean" = function(x, ...) rowMeans(x, na.rm = na.rm), + "max" = function(x, ...) apply(x, 1, max, na.rm = na.rm), + "median" = function(x, ...) apply(x, 1, stats::median, na.rm = na.rm) + ) comb <- agg(z_mat) # Single-row / all-NA edge case: rowMeans returns NaN, min/max/median return NA - if (combine_rule == "mean") comb[!is.finite(comb)] <- NA_real_ + if (combine_rule == "mean") { + comb[!is.finite(comb)] <- NA_real_ + } # --- 5. Assemble output --------------------------------------------------- - out <- data.frame(patient = as.character(patient), - clone_id = as.character(clone_id), - comb_viability = as.numeric(comb), - stringsAsFactors = FALSE) + out <- data.frame( + patient = as.character(patient), + clone_id = as.character(clone_id), + comb_viability = as.numeric(comb), + stringsAsFactors = FALSE + ) if (include_single_z) { z_df <- as.data.frame(z_mat) @@ -530,4 +606,3 @@ combine_drugs <- function(pred, out } - diff --git a/R/stats.R b/R/stats.R index c01331f..505d237 100644 --- a/R/stats.R +++ b/R/stats.R @@ -22,7 +22,12 @@ NULL #' #' @return Numeric p-value. #' @export -hypergeometric_test_for_twolists <- function(test_list, base_list, global, lower.tail = FALSE) { +hypergeometric_test_for_twolists <- function( + test_list, + base_list, + global, + lower.tail = FALSE +) { base_in_global <- global[na.omit(match(base_list, global))] test_in_global <- test_list[!is.na(match(test_list, global))] overlap <- test_in_global[!is.na(match(test_in_global, base_in_global))] @@ -39,7 +44,6 @@ hypergeometric_test_for_twolists <- function(test_list, base_list, global, lower } - #' FDR correction for multiple testing #' #' Performs False Discovery Rate (FDR) correction using the Benjamini-Hochberg method. @@ -53,7 +57,6 @@ fdrcorr <- function(test_list) { } - #' Rank-normalize each column of a matrix #' #' Converts each column to ranks divided by column length, producing values in @@ -90,15 +93,15 @@ fdrcorr <- function(test_list) { #' 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) -rank_normalization_mat <- function(mat){ +rank_normalization_mat <- function(mat) { apply( mat, 2, - function(x) rank(x, ties.method = "average")/length(x)) + function(x) rank(x, ties.method = "average") / length(x) + ) } - #' Change range to 0-1 #' #' Scales a numeric vector to the 0-1 range using the 5th and 95th percentiles @@ -107,9 +110,9 @@ rank_normalization_mat <- function(mat){ #' @param x A numeric vector. #' @return A numeric vector scaled between 0 and 1. #' @export -range01 <- function(x){ - substitute_of_Min <- topXPercentValue(vec=x, X_percentile=5) - substitute_of_Max <- topXPercentValue(vec=x, X_percentile=95) +range01 <- function(x) { + substitute_of_Min <- topXPercentValue(vec = x, X_percentile = 5) + substitute_of_Max <- topXPercentValue(vec = x, X_percentile = 95) denom <- substitute_of_Max - substitute_of_Min if (!is.finite(denom) || denom == 0) { # No spread between the 5th and 95th percentiles — the vector is @@ -127,7 +130,6 @@ range01 <- function(x){ } - #' Compute clone-level mean expression from single-cell data #' #' For each patient, groups cells by clone_id and computes the mean @@ -144,24 +146,33 @@ range01 <- function(x){ #' @return A named list of matrices, one per patient. Each matrix has genes as rows #' and clone IDs as columns, with mean expression values. #' @export -clone_mean_expression <- function(expression_matrix, cell_clone_map, patient_ids = NULL) { - +clone_mean_expression <- function( + expression_matrix, + cell_clone_map, + patient_ids = NULL +) { if (!all(c("cell_id", "clone_id") %in% colnames(cell_clone_map))) { - stop("cell_clone_map must have columns 'cell_id' and 'clone_id'.") + cli::cli_abort( + "cell_clone_map must have columns {.field cell_id} and {.field clone_id}." + ) } cell_ids <- colnames(expression_matrix) if (is.null(cell_ids)) { - stop("expression_matrix must have column names (cell IDs).") + cli::cli_abort("expression_matrix must have column names (cell IDs).") } # Filter to cells present in both expression matrix and mapping common_cells <- intersect(cell_ids, as.character(cell_clone_map$cell_id)) if (length(common_cells) == 0) { - stop("No matching cells between expression matrix and cell_clone_map.") + cli::cli_abort( + "No matching cells between expression matrix and cell_clone_map." + ) } - cell_clone_map <- cell_clone_map[match(common_cells, cell_clone_map$cell_id), ] + cell_clone_map <- cell_clone_map[ + match(common_cells, cell_clone_map$cell_id), + ] expr_subset <- expression_matrix[, common_cells, drop = FALSE] if (is.null(patient_ids)) { @@ -183,20 +194,29 @@ clone_mean_expression <- function(expression_matrix, cell_clone_map, patient_ids pat_cells <- names(patient_ids[patient_ids == pat]) pat_map <- cell_clone_map[cell_clone_map$cell_id %in% pat_cells, ] - if (nrow(pat_map) == 0) next + if (nrow(pat_map) == 0) { + next + } clone_ids <- unique(pat_map$clone_id) - clone_expr <- do.call(cbind, lapply(clone_ids, function(cl) { - cl_cells <- as.character(pat_map$cell_id[pat_map$clone_id == cl]) - cl_cells <- intersect(cl_cells, colnames(expr_subset)) - if (length(cl_cells) == 0) return(NULL) - if (length(cl_cells) == 1) { - return(expr_subset[, cl_cells]) - } - rowMeans_if_one_row(data.frame(expr_subset[, cl_cells, drop = FALSE])) - })) - - if (is.null(clone_expr) || length(clone_expr) == 0) next + clone_expr <- do.call( + cbind, + lapply(clone_ids, function(cl) { + cl_cells <- as.character(pat_map$cell_id[pat_map$clone_id == cl]) + cl_cells <- intersect(cl_cells, colnames(expr_subset)) + if (length(cl_cells) == 0) { + return(NULL) + } + if (length(cl_cells) == 1) { + return(expr_subset[, cl_cells]) + } + rowMeans_if_one_row(data.frame(expr_subset[, cl_cells, drop = FALSE])) + }) + ) + + if (is.null(clone_expr) || length(clone_expr) == 0) { + next + } if (!is.matrix(clone_expr)) { clone_expr <- matrix(clone_expr, nrow = nrow(expr_subset)) @@ -215,7 +235,6 @@ clone_mean_expression <- function(expression_matrix, cell_clone_map, patient_ids } - #' Z-score scale viability values across patients #' #' Applies base R \code{scale()} to each drug column across all patients, @@ -232,40 +251,44 @@ clone_mean_expression <- function(expression_matrix, cell_clone_map, patient_ids #' @return A data frame with the same structure, but drug columns z-score scaled. #' @export zscore_viability <- function(clone_viability_df, cols = NULL) { - if (!"patient" %in% colnames(clone_viability_df)) { - stop("clone_viability_df must have a 'patient' column.") + cli::cli_abort("clone_viability_df must have a {.field patient} column.") } drug_cols <- setdiff(colnames(clone_viability_df), c("patient", "clone_id")) if (length(drug_cols) == 0) { - stop("No drug columns found (expected columns other than 'patient' and 'clone_id').") + cli::cli_abort( + "No drug columns found (expected columns other than {.field patient} and {.field clone_id})." + ) } if (!is.null(cols)) { missing_cols <- setdiff(cols, drug_cols) if (length(missing_cols) > 0) { - stop("Column(s) not found in clone_viability_df: ", - paste(missing_cols, collapse = ", ")) + cli::cli_abort( + "Column(s) not found in clone_viability_df: {paste(missing_cols, collapse = ', ')}" + ) } drug_cols <- cols if (length(drug_cols) == 0) return(clone_viability_df) } - clone_viability_df[drug_cols] <- lapply(clone_viability_df[drug_cols], function(col) { - as.numeric(scale(as.numeric(col))) - }) + clone_viability_df[drug_cols] <- lapply( + clone_viability_df[drug_cols], + function(col) { + as.numeric(scale(as.numeric(col))) + } + ) return(clone_viability_df) } - # topXPercentValue of a vector -topXPercentValue <- function(vec, X_percentile=95){ - vec=na.omit(vec) - len=length(vec) - vec=sort(vec) - vec[ceiling(len*(X_percentile/100))] +topXPercentValue <- function(vec, X_percentile = 95) { + vec <- na.omit(vec) + len <- length(vec) + vec <- sort(vec) + vec[ceiling(len * (X_percentile / 100))] } diff --git a/R/train.R b/R/train.R index 39d1f62..b378dc1 100644 --- a/R/train.R +++ b/R/train.R @@ -21,7 +21,9 @@ NULL #' @export get_response_matrix <- function(infunc_drugName) { if (!exists("DepMap")) { - stop("DepMap data not loaded. Please run load_depmap(read = TRUE) first.") + cli::cli_abort( + "DepMap data not loaded. Please run load_depmap(read = TRUE) first." + ) } # Strip BOTH sides: stripall2match() removes non-alphanumerics, so comparing @@ -30,27 +32,49 @@ get_response_matrix <- function(infunc_drugName) { # != "5-fluorouracil"). That yielded an empty row index, and colMeans() of the # resulting 0-row matrix returned an all-NaN vector, so training reported # "feature ranking failed" for a drug whose response data was present. - infunc_drugName_id <- which(stripall2match(DepMap$secondary_screen_drugAnnotation$CommonName) == - stripall2match(infunc_drugName)) + infunc_drugName_id <- which( + stripall2match(DepMap$secondary_screen_drugAnnotation$CommonName) == + stripall2match(infunc_drugName) + ) infunc_response <- DepMap$secondary_prism[infunc_drugName_id, ] if (is.matrix(infunc_response)) { - infunc_drugName_screenID <- DepMap$secondary_screen_drugAnnotation$Screen_id[infunc_drugName_id] - infunc_drugName_screenID_trimmed <- substring(infunc_drugName_screenID, 0, 3) - - if (sum(infunc_drugName_screenID_trimmed == 'HTS') == 1 & - sum(infunc_drugName_screenID_trimmed == 'MTS') == 1) { - infunc_response <- infunc_response[infunc_drugName_screenID_trimmed == 'MTS', ] - } else if (sum(infunc_drugName_screenID_trimmed == 'HTS') == 1 & - sum(infunc_drugName_screenID_trimmed == 'MTS') > 1) { - infunc_response <- infunc_response[infunc_drugName_screenID_trimmed == 'MTS', ] - infunc_response <- infunc_response[count_row_NAs(infunc_response) == min(count_row_NAs(infunc_response)), ] + infunc_drugName_screenID <- DepMap$secondary_screen_drugAnnotation$Screen_id[ + infunc_drugName_id + ] + infunc_drugName_screenID_trimmed <- substring( + infunc_drugName_screenID, + 0, + 3 + ) + + if ( + sum(infunc_drugName_screenID_trimmed == 'HTS') == 1 & + sum(infunc_drugName_screenID_trimmed == 'MTS') == 1 + ) { + infunc_response <- infunc_response[ + infunc_drugName_screenID_trimmed == 'MTS', + ] + } else if ( + sum(infunc_drugName_screenID_trimmed == 'HTS') == 1 & + sum(infunc_drugName_screenID_trimmed == 'MTS') > 1 + ) { + infunc_response <- infunc_response[ + infunc_drugName_screenID_trimmed == 'MTS', + ] + infunc_response <- infunc_response[ + count_row_NAs(infunc_response) == min(count_row_NAs(infunc_response)), + ] # Fall through to the colMeans() below: when several MTS batches tie on # NA count they are averaged ACROSS cell lines. (rowMeans here would # collapse to one scalar per batch and destroy cell-line granularity.) - } else if (sum(infunc_drugName_screenID_trimmed == 'HTS') == 0 & - sum(infunc_drugName_screenID_trimmed == 'MTS') > 1) { - infunc_response <- infunc_response[count_row_NAs(infunc_response) == min(count_row_NAs(infunc_response)), ] + } else if ( + sum(infunc_drugName_screenID_trimmed == 'HTS') == 0 & + sum(infunc_drugName_screenID_trimmed == 'MTS') > 1 + ) { + infunc_response <- infunc_response[ + count_row_NAs(infunc_response) == min(count_row_NAs(infunc_response)), + ] } if (is.matrix(infunc_response)) { infunc_response <- colMeans(infunc_response, na.rm = TRUE) @@ -80,44 +104,68 @@ get_response_matrix <- function(infunc_drugName) { #' } #' #' @export -get_cellLine_list <- function(infunc_cancerType = "PanCan", - infunc_drugName, - exclude_cancer = "PanCan", - infunc_response, - force_add_cellLines = TRUE, - force_add_cellLines_list = NA) { +get_cellLine_list <- function( + infunc_cancerType = "PanCan", + infunc_drugName, + exclude_cancer = "PanCan", + infunc_response, + force_add_cellLines = TRUE, + force_add_cellLines_list = NA +) { if (infunc_cancerType == "PanCan") { CellLines_with_drugResponse <- names(infunc_response) CellLines_with_bulkExp <- colnames(DepMap$expression_rnorm) CellLines_with_singleCellExp <- colnames(DepMap$scRNA_complete) CellLinee2exclude <- DepMap$annotation_20Q4$DepMap_ID[ - grep(exclude_cancer, DepMap$annotation_20Q4$lineage)] + grep(exclude_cancer, DepMap$annotation_20Q4$lineage) + ] if (exclude_cancer == "PanCan") { - CellLinee2exclude <- intersect(CellLines_with_singleCellExp, - DepMap$annotation_20Q4$DepMap_ID) + CellLinee2exclude <- intersect( + CellLines_with_singleCellExp, + DepMap$annotation_20Q4$DepMap_ID + ) } - cellLines2remove <- intersect(CellLinee2exclude, CellLines_with_singleCellExp) + cellLines2remove <- intersect( + CellLinee2exclude, + CellLines_with_singleCellExp + ) - common_cellLines <- setdiff(intersect(CellLines_with_drugResponse, CellLines_with_bulkExp), - cellLines2remove) + common_cellLines <- setdiff( + intersect(CellLines_with_drugResponse, CellLines_with_bulkExp), + cellLines2remove + ) if (force_add_cellLines) { - common_cellLines <- c(common_cellLines, intersect(CellLines_with_bulkExp, force_add_cellLines_list)) + common_cellLines <- c( + common_cellLines, + intersect(CellLines_with_bulkExp, force_add_cellLines_list) + ) } } else { CellLines_cancer <- DepMap$annotation_20Q4$DepMap_ID[ - grep(infunc_cancerType, DepMap$annotation_20Q4$lineage)] + grep(infunc_cancerType, DepMap$annotation_20Q4$lineage) + ] CellLines_with_drugResponse <- names(infunc_response) CellLines_with_bulkExp <- colnames(DepMap$expression_rnorm) CellLines_with_singleCellExp <- colnames(DepMap$scRNA_complete) - cellLines2remove <- intersect(CellLines_cancer, CellLines_with_singleCellExp) - common_cellLines <- setdiff(Reduce(intersect, list(CellLines_with_drugResponse, - CellLines_with_bulkExp, - CellLines_cancer)), - cellLines2remove) + cellLines2remove <- intersect( + CellLines_cancer, + CellLines_with_singleCellExp + ) + common_cellLines <- setdiff( + Reduce( + intersect, + list( + CellLines_with_drugResponse, + CellLines_with_bulkExp, + CellLines_cancer + ) + ), + cellLines2remove + ) } list(common_cellLines, cellLines2remove) } @@ -136,13 +184,16 @@ get_cellLine_list <- function(infunc_cancerType = "PanCan", #' #' @return Matrix of ranked features with columns: p.value, estimate.cor (sorted by abs(cor) descending) #' @export -feature_ranking_bulk <- function(infunc_drugName, - infunc_cancerType = "PanCan", - exclude_cancer = "PanCan", - infunc_GOI) { - +feature_ranking_bulk <- function( + infunc_drugName, + infunc_cancerType = "PanCan", + exclude_cancer = "PanCan", + infunc_GOI +) { if (!exists("DepMap")) { - stop("DepMap data not loaded. Please run load_depmap(read = TRUE) first.") + cli::cli_abort( + "DepMap data not loaded. Please run load_depmap(read = TRUE) first." + ) } # Get drug response (AUC only, as IC50/VFC data not included in DepMap) @@ -155,28 +206,44 @@ feature_ranking_bulk <- function(infunc_drugName, CellLines_with_singleCellExp <- colnames(DepMap$scRNA_complete) CellLinee2exclude <- DepMap$annotation_20Q4$DepMap_ID[ - grep(exclude_cancer, DepMap$annotation_20Q4$lineage)] + grep(exclude_cancer, DepMap$annotation_20Q4$lineage) + ] if (exclude_cancer == "PanCan") { - CellLinee2exclude <- intersect(CellLines_with_singleCellExp, - DepMap$annotation_20Q4$DepMap_ID) + CellLinee2exclude <- intersect( + CellLines_with_singleCellExp, + DepMap$annotation_20Q4$DepMap_ID + ) } - cellLines2remove <- intersect(CellLinee2exclude, CellLines_with_singleCellExp) - - common_cellLines <- setdiff(intersect(CellLines_with_drugResponse, CellLines_with_bulkExp), - cellLines2remove) - message(" Common cell lines: ", length(common_cellLines)) + cellLines2remove <- intersect( + CellLinee2exclude, + CellLines_with_singleCellExp + ) + + common_cellLines <- setdiff( + intersect(CellLines_with_drugResponse, CellLines_with_bulkExp), + cellLines2remove + ) + cli::cli_alert_info("Common cell lines: {length(common_cellLines)}") } else { CellLines_cancer <- DepMap$annotation_20Q4$DepMap_ID[ - grep(infunc_cancerType, DepMap$annotation_20Q4$lineage)] + grep(infunc_cancerType, DepMap$annotation_20Q4$lineage) + ] CellLines_with_drugResponse <- names(infunc_response) CellLines_with_bulkExp <- colnames(DepMap$expression_rnorm) CellLines_with_singleCellExp <- colnames(DepMap$scRNA_complete) - common_cellLines <- setdiff(Reduce(intersect, list(CellLines_with_drugResponse, - CellLines_with_bulkExp, - CellLines_cancer)), - colnames(DepMap$scRNA_complete)) - message(" Common cell lines: ", length(common_cellLines)) + common_cellLines <- setdiff( + Reduce( + intersect, + list( + CellLines_with_drugResponse, + CellLines_with_bulkExp, + CellLines_cancer + ) + ), + colnames(DepMap$scRNA_complete) + ) + cli::cli_alert_info("Common cell lines: {length(common_cellLines)}") } # Compute correlations — vectorized across ALL genes in one pass. @@ -193,14 +260,14 @@ feature_ranking_bulk <- function(infunc_drugName, X <- X[, y_ok, drop = FALSE] y <- y[y_ok] - ok <- !is.na(X) # per-gene complete-cell mask + ok <- !is.na(X) # per-gene complete-cell mask n_eff <- rowSums(ok) r <- as.numeric(cor(t(X), y, use = "pairwise.complete.obs")) df <- n_eff - 2L t_stat <- sqrt(df) * r / sqrt(1 - r^2) pval <- 2 * pt(-abs(t_stat), df) pval[!is.finite(t_stat) | is.na(r) | df < 1L] <- NA - r[!is.finite(t_stat)] <- NA # constant rows (sd = 0) -> NA, like cor.test + r[!is.finite(t_stat)] <- NA # constant rows (sd = 0) -> NA, like cor.test cor_profile <- cbind(p.value = pval, estimate.cor = r) rownames(cor_profile) <- rownames(X) @@ -228,21 +295,25 @@ feature_ranking_bulk <- function(infunc_drugName, #' #' @return A list of feature ranking results, one per drug. #' @export -run_parallel_feature_ranking_bulk <- function(infunc_DrugsToUse, - id_cancerType = "PanCan", - infunc_exclude_cancer = "PanCan", - infunc_GOI, - ncores = 4) { - +run_parallel_feature_ranking_bulk <- function( + infunc_DrugsToUse, + id_cancerType = "PanCan", + infunc_exclude_cancer = "PanCan", + infunc_GOI, + ncores = 4 +) { idx <- seq_along(infunc_DrugsToUse) featuresRank_fromBulk <- lapply( idx, - function(x) - err_handle(feature_ranking_bulk(infunc_drugName = infunc_DrugsToUse[x], - infunc_cancerType = id_cancerType, - infunc_GOI = infunc_GOI, - exclude_cancer = infunc_exclude_cancer)) + function(x) { + err_handle(feature_ranking_bulk( + infunc_drugName = infunc_DrugsToUse[x], + infunc_cancerType = id_cancerType, + infunc_GOI = infunc_GOI, + exclude_cancer = infunc_exclude_cancer + )) + } ) names(featuresRank_fromBulk) <- infunc_DrugsToUse @@ -276,96 +347,146 @@ run_parallel_feature_ranking_bulk <- function(infunc_DrugsToUse, #' performance_in_bulk, performance_in_pseudo_bulk, performance_in_scRNA, #' predVSgroundTruth. #' @export -build_on_BULK_v2 <- function(infunc_drugName, - infunc_cancerType = "PanCan", - exclude_cancer = "PanCan", - infunc_features, - single_best = infunc_features[1], - k_features = 100, - infunc_alpha = 1, - model_type = "glmnet", - num_folds = 3, - num_tree = 500, - seed = 1, - alpha_gradient = 0.05, - lambda_gradient = 20, - lambda_range = c(0.0001, 1), - cv_method = "cv") { - +build_on_BULK_v2 <- function( + infunc_drugName, + infunc_cancerType = "PanCan", + exclude_cancer = "PanCan", + infunc_features, + single_best = infunc_features[1], + k_features = 100, + infunc_alpha = 1, + model_type = "glmnet", + num_folds = 3, + num_tree = 500, + seed = 1, + alpha_gradient = 0.05, + lambda_gradient = 20, + lambda_range = c(0.0001, 1), + cv_method = "cv" +) { # Get drug response infunc_response <- get_response_matrix(infunc_drugName = infunc_drugName) # Get training cell lines - common_cellLines <- get_cellLine_list(infunc_cancerType = infunc_cancerType, - infunc_drugName = infunc_drugName, - exclude_cancer = exclude_cancer, - infunc_response = infunc_response, - force_add_cellLines = TRUE)[[1]] + common_cellLines <- get_cellLine_list( + infunc_cancerType = infunc_cancerType, + infunc_drugName = infunc_drugName, + exclude_cancer = exclude_cancer, + infunc_response = infunc_response, + force_add_cellLines = TRUE + )[[1]] # Get test cell lines (excluded from training) - cellLines2remove <- get_cellLine_list(infunc_cancerType = infunc_cancerType, - infunc_drugName = infunc_drugName, - exclude_cancer = exclude_cancer, - infunc_response = infunc_response)[[2]] + cellLines2remove <- get_cellLine_list( + infunc_cancerType = infunc_cancerType, + infunc_drugName = infunc_drugName, + exclude_cancer = exclude_cancer, + infunc_response = infunc_response + )[[2]] # Check consistency between rnorm matrices if (nrow(DepMap$expression_rnorm) != nrow(DepMap$scRNA_subset_rnorm)) { - warning("Mismatch in initial features (rNorm sc vs bulk); skipping this model.") + warning( + "Mismatch in initial features (rNorm sc vs bulk); skipping this model." + ) return(NULL) } ############ # Train Data: on bulk ########## - Train_infunc_features_id <- head(na.omit(match(infunc_features, - rownames(DepMap$expression_rnorm))), k_features) - Train_features <- t(DepMap$expression_rnorm[Train_infunc_features_id, common_cellLines]) + Train_infunc_features_id <- head( + na.omit(match(infunc_features, rownames(DepMap$expression_rnorm))), + k_features + ) + Train_features <- t(DepMap$expression_rnorm[ + Train_infunc_features_id, + common_cellLines + ]) Train_Target_Label <- infunc_response[common_cellLines] Train_features <- Train_features[which(!is.na(Train_Target_Label)), ] - Train_Target_Label <- unlist(Train_Target_Label[which(!is.na(Train_Target_Label))]) + Train_Target_Label <- unlist(Train_Target_Label[which( + !is.na(Train_Target_Label) + )]) Train_features <- Train_features[which(Train_Target_Label < 10^100), ] - Train_Target_Label <- unlist(Train_Target_Label[which(Train_Target_Label < 10^100)]) + Train_Target_Label <- unlist(Train_Target_Label[which( + Train_Target_Label < 10^100 + )]) ############ # Test Data 1: on pseudo-Bulk ########## - cell_ID_for_test_data1 <- Reduce(intersect, list(cellLines2remove, - colnames(DepMap$scRNA_subset_rnorm), - names(infunc_response))) - Test_infunc_features_id <- head(na.omit(match(infunc_features, - rownames(DepMap$scRNA_subset_rnorm))), k_features) - Test_features <- t(DepMap$scRNA_subset_rnorm[Test_infunc_features_id, cell_ID_for_test_data1]) + cell_ID_for_test_data1 <- Reduce( + intersect, + list( + cellLines2remove, + colnames(DepMap$scRNA_subset_rnorm), + names(infunc_response) + ) + ) + Test_infunc_features_id <- head( + na.omit(match(infunc_features, rownames(DepMap$scRNA_subset_rnorm))), + k_features + ) + Test_features <- t(DepMap$scRNA_subset_rnorm[ + Test_infunc_features_id, + cell_ID_for_test_data1 + ]) Test_Target_Label <- unlist(infunc_response)[cell_ID_for_test_data1] Test_features <- Test_features[which(!is.na(Test_Target_Label)), ] - Test_Target_Label <- unlist(Test_Target_Label[which(!is.na(Test_Target_Label))]) + Test_Target_Label <- unlist(Test_Target_Label[which( + !is.na(Test_Target_Label) + )]) ############ # Test Data 2: on bulk ########## - cell_ID_for_test_data2 <- Reduce(intersect, list(cellLines2remove, - colnames(DepMap$expression_rnorm), - names(infunc_response))) - Test2_infunc_features_id <- head(na.omit(match(infunc_features, - rownames(DepMap$expression_rnorm))), k_features) - Test2_features <- t(DepMap$expression_rnorm[Test2_infunc_features_id, cell_ID_for_test_data2]) + cell_ID_for_test_data2 <- Reduce( + intersect, + list( + cellLines2remove, + colnames(DepMap$expression_rnorm), + names(infunc_response) + ) + ) + Test2_infunc_features_id <- head( + na.omit(match(infunc_features, rownames(DepMap$expression_rnorm))), + k_features + ) + Test2_features <- t(DepMap$expression_rnorm[ + Test2_infunc_features_id, + cell_ID_for_test_data2 + ]) Test2_Target_Label <- unlist(infunc_response)[cell_ID_for_test_data2] Test2_features <- Test2_features[which(!is.na(Test2_Target_Label)), ] - Test2_Target_Label <- unlist(Test2_Target_Label[which(!is.na(Test2_Target_Label))]) + Test2_Target_Label <- unlist(Test2_Target_Label[which( + !is.na(Test2_Target_Label) + )]) ############ # Test Data 3: on sc-RNA-seq (All cancer) ########## cells_ID_for_test_data3 <- DepMap$metadata_CPM_scRNA$NAME[ - DepMap$metadata_CPM_scRNA$DepMap_ID %in% Reduce(intersect, list(cellLines2remove, - names(infunc_response)))] + DepMap$metadata_CPM_scRNA$DepMap_ID %in% + Reduce(intersect, list(cellLines2remove, names(infunc_response))) + ] cellLine_ID_for_test_data3 <- unique( - DepMap$metadata_CPM_scRNA$DepMap_ID[DepMap$metadata_CPM_scRNA$DepMap_ID %in% - Reduce(intersect, list(cellLines2remove, names(infunc_response)))]) - Test3_infunc_features_id <- head(na.omit(match(infunc_features, - rownames(DepMap$CPM_scRNA_CCLE_rnorm))), k_features) - Test3_features <- t(DepMap$CPM_scRNA_CCLE_rnorm[Test3_infunc_features_id, - cells_ID_for_test_data3]) - Test3_Target_Label <- unlist(infunc_response)[as.character(cellLine_ID_for_test_data3)] + DepMap$metadata_CPM_scRNA$DepMap_ID[ + DepMap$metadata_CPM_scRNA$DepMap_ID %in% + Reduce(intersect, list(cellLines2remove, names(infunc_response))) + ] + ) + Test3_infunc_features_id <- head( + na.omit(match(infunc_features, rownames(DepMap$CPM_scRNA_CCLE_rnorm))), + k_features + ) + Test3_features <- t(DepMap$CPM_scRNA_CCLE_rnorm[ + Test3_infunc_features_id, + cells_ID_for_test_data3 + ]) + Test3_Target_Label <- unlist(infunc_response)[as.character( + cellLine_ID_for_test_data3 + )] ########## # ML Model @@ -375,22 +496,28 @@ build_on_BULK_v2 <- function(infunc_drugName, if (model_type == 'rf') { tunegrid <- expand.grid(.mtry = ncol(Train_features) / seq(10, 1, -3)) - cv.out <- suppressWarnings(caret::train(Train_Target_Label ~ ., - data = data.frame(Train_Target_Label, Train_features), - method = 'rf', - trControl = tc, - tunegrid = tunegrid, - ntree = num_tree)) + cv.out <- suppressWarnings(caret::train( + Train_Target_Label ~ ., + data = data.frame(Train_Target_Label, Train_features), + method = 'rf', + trControl = tc, + tunegrid = tunegrid, + ntree = num_tree + )) } else if (model_type == 'glmnet') { - tunegrid <- expand.grid(alpha = seq(0, 1, alpha_gradient), - lambda = seq(lambda_range[1], lambda_range[2], length = lambda_gradient)) - cv.out <- suppressWarnings(caret::train(Train_Target_Label ~ ., - data = data.frame(Train_Target_Label, Train_features), - method = 'glmnet', - trControl = tc, - metric = "RMSE", - tuneGrid = tunegrid, - savePredictions = "final")) + tunegrid <- expand.grid( + alpha = seq(0, 1, alpha_gradient), + lambda = seq(lambda_range[1], lambda_range[2], length = lambda_gradient) + ) + cv.out <- suppressWarnings(caret::train( + Train_Target_Label ~ ., + data = data.frame(Train_Target_Label, Train_features), + method = 'glmnet', + trControl = tc, + metric = "RMSE", + tuneGrid = tunegrid, + savePredictions = "final" + )) } ############ @@ -402,46 +529,68 @@ build_on_BULK_v2 <- function(infunc_drugName, # Test on bulk (test 2) Test_pred_bulk <- predict(cv.out, Test2_features) - performance_in_bulk <- unlist(cor.test(Test_pred_bulk, - Test2_Target_Label, method = "pearson")[c(3, 4)]) + performance_in_bulk <- unlist(cor.test( + Test_pred_bulk, + Test2_Target_Label, + method = "pearson" + )[c(3, 4)]) # Test on pseudo-Bulk (test 1) Test_pred_Msc <- predict(cv.out, newdata = Test_features) - performance_in_pseudo_bulk <- unlist(cor.test(Test_pred_Msc, - Test_Target_Label, method = "pearson")[c(3, 4)]) + performance_in_pseudo_bulk <- unlist(cor.test( + Test_pred_Msc, + Test_Target_Label, + method = "pearson" + )[c(3, 4)]) # Test on scRNA-seq (test 3) Test_pred_sc <- predict(cv.out, newdata = Test3_features) cells_mapping2_cellLine <- DepMap$metadata_CPM_scRNA$DepMap_ID[ - DepMap$metadata_CPM_scRNA$NAME %in% names(Test_pred_sc)] - Test_pred_sc_mean_byCellLine <- aggregate(Test_pred_sc ~ cells_mapping2_cellLine, - data.frame(Test_pred_sc, cells_mapping2_cellLine), - function(x) mean(x, na.rm = TRUE)) - performance_in_scRNA <- unlist(cor.test(Test_pred_sc_mean_byCellLine$Test_pred_sc, - Test3_Target_Label[ - as.character(Test_pred_sc_mean_byCellLine$cells_mapping2_cellLine)], - method = "pearson")[c(3, 4)]) + DepMap$metadata_CPM_scRNA$NAME %in% names(Test_pred_sc) + ] + Test_pred_sc_mean_byCellLine <- aggregate( + Test_pred_sc ~ cells_mapping2_cellLine, + data.frame(Test_pred_sc, cells_mapping2_cellLine), + function(x) mean(x, na.rm = TRUE) + ) + performance_in_scRNA <- unlist(cor.test( + Test_pred_sc_mean_byCellLine$Test_pred_sc, + Test3_Target_Label[ + as.character(Test_pred_sc_mean_byCellLine$cells_mapping2_cellLine) + ], + method = "pearson" + )[c(3, 4)]) # Predictions vs ground truth predVSgroundTruth <- list( - pred_gt_scRNA = data.frame(Test_pred_sc = Test_pred_sc_mean_byCellLine$Test_pred_sc, - Observed = Test3_Target_Label[as.character(Test_pred_sc_mean_byCellLine$cells_mapping2_cellLine)]), - pred_gt_bulk = data.frame(Test_pred_Msc = Test_pred_bulk, - Observed = Test2_Target_Label), - pred_gt_mscRNA = data.frame(Test_pred_Msc = Test_pred_Msc, - Observed = Test_Target_Label) + pred_gt_scRNA = data.frame( + Test_pred_sc = Test_pred_sc_mean_byCellLine$Test_pred_sc, + Observed = Test3_Target_Label[as.character( + Test_pred_sc_mean_byCellLine$cells_mapping2_cellLine + )] + ), + pred_gt_bulk = data.frame( + Test_pred_Msc = Test_pred_bulk, + Observed = Test2_Target_Label + ), + pred_gt_mscRNA = data.frame( + Test_pred_Msc = Test_pred_Msc, + Observed = Test_Target_Label + ) ) ############ # Return ########## - toreturn <- list(model = cv.out, - single_best = single_best, - model_performance_during_cv = model_performance_cv, - performance_in_bulk = performance_in_bulk, - performance_in_pseudo_bulk = performance_in_pseudo_bulk, - performance_in_scRNA = performance_in_scRNA, - predVSgroundTruth = predVSgroundTruth) + toreturn <- list( + model = cv.out, + single_best = single_best, + model_performance_during_cv = model_performance_cv, + performance_in_bulk = performance_in_bulk, + performance_in_pseudo_bulk = performance_in_pseudo_bulk, + performance_in_scRNA = performance_in_scRNA, + predVSgroundTruth = predVSgroundTruth + ) toreturn } @@ -487,22 +636,24 @@ build_on_BULK_v2 <- function(infunc_drugName, #' } #' #' @export -train_models <- function(drug_list = NULL, - cancer_type = "PanCan", - exclude_cancer = "PanCan", - GOI = NULL, - k_features_values = NULL, - ncores = 4, - output_dir = "./models", - model_type = "glmnet", - num_folds = 3, - num_tree = 500, - seed = 1, - alpha_gradient = 0.05, - lambda_gradient = 20, - lambda_range = c(0.0001, 1), - cv_method = "cv", - progress_cb = NULL) { +train_models <- function( + drug_list = NULL, + cancer_type = "PanCan", + exclude_cancer = "PanCan", + GOI = NULL, + k_features_values = NULL, + ncores = 4, + output_dir = "./models", + model_type = "glmnet", + num_folds = 3, + num_tree = 500, + seed = 1, + alpha_gradient = 0.05, + lambda_gradient = 20, + lambda_range = c(0.0001, 1), + cv_method = "cv", + progress_cb = NULL +) { # progress_cb: optional function(phase, i, n, drug) called as training # advances — phase is "rank" (feature ranking done) or "train" (per drug, # i/n with the drug name). Lets a Shiny app drive a progress bar during the @@ -516,27 +667,39 @@ train_models <- function(drug_list = NULL, # 1. Check DepMap data # ============================================================================ if (!exists("DepMap")) { - stop("DepMap data not loaded. Please run load_depmap(read = TRUE) first.") + cli::cli_abort( + "DepMap data not loaded. Please run load_depmap(read = TRUE) first." + ) } # ============================================================================ # 2. Set up GOI (Genes of Interest) # ============================================================================ if (is.null(GOI)) { - GOI <- intersect(rownames(DepMap$expression_20Q4), - rownames(DepMap$scRNA_complete)) - message("Using all ", length(GOI), " intersecting genes as features.") + GOI <- intersect( + rownames(DepMap$expression_20Q4), + rownames(DepMap$scRNA_complete) + ) + cli::cli_alert_info( + "Using all {length(GOI)} intersecting genes as features." + ) } else { available_genes <- intersect(GOI, rownames(DepMap$expression_20Q4)) if (length(available_genes) == 0) { - stop("None of the provided GOI genes were found in DepMap expression data.") + cli::cli_abort( + "None of the provided GOI genes were found in DepMap expression data." + ) } if (length(available_genes) < length(GOI)) { - warning("Some GOI genes not found in DepMap: ", - paste(setdiff(GOI, available_genes), collapse = ", ")) + warning( + "Some GOI genes not found in DepMap: ", + paste(setdiff(GOI, available_genes), collapse = ", ") + ) } GOI <- available_genes - message("Using user-specified ", length(GOI), " genes as features.") + cli::cli_alert_info( + "Using user-specified {length(GOI)} genes as features." + ) } # ============================================================================ @@ -553,7 +716,9 @@ train_models <- function(drug_list = NULL, n_genes_total <- nrow(DepMap$expression_rnorm) k_features_values <- n_genes_total * seq(0.0005, 0.02, length = 5) k_features_values <- round(k_features_values) - message("Testing feature counts: ", paste(k_features_values, collapse = ", ")) + cli::cli_alert_info( + "Testing feature counts: {paste(k_features_values, collapse = ', ')}" + ) } # ============================================================================ @@ -568,7 +733,9 @@ train_models <- function(drug_list = NULL, # ============================================================================ # 6. Step 1: Parallel feature ranking for all drugs # ============================================================================ - message("Step 1/2: Feature ranking for ", length(drug_list), " drugs...") + cli::cli_progress_step( + "Step 1/2: Feature ranking for {length(drug_list)} drugs..." + ) features_list <- run_parallel_feature_ranking_bulk( infunc_DrugsToUse = drug_list, id_cancerType = cancer_type, @@ -576,21 +743,27 @@ train_models <- function(drug_list = NULL, infunc_GOI = GOI, ncores = ncores ) - if (!is.null(progress_cb)) progress_cb("rank", 0L, length(drug_list), "") + if (!is.null(progress_cb)) { + progress_cb("rank", 0L, length(drug_list), "") + } # ============================================================================ # 7. Step 2: Train models for each drug with hyperparameter tuning # (matches original Step1_Build_Perception_models.Rmd logic exactly) # ============================================================================ - message("Step 2/2: Training models with hyperparameter tuning...") + cli::cli_progress_step( + "Step 2/2: Training models with hyperparameter tuning..." + ) for_output_lung_Test_vglm <- list() Performance_by_features <- list() for (i in seq_along(drug_list)) { drug <- drug_list[i] - message(" Processing: ", drug) - if (!is.null(progress_cb)) progress_cb("train", i, length(drug_list), drug) + cli::cli_progress_step("{i}/{length(drug_list)} Processing: {.val {drug}}") + if (!is.null(progress_cb)) { + progress_cb("train", i, length(drug_list), drug) + } # Check if feature ranking succeeded features <- features_list[[i]] @@ -603,8 +776,10 @@ train_models <- function(drug_list = NULL, # Check if drug exists in DepMap response data # Strip both sides here too, for the same reason as get_response_matrix(): # a raw comparison rejects every drug name containing a hyphen or space. - drug_match <- which(stripall2match(DepMap$secondary_screen_drugAnnotation$CommonName) == - stripall2match(drug)) + drug_match <- which( + stripall2match(DepMap$secondary_screen_drugAnnotation$CommonName) == + stripall2match(drug) + ) if (length(drug_match) == 0) { warning(" Skipping ", drug, " - drug not found in DepMap response data.") for_output_lung_Test_vglm[i] <- list(NULL) @@ -635,7 +810,14 @@ train_models <- function(drug_list = NULL, cv_method = cv_method ), error = function(e) { - warning(" build_on_BULK_v2 failed for ", drug, " (k=", infunc_k_features_grid, "): ", e$message) + warning( + " build_on_BULK_v2 failed for ", + drug, + " (k=", + infunc_k_features_grid, + "): ", + e$message + ) NULL } ) @@ -643,17 +825,24 @@ train_models <- function(drug_list = NULL, } # Check if any models were successfully built - if (length(Raw_models_output) == 0 || all(sapply(Raw_models_output, is.null))) { + if ( + length(Raw_models_output) == 0 || all(sapply(Raw_models_output, is.null)) + ) { warning(" Skipping ", drug, " - all model builds failed.") for_output_lung_Test_vglm[i] <- list(NULL) next } # Keep only successful builds (some may be NULL or the "Mismatch" string). - valid <- vapply(Raw_models_output, function(x) { - is.list(x) && !is.null(x$performance_in_scRNA) && - length(x$performance_in_scRNA) >= 2 - }, logical(1)) + valid <- vapply( + Raw_models_output, + function(x) { + is.list(x) && + !is.null(x$performance_in_scRNA) && + length(x$performance_in_scRNA) >= 2 + }, + logical(1) + ) if (!any(valid)) { warning(" Skipping ", drug, " - all model builds failed.") @@ -664,8 +853,10 @@ train_models <- function(drug_list = NULL, # Print and store the performance (rows: p-value, correlation) perf <- sapply(Raw_models_output[valid], function(x) x$performance_in_scRNA) print(perf) - Performance_by_features[[i]] <- lapply(Raw_models_output[valid], - function(x) x$performance_in_scRNA) + Performance_by_features[[i]] <- lapply( + Raw_models_output[valid], + function(x) x$performance_in_scRNA + ) # Store the Tuned model (select based on highest correlation estimate) best_pos <- which.max(perf[2, ]) @@ -677,16 +868,27 @@ train_models <- function(drug_list = NULL, } # All drugs processed — final tick so a progress bar reaches 100%. - if (!is.null(progress_cb)) progress_cb("done", length(drug_list), length(drug_list), "") + if (!is.null(progress_cb)) { + progress_cb("done", length(drug_list), length(drug_list), "") + } # Assign names and filter out NULL entries (failed drugs) names(for_output_lung_Test_vglm) <- drug_list - for_output_lung_Test_vglm <- for_output_lung_Test_vglm[!sapply(for_output_lung_Test_vglm, is.null)] + for_output_lung_Test_vglm <- for_output_lung_Test_vglm[ + !sapply(for_output_lung_Test_vglm, is.null) + ] Tuned_models_output <- for_output_lung_Test_vglm timestamp <- format(training_start, "%Y%m%d_%H%M%S") - save_filename <- paste0("PERCEPTIONx_models_", cancer_type, - "_ex", exclude_cancer, "_", timestamp, ".RDS") + save_filename <- paste0( + "PERCEPTIONx_models_", + cancer_type, + "_ex", + exclude_cancer, + "_", + timestamp, + ".RDS" + ) save_path <- file.path(output_dir, save_filename) # Strip formula/call environment references before serialization. The model's @@ -697,16 +899,22 @@ train_models <- function(drug_list = NULL, strip_model_env <- function(m) { if (is.list(m) && inherits(m$model, "train")) { m$model$call <- NULL - if (!is.null(m$model$terms)) attr(m$model$terms, ".Environment") <- baseenv() + if (!is.null(m$model$terms)) { + attr(m$model$terms, ".Environment") <- baseenv() + } } m } out_for_save <- lapply(Tuned_models_output, strip_model_env) saveRDS(out_for_save, save_path) - message("\nAll models saved to: ", save_path) + cli::cli_alert_success("All models saved to: {.path {save_path}}") - successful <- sum(!sapply(Tuned_models_output, function(x) length(x) == 1 && is.na(x))) - message("Training complete. Successful models: ", successful, " / ", length(drug_list)) + successful <- sum( + !sapply(Tuned_models_output, function(x) length(x) == 1 && is.na(x)) + ) + cli::cli_alert_success( + "Training complete. Successful models: {successful} / {length(drug_list)}" + ) return(invisible(Tuned_models_output)) } diff --git a/R/utils.R b/R/utils.R index a443d6b..09ea956 100644 --- a/R/utils.R +++ b/R/utils.R @@ -1,7 +1,7 @@ # RowMeans functions considering the boundary case where mat has a single # column (one cell / sample) — rowMeans would error on a one-column matrix. -rowMeans_if_one_row <- function(mat){ - if(ncol(mat)>1){ +rowMeans_if_one_row <- function(mat) { + if (ncol(mat) > 1) { return(rowMeans(mat)) } else { return(mat) @@ -10,20 +10,24 @@ rowMeans_if_one_row <- function(mat){ # Count the number of NAs in each row of a matrix -count_row_NAs <- function(df){ - apply(df, 1, function(x) sum(is.na(x))) +count_row_NAs <- function(df) { + rowSums(is.na(df)) } # Handing a error when a function is run and returning NA in case of error # instead of stopping the task. -err_handle <- function(x){ tryCatch(x, error=function(e){NA}) } +err_handle <- function(x) { + tryCatch(x, error = function(e) { + NA + }) +} # Lowercase and strip non-alphanumeric characters (keep underscores) — used # to make inconsistent drug / gene names comparable (e.g. "Drug-1" vs "Drug_1"). -stripall2match <- function(x){ - tolower(gsub('[^A-z0-9]', '', x) ) +stripall2match <- function(x) { + tolower(gsub('[^A-z0-9]', '', x)) } @@ -40,7 +44,7 @@ stripall2match <- function(x){ parse_clone_keys <- function(x) { parts <- strsplit(as.character(x), "@@") data.frame( - patient = sapply(parts, `[`, 1), + patient = sapply(parts, `[`, 1), clone_id = sapply(parts, `[`, 2), stringsAsFactors = FALSE ) @@ -61,4 +65,3 @@ parse_clone_keys <- function(x) { build_clone_key <- function(patient, clone_id) { paste(as.character(patient), as.character(clone_id), sep = "@@") } - diff --git a/R/utils_cortest.R b/R/utils_cortest.R index a62b880..f81a30a 100644 --- a/R/utils_cortest.R +++ b/R/utils_cortest.R @@ -46,19 +46,29 @@ cor.test_trimmed_v0 <- function(x, ...) UseMethod("cor.test_trimmed_v0") #' @noRd #' @export cor.test_trimmed_v0.default <- - function(x, y, alternative = c("two.sided", "less", "greater"), - method = c("pearson"), exact = NULL, - # conf.level = 0.95, - continuity = FALSE, ...) - { - alternative <- match.arg(alternative) - method <- match.arg(method) + function( + x, + y, + alternative = c("two.sided", "less", "greater"), + method = c("pearson"), + exact = NULL, + # conf.level = 0.95, + continuity = FALSE, + ... + ) { + alternative <- rlang::arg_match(alternative) + method <- rlang::arg_match(method) DNAME <- paste(deparse(substitute(x)), "and", deparse(substitute(y))) - if(length(x) != length(y)) - stop("'x' and 'y' must have the same length") - if(!is.numeric(x)) stop("'x' must be a numeric vector") - if(!is.numeric(y)) stop("'y' must be a numeric vector") + if (length(x) != length(y)) { + cli::cli_abort("{.arg x} and {.arg y} must have the same length.") + } + if (!is.numeric(x)) { + cli::cli_abort("{.arg x} must be a numeric vector.") + } + if (!is.numeric(y)) { + cli::cli_abort("{.arg y} must be a numeric vector.") + } OK <- complete.cases(x, y) x <- x[OK] y <- y[OK] @@ -67,9 +77,10 @@ cor.test_trimmed_v0.default <- NVAL <- 0 # conf.int <- FALSE - if(method == "pearson") { - if(n < 3L) - stop("not enough finite observations") + if (method == "pearson") { + if (n < 3L) { + cli::cli_abort("not enough finite observations") + } method <- "Pearson's product-moment correlation" names(NVAL) <- "correlation" r <- cor(x, y) @@ -95,11 +106,13 @@ cor.test_trimmed_v0.default <- # cint <- tanh(cint) # attr(cint, "conf.level") <- conf.level # } - PVAL <- switch(alternative, - "less" = pt(STATISTIC, df), - "greater" = pt(STATISTIC, df, lower.tail=FALSE), - "two.sided" = 2 * min(pt(STATISTIC, df), - pt(STATISTIC, df, lower.tail=FALSE))) + PVAL <- switch( + alternative, + "less" = pt(STATISTIC, df), + "greater" = pt(STATISTIC, df, lower.tail = FALSE), + "two.sided" = 2 * + min(pt(STATISTIC, df), pt(STATISTIC, df, lower.tail = FALSE)) + ) } RVAL <- list( @@ -120,7 +133,6 @@ cor.test_trimmed_v0.default <- } - #' Formula interface for fast correlation test #' #' Provides a formula interface to \code{\link{cor.test_trimmed_v0.default}}, @@ -141,25 +153,32 @@ cor.test_trimmed_v0.default <- #' @keywords internal #' @noRd #' @export -cor.test_trimmed_v0.formula <- - function(formula, data, subset, na.action, ...) - { - if(missing(formula) - || !inherits(formula, "formula") - || length(formula) != 2L) - stop("'formula' missing or invalid") - m <- match.call(expand.dots = FALSE) - if(is.matrix(eval(m$data, parent.frame()))) - m$data <- as.data.frame(data) - ## need stats:: for non-standard evaluation - m[[1L]] <- quote(stats::model.frame) - m$... <- NULL - mf <- eval(m, environment(formula)) - if(length(mf) != 2L) - stop("invalid formula") - DNAME <- paste(names(mf), collapse = " and ") - names(mf) <- c("x", "y") - y <- do.call("cor.test_trimmed_v0", c(mf, list(...))) - y$data.name <- DNAME - y +cor.test_trimmed_v0.formula <- function( + formula, + data, + subset, + na.action, + ... +) { + if ( + missing(formula) || !inherits(formula, "formula") || length(formula) != 2L + ) { + cli::cli_abort("{.arg formula} is missing or invalid.") + } + m <- match.call(expand.dots = FALSE) + if (is.matrix(eval(m$data, parent.frame()))) { + m$data <- as.data.frame(data) + } + ## need stats:: for non-standard evaluation + m[[1L]] <- quote(stats::model.frame) + m$... <- NULL + mf <- eval(m, environment(formula)) + if (length(mf) != 2L) { + cli::cli_abort("Invalid {.arg formula}.") } + DNAME <- paste(names(mf), collapse = " and ") + names(mf) <- c("x", "y") + y <- do.call("cor.test_trimmed_v0", c(mf, list(...))) + y$data.name <- DNAME + y +} diff --git a/air.toml b/air.toml new file mode 100644 index 0000000..e69de29 diff --git a/inst/WORDLIST b/inst/WORDLIST new file mode 100644 index 0000000..4127678 --- /dev/null +++ b/inst/WORDLIST @@ -0,0 +1,100 @@ +Barcode +Benjamini +Biomarker +CMD +DARA +DeepWiki +DepMap +EACCES +FPR +Hochberg +KRD +Lifecycle +Louvain +MTS +Mukherjee +NFeatures +ONcology +PERsonalized +PRJNA +PSOCK +PanCan +Pre +README +RStudio +Responder +Responders +SNE +Sinha +TPR +TSV +TTL +Transcriptomics +UI +UMAP +Vegesna +WangLabCSU +al +biomarker +callr +catalogue +cellLines +clusterExport +coords +csv +cv +debounced +densified +deserialized +dev +dropdown +erlotinib +et +fdr +gefitinib +ggiraph +ggplot +github +glmnet +grey +gtable +gzip +infunc +lolliplot +mvp +nginx +ntree +pkgdown +plotly +pos +pre +predVSgroundTruth +px +responder +responders +rf +rnorm +scRNA +selectize +sep +stackplot +standardise +standardising +stderr +subclone +subclones +tSNE +th +trainControl +transcriptional +transcriptomics +viabilityv +visualisation +vst +walkthrough +walkthroughs +winsorized +xls +xlsx +zoomable +一 diff --git a/jarl.toml b/jarl.toml new file mode 100644 index 0000000..83c504b --- /dev/null +++ b/jarl.toml @@ -0,0 +1,20 @@ +# jarl configuration file +# Reference: https://jarl.etiennebacher.com/reference/config-file + +[lint] +# Rules enabled on top of jarl's default rule set. The `TESTTHAT` group is +# opt-in, so it has to be requested explicitly. +extend-select = ["TESTTHAT"] + +# Files or directories that jarl should not lint. +exclude = ["R/vendor-*.R"] + +# Also lint the R code inside `@examples` and `@examplesIf` tags +# (the default). +check-roxygen = true + +# Rules that `jarl check --fix` is allowed to fix (all rules by default). +# fixable = ["PERF"] + +# Rules that `jarl check --fix` must leave untouched. +# unfixable = ["undesirable_function"] diff --git a/man/PERCEPTIONx-package.Rd b/man/PERCEPTIONx-package.Rd new file mode 100644 index 0000000..bdc5d49 --- /dev/null +++ b/man/PERCEPTIONx-package.Rd @@ -0,0 +1,38 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/PERCEPTIONx-package.R +\docType{package} +\name{PERCEPTIONx-package} +\alias{PERCEPTIONx-package} +\alias{PERCEPTIONx} +\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. +} +\section{License}{ + +MIT + file LICENSE +} + +\seealso{ +Useful links: +\itemize{ + \item \url{https://wanglabcsu.github.io/PERCEPTIONx} + \item \url{https://github.com/WangLabCSU/PERCEPTIONx} + \item Report bugs at \url{https://github.com/WangLabCSU/PERCEPTIONx/issues} +} + +} +\author{ +\strong{Maintainer}: Jia Ding \email{jiading682@qq.com} (\href{https://orcid.org/0009-0002-2530-0897}{ORCID}) + +Authors: +\itemize{ + \item Jia Ding \email{jiading682@qq.com} (\href{https://orcid.org/0009-0002-2530-0897}{ORCID}) +} + +} +\keyword{internal} diff --git a/tests/spelling.R b/tests/spelling.R new file mode 100644 index 0000000..6713838 --- /dev/null +++ b/tests/spelling.R @@ -0,0 +1,3 @@ +if(requireNamespace('spelling', quietly = TRUE)) + spelling::spell_check_test(vignettes = TRUE, error = FALSE, + skip_on_cran = TRUE) From 96802526b5629764b4de779c9bead5c212305f8d Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Wed, 4 Nov 2026 23:31:52 -0500 Subject: [PATCH 2/4] refactor: migrate to data.table, bump version to 0.4.0 - convert internal data manipulation in annotate/prepare_data to data.table - move glmnet/randomForest to Suggests, add data.table to Imports - export perception_depmap_drugs/perception_fda_approved_drugs - add Yuxi Yang as contributor in DESCRIPTION - ignore *.qs2 and README.Rmd build artifacts --- .Rbuildignore | 2 + .github/.gitignore | 1 + .github/CODE_OF_CONDUCT.md | 126 ++ .github/CONTRIBUTING.md | 47 + .github/ISSUE_TEMPLATE/issue_template.md | 16 + .github/SUPPORT.md | 35 + .github/workflows/feishu.yaml | 66 + .gitignore | 1 + DESCRIPTION | 20 +- NAMESPACE | 81 +- R/PERCEPTIONx-package.R | 4 + R/annotate.R | 205 +-- R/app.R | 4 +- R/depmap_meta.R | 8 +- R/evaluate.R | 57 +- R/load.R | 45 +- R/plot.R | 690 +++---- R/predict.R | 340 ++-- R/stats.R | 47 +- R/train.R | 155 +- R/utils.R | 6 +- R/utils_cortest.R | 30 +- README.Rmd | 210 +++ README.md | 171 +- _pkgdown.yml | 2 + dev/bench_girafe.R | 19 +- dev/time_demo.R | 188 +- inst/shiny/app/R/async_jobs.R | 1215 +++++++++---- inst/shiny/app/R/mod_data.R | 2088 +++++++++++++++------- inst/shiny/app/R/mod_help.R | 1175 ++++++++---- inst/shiny/app/R/mod_home.R | 278 ++- inst/shiny/app/R/mod_predict.R | 386 ++-- inst/shiny/app/R/mod_train.R | 831 ++++++--- inst/shiny/app/R/mod_visualize.R | 1190 ++++++++---- inst/shiny/app/R/shiny_helpers.R | 428 +++-- inst/shiny/app/app.R | 80 +- man/PERCEPTIONx-package.Rd | 5 + man/annotate_clones.Rd | 12 +- man/build_on_BULK_v2.Rd | 16 +- man/combine_drugs.Rd | 11 +- man/each_patient_pseudo_bulk.Rd | 2 +- man/export_plot_cairo.Rd | 6 +- man/load_depmap.Rd | 4 +- man/load_model.Rd | 4 +- man/perception_depmap_drugs.Rd | 19 + man/perception_fda_approved_drugs.Rd | 15 + man/plot_clone_distribution.Rd | 2 +- man/plot_clone_umap.Rd | 2 +- man/plot_clone_viability.Rd | 4 +- man/plot_model_performance.Rd | 2 +- man/plot_model_roc.Rd | 2 +- man/plot_response_boxplot.Rd | 2 +- man/plot_roc_curve.Rd | 4 +- man/plot_seurat_clustering.Rd | 10 +- man/plot_tsne_biomarker_viability.Rd | 4 +- man/plot_tsne_response.Rd | 4 +- man/predict_drugs.Rd | 6 +- man/predict_patients.Rd | 9 +- man/prepare_data.Rd | 12 +- man/run_parallel_feature_ranking_bulk.Rd | 2 +- man/train_models.Rd | 12 +- 61 files changed, 7262 insertions(+), 3156 deletions(-) create mode 100644 .github/.gitignore create mode 100644 .github/CODE_OF_CONDUCT.md create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/ISSUE_TEMPLATE/issue_template.md create mode 100644 .github/SUPPORT.md create mode 100644 .github/workflows/feishu.yaml create mode 100644 README.Rmd create mode 100644 man/perception_depmap_drugs.Rd create mode 100644 man/perception_fda_approved_drugs.Rd diff --git a/.Rbuildignore b/.Rbuildignore index 56ffddb..faba5e2 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -19,3 +19,5 @@ ^[.]?air[.]toml$ ^\.vscode$ ^jarl\.toml$ +\.qs2$ +^README\.Rmd$ diff --git a/.github/.gitignore b/.github/.gitignore new file mode 100644 index 0000000..2d19fc7 --- /dev/null +++ b/.github/.gitignore @@ -0,0 +1 @@ +*.html diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3ac34c8 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,126 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at codeofconduct@posit.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][https://github.com/mozilla/inclusion]. + +For answers to common questions about this code of conduct, see the FAQ at +. Translations are available at . + +[homepage]: https://www.contributor-covenant.org diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..fe33ff2 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# Contributing to PERCEPTIONx + +This outlines how to propose a change to PERCEPTIONx. +For a detailed discussion on contributing to this and other tidyverse packages, please see the [development contributing guide](https://rstd.io/tidy-contrib) and our [code review principles](https://code-review.tidyverse.org/). + +## Fixing typos + +You can fix typos, spelling mistakes, or grammatical errors in the documentation directly using the GitHub web interface, as long as the changes are made in the _source_ file. +This generally means you'll need to edit [roxygen2 comments](https://roxygen2.r-lib.org/articles/roxygen2.html) in an `.R`, not a `.Rd` file. +You can find the `.R` file that generates the `.Rd` by reading the comment in the first line. + +## Bigger changes + +If you want to make a bigger change, it's a good idea to first file an issue and make sure someone from the team agrees that it’s needed. +If you’ve found a bug, please file an issue that illustrates the bug with a minimal +[reprex](https://www.tidyverse.org/help/#reprex) (this will also help you write a unit test, if needed). +See our guide on [how to create a great issue](https://code-review.tidyverse.org/issues/) for more advice. + +### Pull request process + +* Fork the package and clone onto your computer. If you haven't done this before, we recommend using `usethis::create_from_github("WangLabCSU/PERCEPTIONx", fork = TRUE)`. + +* Install all development dependencies with `devtools::install_dev_deps()`, and then make sure the package passes R CMD check by running `devtools::check()`. + If R CMD check doesn't pass cleanly, it's a good idea to ask for help before continuing. +* Create a Git branch for your pull request (PR). We recommend using `usethis::pr_init("brief-description-of-change")`. + +* Make your changes, commit to git, and then create a PR by running `usethis::pr_push()`, and following the prompts in your browser. + The title of your PR should briefly describe the change. + The body of your PR should contain `Fixes #issue-number`. + +* For user-facing changes, add a bullet to the top of `NEWS.md` (i.e. just below the first header). Follow the style described in . + +### Code style + +* New code should follow the tidyverse [style guide](https://style.tidyverse.org). + You can use [Air](https://posit-dev.github.io/air/) to apply this style, but please don't restyle code that has nothing to do with your PR. + +* We use [roxygen2](https://cran.r-project.org/package=roxygen2), with [Markdown syntax](https://cran.r-project.org/web/packages/roxygen2/vignettes/rd-formatting.html), for documentation. + +* We use [testthat](https://cran.r-project.org/package=testthat) for unit tests. + Contributions with test cases included are easier to accept. + +## Code of Conduct + +Please note that the PERCEPTIONx project is released with a +[Contributor Code of Conduct](CODE_OF_CONDUCT.md). By contributing to this +project you agree to abide by its terms. diff --git a/.github/ISSUE_TEMPLATE/issue_template.md b/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000..d7c9eba --- /dev/null +++ b/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,16 @@ +--- +name: Bug report or feature request +about: Describe a bug you've seen or make a case for a new feature +--- + +Please briefly describe your problem and what output you expect. If you have a question, please don't use this form. Instead, ask on or . + +Please include a minimal reproducible example (AKA a reprex). If you've never heard of a [reprex](http://reprex.tidyverse.org/) before, start by reading . + +For more advice on how to write a great issue, see . + +Brief description of the problem + +```r +# insert reprex here +``` diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md new file mode 100644 index 0000000..1b7737f --- /dev/null +++ b/.github/SUPPORT.md @@ -0,0 +1,35 @@ +# Getting help with PERCEPTIONx + +Thanks for using PERCEPTIONx! +Before filing an issue, there are a few places to explore and pieces to put together to make the process as smooth as possible. + +## Make a reprex + +Start by making a minimal **repr**oducible **ex**ample using the [reprex](https://reprex.tidyverse.org/) package. +If you haven't heard of or used reprex before, you're in for a treat! +Seriously, reprex will make all of your R-question-asking endeavors easier (which is a pretty incredible ROI for the five to ten minutes it'll take you to learn what it's all about). +For additional reprex pointers, check out the [Get help!](https://www.tidyverse.org/help/) section of the tidyverse site. + +## Where to ask? + +Armed with your reprex, the next step is to figure out [where to ask](https://www.tidyverse.org/help/#where-to-ask). + +* If it's a question: start with [community.rstudio.com](https://community.rstudio.com/), and/or StackOverflow. There are more people there to answer questions. + +* If it's a bug: you're in the right place, [file an issue](https://github.com/WangLabCSU/PERCEPTIONx/issues/new). + +* If you're not sure: let the community help you figure it out! + If your problem _is_ a bug or a feature request, you can easily return here and report it. + +Before opening a new issue, be sure to [search issues and pull requests](https://github.com/WangLabCSU/PERCEPTIONx/issues) to make sure the bug hasn't been reported and/or already fixed in the development version. +By default, the search will be pre-populated with `is:issue is:open`. +You can [edit the qualifiers](https://help.github.com/articles/searching-issues-and-pull-requests/) (e.g. `is:pr`, `is:closed`) as needed. +For example, you'd simply remove `is:open` to search _all_ issues in the repo, open or closed. + +## What happens next? + +To be as efficient as possible, development of tidyverse packages tends to be very bursty, so you shouldn't worry if you don't get an immediate response. +Typically we don't look at a repo until a sufficient quantity of issues accumulates, then there’s a burst of intense activity as we focus our efforts. +That makes development more efficient because it avoids expensive context switching between problems, at the cost of taking longer to get back to you. +This process makes a good reprex particularly important because it might be multiple months between your initial report and when we start working on it. +If we can’t reproduce the bug, we can’t fix it! diff --git a/.github/workflows/feishu.yaml b/.github/workflows/feishu.yaml new file mode 100644 index 0000000..b61b04e --- /dev/null +++ b/.github/workflows/feishu.yaml @@ -0,0 +1,66 @@ +name: feishu bot + +on: + branch_protection_rule: + types: [created, deleted] + check_run: + types: [rerequested, completed] + check_suite: + types: [completed] + create: + delete: + deployment_status: + discussion: + types: [created, edited, answered] + discussion_comment: + types: [created, deleted] + fork: + gollum: + issues: + types: [opened, edited, milestoned, pinned, reopened] + issue_comment: + types: [created, deleted] + label: + types: [created, deleted] + merge_group: + types: [checks_requested] + milestone: + types: [opened, deleted] + page_build: + project: + types: [created, deleted, reopened] + project_card: + types: [created, deleted] + project_column: + types: [created, deleted] + public: + pull_request: + branches: ['main', 'devel'] + types: [opened, reopened] + pull_request_review: + types: [edited, dismissed, submitted] + pull_request_review_comment: + types: [created, edited, deleted] + pull_request_target: + types: [assigned, opened, synchronize, reopened] + push: + branches: ['main', 'devel'] + registry_package: + types: [published] + release: + types: [published] + status: + watch: + types: [started] +# schedule: +# - cron: '30 2 * * *' + +jobs: + send-event: + name: Webhook + runs-on: ubuntu-latest + steps: + - uses: WangLabCSU/feishu-bot-webhook-action@main + with: + webhook: ${{ secrets.FEISHU_BOT_WEBHOOK }} + signkey: ${{ secrets.FEISHU_BOT_SIGNKEY }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index fba02bc..62b3a74 100644 --- a/.gitignore +++ b/.gitignore @@ -46,3 +46,4 @@ inst/testdata/ # pkgdown site output (built by CI, deployed to gh-pages) docs/ +*.qs2 \ No newline at end of file diff --git a/DESCRIPTION b/DESCRIPTION index 57a52f9..8ae9a29 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,9 +1,12 @@ Package: PERCEPTIONx Title: Personalized Drug Response Prediction from Single-Cell Transcriptomics -Version: 0.3.1 -Authors@R: +Version: 0.4.0 +Authors@R: c( person("Jia", "Ding", , "jiading682@qq.com", role = c("aut", "cre"), - comment = c(ORCID = "0009-0002-2530-0897")) + comment = c(ORCID = "0009-0002-2530-0897")), + person("Yuxi", "Yang", , "15364051195@163.com", role = c("ctb"), + comment = c(ORCID = "0009-0006-1329-1224")) + ) 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 @@ -18,9 +21,7 @@ VignetteBuilder: knitr Imports: ggplot2, gridExtra, - glmnet, caret, - randomForest, pROC, rlang, Seurat, @@ -29,7 +30,8 @@ Imports: ggiraph, parallel, cli, - lifecycle + lifecycle, + data.table URL: https://wanglabcsu.github.io/PERCEPTIONx, https://github.com/WangLabCSU/PERCEPTIONx BugReports: https://github.com/WangLabCSU/PERCEPTIONx/issues Suggests: @@ -44,7 +46,11 @@ Suggests: thematic, readxl, callr, - spelling + spelling, + WGCNA, + matrixStats, + glmnet, + randomForest Config/testthat/edition: 3 Language: en-US Config/roxygen2/version: 8.1.0 diff --git a/NAMESPACE b/NAMESPACE index 97ebbb5..06206ac 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -26,6 +26,8 @@ export(list_mirrors) export(load_depmap) export(load_model) export(parse_clone_keys) +export(perception_depmap_drugs) +export(perception_fda_approved_drugs) export(plot_clone_distribution) export(plot_clone_umap) export(plot_clone_viability) @@ -47,79 +49,10 @@ export(run_parallel_feature_ranking_bulk) export(run_perception_app) export(train_models) export(zscore_viability) -importFrom(caret,predict.train) -importFrom(ggplot2, - aes, - annotate, - coord_cartesian, - coord_equal, - element_blank, - element_line, - element_rect, - element_text, - facet_grid, - facet_wrap, - geom_abline, - geom_bar, - geom_boxplot, - geom_hline, - geom_jitter, - geom_line, - geom_point, - geom_rect, - geom_segment, - geom_text, - geom_violin, - geom_vline, - ggplot, - ggtitle, - guide_colourbar, - guide_legend, - guides, - labs, - margin, - rel, - scale_color_manual, - scale_colour_gradient2, - scale_colour_gradientn, - scale_colour_manual, - scale_fill_manual, - scale_size, - scale_x_discrete, - theme, - theme_bw, - theme_void, - unit, - vars +importFrom(data.table, + "%chin%", + ":=", + .N, + .SD ) -importFrom(glmnet,glmnet) -importFrom(pROC, - auc, - ggroc, - roc, - smooth -) -importFrom(randomForest,randomForest) importFrom(rlang,.data) -importFrom(stats, - aggregate, - complete.cases, - cor, - cor.test, - median, - na.omit, - p.adjust, - phyper, - pnorm, - predict, - pt, - reformulate, - setNames, - t.test, - wilcox.test -) -importFrom(utils, - combn, - download.file, - head -) diff --git a/R/PERCEPTIONx-package.R b/R/PERCEPTIONx-package.R index 287ccb8..bb0a44f 100644 --- a/R/PERCEPTIONx-package.R +++ b/R/PERCEPTIONx-package.R @@ -87,6 +87,10 @@ startup_message_allowed <- function() { } ## usethis namespace: start +#' @importFrom data.table .N +#' @importFrom data.table %chin% +#' @importFrom data.table := +#' @importFrom data.table .SD ## usethis namespace: end NULL diff --git a/R/annotate.R b/R/annotate.R index f31a2c4..48bac9f 100644 --- a/R/annotate.R +++ b/R/annotate.R @@ -26,7 +26,7 @@ run_seurat_pipeline <- function( resolution, seed, progress_cb = NULL, - cluster_algorithm = 1, + cluster_algorithm = 1L, variable_selection = c("vst", "dispersion", "mvp") ) { lifecycle::deprecate_soft("0.3.1", "run_seurat_pipeline()") @@ -46,7 +46,7 @@ run_seurat_pipeline <- function( so <- Seurat::NormalizeData( so, normalization.method = "LogNormalize", - scale.factor = 10000 + scale.factor = 10000L ) notify("variable-features") # vst is the most accurate but by far the slowest variable-feature method @@ -62,10 +62,10 @@ run_seurat_pipeline <- function( # PCA requires npcs < min(nrow, ncol) of the scaled matrix -- cap dims to the # number actually available so small datasets do not error out. - max_pcs <- min(ncol(so), length(Seurat::VariableFeatures(object = so))) - 1 + max_pcs <- min(ncol(so), length(Seurat::VariableFeatures(object = so))) - 1L actual_dims <- min(dims, max_pcs) - if (actual_dims < 1) { - actual_dims <- 1 + if (actual_dims < 1L) { + actual_dims <- 1L } if (actual_dims < dims) { @@ -117,21 +117,21 @@ run_seurat_pipeline <- function( # uwot requires n_neighbors < number of points; cap it for tiny datasets # so a small test matrix (<= 15 cells) does not crash with an Annoy # index error. - n_neighbors <- min(15, max(2L, nrow(pca_emb) - 1L)) + n_neighbors <- min(15L, max(2L, nrow(pca_emb) - 1L)) coords <- uwot::umap( X = pca_emb, n_neighbors = n_neighbors, - n_components = 2, - n_epochs = 200, - n_trees = 10, + n_components = 2L, + n_epochs = 200L, + n_trees = 10L, metric = "cosine", - learning_rate = 1, + learning_rate = 1L, min_dist = 0.3, - spread = 1, - set_op_mix_ratio = 1, - local_connectivity = 1, - repulsion_strength = 1, - negative_sample_rate = 5, + spread = 1L, + set_op_mix_ratio = 1L, + local_connectivity = 1L, + repulsion_strength = 1L, + negative_sample_rate = 5L, n_threads = n_threads, verbose = FALSE ) @@ -196,14 +196,14 @@ run_seurat_pipeline <- function( annotate_clones <- function( method = c("umap", "tsne"), expression_matrix, - min_cells = 3, - min_features = 200, - nfeatures = 2000, - dims = 10, + min_cells = 3L, + min_features = 200L, + nfeatures = 2000L, + dims = 10L, resolution = 0.8, - seed = 42, + seed = 42L, progress_cb = NULL, - cluster_algorithm = 1, + cluster_algorithm = 1L, variable_selection = c("vst", "dispersion", "mvp") ) { method <- rlang::arg_match(method) @@ -229,12 +229,11 @@ annotate_clones <- function( cluster_ids <- Seurat::Idents(so) emb <- Seurat::Embeddings(so, reduction = method) - data.frame( + data.table::data.table( cell_id = names(cluster_ids), clone_id = as.character(cluster_ids), - dim_1 = emb[, 1], - dim_2 = emb[, 2], - stringsAsFactors = FALSE + dim_1 = emb[, 1L], + dim_2 = emb[, 2L] ) } @@ -262,28 +261,37 @@ build_clone_counts <- function(cell_clone_map, patient_ids) { ) } - map_df <- data.frame( + map_dt <- data.table::data.table( patient = patient_ids, - clone_id = cell_clone_map$clone_id, # Clone names are only unique *within* a patient (e.g. "Kydar01_c1" and # "Kydar02_c1" both shorten to "c1"). Keying the abundance columns on # "patient@@clone" keeps them aligned with the clone_expression_rnorm # columns and prevents abundance from being summed across patients. - clone_key = paste(patient_ids, cell_clone_map$clone_id, sep = "@@"), - stringsAsFactors = FALSE + clone_key = paste(patient_ids, cell_clone_map$clone_id, sep = "@@") ) - all_keys <- unique(map_df$clone_key) - all_patients <- unique(patient_ids) + all_patients <- unique(map_dt$patient) + all_keys <- unique(map_dt$clone_key) + + # Count cells per (patient, clone) pair, then pivot wide so that every clone + # key becomes a column of per-patient abundances. + patient <- clone_key <- NULL # * ease checking NOTE + counts <- map_dt[, list(n_cells = .N), by = list(patient, clone_key)] + counts <- data.table::dcast( + counts, + patient ~ clone_key, + value.var = "n_cells", + fill = 0L + ) - result <- data.frame(patients = all_patients, stringsAsFactors = FALSE) - for (cl in all_keys) { - result[[cl]] <- sapply(all_patients, function(pat) { - sum(map_df$patient == pat & map_df$clone_key == cl) - }) - } + # dcast sorts the clone keys; restore first-appearance column order so the + # columns line up with the clone_expression_rnorm columns. + data.table::setnames(counts, "patient", "patients") + data.table::setcolorder(counts, c("patients", all_keys)) - result + # Plain data.frame is the documented contract: predict_patients() subsets it + # as clone_counts[i, clone_cols], which is data.frame (not data.table) syntax. + as.data.frame(counts) } @@ -403,14 +411,14 @@ prepare_data <- function( patient_col = "patient_id", parse_patient = FALSE, patient_sep = "_", - patient_pos = 1, + patient_pos = 1L, genes_to_use = NULL, seurat_resolution = 0.8, - seurat_dims = 10, - seurat_nfeatures = 2000, - seurat_min_cells = 3, - seurat_min_features = 200, - seurat_seed = 42, + seurat_dims = 10L, + seurat_nfeatures = 2000L, + seurat_min_cells = 3L, + seurat_min_features = 200L, + seurat_seed = 42L, skip_clustering = FALSE, progress_cb = NULL ) { @@ -440,7 +448,12 @@ prepare_data <- function( } # --- Convert patient_mapping to list format if data frame --- - if (is.data.frame(patient_mapping)) { + if ( + is.data.frame(patient_mapping) || data.table::is.data.table(patient_mapping) + ) { + # Copy, so that set-by-reference edits below never touch the caller's object. + patient_mapping <- data.table::as.data.table(patient_mapping) + # Optional per-clone abundance column (count / cells / n_cells / # n_cells_per_clone / abundance): expand each row to that many rows so that # clone weights reflect TRUE cell numbers instead of equal 1/n per clone. @@ -452,25 +465,23 @@ prepare_data <- function( c("count", "cells", "n_cells", "n_cells_per_clone", "abundance"), tolower(colnames(patient_mapping)) ) - if (length(count_col) > 0) { + if (length(count_col) > 0L) { cnt_col <- colnames(patient_mapping)[ - tolower(colnames(patient_mapping)) == count_col[1] - ][1] + tolower(colnames(patient_mapping)) == count_col[1L] + ][1L] cnt <- suppressWarnings(as.numeric(patient_mapping[[cnt_col]])) - cnt[is.na(cnt) | cnt < 1] <- 1L - patient_mapping <- patient_mapping[ - rep(seq_len(nrow(patient_mapping)), cnt), - , - drop = FALSE - ] - patient_mapping[[cnt_col]] <- NULL - rownames(patient_mapping) <- NULL + cnt[is.na(cnt) | cnt < 1L] <- 1L + patient_mapping <- patient_mapping[rep( + seq_len(nrow(patient_mapping)), + cnt + )] + patient_mapping[, (cnt_col) := NULL] cli::cli_progress_step( "Expanded mapping by '{cnt_col}' to {nrow(patient_mapping)} rows (true clone abundance)" ) } - if (!cell_col %in% colnames(patient_mapping)) { + if (!cell_col %chin% colnames(patient_mapping)) { cli::cli_abort( "patient_mapping data frame must have a column named '{cell_col}'" ) @@ -505,17 +516,17 @@ prepare_data <- function( } # Add parsed patient IDs to the data frame - patient_mapping$patient_id_parsed <- patient_ids_parsed + patient_mapping[, patient_id_parsed := patient_ids_parsed] sample_cell_names <- split( patient_mapping[[cell_col]], - patient_mapping$patient_id_parsed + patient_mapping[["patient_id_parsed"]] ) cli::cli_progress_step( "Parsed {length(unique(patient_ids_parsed))} unique patient IDs" ) } else { # Use existing patient_col - if (!patient_col %in% colnames(patient_mapping)) { + if (!patient_col %chin% colnames(patient_mapping)) { cli::cli_abort( c( "patient_mapping data frame must have a column named '{patient_col}'", @@ -553,27 +564,25 @@ prepare_data <- function( # clone abundances reflect TRUE cell counts (matching the paper's figures) # instead of equal weights per clone. If the mapping is 1:1 with the matrix # columns (legacy equal-weight case) the behavior is unchanged. - sample_cell_ids <- NULL - if (is.list(sample_cell_names)) { - sample_cell_ids <- unlist(sample_cell_names, use.names = FALSE) + sample_cell_ids <- if (is.list(sample_cell_names)) { + unlist(sample_cell_names, use.names = FALSE) } else if (is.character(sample_cell_names)) { - sample_cell_ids <- sample_cell_names + sample_cell_names + } else { + NULL } + if ( !is.null(sample_cell_ids) && - anyDuplicated(sample_cell_ids) > 0 && + anyDuplicated(sample_cell_ids) > 0L && all(cn %in% sample_cell_ids) ) { - cell_clone_map <- data.frame( + cell_clone_map <- data.table::data.table( cell_id = sample_cell_ids, - clone_id = sample_cell_ids, - stringsAsFactors = FALSE + clone_id = sample_cell_ids ) - cell_clone_map <- cell_clone_map[ - cell_clone_map$cell_id %in% cn, - , - drop = FALSE - ] + cell_id <- NULL # ease check NOTE + cell_clone_map <- cell_clone_map[cell_id %in% cn] cli::cli_progress_step( "Using cell-count-resolved mapping: {nrow(cell_clone_map)} cells across {length(unique(cell_clone_map$cell_id))} clones" ) @@ -581,10 +590,9 @@ prepare_data <- function( # Keep the full column name as the unique clone identity (e.g. "Kydar01_c1"). # This is universal: clone names are whatever the user's data uses. Patient # separation is guaranteed downstream via "patient@@clone" keys. - cell_clone_map <- data.frame( + cell_clone_map <- data.table::data.table( cell_id = cn, - clone_id = cn, - stringsAsFactors = FALSE + clone_id = cn ) cli::cli_progress_step("Using {length(cn)} provided clone columns") } @@ -595,13 +603,13 @@ prepare_data <- function( # Auto-adjust min_features and nfeatures if gene count is small n_genes <- nrow(expression_matrix) if (n_genes < seurat_min_features) { - seurat_min_features <- max(1, floor(n_genes * 0.1)) + seurat_min_features <- max(1L, floor(n_genes * 0.1)) cli::cli_progress_step( "Adjusting min_features to {seurat_min_features} (only {n_genes} genes in expression matrix)" ) } if (n_genes < seurat_nfeatures) { - seurat_nfeatures <- max(10, n_genes) + seurat_nfeatures <- max(10L, n_genes) cli::cli_progress_step( "Adjusting nfeatures to {seurat_nfeatures} (only {n_genes} genes available)" ) @@ -646,18 +654,16 @@ prepare_data <- function( "{sum(unassigned)} cells could not be assigned to any patient. Removing them." ) keep_cells <- names(patient_ids)[!unassigned] - expression_matrix <- expression_matrix[, keep_cells, drop = FALSE] + expression_matrix <- expression_matrix[, keep_cells] patient_ids <- patient_ids[!unassigned] - cell_clone_map <- cell_clone_map[cell_clone_map$cell_id %in% keep_cells, ] + cell_clone_map <- cell_clone_map[cell_id %chin% keep_cells, ] } } cli::cli_progress_step("Found {length(unique(patient_ids))} patients") - # Add patient column to cell_clone_map - cell_clone_map$patient <- patient_ids[match( - cell_clone_map$cell_id, - names(patient_ids) - )] + # Add patient column to cell_clone_map; patient_ids is named by cell id, so the + # lookup needs no match(). + cell_clone_map[, patient := unname(patient_ids[cell_id])] # In clone-level mode, refine the clone label to the per-patient category # (e.g. "Kydar01_c1" -> "c1") using the KNOWN patient id, so clone keys @@ -665,19 +671,18 @@ prepare_data <- function( # when the cell name actually starts with its patient id; any other naming # scheme keeps the full name, so the behavior is universal. if (isTRUE(skip_clustering)) { - cell_clone_map$clone_id <- vapply( - seq_len(nrow(cell_clone_map)), - function(i) { - cell <- cell_clone_map$cell_id[i] - pat <- cell_clone_map$patient[i] - if (is.na(pat) || !startsWith(cell, pat)) { - return(cell) - } - rest <- sub("^[\\._-]", "", substring(cell, nchar(pat) + 1)) - if (nchar(rest) == 0) cell else rest - }, - character(1) - ) + clone_id <- patient <- cell_id <- NULL # ease checking NOTE + cell_clone_map[, + clone_id := { + has_prefix <- !is.na(patient) & startsWith(cell_id, patient) + stripped <- sub( + "^[\\._-]", + "", + substring(cell_id, nchar(patient) + 1L) + ) + data.table::fifelse(has_prefix & nzchar(stripped), stripped, cell_id) + } + ] } # --- Step 3: Compute clone-level mean expression --- @@ -688,7 +693,7 @@ prepare_data <- function( patient_ids = patient_ids ) - if (length(clone_expr_list) == 0) { + if (length(clone_expr_list) == 0L) { cli::cli_abort( "No clone expression matrices were produced. Check cell-clone mapping." ) @@ -704,7 +709,7 @@ prepare_data <- function( cli::cli_progress_step("[4/5] Rank-normalizing clone expression...") if (!is.null(genes_to_use)) { available_genes <- intersect(genes_to_use, rownames(clone_expr_merged)) - if (length(available_genes) == 0) { + if (length(available_genes) == 0L) { rlang::abort( "None of the provided genes_to_use were found in the expression matrix." ) diff --git a/R/app.R b/R/app.R index 6f17e3a..4d65440 100644 --- a/R/app.R +++ b/R/app.R @@ -27,7 +27,7 @@ run_perception_app <- function() { if (appDir == "") { cli::cli_abort(c( x = "Could not find PERCEPTIONx dashboard. ", - i = "Try re-installing the package with: `install.packages('PERCEPTIONx', repos = NULL, type = 'source')`" + i = "Try re-installing the package with: `utils::install.packages('PERCEPTIONx', repos = NULL, type = 'source')`" )) } @@ -39,7 +39,7 @@ run_perception_app <- function() { reason = "for PERCEPTIONx dashboard" ) # Set max upload size to 1 GB (for DepMap ~567MB + models) - options(shiny.maxRequestSize = 1024 * 1024^2) + options(shiny.maxRequestSize = 1024L * 1024L^2L) # Shiny Server mode: the server runs app.R and expects a shiny app OBJECT # back — a nested runApp() fails there. Detect it via SHINY_PORT (Shiny diff --git a/R/depmap_meta.R b/R/depmap_meta.R index 534a431..834b9f7 100644 --- a/R/depmap_meta.R +++ b/R/depmap_meta.R @@ -32,7 +32,7 @@ extract_depmap_meta <- function(depmap_path, cache_file = NULL) { DepMap <- readRDS(depmap_path) if (!is.list(DepMap)) { cli::cli_abort(c( - x = "The file is not a {.cls list}.", + x = "The file is not a list.", i = "Expected a DepMap.RDS from the PERCEPTIONx release (or an object with the same structure)." )) } @@ -48,7 +48,7 @@ extract_depmap_meta <- function(depmap_path, cache_file = NULL) { "expression_20Q4" ) missing_fields <- setdiff(required_fields, names(DepMap)) - if (length(missing_fields) > 0) { + if (length(missing_fields) > 0L) { cli::cli_abort(c( "The RDS is missing required components: {.field {missing_fields}}.", "i" = "Re-save it with these components, or use the built-in 'Download & Load' (known-good)." @@ -61,10 +61,10 @@ extract_depmap_meta <- function(depmap_path, cache_file = NULL) { list( nrow = nrow(obj), ncol = ncol(obj), - cols_preview = head(colnames(obj), 12) + cols_preview = utils::head(colnames(obj), 12L) ) } else { - list(nrow = NA_integer_, ncol = NA_integer_, cols_preview = character(0)) + list(nrow = NA_integer_, ncol = NA_integer_, cols_preview = character(0L)) } }) names(components) <- nms diff --git a/R/evaluate.R b/R/evaluate.R index 5a2dfff..02f3061 100644 --- a/R/evaluate.R +++ b/R/evaluate.R @@ -4,7 +4,6 @@ #' #' @name evaluate_perception #' @keywords internal -#' @importFrom stats reformulate aggregate median NULL @@ -22,13 +21,13 @@ perf_to_vector <- function(perf) { if (is.data.frame(perf)) { cor <- if ("estimate.cor" %in% names(perf)) { - perf$estimate.cor[1] + perf$estimate.cor[1L] } else if ("correlation" %in% names(perf)) { - perf$correlation[1] + perf$correlation[1L] } else { NA } - p <- if ("p.value" %in% names(perf)) perf$p.value[1] else NA + p <- if ("p.value" %in% names(perf)) perf$p.value[1L] else NA return(c(pvalue = unname(p), correlation = unname(cor))) } @@ -44,10 +43,12 @@ perf_to_vector <- function(perf) { return(c(pvalue = unname(p), correlation = unname(cor))) } - if (is.numeric(perf) && length(perf) >= 2) { - return(c(pvalue = as.numeric(perf[1]), correlation = as.numeric(perf[2]))) + if (is.numeric(perf) && length(perf) >= 2L) { + return(c(pvalue = as.numeric(perf[1L]), correlation = as.numeric(perf[2L]))) } + warning("Unable to interpret performance object. Using NA.") + c(pvalue = NA, correlation = NA) } @@ -79,8 +80,10 @@ perf_to_vector <- function(perf) { #' @export compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { # Validate input - if (!is.list(model_list) || length(model_list) == 0) { - cli::cli_abort("model_list must be a non-empty list of trained models.") + if (!is.list(model_list) || length(model_list) == 0L) { + cli::cli_abort( + "`model_list` must be a non-empty {.cls list} of trained models." + ) } # Extract performance metrics from each model @@ -89,18 +92,21 @@ compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { perf_cv <- do.call( rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) { + if (is.null(x) || (length(x) == 1L && is.na(x))) { return(c(pvalue = NA, correlation = NA)) } # CV stores sqrt(R²) = |correlation| only (no p-value available). - c(pvalue = NA, correlation = as.numeric(x$model_performance_during_cv)[1]) + c( + pvalue = NA, + correlation = as.numeric(x$model_performance_during_cv)[1L] + ) }) ) perf_bulk <- do.call( rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) { + if (is.null(x) || (length(x) == 1L && is.na(x))) { return(c(pvalue = NA, correlation = NA)) } perf_to_vector(x$performance_in_bulk) @@ -110,7 +116,7 @@ compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { perf_pseudo_bulk <- do.call( rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) { + if (is.null(x) || (length(x) == 1L && is.na(x))) { return(c(pvalue = NA, correlation = NA)) } perf_to_vector(x$performance_in_pseudo_bulk) @@ -120,7 +126,7 @@ compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { perf_scRNA <- do.call( rbind, lapply(model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) { + if (is.null(x) || (length(x) == 1L && is.na(x))) { return(c(pvalue = NA, correlation = NA)) } perf_to_vector(x$performance_in_scRNA) @@ -179,7 +185,7 @@ compare_performance <- function(model_list, threshold = 0.3, verbose = TRUE) { "scRNA: {round(mean_corrs['perf_scRNA'], 3)}" )) - if (length(passing_drugs) > 0) { + if (length(passing_drugs) > 0L) { cli::cli_alert_info("Drugs passing threshold in scRNA:") cli::cli_ul(passing_drugs) } @@ -239,7 +245,7 @@ get_performance <- function(filepath, drug_names = NULL) { # Filter by drug names if specified if (!is.null(drug_names)) { available_drugs <- intersect(drug_names, names(model_data)) - if (length(available_drugs) == 0) { + if (length(available_drugs) == 0L) { cli::cli_abort( "None of the specified {.arg drug_names} found in the model file." ) @@ -249,7 +255,7 @@ get_performance <- function(filepath, drug_names = NULL) { # Extract only performance metrics (memory efficient) performance_only <- lapply(model_data, function(x) { - if (is.null(x) || length(x) == 1 && is.na(x)) { + if (is.null(x) || length(x) == 1L && is.na(x)) { return(list( model_performance_during_cv = c(NA, NA), performance_in_bulk = c(NA, NA), @@ -296,10 +302,7 @@ get_significant_models <- function( dataset = "scRNA" ) { # Validate dataset parameter - valid_datasets <- c("scRNA", "bulk", "pseudo_bulk", "cv") - if (!dataset %in% valid_datasets) { - cli::cli_abort("{.arg dataset} must be one of: {.val {valid_datasets}}") - } + dataset <- rlang::arg_match0(dataset, c("scRNA", "bulk", "pseudo_bulk", "cv")) # Get the appropriate performance element name perf_element <- switch( @@ -315,14 +318,14 @@ get_significant_models <- function( significant_models <- model_list[vapply( model_list, function(x) { - if (is.null(x) || (length(x) == 1 && is.na(x))) { + if (is.null(x) || (length(x) == 1L && is.na(x))) { return(FALSE) } if (dataset == "cv") { cv <- x$model_performance_during_cv return( - is.numeric(cv) && length(cv) >= 1 && isTRUE(cv[1] > min_correlation) + is.numeric(cv) && length(cv) >= 1L && isTRUE(cv[1L] > min_correlation) ) } @@ -330,7 +333,7 @@ get_significant_models <- function( isTRUE(perf[["correlation"]] > min_correlation) && isTRUE(perf[["pvalue"]] < max_pvalue) }, - logical(1) + logical(1L) )] cli::cli_alert_info( @@ -357,7 +360,7 @@ get_significant_models <- function( #' #' @export each_patient_pseudo_bulk <- function( - x = 1, + x = 1L, comb_viability_df, Clone_Counts_per_patients, clone_Level_z_expression_df @@ -376,7 +379,7 @@ each_patient_pseudo_bulk <- function( unlist(Clone_Counts_per_patients[x, col_clone_ids]), na.rm = TRUE ) - if (!is.finite(total_cells) || total_cells == 0 || length(cols) == 0) { + if (!is.finite(total_cells) || total_cells == 0L || length(cols) == 0L) { # No cells / no clones for this patient: return all-NA pseudo-bulk. return(rep(NA_real_, nrow(clone_Level_z_expression_df))) } @@ -386,10 +389,10 @@ each_patient_pseudo_bulk <- function( sub <- clone_Level_z_expression_df[, cols, drop = FALSE] - if (ncol(sub) > 1) { + if (ncol(sub) > 1L) { pseudo_bulk <- drop(sub %*% clone_weights) } else { - pseudo_bulk <- sub[, 1] + pseudo_bulk <- sub[, 1L] } pseudo_bulk } diff --git a/R/load.R b/R/load.R index b32903c..b666243 100644 --- a/R/load.R +++ b/R/load.R @@ -2,7 +2,6 @@ #' #' @name load_perception #' @keywords internal -#' @importFrom utils download.file NULL # Package-level environment for storing DepMap data @@ -13,7 +12,7 @@ NULL # truncated downloads / partial cache files so they are never cached or # parsed. Bump this if the release asset is ever regenerated with a # different size. -.depmap_release_size <- 594589700 +.depmap_release_size <- 594589700L #' Get the DepMap dataset #' @@ -65,9 +64,9 @@ download_with_mirrors <- function( urls, destfile, quiet = FALSE, - speed_threshold = 10, - timeout_seconds = 30, - retries = 0, + speed_threshold = 10L, + timeout_seconds = 30L, + retries = 0L, expected_size = NULL ) { # Save and restore R timeout setting @@ -106,8 +105,8 @@ download_with_mirrors <- function( cli::cli_alert_info("Trying mirror {i}/{length(urls)}") } - for (attempt in 0:retries) { - if (attempt > 0 && !quiet) { + for (attempt in 0L:retries) { + if (attempt > 0L && !quiet) { cli::cli_alert_info("Retry attempt {attempt}") } @@ -119,12 +118,12 @@ download_with_mirrors <- function( tryCatch( { suppressWarnings({ - curl_extra <- if (attempt > 0) { + curl_extra <- if (attempt > 0L) { paste(extra_base, "-C -") } else { extra_base } - download.file( + utils::download.file( urls[i], destfile, mode = "wb", @@ -168,7 +167,7 @@ download_with_mirrors <- function( incomplete <- TRUE if (!quiet) { cli::cli_alert_warning( - "Incomplete download: {sz} of {expected_size} bytes ({round(100 * sz / expected_size, 1)}%), discarding and retrying." + "Incomplete download: {sz} of {expected_size} rlang::bytes ({round(100 * sz / expected_size, 1)}%), discarding and retrying." ) } file.remove(destfile) @@ -176,11 +175,11 @@ download_with_mirrors <- function( } } - if (success && file.exists(destfile) && file.size(destfile) > 0) { + if (success && file.exists(destfile) && file.size(destfile) > 0L) { end_time <- Sys.time() elapsed <- as.numeric(difftime(end_time, start_time, units = "secs")) - file_size_mb <- file.size(destfile) / 1024 / 1024 - speed_kb_s <- (file.size(destfile) / 1024) / elapsed + file_size_mb <- file.size(destfile) / 1024L / 1024L + speed_kb_s <- (file.size(destfile) / 1024L) / elapsed if (!quiet) { cli::cli_alert_success( @@ -272,7 +271,7 @@ add_mirrors <- function(urls, position = c("first", "last")) { urls <- unique(urls) urls <- urls[!urls %in% current_mirrors] - if (length(urls) == 0) { + if (length(urls) == 0L) { cli::cli_alert_info("All mirrors already exist.") return(invisible(current_mirrors)) } @@ -410,14 +409,14 @@ load_model <- function( read = FALSE, mirror = FALSE, mirror_url = NULL, - timeout_seconds = 30, - retries = 0, + timeout_seconds = 30L, + retries = 0L, force = FALSE, all = FALSE ) { drugs <- tolower(c(...)) if (all) { - if (length(drugs) > 0) { + if (length(drugs) > 0L) { warning( "all = TRUE overrides the drug names given in ...; downloading all 44 models.", call. = FALSE @@ -425,7 +424,7 @@ load_model <- function( } drugs <- perception_all_drugs } - if (length(drugs) == 0) { + if (length(drugs) == 0L) { cli::cli_abort( "Drug list is empty. Pass drug names or set {.code all = TRUE} to download all 44 pre-trained models." ) @@ -488,7 +487,7 @@ load_model <- function( } } - if (read && length(result) > 0) { + if (read && length(result) > 0L) { return(result) } @@ -540,8 +539,8 @@ load_depmap <- function( read = FALSE, mirror = FALSE, mirror_url = NULL, - timeout_seconds = 300, - retries = 1, + timeout_seconds = 300L, + retries = 1L, force = FALSE ) { if (!dir.exists(dest)) { @@ -623,7 +622,9 @@ load_depmap <- function( cli::cli_alert_success( "Assigned {.val DepMap} to package cache and global environment." ) - cli::cli_alert_info("Use {.code get_depmap()} or {.code DepMap} to access the data.") + cli::cli_alert_info( + "Use {.code get_depmap()} or {.code DepMap} to access the data." + ) return(invisible(DepMap)) } diff --git a/R/plot.R b/R/plot.R index e46a8cc..837a36c 100644 --- a/R/plot.R +++ b/R/plot.R @@ -9,11 +9,7 @@ #' #' @name plot_perception #' @keywords internal -#' @importFrom ggplot2 ggplot aes geom_point geom_segment geom_boxplot geom_violin geom_bar geom_hline geom_line geom_vline geom_jitter geom_text geom_rect geom_abline coord_cartesian coord_equal theme theme_bw theme_void labs element_text element_rect element_line element_blank facet_grid facet_wrap vars scale_colour_gradientn scale_colour_gradient2 scale_fill_manual scale_color_manual scale_colour_manual scale_x_discrete scale_size margin unit guide_colourbar guides guide_legend ggtitle annotate rel #' @importFrom rlang .data -#' @importFrom pROC ggroc roc auc smooth -#' @importFrom stats t.test wilcox.test -#' @importFrom utils combn NULL # Column names used in aes() - declare as global variables to suppress R CMD check notes @@ -42,7 +38,9 @@ utils::globalVariables(c( "Dataset", "y_mid", "Label", - "AUC" + "AUC", + # data.table non-standard evaluation pronoun + ".SD" )) # --------------------------------------------------------------------------- @@ -51,48 +49,54 @@ utils::globalVariables(c( # Unified theme for all PERCEPTIONx plots: white background, subtle grid, # consistent font hierarchy and legend styling. -theme_perception <- function(base_size = 11, base_family = "") { +theme_perception <- function(base_size = 11L, base_family = "") { ggplot2::theme_bw(base_size = base_size, base_family = base_family) + ggplot2::theme( - panel.background = element_rect(fill = "white", color = NA), - plot.background = element_rect(fill = "white", color = NA), - panel.border = element_rect(color = "#dfe3ee", linewidth = 0.5), - panel.grid.major = element_line(color = "#eef0f6", linewidth = 0.4), - panel.grid.minor = element_blank(), - axis.ticks = element_line(color = "#b6becd"), - axis.title = element_text(face = "bold", color = "#1e2a4a"), - axis.text = element_text(color = "#3d4a63"), - plot.title = element_text( + panel.background = ggplot2::element_rect(fill = "white", color = NA), + plot.background = ggplot2::element_rect(fill = "white", color = NA), + panel.border = ggplot2::element_rect(color = "#dfe3ee", linewidth = 0.5), + panel.grid.major = ggplot2::element_line( + color = "#eef0f6", + linewidth = 0.4 + ), + panel.grid.minor = ggplot2::element_blank(), + axis.ticks = ggplot2::element_line(color = "#b6becd"), + axis.title = ggplot2::element_text(face = "bold", color = "#1e2a4a"), + axis.text = ggplot2::element_text(color = "#3d4a63"), + plot.title = ggplot2::element_text( face = "bold", color = "#1e2a4a", - hjust = 0, - margin = margin(b = 4) + hjust = 0L, + margin = ggplot2::margin(b = 4L) ), - plot.subtitle = element_text( + plot.subtitle = ggplot2::element_text( color = "#5a6a8a", - hjust = 0, - margin = margin(b = 8) + hjust = 0L, + margin = ggplot2::margin(b = 8L) ), - legend.background = element_rect(fill = "white", color = NA), - legend.key = element_rect(fill = "white", color = NA), - legend.box.background = element_rect(fill = "white", color = NA), - legend.title = element_text( + legend.background = ggplot2::element_rect(fill = "white", color = NA), + legend.key = ggplot2::element_rect(fill = "white", color = NA), + legend.box.background = ggplot2::element_rect(fill = "white", color = NA), + legend.title = ggplot2::element_text( face = "bold", color = "#1e2a4a", - size = rel(0.85) + size = ggplot2::rel(0.85) + ), + legend.text = ggplot2::element_text( + color = "#3d4a63", + size = ggplot2::rel(0.8) ), - legend.text = element_text(color = "#3d4a63", size = rel(0.8)), - strip.background = element_rect( + strip.background = ggplot2::element_rect( fill = "#f6f8fc", color = "#dfe3ee", linewidth = 0.5 ), - strip.text = element_text( + strip.text = ggplot2::element_text( face = "bold", color = "#1e2a4a", - size = rel(0.85) + size = ggplot2::rel(0.85) ), - plot.margin = margin(t = 6, r = 8, b = 6, l = 6) + plot.margin = ggplot2::margin(t = 6L, r = 8L, b = 6L, l = 6L) ) } @@ -124,8 +128,8 @@ clone_palette <- function(n) { # More clones: evenly space hues around the wheel, anchored on the deep # blue of the first curated color (hue ~214 deg), with moderate chroma and # high-ish lightness for a soft, harmonious look. - hues <- (214 + seq(0, n - 1) * 360 / n) %% 360 - unname(grDevices::hcl(h = hues, c = 65, l = 70)) + hues <- (214L + seq(0L, n - 1L) * 360L / n) %% 360L + unname(grDevices::hcl(h = hues, c = 65L, l = 70L)) } # Diverging scale for z-score / 0-1 style values: the two ends are pinned to @@ -153,7 +157,7 @@ natural_levels <- function(x) { paste(p[c(TRUE, FALSE)], collapse = "") } }, - character(1) + character(1L) ) num <- vapply( parts, @@ -164,7 +168,7 @@ natural_levels <- function(x) { suppressWarnings(as.integer(paste(p[c(FALSE, TRUE)], collapse = ""))) } }, - integer(1) + integer(1L) ) num[is.na(num)] <- 0L lv[order(pref, num)] @@ -224,9 +228,9 @@ plot_tsne_response <- function( point_size = NULL, colors = NULL, palette = c("viridis", "diverging"), - midpoint = 0, + midpoint = 0L, limits = NULL, - base_size = 11, + base_size = 11L, tooltip = TRUE, tooltip_col = NULL ) { @@ -247,30 +251,30 @@ plot_tsne_response <- function( # Adaptive point size / alpha to prevent overplotting on large scRNA data. if (is.null(point_size)) { - point_size <- if (n_points > 50000) { + point_size <- if (n_points > 50000L) { 0.4 - } else if (n_points > 20000) { + } else if (n_points > 20000L) { 0.5 - } else if (n_points > 8000) { + } else if (n_points > 8000L) { 0.6 } else { 0.8 } } - point_alpha <- if (n_points > 50000) { + point_alpha <- if (n_points > 50000L) { 0.35 - } else if (n_points > 20000) { + } else if (n_points > 20000L) { 0.5 - } else if (n_points > 8000) { + } else if (n_points > 8000L) { 0.65 } else { 0.8 } # Downsample extremely large datasets for smooth interactive rendering. - if (n_points > 50000) { - set.seed(42) - keep <- sample.int(n_points, 50000) + if (n_points > 50000L) { + set.seed(42L) + keep <- sample.int(n_points, 50000L) tsne_data <- tsne_data[keep, , drop = FALSE] cli::cli_alert_info( "Downsampled to 50,000 points for rendering (n = {n_points})." @@ -295,32 +299,35 @@ plot_tsne_response <- function( } tsne_data$data_id <- paste0("cell_", seq_len(nrow(tsne_data))) - p <- ggplot(tsne_data, aes(x = X, y = Y, color = .data[[color_var]])) + + p <- ggplot2::ggplot( + tsne_data, + ggplot2::aes(x = X, y = Y, color = .data[[color_var]]) + ) + { if (tt_ok) { ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), + ggplot2::aes(tooltip = tooltip_text, data_id = data_id), size = point_size, alpha = point_alpha ) } else { - geom_point(size = point_size, alpha = point_alpha) + ggplot2::geom_point(size = point_size, alpha = point_alpha) } } + theme_perception(base_size = base_size) + - labs(color = color_label, x = "", y = "") + - theme( + ggplot2::labs(color = color_label, x = "", y = "") + + ggplot2::theme( legend.position = "top", - legend.key.height = unit(0.9, "lines"), - legend.key.width = unit(2.6, "lines") + legend.key.height = ggplot2::unit(0.9, "lines"), + legend.key.width = ggplot2::unit(2.6, "lines") ) if (palette == "diverging") { p <- p + - scale_colour_gradient2( - low = diverging_colors[1], - mid = diverging_colors[2], - high = diverging_colors[3], + ggplot2::scale_colour_gradient2( + low = diverging_colors[1L], + mid = diverging_colors[2L], + high = diverging_colors[3L], midpoint = midpoint, limits = limits ) @@ -329,11 +336,11 @@ plot_tsne_response <- function( # Pass limits through: with a fixed 0-1 scale (e.g. gene expression), # a constant-0 vector maps to the LOW (grey) end instead of falling to # the high end (red) when the data range degenerates to a single value. - p <- p + scale_colour_gradientn(colours = cols, limits = limits) + p <- p + ggplot2::scale_colour_gradientn(colours = cols, limits = limits) } if (!is.null(title)) { - p <- p + ggtitle(title) + p <- p + ggplot2::ggtitle(title) } return(p) @@ -371,7 +378,7 @@ plot_clone_umap <- function( title = NULL, color_label = "Clone", point_size = NULL, - base_size = 11, + base_size = 11L, tooltip = TRUE, tooltip_col = NULL ) { @@ -385,30 +392,30 @@ plot_clone_umap <- function( # Adaptive point size / alpha to prevent overplotting on large scRNA data. if (is.null(point_size)) { - point_size <- if (n_points > 50000) { + point_size <- if (n_points > 50000L) { 0.4 - } else if (n_points > 20000) { + } else if (n_points > 20000L) { 0.5 - } else if (n_points > 8000) { + } else if (n_points > 8000L) { 0.6 } else { 0.8 } } - point_alpha <- if (n_points > 50000) { + point_alpha <- if (n_points > 50000L) { 0.35 - } else if (n_points > 20000) { + } else if (n_points > 20000L) { 0.5 - } else if (n_points > 8000) { + } else if (n_points > 8000L) { 0.65 } else { 0.8 } # Downsample extremely large datasets for smooth interactive rendering. - if (n_points > 50000) { - set.seed(42) - keep <- sample.int(n_points, 50000) + if (n_points > 50000L) { + set.seed(42L) + keep <- sample.int(n_points, 50000L) tsne_data <- tsne_data[keep, , drop = FALSE] cli::cli_alert_info( "Downsampled to 50,000 points for rendering (n = {n_points})." @@ -432,42 +439,45 @@ plot_clone_umap <- function( } tsne_data$data_id <- paste0("cell_", seq_len(nrow(tsne_data))) - p <- ggplot(tsne_data, aes(x = X, y = Y, color = .data[[clone_col]])) + + p <- ggplot2::ggplot( + tsne_data, + ggplot2::aes(x = X, y = Y, color = .data[[clone_col]]) + ) + { if (tt_ok) { ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), + ggplot2::aes(tooltip = tooltip_text, data_id = data_id), size = point_size, alpha = point_alpha ) } else { - geom_point(size = point_size, alpha = point_alpha) + ggplot2::geom_point(size = point_size, alpha = point_alpha) } } + - scale_colour_manual( + ggplot2::scale_colour_manual( values = clone_palette(length(clone_levels)), drop = FALSE ) + theme_perception(base_size = base_size) + - labs(color = color_label, x = "", y = "") + + ggplot2::labs(color = color_label, x = "", y = "") + # Compact legend: force 2 rows so a 15-clone palette (8+7) does not wrap # into 3+ rows and compress the plot canvas. - guides( - color = guide_legend( - nrow = 2, - keywidth = unit(0.7, "lines"), - keyheight = unit(0.7, "lines"), + ggplot2::guides( + color = ggplot2::guide_legend( + nrow = 2L, + keywidth = ggplot2::unit(0.7, "lines"), + keyheight = ggplot2::unit(0.7, "lines"), override.aes = list(size = 2.5) ) ) + - theme( + ggplot2::theme( legend.position = "top", - legend.key.height = unit(0.7, "lines"), - legend.key.width = unit(0.7, "lines") + legend.key.height = ggplot2::unit(0.7, "lines"), + legend.key.width = ggplot2::unit(0.7, "lines") ) if (!is.null(title)) { - p <- p + ggtitle(title) + p <- p + ggplot2::ggtitle(title) } return(p) @@ -508,7 +518,7 @@ plot_clone_umap <- function( plot_clone_distribution <- function( clone_distribution, response_var = NULL, - base_size = 15, + base_size = 15L, tooltip = TRUE, tooltip_col = NULL ) { @@ -545,12 +555,12 @@ plot_clone_distribution <- function( key_pref <- vapply( pat_parts, function(p) paste(p[c(TRUE, FALSE)], collapse = ""), - character(1) + character(1L) ) key_num <- suppressWarnings(vapply( pat_parts, function(p) as.integer(paste(p[c(FALSE, TRUE)], collapse = "")), - integer(1) + integer(1L) )) key_num[is.na(key_num)] <- 0L clone_distribution$patients <- factor( @@ -571,9 +581,9 @@ plot_clone_distribution <- function( # Adaptive x-axis labels: rotate 45 deg only when many patients would # otherwise overlap. The FACET STRIP labels (R/NR on top) stay horizontal. # All patient labels are always shown (no downsampling). - x_angle <- if (n_patients <= 8) 0 else 45 - x_hjust <- if (n_patients <= 8) 0.5 else 1 - x_vjust <- if (n_patients <= 8) 0.5 else 1 + x_angle <- if (n_patients <= 8L) 0L else 45L + x_hjust <- if (n_patients <= 8L) 0.5 else 1L + x_vjust <- if (n_patients <= 8L) 0.5 else 1L # Tooltip for ggiraph interactivity (hover shows clone + proportion). tt_ok <- tooltip && requireNamespace("ggiraph", quietly = TRUE) @@ -595,14 +605,14 @@ plot_clone_distribution <- function( "tooltip_text" } - p <- ggplot( + p <- ggplot2::ggplot( clone_distribution, - aes(fill = clones, y = weights, x = patients) + ggplot2::aes(fill = clones, y = weights, x = patients) ) + { if (tt_ok) { ggiraph::geom_bar_interactive( - aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), + ggplot2::aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), position = "stack", stat = "identity", width = 0.75, @@ -610,7 +620,7 @@ plot_clone_distribution <- function( linewidth = 0.15 ) } else { - geom_bar( + ggplot2::geom_bar( position = "stack", stat = "identity", width = 0.75, @@ -619,28 +629,28 @@ plot_clone_distribution <- function( ) } } + - scale_fill_manual(values = clone_palette(n_clones)) + + ggplot2::scale_fill_manual(values = clone_palette(n_clones)) + theme_perception(base_size = base_size) + - theme( - axis.text.x = element_text( + ggplot2::theme( + axis.text.x = ggplot2::element_text( angle = x_angle, hjust = x_hjust, vjust = x_vjust, - size = rel(0.8), - margin = margin(t = 4) + size = ggplot2::rel(0.8), + margin = ggplot2::margin(t = 4L) ), legend.position = "bottom", - legend.text = element_text(size = rel(0.7)), - legend.key.height = unit(0.7, "lines"), + legend.text = ggplot2::element_text(size = ggplot2::rel(0.7)), + legend.key.height = ggplot2::unit(0.7, "lines"), strip.placement = "outside", - strip.text = element_text( - angle = 0, + strip.text = ggplot2::element_text( + angle = 0L, hjust = 0.5, vjust = 0.5, - size = rel(0.8) + size = ggplot2::rel(0.8) ) ) + - labs(y = "Clone Proportion", x = "Patients", fill = "Clone") + ggplot2::labs(y = "Clone Proportion", x = "Patients", fill = "Clone") # Facet by response group (R/NR) -- Y axis kept fixed (0-1) so proportions # are directly comparable across facets; only X is free. @@ -648,8 +658,8 @@ plot_clone_distribution <- function( !is.null(response_var) && response_var %in% colnames(clone_distribution) ) { p <- p + - facet_grid( - cols = vars(.data[[response_var]]), + ggplot2::facet_grid( + cols = ggplot2::vars(.data[[response_var]]), shrink = TRUE, scales = "free_x", space = "free_x" @@ -670,7 +680,7 @@ fmt_pval <- function(p) { return("NA") } if (p < 0.001) { - format(p, scientific = TRUE, digits = 2) + format(p, scientific = TRUE, digits = 2L) } else { sprintf("%.3f", p) } @@ -758,8 +768,8 @@ plot_clone_viability <- function( weights_var = NULL, response_var = NULL, drug = NULL, - base_size = 11, - y_limits = c(-3, 1.2), + base_size = 11L, + y_limits = c(-3L, 1.2), viridis_scale = FALSE, tooltip = TRUE, tooltip_col = NULL @@ -792,7 +802,7 @@ plot_clone_viability <- function( tag <- resp_short_tag(rv) paste0(tag, " ", pat) }, - character(1) + character(1L) ) # Two-line variant used by facet_wrap (top strip, no rotation) clone_viability$facet_label_wrap <- vapply( @@ -802,7 +812,7 @@ plot_clone_viability <- function( tag <- resp_short_tag(rv) paste0(tag, "\n", pat) }, - character(1) + character(1L) ) } else { clone_viability$facet_label <- as.character(clone_viability$patient) @@ -844,7 +854,7 @@ plot_clone_viability <- function( # size range (scale_size below), not by clamping the value. clone_viability$size_val <- clone_viability[[weights_var]] } - aes_mapping <- aes( + aes_mapping <- ggplot2::aes( y = .data[[viability_var]], x = clone_id, color = .data[[viability_var]] @@ -882,12 +892,12 @@ plot_clone_viability <- function( y_data <- clone_viability[[viability_var]] y_min <- min(y_data, na.rm = TRUE) y_max <- max(y_data, na.rm = TRUE) - y_bottom <- min(0, y_min) + y_bottom <- min(0L, y_min) y_top <- y_max + (y_max - y_bottom) * 0.1 # Adaptive facet layout: wrap for many patients, single-row grid otherwise n_patients <- length(unique(clone_viability$facet_label)) - wrap_mode <- n_patients > 12 + wrap_mode <- n_patients > 12L # hline data (one per facet) so ggplotly can locate the facet column facet_var <- if (wrap_mode) "facet_label_wrap" else "facet_label" @@ -896,24 +906,29 @@ plot_clone_viability <- function( facet_var, drop = FALSE ] - hline_data$yintercept <- 0 + hline_data$yintercept <- 0L - p <- ggplot(clone_viability, aes_mapping) + - geom_hline( + p <- ggplot2::ggplot(clone_viability, aes_mapping) + + ggplot2::geom_hline( data = hline_data, - mapping = aes(yintercept = yintercept), + mapping = ggplot2::aes(yintercept = yintercept), color = "grey60", linewidth = 0.3 ) + - geom_segment( - aes(x = clone_id, xend = clone_id, y = 0, yend = .data[[viability_var]]), + ggplot2::geom_segment( + ggplot2::aes( + x = clone_id, + xend = clone_id, + y = 0L, + yend = .data[[viability_var]] + ), color = "grey40", linewidth = 0.35 ) + { if (tt_ok && has_weights) { ggiraph::geom_point_interactive( - aes( + ggplot2::aes( size = size_val, tooltip = .data[[tt_col]], data_id = .data[[tt_col]] @@ -922,30 +937,30 @@ plot_clone_viability <- function( ) } else if (tt_ok) { ggiraph::geom_point_interactive( - aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), + ggplot2::aes(tooltip = .data[[tt_col]], data_id = .data[[tt_col]]), alpha = 0.85 ) } else if (has_weights) { - geom_point(aes(size = size_val), alpha = 0.85) + ggplot2::geom_point(ggplot2::aes(size = size_val), alpha = 0.85) } else { - geom_point(alpha = 0.85) + ggplot2::geom_point(alpha = 0.85) } } + - coord_cartesian(ylim = c(y_bottom, y_top)) + + ggplot2::coord_cartesian(ylim = c(y_bottom, y_top)) + theme_perception(base_size = base_size) + - labs( + ggplot2::labs( x = "Clones", y = "Predicted Viability (z-score)", color = "Predicted Viability", size = if (has_weights) "Proportion in Tumor" else NULL, caption = "Higher = more resistant - lower = more sensitive (stronger drug killing). Z-scores are standardized across all patients, so clones are comparable across patients." ) + - theme( + ggplot2::theme( legend.position = "top", legend.box = "horizontal", - legend.box.spacing = unit(8, "pt"), - legend.key.size = unit(13, "pt"), - axis.title.y = element_text(margin = margin(r = 6)) + legend.box.spacing = ggplot2::unit(8L, "pt"), + legend.key.size = ggplot2::unit(13L, "pt"), + axis.title.y = ggplot2::element_text(margin = ggplot2::margin(r = 6L)) ) # Color scale: red-blue diverging by default (blue = low/sensitive, white = @@ -956,72 +971,76 @@ plot_clone_viability <- function( # available via viridis_scale = TRUE. if (viridis_scale) { p <- p + - scale_colour_gradientn( + ggplot2::scale_colour_gradientn( colours = sequential_colors, - breaks = function(limits) pretty(limits, n = 4) + breaks = function(limits) pretty(limits, n = 4L) ) } else { p <- p + - scale_colour_gradient2( - low = diverging_colors[1], - mid = diverging_colors[2], - high = diverging_colors[3], - midpoint = 0, - breaks = function(limits) pretty(limits, n = 4) + ggplot2::scale_colour_gradient2( + low = diverging_colors[1L], + mid = diverging_colors[2L], + high = diverging_colors[3L], + midpoint = 0L, + breaks = function(limits) pretty(limits, n = 4L) ) } if (has_weights) { max_w <- max(clone_viability[[weights_var]], na.rm = TRUE) - if (!is.finite(max_w) || max_w <= 0) { - max_w <- 1 + if (!is.finite(max_w) || max_w <= 0L) { + max_w <- 1L } # Point size = true proportion on its NATURAL 0..1 scale: a 0.8 clone is # always visibly larger than a 0.4 clone (no clamping). The upper range is # kept modest (3 instead of 5) so high-abundance clones do not dominate the # panel. Legend breaks span the full 0..max_w range so the legend matches # real circles. Tune here if the lollipop balls look too big/small. - size_breaks <- pretty(c(0, max_w), n = 3) - size_breaks <- size_breaks[size_breaks >= 0 & size_breaks <= max_w] - if (length(size_breaks) < 2) { - size_breaks <- c(0, max_w) + size_breaks <- pretty(c(0L, max_w), n = 3L) + size_breaks <- size_breaks[size_breaks >= 0L & size_breaks <= max_w] + if (length(size_breaks) < 2L) { + size_breaks <- c(0L, max_w) } p <- p + - scale_size(range = c(1, 3), limits = c(0, max_w), breaks = size_breaks) + ggplot2::scale_size( + range = c(1L, 3L), + limits = c(0L, max_w), + breaks = size_breaks + ) } else { - p <- p + guides(size = "none") + p <- p + ggplot2::guides(size = "none") } if (wrap_mode) { - ncol <- min(6, max(2, ceiling(sqrt(n_patients) * 1.4))) + ncol <- min(6L, max(2L, ceiling(sqrt(n_patients) * 1.4))) p <- p + - facet_wrap( - reformulate(facet_var), + ggplot2::facet_wrap( + stats::reformulate(facet_var), scales = "free_x", ncol = ncol, drop = TRUE, strip.position = "top" ) + - theme( - strip.text = element_text( - angle = 0, + ggplot2::theme( + strip.text = ggplot2::element_text( + angle = 0L, hjust = 0.5, vjust = 0.5, - size = rel(0.62), + size = ggplot2::rel(0.62), lineheight = 0.9 ), - axis.text.x = element_text( - angle = 0, + axis.text.x = ggplot2::element_text( + angle = 0L, hjust = 0.5, vjust = 0.5, - size = rel(0.55) + size = ggplot2::rel(0.55) ), - panel.spacing = unit(0.3, "lines") + panel.spacing = ggplot2::unit(0.3, "lines") ) } else { p <- p + - facet_grid( - reformulate(facet_var, "."), + ggplot2::facet_grid( + stats::reformulate(facet_var, "."), scales = "free_x", shrink = TRUE, drop = TRUE, @@ -1029,21 +1048,22 @@ plot_clone_viability <- function( switch = "x", as.table = TRUE ) + - theme( - strip.text = element_text( - angle = 45, - hjust = 0, + ggplot2::theme( + strip.text = ggplot2::element_text( + angle = 45L, + hjust = 0L, vjust = 0.5, - size = rel(0.75), + size = ggplot2::rel(0.75), lineheight = 0.9, - margin = margin(t = 2, b = 2, l = 4, r = 4, unit = "pt") + margin = ggplot2::margin(t = 2L, b = 2L, l = 4L, r = 4L, unit = "pt") ), - panel.spacing = unit(0.15, "lines") + panel.spacing = ggplot2::unit(0.15, "lines") ) } - if (!is.null(drug) && nchar(drug) > 0) { - p <- p + ggtitle(drug, subtitle = sprintf("N = %d patients", n_patients)) + if (!is.null(drug) && nchar(drug) > 0L) { + p <- p + + ggplot2::ggtitle(drug, subtitle = sprintf("N = %d patients", n_patients)) } p @@ -1080,20 +1100,20 @@ plot_roc_curve <- function( response, predictor, smooth_curve = TRUE, - base_size = 15, - auc_digits = 3, + base_size = 15L, + auc_digits = 3L, title = NULL, tooltip = TRUE ) { if (!requireNamespace("pROC", quietly = TRUE)) { cli::cli_abort(c( "Package {.pkg pROC} is required for ROC curve plotting.", - "i" = "Install with {.run install.packages('pROC')}." + "i" = "Install with {.run utils::install.packages('pROC')}." )) } # Single-class response cannot build a ROC curve -- return an informative placeholder - if (length(unique(response[!is.na(response)])) < 2) { + if (length(unique(response[!is.na(response)])) < 2L) { cli::cli_abort( "ROC curve requires at least two response classes (e.g. both R and NR)." ) @@ -1135,16 +1155,16 @@ plot_roc_curve <- function( transpose = FALSE ) ) - sp$fpr <- 1 - sp$specificity + sp$fpr <- 1L - sp$specificity sp <- sp[order(sp$fpr), ] sp <- sp[!duplicated(sp$fpr), ] - if (nrow(sp) > 2) { + if (nrow(sp) > 2L) { dens <- stats::approx( sp$fpr, sp$sensitivity, - xout = seq(0, 1, length.out = 200) + xout = seq(0L, 1L, length.out = 200L) ) - curve_df <- data.frame(specificity = 1 - dens$x, sensitivity = dens$y) + curve_df <- data.frame(specificity = 1L - dens$x, sensitivity = dens$y) } else { curve_df <- sp } @@ -1158,7 +1178,7 @@ plot_roc_curve <- function( ) ) } - curve_df$fpr <- 1 - curve_df$specificity + curve_df$fpr <- 1L - curve_df$specificity curve_df$tpr <- curve_df$sensitivity curve_df$tooltip_text <- sprintf( "FPR: %.3f\nTPR: %.3f", @@ -1175,48 +1195,48 @@ plot_roc_curve <- function( can_line <- nrow(curve_df) >= 2L if (tt_ok) { - p <- ggplot(curve_df, aes(x = fpr, y = tpr)) + p <- ggplot2::ggplot(curve_df, ggplot2::aes(x = fpr, y = tpr)) if (can_line) { p <- p + ggiraph::geom_line_interactive( - aes(tooltip = tooltip_text, data_id = data_id), + ggplot2::aes(tooltip = tooltip_text, data_id = data_id), linewidth = 1.1, color = "#2E86AB" ) } p <- p + ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), + ggplot2::aes(tooltip = tooltip_text, data_id = data_id), size = 1.4, color = "#2E86AB", alpha = 0.7 ) } else { - p <- ggplot(curve_df, aes(x = fpr, y = tpr)) + p <- ggplot2::ggplot(curve_df, ggplot2::aes(x = fpr, y = tpr)) if (can_line) { - p <- p + geom_line(linewidth = 1.1, color = "#2E86AB") + p <- p + ggplot2::geom_line(linewidth = 1.1, color = "#2E86AB") } - p <- p + geom_point(size = 1.4, color = "#2E86AB", alpha = 0.7) + p <- p + ggplot2::geom_point(size = 1.4, color = "#2E86AB", alpha = 0.7) } p <- p + theme_perception(base_size = base_size) + - labs(x = "1 - Specificity (FPR)", y = "Sensitivity (TPR)") + - coord_equal() + + ggplot2::labs(x = "1 - Specificity (FPR)", y = "Sensitivity (TPR)") + + ggplot2::coord_equal() + # Random-chance diagonal from (0,0) to (1,1) - annotate( + ggplot2::annotate( "segment", - x = 0, - xend = 1, - y = 0, - yend = 1, + x = 0L, + xend = 1L, + y = 0L, + yend = 1L, color = "grey60", linewidth = 0.5, linetype = "dashed" ) + # AUC badge in a rounded, semi-transparent box (bottom-right corner, # inside the region below the curve). - annotate( + ggplot2::annotate( "rect", xmin = 0.60, xmax = 0.98, @@ -1227,7 +1247,7 @@ plot_roc_curve <- function( color = "#dfe3ee", linewidth = 0.3 ) + - annotate( + ggplot2::annotate( "text", x = 0.79, y = 0.125, @@ -1238,7 +1258,7 @@ plot_roc_curve <- function( ) if (!is.null(title)) { - p <- p + ggtitle(title) + p <- p + ggplot2::ggtitle(title) } return(p) @@ -1282,7 +1302,7 @@ plot_response_boxplot <- function( response_var = "response", predicted_var = "predicted_viability", y_label = "Predicted Viability (z-score)", - base_size = 15, + base_size = 15L, compare_method = "wilcox.test", alternative = "less", tooltip = TRUE @@ -1312,7 +1332,7 @@ plot_response_boxplot <- function( # groups use a qualitative palette covering every level. Beyond the fixed # 6-color palette, generate evenly-spaced hues (ggplot2's default scheme), # so any number of response groups is supported. - n_lv <- length(levels(exp_vs_pred[[response_var]])) + n_lv <- nlevels(exp_vs_pred[[response_var]]) fixed_pal <- c( "#C13232", "#2E86AB", @@ -1325,9 +1345,9 @@ plot_response_boxplot <- function( grp_colors <- fixed_pal[seq_len(n_lv)] } else { grp_colors <- grDevices::hcl( - h = seq(15, 375, length.out = n_lv + 1)[seq_len(n_lv)], - c = 100, - l = 65 + h = seq(15L, 375L, length.out = n_lv + 1L)[seq_len(n_lv)], + c = 100L, + l = 65L ) } names(grp_colors) <- levels(exp_vs_pred[[response_var]]) @@ -1347,18 +1367,18 @@ plot_response_boxplot <- function( # violin's silhouette, # 3) jitter = raw points, spread across the violin width so the dots # visually match the density shape. - p <- ggplot( + p <- ggplot2::ggplot( exp_vs_pred, - aes(x = .data[[response_var]], y = .data[[predicted_var]]) + ggplot2::aes(x = .data[[response_var]], y = .data[[predicted_var]]) ) + - geom_violin( - aes(fill = .data[[response_var]]), + ggplot2::geom_violin( + ggplot2::aes(fill = .data[[response_var]]), alpha = 0.25, width = 0.80, color = "grey40", linewidth = 0.35 ) + - geom_boxplot( + ggplot2::geom_boxplot( width = 0.14, outlier.shape = NA, fill = NA, @@ -1368,7 +1388,7 @@ plot_response_boxplot <- function( { if (tt_ok) { ggiraph::geom_jitter_interactive( - aes( + ggplot2::aes( color = .data[[response_var]], tooltip = tooltip_text, data_id = data_id @@ -1378,8 +1398,8 @@ plot_response_boxplot <- function( alpha = 0.55 ) } else { - geom_jitter( - aes(color = .data[[response_var]]), + ggplot2::geom_jitter( + ggplot2::aes(color = .data[[response_var]]), width = 0.18, size = 1.5, alpha = 0.55 @@ -1387,10 +1407,10 @@ plot_response_boxplot <- function( } } + theme_perception(base_size = base_size) + - labs(y = y_label, x = "") + - theme(legend.position = "none") + - scale_fill_manual(values = grp_colors) + - scale_color_manual(values = grp_colors) + ggplot2::labs(y = y_label, x = "") + + ggplot2::theme(legend.position = "none") + + ggplot2::scale_fill_manual(values = grp_colors) + + ggplot2::scale_color_manual(values = grp_colors) # Statistical annotation: pairwise bracket for 2 groups (one-sided Wilcoxon, # alternative = first group < second); for 3-4 groups pairwise two-sided @@ -1398,16 +1418,20 @@ plot_response_boxplot <- function( # correction; for 5+ groups a single Kruskal-Wallis omnibus test (too many # brackets to read). A global Kruskal-Wallis only says "at least one group # differs" -- it cannot say WHICH pairs differ, so pairwise is used instead. - n_lv <- length(levels(exp_vs_pred[[response_var]])) - if (n_lv == 2) { + n_lv <- nlevels(exp_vs_pred[[response_var]]) + if (n_lv == 2L) { lvls <- levels(exp_vs_pred[[response_var]]) - grp1 <- exp_vs_pred[[predicted_var]][exp_vs_pred[[response_var]] == lvls[1]] - grp2 <- exp_vs_pred[[predicted_var]][exp_vs_pred[[response_var]] == lvls[2]] - if (length(grp1) > 1 && length(grp2) > 1) { + grp1 <- exp_vs_pred[[predicted_var]][ + exp_vs_pred[[response_var]] == lvls[1L] + ] + grp2 <- exp_vs_pred[[predicted_var]][ + exp_vs_pred[[response_var]] == lvls[2L] + ] + if (length(grp1) > 1L && length(grp2) > 1L) { test_fun <- if (tolower(compare_method) == "t.test") { - t.test + stats::t.test } else { - wilcox.test + stats::wilcox.test } wt <- tryCatch( test_fun(grp1, grp2, alternative = alternative), @@ -1420,34 +1444,34 @@ plot_response_boxplot <- function( y_pos <- y_max + (y_max - min(exp_vs_pred[[predicted_var]], na.rm = TRUE)) * 0.10 p <- p + - annotate( + ggplot2::annotate( "segment", - x = 1, - xend = 1, + x = 1L, + xend = 1L, y = y_pos * 0.985, yend = y_pos, color = "#1e2a4a", linewidth = 0.4 ) + - annotate( + ggplot2::annotate( "segment", - x = 2, - xend = 2, + x = 2L, + xend = 2L, y = y_pos * 0.985, yend = y_pos, color = "#1e2a4a", linewidth = 0.4 ) + - annotate( + ggplot2::annotate( "segment", - x = 1, - xend = 2, + x = 1L, + xend = 2L, y = y_pos, yend = y_pos, color = "#1e2a4a", linewidth = 0.4 ) + - annotate( + ggplot2::annotate( "text", x = 1.5, y = y_pos * 1.03, @@ -1457,41 +1481,41 @@ plot_response_boxplot <- function( fontface = "italic", color = "#1e2a4a" ) + - coord_cartesian(ylim = c(NA, y_pos * 1.06)) + ggplot2::coord_cartesian(ylim = c(NA, y_pos * 1.06)) } } } - } else if (n_lv > 2) { + } else if (n_lv > 2L) { test_data <- exp_vs_pred[ !is.na(exp_vs_pred[[response_var]]) & !is.na(exp_vs_pred[[predicted_var]]), ] if ( - nrow(test_data) >= 6 && length(unique(test_data[[response_var]])) >= 2 + nrow(test_data) >= 6L && length(unique(test_data[[response_var]])) >= 2L ) { lvls <- levels(exp_vs_pred[[response_var]]) - if (n_lv <= 4) { + if (n_lv <= 4L) { # Pairwise Wilcoxon rank-sum tests (two-sided: no directional hypothesis # among arbitrary groups like PD/RD/TN), BH-adjusted across all pairs. - combos <- combn(seq_along(lvls), 2, simplify = FALSE) + combos <- utils::combn(seq_along(lvls), 2L, simplify = FALSE) res_list <- lapply(combos, function(ij) { g1 <- test_data[[predicted_var]][ - test_data[[response_var]] == lvls[ij[1]] + test_data[[response_var]] == lvls[ij[1L]] ] g2 <- test_data[[predicted_var]][ - test_data[[response_var]] == lvls[ij[2]] + test_data[[response_var]] == lvls[ij[2L]] ] - if (length(g1) < 2 || length(g2) < 2) { + if (length(g1) < 2L || length(g2) < 2L) { return(NULL) } - wt <- tryCatch(wilcox.test(g1, g2), error = function(e) NULL) + wt <- tryCatch(stats::wilcox.test(g1, g2), error = function(e) NULL) if (is.null(wt)) { return(NULL) } - data.frame(i = ij[1], j = ij[2], p = wt$p.value) + data.frame(i = ij[1L], j = ij[2L], p = wt$p.value) }) res_df <- do.call(rbind, res_list) - if (!is.null(res_df) && nrow(res_df) > 0) { + if (!is.null(res_df) && nrow(res_df) > 0L) { res_df$p_adj <- stats::p.adjust(res_df$p, method = "BH") y_max <- max(test_data[[predicted_var]], na.rm = TRUE) y_min <- min(test_data[[predicted_var]], na.rm = TRUE) @@ -1503,7 +1527,7 @@ plot_response_boxplot <- function( x2 <- res_df$j[k] p_label <- sprintf("adj. p = %s", fmt_pval(res_df$p_adj[k])) p <- p + - annotate( + ggplot2::annotate( "segment", x = x1, xend = x1, @@ -1512,7 +1536,7 @@ plot_response_boxplot <- function( color = "#1e2a4a", linewidth = 0.4 ) + - annotate( + ggplot2::annotate( "segment", x = x2, xend = x2, @@ -1521,7 +1545,7 @@ plot_response_boxplot <- function( color = "#1e2a4a", linewidth = 0.4 ) + - annotate( + ggplot2::annotate( "segment", x = x1, xend = x2, @@ -1530,9 +1554,9 @@ plot_response_boxplot <- function( color = "#1e2a4a", linewidth = 0.4 ) + - annotate( + ggplot2::annotate( "text", - x = (x1 + x2) / 2, + x = (x1 + x2) / 2L, y = y_pos + span * 0.025, label = p_label, size = base_size * 0.28, @@ -1542,11 +1566,11 @@ plot_response_boxplot <- function( ) } p <- p + - labs( + ggplot2::labs( caption = "Pairwise Wilcoxon rank-sum tests (two-sided), BH-adjusted p-values" ) + - coord_cartesian( - ylim = c(NA, y_max + span * (0.06 + 0.07 * (nrow(res_df) + 1))) + ggplot2::coord_cartesian( + ylim = c(NA, y_max + span * (0.06 + 0.07 * (nrow(res_df) + 1L))) ) } } @@ -1566,9 +1590,9 @@ plot_response_boxplot <- function( if (is.finite(y_max) && is.finite(y_min)) { y_pos <- y_max + (y_max - y_min) * 0.08 p <- p + - annotate( + ggplot2::annotate( "text", - x = (1 + n_lv) / 2, + x = (1L + n_lv) / 2L, y = y_pos, label = p_label, size = base_size * 0.3, @@ -1576,7 +1600,7 @@ plot_response_boxplot <- function( fontface = "italic", color = "#1e2a4a" ) + - coord_cartesian(ylim = c(NA, y_pos * 1.10)) + ggplot2::coord_cartesian(ylim = c(NA, y_pos * 1.10)) } } } @@ -1617,7 +1641,7 @@ plot_response_boxplot <- function( plot_model_performance <- function( performance_list, threshold_range = NULL, - base_size = 20, + base_size = 20L, highlight_threshold = 0.3, tooltip = TRUE ) { @@ -1634,7 +1658,7 @@ plot_model_performance <- function( if (!(col %in% colnames(el))) { return(NULL) } - el[[col]][1] + el[[col]][1L] } else { if (is.null(names(el)) || !(col %in% names(el))) { return(NULL) @@ -1643,7 +1667,7 @@ plot_model_performance <- function( } }) vals <- vals[!sapply(vals, is.null)] - if (length(vals) == 0) { + if (length(vals) == 0L) { cli::cli_abort( "No performance metrics found in performance_list (missing {.field {what}})." ) @@ -1674,7 +1698,7 @@ plot_model_performance <- function( all_cors <- c(cor_scRNA, cor_bulk, cor_pseudo) hi <- suppressWarnings(max( 0.6, - ceiling(max(all_cors, na.rm = TRUE) * 100) / 100 + ceiling(max(all_cors, na.rm = TRUE) * 100L) / 100L )) if (!is.finite(hi) || hi <= 0.1) { hi <- 0.6 @@ -1730,40 +1754,40 @@ plot_model_performance <- function( ) df2plot$data_id <- paste0("perf_", seq_len(nrow(df2plot))) - p <- ggplot( + p <- ggplot2::ggplot( df2plot, - aes(x = Predictability, y = drugProp, color = dataused) + ggplot2::aes(x = Predictability, y = drugProp, color = dataused) ) + - geom_vline( + ggplot2::geom_vline( xintercept = highlight_threshold, linetype = "dashed", color = "#C13232", alpha = 0.5, linewidth = 0.4 ) + - geom_line(linewidth = 0.9) + + ggplot2::geom_line(linewidth = 0.9) + { if (tt_ok) { ggiraph::geom_point_interactive( - aes(tooltip = tooltip_text, data_id = data_id), + ggplot2::aes(tooltip = tooltip_text, data_id = data_id), size = 1.8, alpha = 0.85 ) } else { - geom_point(size = 1.8, alpha = 0.85) + ggplot2::geom_point(size = 1.8, alpha = 0.85) } } + - scale_color_manual(values = dataset_colors) + + ggplot2::scale_color_manual(values = dataset_colors) + theme_perception(base_size = base_size) + - labs( + ggplot2::labs( y = "Proportion of Drugs", color = "Validation Dataset", x = "Predictability (Pearson Correlation)" ) + - theme( + ggplot2::theme( legend.position = "top", legend.box = "horizontal", - legend.box.spacing = unit(8, "pt") + legend.box.spacing = ggplot2::unit(8L, "pt") ) return(p) @@ -1797,15 +1821,15 @@ plot_model_performance <- function( #' } #' #' @export -plot_model_roc <- function(performance_list, base_size = 13) { +plot_model_roc <- function(performance_list, base_size = 13L) { if (!requireNamespace("pROC", quietly = TRUE)) { cli::cli_abort(c( "Package {.pkg pROC} is required for ROC computation.", - "i" = "Install with {.run install.packages('pROC')}." + "i" = "Install with {.run utils::install.packages('pROC')}." )) } if (is.null(names(performance_list))) { - performance_list <- setNames(list(performance_list), "model") + performance_list <- stats::setNames(list(performance_list), "model") } ds_map <- c( @@ -1828,7 +1852,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { } ds_out <- lapply(names(ds_map), function(k) { df <- m$predVSgroundTruth[[k]] - if (is.null(df) || nrow(df) < 6) { + if (is.null(df) || nrow(df) < 6L) { return(list( rows = NULL, why = sprintf( @@ -1844,14 +1868,14 @@ plot_model_roc <- function(performance_list, base_size = 13) { why = sprintf("%s: missing 'Observed' column", k) )) } - pred_col <- setdiff(colnames(df), "Observed")[1] + pred_col <- setdiff(colnames(df), "Observed")[1L] if (is.na(pred_col)) { return(list(rows = NULL, why = sprintf("%s: no prediction column", k))) } obs <- as.numeric(df[["Observed"]]) pred <- as.numeric(df[[pred_col]]) keep <- !is.na(obs) & !is.na(pred) - if (sum(keep) < 4) { + if (sum(keep) < 4L) { return(list( rows = NULL, why = sprintf( @@ -1867,7 +1891,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { # ties -- e.g. many cell lines capped at AUC = 1 for a targeted drug -- # into a single class and makes the ROC impossible. First-tie ranks are # always 1..n, so the median split always yields two balanced classes. - if (length(unique(obs[keep])) < 2) { + if (length(unique(obs[keep])) < 2L) { return(list( rows = NULL, why = sprintf( @@ -1902,7 +1926,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { )) list( rows = data.frame( - fpr = 1 - co$specificity, + fpr = 1L - co$specificity, tpr = co$sensitivity, Dataset = unname(ds_map[[k]]), Drug = d, @@ -1915,7 +1939,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { reasons <- vapply( ds_out, function(x) if (is.null(x$why)) "" else x$why, - character(1) + character(1L) ) reasons <- reasons[nzchar(reasons)] ok_rows <- do.call(rbind, lapply(ds_out, function(x) x$rows)) @@ -1928,9 +1952,9 @@ plot_model_roc <- function(performance_list, base_size = 13) { names(curve_rows) <- names(performance_list) # Drugs that produced no ROC data at all -- record them so the app can tell # the user instead of silently showing fewer panels. - dropped_drugs <- names(curve_rows)[vapply(curve_rows, is.null, logical(1))] - curve_rows <- curve_rows[!vapply(curve_rows, is.null, logical(1))] - if (length(curve_rows) == 0) { + dropped_drugs <- names(curve_rows)[vapply(curve_rows, is.null, logical(1L))] + curve_rows <- curve_rows[!vapply(curve_rows, is.null, logical(1L))] + if (length(curve_rows) == 0L) { cli::cli_abort( "No prediction-vs-observed data available to compute validation ROC." ) @@ -1968,7 +1992,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { # collide with the AUC values there. Use compact but still readable labels -- # the top legend spells the full names out. n_drugs_total <- length(unique(df$Drug)) - short_mode <- n_drugs_total > 4 + short_mode <- n_drugs_total > 4L if (short_mode) { ds_labels <- c( "bulk" = "Bulk", @@ -2017,7 +2041,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { Dataset = ds, y_mid = y_mid, Label = ds_labels[[ds]], - AUC = if (nrow(sub)) sub$AUC[1] else NA_real_, + AUC = if (nrow(sub)) sub$AUC[1L] else NA_real_, stringsAsFactors = FALSE ) }) @@ -2025,18 +2049,18 @@ plot_model_roc <- function(performance_list, base_size = 13) { }) ) - p <- ggplot(df, aes(x = fpr, y = tpr, color = Dataset)) + - geom_abline( - slope = 1, - intercept = 0, + p <- ggplot2::ggplot(df, ggplot2::aes(x = fpr, y = tpr, color = Dataset)) + + ggplot2::geom_abline( + slope = 1L, + intercept = 0L, linetype = "dashed", color = "grey55", linewidth = 0.35 ) + - geom_line(linewidth = 0.9) + + ggplot2::geom_line(linewidth = 0.9) + # shadow layer -- constants passed directly (not aes()) so ggplot2 does not # warn about recycling scalar aesthetics across the per-drug rows. - geom_rect( + ggplot2::geom_rect( data = box_bg, xmin = box_x0 + 0.006, xmax = box_x1 + 0.006, @@ -2048,7 +2072,7 @@ plot_model_roc <- function(performance_list, base_size = 13) { inherit.aes = FALSE ) + # card background - geom_rect( + ggplot2::geom_rect( data = box_bg, xmin = box_x0, xmax = box_x1, @@ -2060,17 +2084,17 @@ plot_model_roc <- function(performance_list, base_size = 13) { inherit.aes = FALSE ) + # title "AUC" + separator line - geom_text( + ggplot2::geom_text( data = box_bg, - x = (box_x0 + box_x1) / 2, - y = box_y1 - header_h / 2, + x = (box_x0 + box_x1) / 2L, + y = box_y1 - header_h / 2L, label = "AUC", inherit.aes = FALSE, size = base_size * 0.28, fontface = "bold", color = "grey35" ) + - geom_segment( + ggplot2::geom_segment( data = box_bg, x = box_x0 + 0.02, xend = box_x1 - 0.02, @@ -2083,43 +2107,43 @@ plot_model_roc <- function(performance_list, base_size = 13) { # each row: colored square marker + left-aligned dataset name + right- # aligned value. Marker uses geom_point (renders reliably in plotly, unlike # a fill-mapped geom_rect which can spread under the text). - geom_point( + ggplot2::geom_point( data = auc_box, - aes(x = swatch_x, y = y_mid, color = Dataset), - shape = 15, + ggplot2::aes(x = swatch_x, y = y_mid, color = Dataset), + shape = 15L, size = 3.2, inherit.aes = FALSE, show.legend = FALSE ) + - geom_text( + ggplot2::geom_text( data = auc_box, - aes(x = label_x, y = y_mid, label = Label), + ggplot2::aes(x = label_x, y = y_mid, label = Label), inherit.aes = FALSE, - hjust = 0, + hjust = 0L, size = label_size, color = "grey25" ) + - geom_text( + ggplot2::geom_text( data = auc_box, - aes(x = value_x, y = y_mid, label = sprintf("%.2f", AUC)), + ggplot2::aes(x = value_x, y = y_mid, label = sprintf("%.2f", AUC)), inherit.aes = FALSE, - hjust = 1, + hjust = 1L, size = value_size, fontface = "bold", color = "grey20" ) + - scale_color_manual(values = dataset_colors) + - coord_cartesian(xlim = c(0, 1.2), ylim = c(0, 1)) + + ggplot2::scale_color_manual(values = dataset_colors) + + ggplot2::coord_cartesian(xlim = c(0L, 1.2), ylim = c(0L, 1L)) + theme_perception(base_size = base_size) + - labs( + ggplot2::labs( x = "1 - Specificity (FPR)", y = "Sensitivity (TPR)", color = "Validation Dataset" ) + - theme( + ggplot2::theme( legend.position = "top", legend.box = "horizontal", - legend.box.spacing = unit(8, "pt") + legend.box.spacing = ggplot2::unit(8L, "pt") ) # Multiple drugs: stack one panel per drug (full width) instead of squeezing @@ -2128,14 +2152,14 @@ plot_model_roc <- function(performance_list, base_size = 13) { # while each panel stays wide enough. The UI grows the plot height to match # (see mod_train.R). n_drugs <- length(unique(df$Drug)) - if (n_drugs > 1) { - roc_ncol <- if (n_drugs <= 4) 1 else 2 - p <- p + facet_wrap(~Drug, ncol = roc_ncol, strip.position = "top") + if (n_drugs > 1L) { + roc_ncol <- if (n_drugs <= 4L) 1L else 2L + p <- p + ggplot2::facet_wrap(~Drug, ncol = roc_ncol, strip.position = "top") } # Surface drugs that could not produce a ROC so the app can warn the user # (otherwise a missing panel looks like a rendering bug). - if (length(dropped_drugs) > 0) { + if (length(dropped_drugs) > 0L) { why <- dropped_reasons[dropped_drugs] warning( "Validation ROC skipped for: ", @@ -2184,19 +2208,19 @@ plot_model_roc <- function(performance_list, base_size = 13) { plot_seurat_clustering <- function( method = c("umap", "tsne"), expression_matrix, - min_cells = 3, - min_features = 200, - nfeatures = 2000, - dims = 10, + min_cells = 3L, + min_features = 200L, + nfeatures = 2000L, + dims = 10L, resolution = 0.8, - seed = 1 + seed = 1L ) { method <- rlang::arg_match(method) if (!requireNamespace("Seurat", quietly = TRUE)) { cli::cli_abort(c( "Package {.pkg Seurat} is required.", - "i" = "Install with {.run install.packages('Seurat')}." + "i" = "Install with {.run utils::install.packages('Seurat')}." )) } @@ -2266,7 +2290,7 @@ plot_patient_response_panel <- function( if (!requireNamespace("gridExtra", quietly = TRUE)) { cli::cli_abort(c( "Package {.pkg gridExtra} is required.", - "i" = "Install with {.run install.packages('gridExtra')}." + "i" = "Install with {.run utils::install.packages('gridExtra')}." )) } @@ -2297,34 +2321,34 @@ plot_patient_response_panel <- function( plot_roc_curve( response = exp_vs_pred[[response_col]], predictor = exp_vs_pred[[predicted_col]], - smooth_curve = n_pts >= 10 + smooth_curve = n_pts >= 10L ) }, error = function(e) { # Last-resort fallback: render an empty placeholder ggplot with error message - ggplot(data.frame( - x = 0, - y = 0, + ggplot2::ggplot(data.frame( + x = 0L, + y = 0L, label = paste("ROC unavailable:", e$message) )) + - geom_text( - aes(x, y, label = label), + ggplot2::geom_text( + ggplot2::aes(x, y, label = label), hjust = 0.5, vjust = 0.5, - size = 3 + size = 3L ) + - theme_void() + - labs(title = "ROC Curve (unavailable)") + ggplot2::theme_void() + + ggplot2::labs(title = "ROC Curve (unavailable)") } ) # Arrange panels if (is.null(layout_matrix)) { layout_matrix <- rbind( - c(1, 1), - c(2, 2), - c(2, 2), - c(3, 4) + c(1L, 1L), + c(2L, 2L), + c(2L, 2L), + c(3L, 4L) ) } @@ -2376,13 +2400,13 @@ plot_tsne_biomarker_viability <- function( viability_var = "viability_scaled", biomarker_label = "Biomarker Exp", viability_label = "Drug Viability", - nrow = 1, - base_size = 8 + nrow = 1L, + base_size = 8L ) { if (!requireNamespace("gridExtra", quietly = TRUE)) { cli::cli_abort(c( "Package {.pkg gridExtra} is required.", - "i" = "Install with {.run install.packages('gridExtra')}." + "i" = "Install with {.run utils::install.packages('gridExtra')}." )) } @@ -2439,9 +2463,9 @@ export_plot_cairo <- function( file, plot, format = "png", - width = 7, - height = 5, - res = 600, + width = 7L, + height = 5L, + res = 600L, draw_fun = NULL ) { format <- tolower(format) @@ -2453,7 +2477,7 @@ export_plot_cairo <- function( width = width, height = height, units = "in", - res = max(res, 96), + res = max(res, 96L), type = "cairo" ) } else { @@ -2462,7 +2486,7 @@ export_plot_cairo <- function( width = width, height = height, units = "in", - res = max(res, 96) + res = max(res, 96L) ) } } else if (format == "svg") { diff --git a/R/predict.R b/R/predict.R index 4b03849..add16d3 100644 --- a/R/predict.R +++ b/R/predict.R @@ -10,8 +10,6 @@ #' #' @name predict_perception #' @keywords internal -#' @importFrom stats predict setNames -#' @importFrom caret predict.train NULL @@ -24,8 +22,10 @@ NULL #' #' @param model_list A named list of model objects (each with a \code{$model} element), #' or a single model object. From \code{train_models()} or \code{load_model()}. -#' @param expr Matrix or data frame. Rank-normalized expression matrix with -#' genes as rows and cells/samples as columns. +#' @param 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. #' #' @return A matrix with cells/samples as rows and drugs as columns, #' containing predicted viability scores. Lower values indicate higher @@ -57,7 +57,7 @@ predict_drugs <- function(model_list, expr) { if (is.null(drug_name)) { drug_name <- "drug1" } - model_list <- setNames(list(model_list), drug_name) + model_list <- stats::setNames(list(model_list), drug_name) } if (!is.list(model_list) || is.null(names(model_list))) { @@ -69,7 +69,7 @@ predict_drugs <- function(model_list, expr) { # Validate expression matrix if (!is.matrix(expr) && !is.data.frame(expr)) { cli::cli_abort( - "expr must be a matrix or data frame with genes as rows and samples as columns." + "expr must be a matrix, data frame, or data.table with genes as rows and samples as columns." ) } @@ -78,7 +78,7 @@ predict_drugs <- function(model_list, expr) { model_obj <- model_list[[drug_name]] # Skip NULL/NA entries - if (is.null(model_obj) || (length(model_obj) == 1 && is.na(model_obj))) { + if (is.null(model_obj) || (length(model_obj) == 1L && is.na(model_obj))) { warning("Skipping NULL model for: ", drug_name) return(NULL) } @@ -97,7 +97,7 @@ predict_drugs <- function(model_list, expr) { # Remove NULL entries viab_raw <- viab_raw[!sapply(viab_raw, is.null)] - if (length(viab_raw) == 0) { + if (length(viab_raw) == 0L) { cli::cli_abort("All model predictions failed.") } @@ -120,18 +120,28 @@ predict_drugs <- function(model_list, expr) { #' #' @keywords internal viability_from_model_internal <- function(drug_name, model, dataset) { - if (is.null(model$coefnames) || length(model$coefnames) == 0) { + if (is.null(model$coefnames) || length(model$coefnames) == 0L) { cli::cli_abort( "Model for drug {.val {drug_name}} has no feature names ({.field coefnames} is NULL/empty). Cannot subset the expression matrix for prediction." ) } + # data.table has no row names, so feature identifiers must come from the first + # column; matrices and data frames keep using rownames(). + if (data.table::is.data.table(dataset)) { + gene_ids <- as.character(dataset[[1L]]) + dataset <- as.matrix(dataset[, -1L]) + rownames(dataset) <- gene_ids + } else { + dataset <- as.matrix(dataset) + } + # Step 1: Try exact match of model features to expression matrix rows feature_match <- match(model$coefnames, rownames(dataset)) # Step 2: If some features not found, try make.names() conversion # (DepMap gene names may use hyphens while external data uses dots after make.names) - if (any(is.na(feature_match))) { + if (anyNA(feature_match)) { dataset_rownames_made <- make.names(rownames(dataset), unique = TRUE) coefnames_made <- make.names(model$coefnames, unique = TRUE) feature_match_alt <- match(coefnames_made, dataset_rownames_made) @@ -147,7 +157,7 @@ viability_from_model_internal <- function(drug_name, model, dataset) { missing_features <- model$coefnames[is.na(feature_match)] - if (length(missing_features) > 0) { + if (length(missing_features) > 0L) { frac_missing <- length(missing_features) / length(model$coefnames) if (frac_missing > 0.5) { cli::cli_abort( @@ -165,7 +175,7 @@ viability_from_model_internal <- function(drug_name, model, dataset) { length(missing_features), length(model$coefnames), drug_name, - paste(head(missing_features, 10), collapse = ", ") + toString(utils::head(missing_features, 10L)) )) impute_mat <- matrix( 0.5, @@ -177,17 +187,15 @@ viability_from_model_internal <- function(drug_name, model, dataset) { feature_match <- match(model$coefnames, rownames(dataset)) } - # Subset expression matrix to model features - orig_colnames <- colnames(dataset) - dataset_FOI <- data.frame( - dataset[feature_match, ], - row.names = rownames(dataset)[feature_match] + # Subset expression matrix to model features and transpose once into the + # samples x features frame caret expects. Transposing the matrix directly keeps + # the sample (row) names intact, unlike data.frame(t(data.frame(...))), which + # runs make.names() and turns clone keys like "Kydar01@@c1" into "..". + dataset_FOI <- as.data.frame( + t(dataset[feature_match, , drop = FALSE]), + row.names = colnames(dataset) ) - dataset_FOI <- data.frame(t(dataset_FOI)) - # data.frame(t()) mangles clone keys (e.g. "@@" -> "..") via make.names(). - # Restore correct clone names as rownames; gene names remain as colnames. - rownames(dataset_FOI) <- orig_colnames - predict(model, dataset_FOI) + stats::predict(model, dataset_FOI) } @@ -203,10 +211,11 @@ viability_from_model_internal <- function(drug_name, model, dataset) { #' \code{prepare_data()}. #' @param prepared_data List from \code{prepare_data()}, containing #' \code{$clone_viability_template} and \code{$clone_counts}. Alternatively, -#' you can pass \code{clone_counts} directly as a data frame (legacy mode). -#' @param clone_counts Optional. Data frame with patients as rows and clone IDs -#' as columns. Only needed if \code{prepared_data} is not a list from -#' \code{prepare_data()}. +#' you can pass \code{clone_counts} directly as a data frame or data.table +#' (legacy mode). +#' @param clone_counts Optional. Data frame or data.table with patients as rows +#' and clone IDs as columns. Only needed if \code{prepared_data} is not a +#' list from \code{prepare_data()}. #' @param mode Character. Aggregation method: #' \describe{ #' \item{"weighted_max"}{Maximum of weighted viability across clones. Default.} @@ -260,7 +269,7 @@ predict_patients <- function( if (is.list(prepared_data) && !is.data.frame(prepared_data) && has_counts) { # Simple mode: extract from prepare_data() output - template_name <- intersect(names(prepared_data), template_names)[1] + template_name <- intersect(names(prepared_data), template_names)[1L] if (is.na(template_name)) { # No template found but has counts - try to build template from clone_pred rownames @@ -268,13 +277,13 @@ predict_patients <- function( "No template found, building from {.field clone_pred} rownames..." ) clone_col_names <- rownames(clone_pred) - if (length(clone_col_names) > 0 && all(grepl("@@", clone_col_names))) { + if (length(clone_col_names) > 0L && all(grepl("@@", clone_col_names))) { clone_template <- parse_clone_keys(clone_col_names) } else { cli::cli_abort( c( "Cannot build template: clone_pred rownames do not follow the {.val Patient@@Clone} format.", - "x" = "clone_pred rownames: {paste(head(rownames(clone_pred), 5), collapse = ', ')}" + "x" = "clone_pred rownames: {toString(head(rownames(clone_pred), 5))}" ) ) } @@ -285,10 +294,9 @@ predict_patients <- function( clone_counts <- prepared_data$clone_counts # Merge clone_pred matrix with template to build clone_viability_matrix - clone_pred_df <- as.data.frame(clone_pred) - clone_pred_df$patient <- clone_template$patient - clone_pred_df$clone_id <- clone_template$clone_id - clone_viability_matrix <- clone_pred_df + clone_viability_matrix <- data.table::as.data.table(clone_pred) + clone_viability_matrix[, patient := clone_template$patient] + clone_viability_matrix[, clone_id := clone_template$clone_id] } else if (is.data.frame(prepared_data)) { # Legacy mode: prepared_data is actually clone_counts, clone_pred is clone_viability_matrix clone_viability_matrix <- clone_pred @@ -308,21 +316,29 @@ predict_patients <- function( ) } + # Normalise tabular inputs to data.table. as.data.table() copies, so the + # caller's objects are never touched by the in-place operations below. + clone_viability_matrix <- data.table::as.data.table(clone_viability_matrix) + clone_counts <- data.table::as.data.table(clone_counts) + + # Column names used through data.table's non-standard evaluation. + patient <- clone_id <- clone_key <- abund_col <- n_cells <- NULL + # Validate inputs - if (!"patient" %in% colnames(clone_viability_matrix)) { - cli::cli_abort("clone_viability_matrix must have a {.field patient} column.") - } - if (!"clone_id" %in% colnames(clone_viability_matrix)) { + if (!"patient" %chin% colnames(clone_viability_matrix)) { + cli::cli_abort( + "clone_viability_matrix must have a {.field patient} column." + ) + } else if (!"clone_id" %chin% colnames(clone_viability_matrix)) { cli::cli_abort( "clone_viability_matrix must have a {.field clone_id} column." ) - } - if (!"patients" %in% colnames(clone_counts)) { + } else if (!"patients" %chin% colnames(clone_counts)) { cli::cli_abort("clone_counts must have a {.field patients} column.") } valid_modes <- c("weighted_average", "min", "max", "weighted_max", "average") - if (!mode %in% valid_modes) { + if (!mode %chin% valid_modes) { cli::cli_abort( "{.arg mode} must be one of: {.val {valid_modes}}" ) @@ -334,6 +350,11 @@ predict_patients <- function( c("patient", "clone_id") ) n_drugs <- length(drug_cols) + if (n_drugs == 0L) { + cli::cli_abort( + "No drug columns found. {.arg clone_viability_matrix} must contain columns besides {.field patient} and {.field clone_id}." + ) + } # Z-score scale drug columns across patients before aggregation. # A pre-combined score (column name "comb_viability", produced by the IDA @@ -344,90 +365,97 @@ predict_patients <- function( # per-drug predictions, so pre-combined columns are left as-is. if (zscore) { scale_cols <- setdiff(drug_cols, "comb_viability") - if (length(scale_cols) > 0) { - clone_viability_matrix <- zscore_viability( - clone_viability_matrix, - cols = scale_cols - ) + if (length(scale_cols) > 0L) { + # Same transformation as zscore_viability(), applied in place. + clone_viability_matrix[, + (scale_cols) := lapply(.SD, function(col) { + as.numeric(scale(as.numeric(col))) + }), + .SDcols = scale_cols + ] } } - # Aggregate for each patient - patient_results <- do.call( - rbind, - lapply(1:nrow(clone_counts), function(x) { - patient_id <- clone_counts$patients[x] - - # Get clone data for this patient - patient_clones <- clone_viability_matrix[ - clone_viability_matrix$patient == patient_id, - ] + # --- Clone weights in long form: one row per (patient, abundance column) --- + patient_order <- as.character(clone_counts$patients) + abundance <- data.table::melt( + clone_counts, + id.vars = "patients", + variable.name = "abund_col", + value.name = "n_cells", + variable.factor = FALSE + ) + data.table::setnames(abundance, "patients", "patient") + abundance[, patient := as.character(patient)] + + # Abundance columns are keyed "patient@@clone" (see build_clone_counts); fall + # back to the bare clone id so objects prepared by earlier versions keep + # working. + clone_viability_matrix[, patient := as.character(patient)] + clone_viability_matrix[, + clone_key := paste(patient, as.character(clone_id), sep = "@@") + ] + clone_viability_matrix[, + abund_col := data.table::fifelse( + clone_key %chin% names(clone_counts), + clone_key, + as.character(clone_id) + ) + ] + + # Attach the cell count that weights each clone, then aggregate per patient. + clone_viability_matrix <- abundance[ + clone_viability_matrix, + on = c("patient", "abund_col") + ] + + n_unmatched <- clone_viability_matrix[is.na(n_cells), .N] + if (n_unmatched > 0L) { + cli::cli_warn( + "{n_unmatched} clone{?s} have no abundance column in {.arg clone_counts}; affected patient scores cannot be weighted and may be {.val NA}." + ) + } - if (nrow(patient_clones) == 0) { - # No clone data for this patient - return(setNames(rep(NA, n_drugs), drug_cols)) - } + aggregate_cols <- switch( + mode, + "weighted_average" = function(values, weights) sum(values * weights), + "weighted_max" = function(values, weights) max(values * weights), + "min" = function(values, weights) min(values), + "max" = function(values, weights) max(values), + "average" = function(values, weights) mean(values) + ) - # Compute clone weights. Abundance columns are keyed "patient@@clone" (see - # build_clone_counts); fall back to the bare clone id so objects prepared by - # earlier versions keep working. - clone_ids <- patient_clones$clone_id - clone_keys <- paste(patient_id, clone_ids, sep = "@@") - use_keys <- if (all(clone_keys %in% colnames(clone_counts))) { - clone_keys + patient_results <- clone_viability_matrix[, + { + total_cells <- sum(n_cells, na.rm = TRUE) + if (!is.finite(total_cells) || total_cells <= 0) { + # No usable abundance for this patient + as.list(stats::setNames(rep(NA_real_, n_drugs), drug_cols)) } else { - clone_ids - } - total_cells <- sum(clone_counts[x, use_keys], na.rm = TRUE) - if (!is.finite(total_cells) || total_cells == 0) { - return(setNames(rep(NA, n_drugs), drug_cols)) + weights <- n_cells / total_cells + as.list(stats::setNames( + vapply( + drug_cols, + function(col) aggregate_cols(.SD[[col]], weights), + numeric(1L) + ), + drug_cols + )) } - clone_weights <- unlist(clone_counts[x, use_keys] / total_cells) - - # Aggregate based on mode - if (n_drugs == 1) { - # Single drug: use comb_viability column if present, otherwise use drug column - if ("comb_viability" %in% colnames(patient_clones)) { - viability_values <- patient_clones$comb_viability - } else { - viability_values <- patient_clones[[drug_cols]] - } - - result <- switch( - mode, - "weighted_average" = sum(viability_values * clone_weights), - "min" = min(viability_values), - "max" = max(viability_values), - "weighted_max" = max(viability_values * clone_weights), - "average" = mean(viability_values) - ) - return(setNames(result, drug_cols)) - } else { - # Multiple drugs: apply aggregation across all drug columns - drug_matrix <- as.matrix(patient_clones[, drug_cols, drop = FALSE]) - - result <- switch( - mode, - "weighted_average" = apply(drug_matrix, 2, function(col) { - sum(col * clone_weights) - }), - "min" = apply(drug_matrix, 2, function(col) min(col)), - "max" = apply(drug_matrix, 2, function(col) max(col)), - "weighted_max" = apply(drug_matrix, 2, function(col) { - max(col * clone_weights) - }), - "average" = apply(drug_matrix, 2, function(col) mean(col)) - ) - return(result) - } - }) - ) + }, + by = "patient", + .SDcols = drug_cols + ] - # Add patient names as row names - rownames(patient_results) <- clone_counts$patients + # Every patient listed in clone_counts gets a row, in its original order (NA + # when no clone-level prediction exists for it). + patient_results <- patient_results[ + match(patient_order, patient_results$patient) + ] - # Convert to data frame - patient_results <- as.data.frame(patient_results) + # Documented output shape: patients as row names, drugs as columns. + patient_results <- as.data.frame(patient_results[, .SD, .SDcols = drug_cols]) + rownames(patient_results) <- patient_order patient_results } @@ -447,11 +475,12 @@ predict_patients <- function( #' [predict_patients()] (as the app's [predict_patients()] already skips #' re-standardising the \code{comb_viability} column) and [plot_clone_viability()]. #' -#' @param pred Matrix or data.frame of clone-level drug viability predictions. -#' Typically the output of [predict_drugs()]. Rows = clones, columns = drugs. -#' Row names must be canonical PERCEPTION clone keys -#' (\code{"patient@@clone_id"}). Alternatively, pass a \code{data.frame} with -#' an explicit \code{patient} column and a \code{clone_id} column. +#' @param pred Matrix, data.frame, or data.table of clone-level drug viability +#' predictions. Typically the output of [predict_drugs()]. Rows = clones, +#' columns = drugs. Row names must be canonical PERCEPTION clone keys +#' (\code{"patient@@clone_id"}). Alternatively, pass a \code{data.frame} / +#' \code{data.table} with an explicit \code{patient} column and a +#' \code{clone_id} column. #' @param patient Optional character vector of patient IDs, length equal to #' \code{nrow(pred)}. Required only when \code{pred} row names are NOT #' \code{"patient@@clone_id"} keys. @@ -511,24 +540,30 @@ combine_drugs <- function( # --- 1. Normalise input to a numeric matrix with row names ---------------- if (is.data.frame(pred)) { - # If user passes data.frame with patient + clone_id columns, stash them - df_cols <- colnames(pred) + # If user passes a data.frame/data.table with patient + clone_id columns, + # stash them and keep every remaining column as a drug. + pred_rn <- rownames(pred) + pred_dt <- data.table::as.data.table(pred) + df_cols <- colnames(pred_dt) drop_cols <- intersect(df_cols, c("patient", "clone_id", "comb_viability")) - pred_mat <- as.matrix(pred[, setdiff(df_cols, drop_cols), drop = FALSE]) - if (ncol(pred_mat) == 0) { + drug_cols <- setdiff(df_cols, drop_cols) + if (length(drug_cols) == 0L) { cli::cli_abort( "No drug columns found in pred. A data.frame input must contain drug columns in addition to {.field patient} / {.field clone_id}." ) } - if (is.null(patient) && "patient" %in% df_cols) { - patient <- as.character(pred$patient) + pred_mat <- as.matrix(pred_dt[, .SD, .SDcols = drug_cols]) + # data.table has no row names, so restore the clone keys carried by `pred`. + rownames(pred_mat) <- pred_rn + if (is.null(patient) && "patient" %chin% df_cols) { + patient <- as.character(pred_dt$patient) } - if (is.null(clone_id) && "clone_id" %in% df_cols) { - clone_id <- as.character(pred$clone_id) + if (is.null(clone_id) && "clone_id" %chin% df_cols) { + clone_id <- as.character(pred_dt$clone_id) } } else if (!is.matrix(pred)) { cli::cli_abort( - "pred must be a matrix or data.frame (from {.fn predict_drugs})." + "pred must be a matrix, data.frame, or data.table::data.table (from {.fn predict_drugs})." ) } else { pred_mat <- pred @@ -536,14 +571,14 @@ combine_drugs <- function( pred_mat <- as.matrix(pred_mat) storage.mode(pred_mat) <- "double" - if (ncol(pred_mat) < 1) { + if (ncol(pred_mat) < 1L) { cli::cli_abort("pred has zero drug columns.") } # --- 2. Resolve patient / clone_id --------------------------------------- if (is.null(patient) || is.null(clone_id)) { rn <- rownames(pred_mat) - if (is.null(rn) || any(!grepl("@@", rn))) { + if (is.null(rn) || !all(grepl("@@", rn))) { cli::cli_abort( c( "pred row names must be canonical PERCEPTION clone keys ({.val patient@@clone_id}),", @@ -568,41 +603,52 @@ combine_drugs <- function( for (j in seq_len(ncol(pred_mat))) { col <- pred_mat[, j] s <- stats::sd(col, na.rm = TRUE) - z_mat[, j] <- if (is.na(s) || s == 0) { - rep(0, length(col)) + z_mat[, j] <- if (is.na(s) || s == 0L) { + rep(0L, length(col)) } else { as.numeric(scale(col)) } } # --- 4. Per-clone combination --------------------------------------------- - agg <- switch( + comb <- switch( combine_rule, - "min" = function(x, ...) apply(x, 1, min, na.rm = na.rm), - "mean" = function(x, ...) rowMeans(x, na.rm = na.rm), - "max" = function(x, ...) apply(x, 1, max, na.rm = na.rm), - "median" = function(x, ...) apply(x, 1, stats::median, na.rm = na.rm) + "min" = if (rlang::is_installed("matrixStats")) { + matrixStats::rowMins(z_mat, na.rm = na.rm) + } else { + apply(z_mat, 1L, min, na.rm = na.rm) + }, + "mean" = rowMeans(z_mat, na.rm = na.rm), + "max" = if (rlang::is_installed("matrixStats")) { + matrixStats::rowMaxs(z_mat, na.rm = na.rm) + } else { + apply(z_mat, 1L, max, na.rm = na.rm) + }, + "median" = if (rlang::is_installed("matrixStats")) { + matrixStats::rowMedians(z_mat, na.rm = na.rm) + } else { + apply(z_mat, 1L, stats::median, na.rm = na.rm) + } ) - - comb <- agg(z_mat) # Single-row / all-NA edge case: rowMeans returns NaN, min/max/median return NA if (combine_rule == "mean") { comb[!is.finite(comb)] <- NA_real_ } # --- 5. Assemble output --------------------------------------------------- - out <- data.frame( + out <- data.table::data.table( patient = as.character(patient), clone_id = as.character(clone_id), - comb_viability = as.numeric(comb), - stringsAsFactors = FALSE + comb_viability = as.numeric(comb) ) if (include_single_z) { - z_df <- as.data.frame(z_mat) - colnames(z_df) <- paste0(colnames(z_mat), ".z") - out <- cbind(out, z_df) + z_dt <- data.table::as.data.table(z_mat) + data.table::setnames(z_dt, paste0(colnames(z_mat), ".z")) + out <- cbind(out, z_dt) } - out + # Documented return shape is a plain data.frame. + # ! return data.frame for compatible with Shiny app + as.data.frame(out) } diff --git a/R/stats.R b/R/stats.R index 505d237..50a8c0c 100644 --- a/R/stats.R +++ b/R/stats.R @@ -2,7 +2,6 @@ #' #' @name stats_perception #' @keywords internal -#' @importFrom stats na.omit phyper p.adjust complete.cases cor pt pnorm NULL #' Hypergeometric test for gene list overlap @@ -28,13 +27,13 @@ hypergeometric_test_for_twolists <- function( global, lower.tail = FALSE ) { - base_in_global <- global[na.omit(match(base_list, global))] + base_in_global <- global[stats::na.omit(match(base_list, global))] test_in_global <- test_list[!is.na(match(test_list, global))] overlap <- test_in_global[!is.na(match(test_in_global, base_in_global))] # q is offset by 1 only for the upper tail (P(X >= x)); the lower tail # (P(X <= x)) must use the observed overlap itself. - q <- if (lower.tail) length(overlap) else length(overlap) - 1 - phyper( + q <- if (lower.tail) length(overlap) else length(overlap) - 1L + stats::phyper( q = q, m = length(base_in_global), n = length(global) - length(base_in_global), @@ -53,7 +52,7 @@ hypergeometric_test_for_twolists <- function( #' @return A numeric vector of FDR-adjusted p-values (q-values). #' @export fdrcorr <- function(test_list) { - p.adjust(test_list, method = "fdr") + stats::p.adjust(test_list, method = "fdr") } @@ -96,7 +95,7 @@ fdrcorr <- function(test_list) { rank_normalization_mat <- function(mat) { apply( mat, - 2, + 2L, function(x) rank(x, ties.method = "average") / length(x) ) } @@ -111,21 +110,21 @@ rank_normalization_mat <- function(mat) { #' @return A numeric vector scaled between 0 and 1. #' @export range01 <- function(x) { - substitute_of_Min <- topXPercentValue(vec = x, X_percentile = 5) - substitute_of_Max <- topXPercentValue(vec = x, X_percentile = 95) + substitute_of_Min <- topXPercentValue(vec = x, X_percentile = 5L) + substitute_of_Max <- topXPercentValue(vec = x, X_percentile = 95L) denom <- substitute_of_Max - substitute_of_Min - if (!is.finite(denom) || denom == 0) { + if (!is.finite(denom) || denom == 0L) { # No spread between the 5th and 95th percentiles — the vector is # effectively constant. This is common for sparse/unexpressed genes whose # 5th and 95th percentiles are BOTH 0 (expressed in <=5% of cells). Map # to 0 (the minimum of the scale = "not expressed / no signal"), NOT the # neutral 0.5 — 0.5 made every unexpressed gene glow medium-yellow in the # Gene Expression plot, looking like a median bug. - return(rep(0, length(x))) + return(rep(0L, length(x))) } x_scaled <- (x - substitute_of_Min) / denom - x_scaled[x_scaled < 0] <- 0 - x_scaled[x_scaled > 1] <- 1 + x_scaled[x_scaled < 0L] <- 0L + x_scaled[x_scaled > 1L] <- 1L x_scaled } @@ -164,7 +163,7 @@ clone_mean_expression <- function( # Filter to cells present in both expression matrix and mapping common_cells <- intersect(cell_ids, as.character(cell_clone_map$cell_id)) - if (length(common_cells) == 0) { + if (length(common_cells) == 0L) { cli::cli_abort( "No matching cells between expression matrix and cell_clone_map." ) @@ -194,7 +193,7 @@ clone_mean_expression <- function( pat_cells <- names(patient_ids[patient_ids == pat]) pat_map <- cell_clone_map[cell_clone_map$cell_id %in% pat_cells, ] - if (nrow(pat_map) == 0) { + if (nrow(pat_map) == 0L) { next } @@ -204,23 +203,23 @@ clone_mean_expression <- function( lapply(clone_ids, function(cl) { cl_cells <- as.character(pat_map$cell_id[pat_map$clone_id == cl]) cl_cells <- intersect(cl_cells, colnames(expr_subset)) - if (length(cl_cells) == 0) { + if (length(cl_cells) == 0L) { return(NULL) } - if (length(cl_cells) == 1) { + if (length(cl_cells) == 1L) { return(expr_subset[, cl_cells]) } rowMeans_if_one_row(data.frame(expr_subset[, cl_cells, drop = FALSE])) }) ) - if (is.null(clone_expr) || length(clone_expr) == 0) { + if (is.null(clone_expr) || length(clone_expr) == 0L) { next } if (!is.matrix(clone_expr)) { clone_expr <- matrix(clone_expr, nrow = nrow(expr_subset)) - colnames(clone_expr) <- clone_ids[1] + colnames(clone_expr) <- clone_ids[1L] rownames(clone_expr) <- rownames(expr_subset) } else { colnames(clone_expr) <- clone_ids @@ -257,7 +256,7 @@ zscore_viability <- function(clone_viability_df, cols = NULL) { drug_cols <- setdiff(colnames(clone_viability_df), c("patient", "clone_id")) - if (length(drug_cols) == 0) { + if (length(drug_cols) == 0L) { cli::cli_abort( "No drug columns found (expected columns other than {.field patient} and {.field clone_id})." ) @@ -265,13 +264,13 @@ zscore_viability <- function(clone_viability_df, cols = NULL) { if (!is.null(cols)) { missing_cols <- setdiff(cols, drug_cols) - if (length(missing_cols) > 0) { + if (length(missing_cols) > 0L) { cli::cli_abort( "Column(s) not found in clone_viability_df: {paste(missing_cols, collapse = ', ')}" ) } drug_cols <- cols - if (length(drug_cols) == 0) return(clone_viability_df) + if (length(drug_cols) == 0L) return(clone_viability_df) } clone_viability_df[drug_cols] <- lapply( @@ -286,9 +285,9 @@ zscore_viability <- function(clone_viability_df, cols = NULL) { # topXPercentValue of a vector -topXPercentValue <- function(vec, X_percentile = 95) { - vec <- na.omit(vec) +topXPercentValue <- function(vec, X_percentile = 95L) { + vec <- stats::na.omit(vec) len <- length(vec) vec <- sort(vec) - vec[ceiling(len * (X_percentile / 100))] + vec[ceiling(len * (X_percentile / 100L))] } diff --git a/R/train.R b/R/train.R index b378dc1..b468aca 100644 --- a/R/train.R +++ b/R/train.R @@ -2,10 +2,6 @@ #' #' @name train_perception #' @keywords internal -#' @importFrom stats cor.test predict aggregate setNames na.omit median -#' @importFrom utils head -#' @importFrom glmnet glmnet -#' @importFrom randomForest randomForest NULL #' Get specific drug response data for cell-lines @@ -44,20 +40,20 @@ get_response_matrix <- function(infunc_drugName) { ] infunc_drugName_screenID_trimmed <- substring( infunc_drugName_screenID, - 0, - 3 + 0L, + 3L ) if ( - sum(infunc_drugName_screenID_trimmed == 'HTS') == 1 & - sum(infunc_drugName_screenID_trimmed == 'MTS') == 1 + sum(infunc_drugName_screenID_trimmed == 'HTS') == 1L && + sum(infunc_drugName_screenID_trimmed == 'MTS') == 1L ) { infunc_response <- infunc_response[ infunc_drugName_screenID_trimmed == 'MTS', ] } else if ( - sum(infunc_drugName_screenID_trimmed == 'HTS') == 1 & - sum(infunc_drugName_screenID_trimmed == 'MTS') > 1 + sum(infunc_drugName_screenID_trimmed == 'HTS') == 1L && + sum(infunc_drugName_screenID_trimmed == 'MTS') > 1L ) { infunc_response <- infunc_response[ infunc_drugName_screenID_trimmed == 'MTS', @@ -69,8 +65,8 @@ get_response_matrix <- function(infunc_drugName) { # NA count they are averaged ACROSS cell lines. (rowMeans here would # collapse to one scalar per batch and destroy cell-line granularity.) } else if ( - sum(infunc_drugName_screenID_trimmed == 'HTS') == 0 & - sum(infunc_drugName_screenID_trimmed == 'MTS') > 1 + sum(infunc_drugName_screenID_trimmed == 'HTS') == 0L && + sum(infunc_drugName_screenID_trimmed == 'MTS') > 1L ) { infunc_response <- infunc_response[ count_row_NAs(infunc_response) == min(count_row_NAs(infunc_response)), @@ -262,16 +258,20 @@ feature_ranking_bulk <- function( ok <- !is.na(X) # per-gene complete-cell mask n_eff <- rowSums(ok) - r <- as.numeric(cor(t(X), y, use = "pairwise.complete.obs")) + r <- if (rlang::is_installed("WGCNA")) { + as.numeric(WGCNA::cor(t(X), y, use = "pairwise.complete.obs")) + } else { + as.numeric(stats::cor(t(X), y, use = "pairwise.complete.obs")) + } df <- n_eff - 2L - t_stat <- sqrt(df) * r / sqrt(1 - r^2) - pval <- 2 * pt(-abs(t_stat), df) + t_stat <- sqrt(df) * r / sqrt(1L - r^2L) + pval <- 2L * stats::pt(-abs(t_stat), df) pval[!is.finite(t_stat) | is.na(r) | df < 1L] <- NA r[!is.finite(t_stat)] <- NA # constant rows (sd = 0) -> NA, like cor.test cor_profile <- cbind(p.value = pval, estimate.cor = r) rownames(cor_profile) <- rownames(X) - cor_profile <- cor_profile[order(abs(cor_profile[, 2]), decreasing = TRUE), ] + cor_profile <- cor_profile[order(abs(cor_profile[, 2L]), decreasing = TRUE), ] return(cor_profile) } @@ -300,7 +300,7 @@ run_parallel_feature_ranking_bulk <- function( id_cancerType = "PanCan", infunc_exclude_cancer = "PanCan", infunc_GOI, - ncores = 4 + ncores = 4L ) { idx <- seq_along(infunc_DrugsToUse) @@ -352,16 +352,16 @@ build_on_BULK_v2 <- function( infunc_cancerType = "PanCan", exclude_cancer = "PanCan", infunc_features, - single_best = infunc_features[1], - k_features = 100, - infunc_alpha = 1, + single_best = infunc_features[1L], + k_features = 100L, + infunc_alpha = 1L, model_type = "glmnet", - num_folds = 3, - num_tree = 500, - seed = 1, + num_folds = 3L, + num_tree = 500L, + seed = 1L, alpha_gradient = 0.05, - lambda_gradient = 20, - lambda_range = c(0.0001, 1), + lambda_gradient = 20L, + lambda_range = c(0.0001, 1L), cv_method = "cv" ) { # Get drug response @@ -374,7 +374,7 @@ build_on_BULK_v2 <- function( exclude_cancer = exclude_cancer, infunc_response = infunc_response, force_add_cellLines = TRUE - )[[1]] + )[[1L]] # Get test cell lines (excluded from training) cellLines2remove <- get_cellLine_list( @@ -382,7 +382,7 @@ build_on_BULK_v2 <- function( infunc_drugName = infunc_drugName, exclude_cancer = exclude_cancer, infunc_response = infunc_response - )[[2]] + )[[2L]] # Check consistency between rnorm matrices if (nrow(DepMap$expression_rnorm) != nrow(DepMap$scRNA_subset_rnorm)) { @@ -395,8 +395,8 @@ build_on_BULK_v2 <- function( ############ # Train Data: on bulk ########## - Train_infunc_features_id <- head( - na.omit(match(infunc_features, rownames(DepMap$expression_rnorm))), + Train_infunc_features_id <- utils::head( + stats::na.omit(match(infunc_features, rownames(DepMap$expression_rnorm))), k_features ) Train_features <- t(DepMap$expression_rnorm[ @@ -408,9 +408,9 @@ build_on_BULK_v2 <- function( Train_Target_Label <- unlist(Train_Target_Label[which( !is.na(Train_Target_Label) )]) - Train_features <- Train_features[which(Train_Target_Label < 10^100), ] + Train_features <- Train_features[which(Train_Target_Label < 10L^100L), ] Train_Target_Label <- unlist(Train_Target_Label[which( - Train_Target_Label < 10^100 + Train_Target_Label < 10L^100L )]) ############ @@ -424,8 +424,8 @@ build_on_BULK_v2 <- function( names(infunc_response) ) ) - Test_infunc_features_id <- head( - na.omit(match(infunc_features, rownames(DepMap$scRNA_subset_rnorm))), + Test_infunc_features_id <- utils::head( + stats::na.omit(match(infunc_features, rownames(DepMap$scRNA_subset_rnorm))), k_features ) Test_features <- t(DepMap$scRNA_subset_rnorm[ @@ -449,8 +449,8 @@ build_on_BULK_v2 <- function( names(infunc_response) ) ) - Test2_infunc_features_id <- head( - na.omit(match(infunc_features, rownames(DepMap$expression_rnorm))), + Test2_infunc_features_id <- utils::head( + stats::na.omit(match(infunc_features, rownames(DepMap$expression_rnorm))), k_features ) Test2_features <- t(DepMap$expression_rnorm[ @@ -476,8 +476,11 @@ build_on_BULK_v2 <- function( Reduce(intersect, list(cellLines2remove, names(infunc_response))) ] ) - Test3_infunc_features_id <- head( - na.omit(match(infunc_features, rownames(DepMap$CPM_scRNA_CCLE_rnorm))), + Test3_infunc_features_id <- utils::head( + stats::na.omit(match( + infunc_features, + rownames(DepMap$CPM_scRNA_CCLE_rnorm) + )), k_features ) Test3_features <- t(DepMap$CPM_scRNA_CCLE_rnorm[ @@ -495,7 +498,7 @@ build_on_BULK_v2 <- function( tc <- caret::trainControl(method = cv_method, number = num_folds) if (model_type == 'rf') { - tunegrid <- expand.grid(.mtry = ncol(Train_features) / seq(10, 1, -3)) + tunegrid <- expand.grid(.mtry = ncol(Train_features) / seq(10L, 1L, -3L)) cv.out <- suppressWarnings(caret::train( Train_Target_Label ~ ., data = data.frame(Train_Target_Label, Train_features), @@ -506,8 +509,8 @@ build_on_BULK_v2 <- function( )) } else if (model_type == 'glmnet') { tunegrid <- expand.grid( - alpha = seq(0, 1, alpha_gradient), - lambda = seq(lambda_range[1], lambda_range[2], length = lambda_gradient) + alpha = seq(0L, 1L, alpha_gradient), + lambda = seq(lambda_range[1L], lambda_range[2L], length = lambda_gradient) ) cv.out <- suppressWarnings(caret::train( Train_Target_Label ~ ., @@ -529,37 +532,37 @@ build_on_BULK_v2 <- function( # Test on bulk (test 2) Test_pred_bulk <- predict(cv.out, Test2_features) - performance_in_bulk <- unlist(cor.test( + performance_in_bulk <- unlist(stats::cor.test( Test_pred_bulk, Test2_Target_Label, method = "pearson" - )[c(3, 4)]) + )[c(3L, 4L)]) # Test on pseudo-Bulk (test 1) Test_pred_Msc <- predict(cv.out, newdata = Test_features) - performance_in_pseudo_bulk <- unlist(cor.test( + performance_in_pseudo_bulk <- unlist(stats::cor.test( Test_pred_Msc, Test_Target_Label, method = "pearson" - )[c(3, 4)]) + )[c(3L, 4L)]) # Test on scRNA-seq (test 3) - Test_pred_sc <- predict(cv.out, newdata = Test3_features) + Test_pred_sc <- stats::predict(cv.out, newdata = Test3_features) cells_mapping2_cellLine <- DepMap$metadata_CPM_scRNA$DepMap_ID[ DepMap$metadata_CPM_scRNA$NAME %in% names(Test_pred_sc) ] - Test_pred_sc_mean_byCellLine <- aggregate( + Test_pred_sc_mean_byCellLine <- stats::aggregate( Test_pred_sc ~ cells_mapping2_cellLine, data.frame(Test_pred_sc, cells_mapping2_cellLine), function(x) mean(x, na.rm = TRUE) ) - performance_in_scRNA <- unlist(cor.test( + performance_in_scRNA <- unlist(stats::cor.test( Test_pred_sc_mean_byCellLine$Test_pred_sc, Test3_Target_Label[ as.character(Test_pred_sc_mean_byCellLine$cells_mapping2_cellLine) ], method = "pearson" - )[c(3, 4)]) + )[c(3L, 4L)]) # Predictions vs ground truth predVSgroundTruth <- list( @@ -642,15 +645,15 @@ train_models <- function( exclude_cancer = "PanCan", GOI = NULL, k_features_values = NULL, - ncores = 4, + ncores = 4L, output_dir = "./models", model_type = "glmnet", - num_folds = 3, - num_tree = 500, - seed = 1, + num_folds = 3L, + num_tree = 500L, + seed = 1L, alpha_gradient = 0.05, - lambda_gradient = 20, - lambda_range = c(0.0001, 1), + lambda_gradient = 20L, + lambda_range = c(0.0001, 1L), cv_method = "cv", progress_cb = NULL ) { @@ -685,7 +688,7 @@ train_models <- function( ) } else { available_genes <- intersect(GOI, rownames(DepMap$expression_20Q4)) - if (length(available_genes) == 0) { + if (length(available_genes) == 0L) { cli::cli_abort( "None of the provided GOI genes were found in DepMap expression data." ) @@ -714,7 +717,7 @@ train_models <- function( # ============================================================================ if (is.null(k_features_values)) { n_genes_total <- nrow(DepMap$expression_rnorm) - k_features_values <- n_genes_total * seq(0.0005, 0.02, length = 5) + k_features_values <- n_genes_total * seq(0.0005, 0.02, length = 5L) k_features_values <- round(k_features_values) cli::cli_alert_info( "Testing feature counts: {paste(k_features_values, collapse = ', ')}" @@ -767,7 +770,7 @@ train_models <- function( # Check if feature ranking succeeded features <- features_list[[i]] - if (is.null(features) || (length(features) == 1 && is.na(features))) { + if (is.null(features) || (length(features) == 1L && is.na(features))) { warning(" Skipping ", drug, " - feature ranking failed.") for_output_lung_Test_vglm[i] <- list(NULL) next @@ -780,7 +783,7 @@ train_models <- function( stripall2match(DepMap$secondary_screen_drugAnnotation$CommonName) == stripall2match(drug) ) - if (length(drug_match) == 0) { + if (length(drug_match) == 0L) { warning(" Skipping ", drug, " - drug not found in DepMap response data.") for_output_lung_Test_vglm[i] <- list(NULL) next @@ -788,7 +791,7 @@ train_models <- function( # Iterate over k_features values (exactly like original script) Raw_models_output <- list() - id_counter <- 1 + id_counter <- 1L build_failed <- FALSE for (infunc_k_features_grid in k_features_values) { @@ -798,7 +801,7 @@ train_models <- function( infunc_cancerType = cancer_type, exclude_cancer = exclude_cancer, infunc_features = rownames(features), - single_best = rownames(features)[1], + single_best = rownames(features)[1L], k_features = infunc_k_features_grid, model_type = model_type, num_folds = num_folds, @@ -810,25 +813,21 @@ train_models <- function( cv_method = cv_method ), error = function(e) { - warning( - " build_on_BULK_v2 failed for ", - drug, - " (k=", - infunc_k_features_grid, - "): ", - e$message + cli::cli_warn( + "build_on_BULK_v2 failed for {drug} (k = {infunc_k_features_grid}): {e$message}" ) NULL } ) - id_counter <- id_counter + 1 + id_counter <- id_counter + 1L } # Check if any models were successfully built if ( - length(Raw_models_output) == 0 || all(sapply(Raw_models_output, is.null)) + length(Raw_models_output) == 0L || + all(sapply(Raw_models_output, base::is.null)) ) { - warning(" Skipping ", drug, " - all model builds failed.") + cli::cli_warn("Skipping {drug} - all model builds failed.") for_output_lung_Test_vglm[i] <- list(NULL) next } @@ -839,13 +838,13 @@ train_models <- function( function(x) { is.list(x) && !is.null(x$performance_in_scRNA) && - length(x$performance_in_scRNA) >= 2 + length(x$performance_in_scRNA) >= 2L }, - logical(1) + logical(1L) ) if (!any(valid)) { - warning(" Skipping ", drug, " - all model builds failed.") + cli::cli_warn("Skipping {drug} - all model builds failed.") for_output_lung_Test_vglm[i] <- list(NULL) next } @@ -859,12 +858,12 @@ train_models <- function( ) # Store the Tuned model (select based on highest correlation estimate) - best_pos <- which.max(perf[2, ]) + best_pos <- which.max(perf[2L, ]) for_output_lung_Test_vglm[[i]] <- Raw_models_output[valid][[best_pos]] # Clean up rm(Raw_models_output) - gc() + gc(verbose = FALSE) } # All drugs processed — final tick so a progress bar reaches 100%. @@ -910,7 +909,11 @@ train_models <- function( cli::cli_alert_success("All models saved to: {.path {save_path}}") successful <- sum( - !sapply(Tuned_models_output, function(x) length(x) == 1 && is.na(x)) + !vapply( + Tuned_models_output, + function(x) length(x) == 1L && is.na(x), + logical(1L) + ) ) cli::cli_alert_success( "Training complete. Successful models: {successful} / {length(drug_list)}" diff --git a/R/utils.R b/R/utils.R index 09ea956..34a88ac 100644 --- a/R/utils.R +++ b/R/utils.R @@ -1,7 +1,7 @@ # RowMeans functions considering the boundary case where mat has a single # column (one cell / sample) — rowMeans would error on a one-column matrix. rowMeans_if_one_row <- function(mat) { - if (ncol(mat) > 1) { + if (ncol(mat) > 1L) { return(rowMeans(mat)) } else { return(mat) @@ -44,8 +44,8 @@ stripall2match <- function(x) { parse_clone_keys <- function(x) { parts <- strsplit(as.character(x), "@@") data.frame( - patient = sapply(parts, `[`, 1), - clone_id = sapply(parts, `[`, 2), + patient = sapply(parts, `[`, 1L), + clone_id = sapply(parts, `[`, 2L), stringsAsFactors = FALSE ) } diff --git a/R/utils_cortest.R b/R/utils_cortest.R index f81a30a..df9d3ed 100644 --- a/R/utils_cortest.R +++ b/R/utils_cortest.R @@ -69,12 +69,12 @@ cor.test_trimmed_v0.default <- if (!is.numeric(y)) { cli::cli_abort("{.arg y} must be a numeric vector.") } - OK <- complete.cases(x, y) + OK <- stats::complete.cases(x, y) x <- x[OK] y <- y[OK] n <- length(x) - NVAL <- 0 + NVAL <- 0L # conf.int <- FALSE if (method == "pearson") { @@ -83,11 +83,11 @@ cor.test_trimmed_v0.default <- } method <- "Pearson's product-moment correlation" names(NVAL) <- "correlation" - r <- cor(x, y) + r <- if (rlang::is_installed("WGCNA")) WGCNA::cor(x, y) else stats::cor(x, y) df <- n - 2L ESTIMATE <- c(cor = r) PARAMETER <- c(df = df) - STATISTIC <- c(t = sqrt(df) * r / sqrt(1 - r^2)) + STATISTIC <- c(t = sqrt(df) * r / sqrt(1L - r^2L)) # Do not compute confidence Int # if(n > 3) { ## confidence int. # if(!missing(conf.level) && @@ -108,10 +108,10 @@ cor.test_trimmed_v0.default <- # } PVAL <- switch( alternative, - "less" = pt(STATISTIC, df), - "greater" = pt(STATISTIC, df, lower.tail = FALSE), - "two.sided" = 2 * - min(pt(STATISTIC, df), pt(STATISTIC, df, lower.tail = FALSE)) + "less" = stats::pt(STATISTIC, df), + "greater" = stats::pt(STATISTIC, df, lower.tail = FALSE), + "two.sided" = 2L * + min(stats::pt(STATISTIC, df), stats::pt(STATISTIC, df, lower.tail = FALSE)) ) } @@ -169,16 +169,20 @@ cor.test_trimmed_v0.formula <- function( if (is.matrix(eval(m$data, parent.frame()))) { m$data <- as.data.frame(data) } - ## need stats:: for non-standard evaluation + ## need stats::for non-standard evaluation m[[1L]] <- quote(stats::model.frame) m$... <- NULL - mf <- eval(m, environment(formula)) + mf <- eval(m, parent.frame()) if (length(mf) != 2L) { cli::cli_abort("Invalid {.arg formula}.") } DNAME <- paste(names(mf), collapse = " and ") names(mf) <- c("x", "y") - y <- do.call("cor.test_trimmed_v0", c(mf, list(...))) - y$data.name <- DNAME - y + # Splice the model frame as named `x`/`y` arguments (equivalent to + # do.call(..., c(mf, list(...)))); passing `mf` unspliced would dispatch + # to the default method with a single data.frame argument. + args <- c(as.list(mf), rlang::list2(...)) + res <- rlang::exec(cor.test_trimmed_v0, !!!args) + res$data.name <- DNAME + res } diff --git a/README.Rmd b/README.Rmd new file mode 100644 index 0000000..061232a --- /dev/null +++ b/README.Rmd @@ -0,0 +1,210 @@ +--- +title: "PERCEPTIONx: Personalized Drug Response Prediction from Single-Cell Transcriptomics" +author: "Jia Ding" +date: "`r Sys.Date()`" +lang: en-US +output: + md_document: + variant: gfm +editor_options: + markdown: + wrap: sentence + chunk_output_type: console +always_allow_html: true +--- + + + +```{r, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>", + fig.path = "man/figures/README-", + out.width = "100%" +) +``` + +# PERCEPTIONx logo + + +[![R >= 4.1.0](https://img.shields.io/badge/R-%3E%3D%204.1.0-276DC3.svg)](https://www.r-project.org/) +[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/license/mit) +[![Lifecycle: experimental](https://img.shields.io/badge/Lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html) +[![R-CMD-check](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/R-CMD-check.yaml) +[![pkgdown](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/pkgdown.yaml/badge.svg)](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/pkgdown.yaml) +[![Last commit](https://img.shields.io/github/last-commit/WangLabCSU/PERCEPTIONx)](https://github.com/WangLabCSU/PERCEPTIONx) +[![Project Status: Active](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) +[![DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/WangLabCSU/PERCEPTIONx) + + +**Predicting Personalized Drug Response and Resistance from Single-Cell Tumor Transcriptomics.** + +PERCEPTIONx trains drug-response models on DepMap cell-line screens and applies them to a patient's single-cell expression profile. It scores sensitivity at the clone and patient level, then turns the results into publication-ready figures, with a point-and-click Shiny web application wrapping the whole pipeline. The method is the [PERCEPTION](https://doi.org/10.1038/s43018-024-00756-7) approach (Sinha et al., *Nat Cancer* 5, 938–952, 2024). + +## 1. Installation + +Install the development version from GitHub: + +```r +# install.packages("remotes") +pak::pak("WangLabCSU/PERCEPTIONx") +``` + +## 2. Quick Start + +The core workflow is five steps. Load the reference data, load pre-trained models (or train your own models with DepMap data), prepare your expression matrix, predict, and plot. + +### 2.1 Load Data + +```r +library(PERCEPTIONx) # after installing (see Section 1) +models <- load_model("abemaciclib", read = TRUE) # pre-trained models (44 drugs) +load_depmap(read = TRUE) # DepMap reference (~567 MB, first run only) +``` + +### 2.2 Train Models (optional) + +The 44 pre-trained models cover prediction out of the box. Train your own when you need other drugs or settings. `train_models()` has sensible defaults for every argument except the drug list: + +```r +models <- train_models(drug_list = "erlotinib") +``` + +### 2.3 Predict Drug Response + +`prepare_data()` clusters the cells (Seurat) and rank-normalizes the clone expression; `predict_drugs()` scores each clone; `predict_patients()` aggregates clone scores to patients (default `weighted_max`): + +```r +prepared <- prepare_data(my_expression_matrix, method = "umap") + +clone_pred <- predict_drugs(models, prepared$clone_expression_rnorm) +patient_pred <- predict_patients(clone_pred, prepared) +``` + +### 2.4 Visualize Results + +Each plotting function takes the corresponding output and returns a `ggplot`: + +```r +plot_tsne_response(tsne_data, color_var = "viability_scaled", title = "Drug Response") +plot_clone_distribution(clone_distribution = clone_dist, response_var = "response") +plot_clone_viability(clone_viability = clone_viability, viability_var = "comb_viability") +plot_roc_curve(response = response, predictor = predictor, smooth_curve = TRUE) +plot_response_boxplot(exp_vs_pred = exp_vs_pred, response_var = "response") +``` + +Every plot accepts `tooltip = TRUE` (default): with the `ggiraph` package installed, points and bars get hover tooltips (clone id, viability score, proportion, FPR/TPR). See the [R Package Tutorial](https://wanglabcsu.github.io/PERCEPTIONx/articles/pipeline.html) for the full workflow, including training, model evaluation, and the complete plotting suite. + +## 3. Shiny Web Application + +PERCEPTION-shiny wraps the whole pipeline in an interactive web dashboard. Heavy computation (training, Seurat clustering, prediction, plotting) runs in background worker processes, so the interface stays responsive while a large job runs. + +```r +library(PERCEPTIONx) +run_perception_app() # starts the app in your browser +``` + +The app has six tabs: Home, Data, Train, Predict, Visualize, and Help, with a Load Demo button that generates a small synthetic dataset (49 genes x 400 cells x 20 patients) to help you test the whole flow. See the [Shiny App Guide](https://wanglabcsu.github.io/PERCEPTIONx/articles/shiny_app.html) for a full walkthrough. + +## 4. Agent Skills + +PERCEPTIONx ships two agent skills so AI coding assistants can drive the package correctly instead of guessing its API: + +| Skill | Purpose | +|---|---| +| [`perceptionx-pipeline`](.claude/skills/perceptionx-pipeline/SKILL.md) | Full workflow: load DepMap & pre-trained models, prepare patient data, predict at clone/patient level, evaluate | +| [`perceptionx-result`](.claude/skills/perceptionx-result/SKILL.md) | Interpret predictions, model performance, ROC curves and result plots | + +Claude Code picks them up automatically from `.claude/skills/`. For other agents (e.g. Codex), copy them into that agent's skills directory: + +```bash +cp -r .claude/skills/perceptionx-pipeline ~/.codex/skills/ +cp -r .claude/skills/perceptionx-result ~/.codex/skills/ +``` + +## 5. Function Reference + +### 5.1 Data Loading + +| Function | Description | +|----------|-------------| +| `load_depmap()` | Download and load DepMap reference datasets | +| `load_model()` | Download and load pre-trained models | +| `get_mirrors()` / `add_mirrors()` / `list_mirrors()` / `reset_mirrors()` | Manage download mirrors | + +### 5.2 Preprocessing + +| Function | Description | +|----------|-------------| +| `prepare_data()` | Seurat clustering + rank normalization → clone-level inputs | + +### 5.3 Model Training + +| Function | Description | +|----------|-------------| +| `train_models()` | Full training pipeline | + +### 5.4 Prediction + +| Function | Description | +|----------|-------------| +| `predict_drugs()` | Predict drug sensitivity at clone level | +| `predict_patients()` | Aggregate clone-level predictions to patient level | + +### 5.5 Evaluation + +| Function | Description | +|----------|-------------| +| `compare_performance()` | Compare performance across model configurations | +| `get_significant_models()` | Filter models with significant stratification | + +### 5.6 Visualization + +| Function | Description | +|----------|-------------| +| `plot_tsne_response()` | t-SNE/UMAP with drug response overlay | +| `plot_tsne_biomarker_viability()` | Biomarker vs. viability side-by-side on t-SNE | +| `plot_clone_distribution()` | Clone abundance stacked bar chart | +| `plot_clone_viability()` | Clone-level viability lollipop plot | +| `plot_roc_curve()` | ROC curve with AUC | +| `plot_response_boxplot()` | Responder vs. non-responder boxplot | +| `plot_model_performance()` | Model performance across thresholds | +| `plot_model_roc()` | Validation ROC curves after training | +| `plot_seurat_clustering()` | Seurat clustering and UMAP visualization | +| `plot_patient_response_panel()` | Composite patient response panel | + +## 6. Workflow + +``` +DepMap Data ──► Model Training ──► Clone Prediction ──► Patient Aggregation + │ │ │ + train_models() predict_drugs() predict_patients() + (weighted_max) + │ +Patient scRNA ──► prepare_data() Visualization & Evaluation + (clustering + │ + rank normalization) plot_*() / compare_performance() +``` + +## 7. Data Requirements + +- **DepMap reference data**: downloaded automatically via `load_depmap()` (bulk expression, single-cell expression, drug response, cell line annotations). +- **Patient data**: single-cell RNA expression matrix (genes as rows, cells as columns). `prepare_data()` handles clustering and rank normalization. +- **Clinical responses (optional)**: patient-level response labels, used for validation (ROC, responder vs. non-responder boxplots). + +## 8. Citation + +If you use this package, please cite both the package and the original PERCEPTION study: + +- **Jia Ding**. PERCEPTIONx: Personalized Drug Response Prediction from Single-Cell Transcriptomics. R package version 0.3.0. +- Sinha, S., Vegesna, R., Mukherjee, S. *et al.* PERCEPTION predicts patient response and resistance to treatment using single-cell transcriptomics of their tumors. *Nat Cancer* 5, 938–952 (2024). https://doi.org/10.1038/s43018-024-00756-7 + +Feedback: jiading682@qq.com + +```{r} +citation("PERCEPTIONx") +``` + +## 9. License + +MIT © PERCEPTIONx authors diff --git a/README.md b/README.md index 70bb9f0..03a1a0b 100644 --- a/README.md +++ b/README.md @@ -1,38 +1,53 @@ + + # PERCEPTIONx logo -[![R >= 4.1.0](https://img.shields.io/badge/R-%3E%3D%204.1.0-276DC3.svg)](https://www.r-project.org/) -[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/license/mit) -[![Lifecycle: experimental](https://img.shields.io/badge/Lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html) +[![R \>= +4.1.0](https://img.shields.io/badge/R-%3E%3D%204.1.0-276DC3.svg)](https://www.r-project.org/) +[![License: +MIT](https://img.shields.io/badge/license-MIT-blue.svg)](https://opensource.org/license/mit) +[![Lifecycle: +experimental](https://img.shields.io/badge/Lifecycle-experimental-orange.svg)](https://lifecycle.r-lib.org/articles/stages.html) [![R-CMD-check](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/R-CMD-check.yaml) [![pkgdown](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/pkgdown.yaml/badge.svg)](https://github.com/WangLabCSU/PERCEPTIONx/actions/workflows/pkgdown.yaml) -[![Last commit](https://img.shields.io/github/last-commit/WangLabCSU/PERCEPTIONx)](https://github.com/WangLabCSU/PERCEPTIONx) -[![Project Status: Active](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) +[![Last +commit](https://img.shields.io/github/last-commit/WangLabCSU/PERCEPTIONx)](https://github.com/WangLabCSU/PERCEPTIONx) +[![Project Status: +Active](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) [![DeepWiki](https://deepwiki.com/badge.svg)](https://deepwiki.com/WangLabCSU/PERCEPTIONx) - -**Predicting Personalized Drug Response and Resistance from Single-Cell Tumor Transcriptomics.** +**Predicting Personalized Drug Response and Resistance from Single-Cell +Tumor Transcriptomics.** -PERCEPTIONx trains drug-response models on DepMap cell-line screens and applies them to a patient's single-cell expression profile. It scores sensitivity at the clone and patient level, then turns the results into publication-ready figures, with a point-and-click Shiny web application wrapping the whole pipeline. The method is the [PERCEPTION](https://doi.org/10.1038/s43018-024-00756-7) approach (Sinha et al., *Nat Cancer* 5, 938–952, 2024). +PERCEPTIONx trains drug-response models on DepMap cell-line screens and +applies them to a patient’s single-cell expression profile. It scores +sensitivity at the clone and patient level, then turns the results into +publication-ready figures, with a point-and-click Shiny web application +wrapping the whole pipeline. The method is the +[PERCEPTION](https://doi.org/10.1038/s43018-024-00756-7) approach (Sinha +et al., *Nat Cancer* 5, 938–952, 2024). ## 1. Installation Install the development version from GitHub: -```r +``` r # install.packages("remotes") -remotes::install_github("WangLabCSU/PERCEPTIONx") +pak::pak("WangLabCSU/PERCEPTIONx") ``` ## 2. Quick Start -The core workflow is five steps. Load the reference data, load pre-trained models (or train your own models with DepMap data), prepare your expression matrix, predict, and plot. +The core workflow is five steps. Load the reference data, load +pre-trained models (or train your own models with DepMap data), prepare +your expression matrix, predict, and plot. ### 2.1 Load Data -```r +``` r library(PERCEPTIONx) # after installing (see Section 1) models <- load_model("abemaciclib", read = TRUE) # pre-trained models (44 drugs) load_depmap(read = TRUE) # DepMap reference (~567 MB, first run only) @@ -40,17 +55,22 @@ load_depmap(read = TRUE) # DepMap reference (~567 MB, first run ### 2.2 Train Models (optional) -The 44 pre-trained models cover prediction out of the box. Train your own when you need other drugs or settings. `train_models()` has sensible defaults for every argument except the drug list: +The 44 pre-trained models cover prediction out of the box. Train your +own when you need other drugs or settings. `train_models()` has sensible +defaults for every argument except the drug list: -```r +``` r models <- train_models(drug_list = "erlotinib") ``` ### 2.3 Predict Drug Response -`prepare_data()` clusters the cells (Seurat) and rank-normalizes the clone expression; `predict_drugs()` scores each clone; `predict_patients()` aggregates clone scores to patients (default `weighted_max`): +`prepare_data()` clusters the cells (Seurat) and rank-normalizes the +clone expression; `predict_drugs()` scores each clone; +`predict_patients()` aggregates clone scores to patients (default +`weighted_max`): -```r +``` r prepared <- prepare_data(my_expression_matrix, method = "umap") clone_pred <- predict_drugs(models, prepared$clone_expression_rnorm) @@ -59,9 +79,10 @@ patient_pred <- predict_patients(clone_pred, prepared) ### 2.4 Visualize Results -Each plotting function takes the corresponding output and returns a `ggplot`: +Each plotting function takes the corresponding output and returns a +`ggplot`: -```r +``` r plot_tsne_response(tsne_data, color_var = "viability_scaled", title = "Drug Response") plot_clone_distribution(clone_distribution = clone_dist, response_var = "response") plot_clone_viability(clone_viability = clone_viability, viability_var = "comb_viability") @@ -69,31 +90,46 @@ plot_roc_curve(response = response, predictor = predictor, smooth_curve = TRUE) plot_response_boxplot(exp_vs_pred = exp_vs_pred, response_var = "response") ``` -Every plot accepts `tooltip = TRUE` (default): with the `ggiraph` package installed, points and bars get hover tooltips (clone id, viability score, proportion, FPR/TPR). See the [R Package Tutorial](https://wanglabcsu.github.io/PERCEPTIONx/articles/pipeline.html) for the full workflow, including training, model evaluation, and the complete plotting suite. +Every plot accepts `tooltip = TRUE` (default): with the `ggiraph` +package installed, points and bars get hover tooltips (clone id, +viability score, proportion, FPR/TPR). See the [R Package +Tutorial](https://wanglabcsu.github.io/PERCEPTIONx/articles/pipeline.html) +for the full workflow, including training, model evaluation, and the +complete plotting suite. ## 3. Shiny Web Application -PERCEPTION-shiny wraps the whole pipeline in an interactive web dashboard. Heavy computation (training, Seurat clustering, prediction, plotting) runs in background worker processes, so the interface stays responsive while a large job runs. +PERCEPTION-shiny wraps the whole pipeline in an interactive web +dashboard. Heavy computation (training, Seurat clustering, prediction, +plotting) runs in background worker processes, so the interface stays +responsive while a large job runs. -```r +``` r library(PERCEPTIONx) run_perception_app() # starts the app in your browser ``` -The app has six tabs: Home, Data, Train, Predict, Visualize, and Help, with a Load Demo button that generates a small synthetic dataset (49 genes x 400 cells x 20 patients) to help you test the whole flow. See the [Shiny App Guide](https://wanglabcsu.github.io/PERCEPTIONx/articles/shiny_app.html) for a full walkthrough. +The app has six tabs: Home, Data, Train, Predict, Visualize, and Help, +with a Load Demo button that generates a small synthetic dataset (49 +genes x 400 cells x 20 patients) to help you test the whole flow. See +the [Shiny App +Guide](https://wanglabcsu.github.io/PERCEPTIONx/articles/shiny_app.html) +for a full walkthrough. ## 4. Agent Skills -PERCEPTIONx ships two agent skills so AI coding assistants can drive the package correctly instead of guessing its API: +PERCEPTIONx ships two agent skills so AI coding assistants can drive the +package correctly instead of guessing its API: | Skill | Purpose | -|---|---| +|----|----| | [`perceptionx-pipeline`](.claude/skills/perceptionx-pipeline/SKILL.md) | Full workflow: load DepMap & pre-trained models, prepare patient data, predict at clone/patient level, evaluate | | [`perceptionx-result`](.claude/skills/perceptionx-result/SKILL.md) | Interpret predictions, model performance, ROC curves and result plots | -Claude Code picks them up automatically from `.claude/skills/`. For other agents (e.g. Codex), copy them into that agent's skills directory: +Claude Code picks them up automatically from `.claude/skills/`. For +other agents (e.g. Codex), copy them into that agent’s skills directory: -```bash +``` bash cp -r .claude/skills/perceptionx-pipeline ~/.codex/skills/ cp -r .claude/skills/perceptionx-result ~/.codex/skills/ ``` @@ -103,7 +139,7 @@ cp -r .claude/skills/perceptionx-result ~/.codex/skills/ ### 5.1 Data Loading | Function | Description | -|----------|-------------| +|----|----| | `load_depmap()` | Download and load DepMap reference datasets | | `load_model()` | Download and load pre-trained models | | `get_mirrors()` / `add_mirrors()` / `list_mirrors()` / `reset_mirrors()` | Manage download mirrors | @@ -111,39 +147,39 @@ cp -r .claude/skills/perceptionx-result ~/.codex/skills/ ### 5.2 Preprocessing | Function | Description | -|----------|-------------| +|----|----| | `prepare_data()` | Seurat clustering + rank normalization → clone-level inputs | ### 5.3 Model Training -| Function | Description | -|----------|-------------| +| Function | Description | +|------------------|------------------------| | `train_models()` | Full training pipeline | ### 5.4 Prediction -| Function | Description | -|----------|-------------| -| `predict_drugs()` | Predict drug sensitivity at clone level | +| Function | Description | +|----------------------|----------------------------------------------------| +| `predict_drugs()` | Predict drug sensitivity at clone level | | `predict_patients()` | Aggregate clone-level predictions to patient level | ### 5.5 Evaluation | Function | Description | -|----------|-------------| +|----|----| | `compare_performance()` | Compare performance across model configurations | | `get_significant_models()` | Filter models with significant stratification | ### 5.6 Visualization | Function | Description | -|----------|-------------| +|----|----| | `plot_tsne_response()` | t-SNE/UMAP with drug response overlay | -| `plot_tsne_biomarker_viability()` | Biomarker vs. viability side-by-side on t-SNE | +| `plot_tsne_biomarker_viability()` | Biomarker vs. viability side-by-side on t-SNE | | `plot_clone_distribution()` | Clone abundance stacked bar chart | | `plot_clone_viability()` | Clone-level viability lollipop plot | | `plot_roc_curve()` | ROC curve with AUC | -| `plot_response_boxplot()` | Responder vs. non-responder boxplot | +| `plot_response_boxplot()` | Responder vs. non-responder boxplot | | `plot_model_performance()` | Model performance across thresholds | | `plot_model_roc()` | Validation ROC curves after training | | `plot_seurat_clustering()` | Seurat clustering and UMAP visualization | @@ -151,31 +187,54 @@ cp -r .claude/skills/perceptionx-result ~/.codex/skills/ ## 6. Workflow -``` -DepMap Data ──► Model Training ──► Clone Prediction ──► Patient Aggregation - │ │ │ - train_models() predict_drugs() predict_patients() - (weighted_max) - │ -Patient scRNA ──► prepare_data() Visualization & Evaluation - (clustering + │ - rank normalization) plot_*() / compare_performance() -``` + DepMap Data ──► Model Training ──► Clone Prediction ──► Patient Aggregation + │ │ │ + train_models() predict_drugs() predict_patients() + (weighted_max) + │ + Patient scRNA ──► prepare_data() Visualization & Evaluation + (clustering + │ + rank normalization) plot_*() / compare_performance() ## 7. Data Requirements -- **DepMap reference data**: downloaded automatically via `load_depmap()` (bulk expression, single-cell expression, drug response, cell line annotations). -- **Patient data**: single-cell RNA expression matrix (genes as rows, cells as columns). `prepare_data()` handles clustering and rank normalization. -- **Clinical responses (optional)**: patient-level response labels, used for validation (ROC, responder vs. non-responder boxplots). +- **DepMap reference data**: downloaded automatically via + `load_depmap()` (bulk expression, single-cell expression, drug + response, cell line annotations). +- **Patient data**: single-cell RNA expression matrix (genes as rows, + cells as columns). `prepare_data()` handles clustering and rank + normalization. +- **Clinical responses (optional)**: patient-level response labels, used + for validation (ROC, responder vs. non-responder boxplots). ## 8. Citation -If you use this package, please cite both the package and the original PERCEPTION study: - -- **Jia Ding**. PERCEPTIONx: Personalized Drug Response Prediction from Single-Cell Transcriptomics. R package version 0.3.0. -- Sinha, S., Vegesna, R., Mukherjee, S. *et al.* PERCEPTION predicts patient response and resistance to treatment using single-cell transcriptomics of their tumors. *Nat Cancer* 5, 938–952 (2024). https://doi.org/10.1038/s43018-024-00756-7 - -Feedback: jiading682@qq.com +If you use this package, please cite both the package and the original +PERCEPTION study: + +- **Jia Ding**. PERCEPTIONx: Personalized Drug Response Prediction from + Single-Cell Transcriptomics. R package version 0.3.0. + +- Sinha, S., Vegesna, R., Mukherjee, S. *et al.* PERCEPTION predicts + patient response and resistance to treatment using single-cell + transcriptomics of their tumors. *Nat Cancer* 5, 938–952 (2024). + + +Feedback: + +``` r +citation("PERCEPTIONx") +#> To cite PERCEPTIONx in publications use: +#> +#> Jia Ding. (2026). PERCEPTIONx: Personalized Drug Response Prediction from Single-Cell Transcriptomics. R package version +#> 0.3.0. https://github.com/WangLabCSU/PERCEPTIONx +#> +#> Sinha, S., Vegesna, R., Mukherjee, S. et al. (2024). PERCEPTION predicts patient response and resistance to treatment +#> using single-cell transcriptomics of their tumors. Nature Cancer 5, 938-952. https://doi.org/10.1038/s43018-024-00756-7 +#> +#> To see these entries in BibTeX format, use 'print(, bibtex=TRUE)', 'toBibtex(.)', or set +#> 'options(citation.bibtex.max=999)'. +``` ## 9. License diff --git a/_pkgdown.yml b/_pkgdown.yml index fbe1bf9..48d19f5 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -98,6 +98,8 @@ reference: - fdrcorr - cor.test_trimmed_v0 - export_plot_cairo + - perception_depmap_drugs + - perception_fda_approved_drugs articles: - title: Tutorials diff --git a/dev/bench_girafe.R b/dev/bench_girafe.R index 36dab3b..d6c0fe4 100644 --- a/dev/bench_girafe.R +++ b/dev/bench_girafe.R @@ -1,11 +1,15 @@ # Time ggiraph conversion for a lollipop-scale plot (demo: 20 patients x 2 clones). -suppressMessages({library(ggplot2); library(ggiraph)}) +suppressMessages({ + library(ggplot2) + library(ggiraph) +}) set.seed(1) d <- expand.grid(patient = paste0("P", 1:20), clone = c("c1", "c2")) -d$v <- rnorm(nrow(d)); d$w <- runif(nrow(d)) +d$v <- rnorm(nrow(d)) +d$w <- runif(nrow(d)) p <- ggplot(d, aes(x = clone, y = v, size = w)) + geom_point() + - facet_wrap(~ patient, scales = "free_y") + + facet_wrap(~patient, scales = "free_y") + theme_bw() t <- system.time(g <- girafe(ggobj = p)) cat("girafe conversion (20 panels, 40 pts):", t[["elapsed"]], "sec\n") @@ -13,9 +17,12 @@ cat("svg widget size:", format(object.size(g), units = "KB"), "\n") # Larger: 200 clones x 20 patients = 4000 pts d2 <- expand.grid(patient = paste0("P", 1:20), clone = paste0("cl", 1:200)) -d2$v <- rnorm(nrow(d2)); d2$w <- runif(nrow(d2)) -p2 <- ggplot(d2, aes(x = clone, y = v, size = w)) + geom_point() + - facet_wrap(~ patient, scales = "free_y") + theme_bw() +d2$v <- rnorm(nrow(d2)) +d2$w <- runif(nrow(d2)) +p2 <- ggplot(d2, aes(x = clone, y = v, size = w)) + + geom_point() + + facet_wrap(~patient, scales = "free_y") + + theme_bw() t2 <- system.time(g2 <- girafe(ggobj = p2)) cat("girafe conversion (20 panels, 4000 pts):", t2[["elapsed"]], "sec\n") cat("svg widget size:", format(object.size(g2), units = "MB"), "\n") diff --git a/dev/time_demo.R b/dev/time_demo.R index d994c3f..755d4a4 100644 --- a/dev/time_demo.R +++ b/dev/time_demo.R @@ -1,47 +1,128 @@ # time_demo.R — measures the demo task phases (Seurat clustering + 2 caret # glmnet models) with the INSTALLED package, replicating run_demo in # async_jobs.R. Usage: Rscript dev/time_demo.R -suppressMessages({ library(PERCEPTIONx, lib.loc = "E:/rlibtest") }) +suppressMessages({ + library(PERCEPTIONx, lib.loc = "E:/rlibtest") +}) t0 <- proc.time()[3] # --- replicate run_demo() data construction --- set.seed(42) -gene_names <- c("TP53", "BRCA1", "EGFR", "MYC", "KRAS", "PIK3CA", "PTEN", "RB1", - "APC", "BRAF", "CDH1", "CDKN2A", "ERBB2", "FGFR1", "ALK", - "MET", "RET", "ROS1", "NRAS", "HRAS", "MAP2K1", "MAPK1", - "JAK2", "STAT3", "MTOR", "AKT1", "AKT2", "CTNNB1", "SMAD4", - "VHL", "NF1", "NF2", "STK11", "FBXW7", "ARID1A", "KDM5C", - "KMT2D", "SETD2", "BAP1", "PBRM1", "NOTCH1", "NOTCH2", - "NOTCH3", "JAK1", "JAK3", "SOX9", "IDH1", "IDH2", "FLT3") -n_cells <- 400; n_patients <- 20 +gene_names <- c( + "TP53", + "BRCA1", + "EGFR", + "MYC", + "KRAS", + "PIK3CA", + "PTEN", + "RB1", + "APC", + "BRAF", + "CDH1", + "CDKN2A", + "ERBB2", + "FGFR1", + "ALK", + "MET", + "RET", + "ROS1", + "NRAS", + "HRAS", + "MAP2K1", + "MAPK1", + "JAK2", + "STAT3", + "MTOR", + "AKT1", + "AKT2", + "CTNNB1", + "SMAD4", + "VHL", + "NF1", + "NF2", + "STK11", + "FBXW7", + "ARID1A", + "KDM5C", + "KMT2D", + "SETD2", + "BAP1", + "PBRM1", + "NOTCH1", + "NOTCH2", + "NOTCH3", + "JAK1", + "JAK3", + "SOX9", + "IDH1", + "IDH2", + "FLT3" +) +n_cells <- 400 +n_patients <- 20 cell_names <- paste0("CELL_", sprintf("%04d", 1:n_cells)) patient_names <- paste0("PAT_", sprintf("%03d", 1:n_patients)) response_labels <- c(rep("Responder", 10), rep("Non-responder", 10)) -clinical_response <- data.frame(patient = patient_names, response = response_labels, stringsAsFactors = FALSE) -patient_assignment <- rep(patient_names, each = ceiling(n_cells / n_patients))[1:n_cells] -patient_mapping <- data.frame(cell_id = cell_names, patient_id = patient_assignment, stringsAsFactors = FALSE) -is_responder_cell <- clinical_response$response[match(patient_assignment, clinical_response$patient)] == "Responder" +clinical_response <- data.frame( + patient = patient_names, + response = response_labels, + stringsAsFactors = FALSE +) +patient_assignment <- rep(patient_names, each = ceiling(n_cells / n_patients))[ + 1:n_cells +] +patient_mapping <- data.frame( + cell_id = cell_names, + patient_id = patient_assignment, + stringsAsFactors = FALSE +) +is_responder_cell <- clinical_response$response[match( + patient_assignment, + clinical_response$patient +)] == + "Responder" abemaciclib_markers <- gene_names[1:5] -erlotinib_markers <- gene_names[6:10] -noise_genes <- gene_names[11:length(gene_names)] +erlotinib_markers <- gene_names[6:10] +noise_genes <- gene_names[11:length(gene_names)] expr_matrix <- matrix(0.1, nrow = length(gene_names), ncol = n_cells) -rownames(expr_matrix) <- gene_names; colnames(expr_matrix) <- cell_names +rownames(expr_matrix) <- gene_names +colnames(expr_matrix) <- cell_names for (g in abemaciclib_markers) { - expr_matrix[g, is_responder_cell] <- pmax(rnorm(sum(is_responder_cell), mean = 8, sd = 3), 0.1) - expr_matrix[g, !is_responder_cell] <- pmax(rnorm(sum(!is_responder_cell), mean = 3, sd = 2), 0.1) + expr_matrix[g, is_responder_cell] <- pmax( + rnorm(sum(is_responder_cell), mean = 8, sd = 3), + 0.1 + ) + expr_matrix[g, !is_responder_cell] <- pmax( + rnorm(sum(!is_responder_cell), mean = 3, sd = 2), + 0.1 + ) } for (g in erlotinib_markers) { - expr_matrix[g, is_responder_cell] <- pmax(rnorm(sum(is_responder_cell), mean = 3, sd = 2), 0.1) - expr_matrix[g, !is_responder_cell] <- pmax(rnorm(sum(!is_responder_cell), mean = 8, sd = 3), 0.1) + expr_matrix[g, is_responder_cell] <- pmax( + rnorm(sum(is_responder_cell), mean = 3, sd = 2), + 0.1 + ) + expr_matrix[g, !is_responder_cell] <- pmax( + rnorm(sum(!is_responder_cell), mean = 8, sd = 3), + 0.1 + ) +} +for (g in noise_genes) { + expr_matrix[g, ] <- runif(n_cells, 0.5, 8) } -for (g in noise_genes) expr_matrix[g, ] <- runif(n_cells, 0.5, 8) storage.mode(expr_matrix) <- "numeric" cat(sprintf("data construction: %.1fs\n", proc.time()[3] - t0)) t1 <- proc.time()[3] prepared <- PERCEPTIONx::prepare_data( - method = "umap", expression_matrix = expr_matrix, patient_mapping = patient_mapping, - seurat_resolution = 0.8, seurat_dims = 10, seurat_nfeatures = min(2000, length(gene_names))) + method = "umap", + expression_matrix = expr_matrix, + patient_mapping = patient_mapping, + seurat_resolution = 0.8, + seurat_dims = 10, + seurat_nfeatures = min(2000, length(gene_names)) +) cat(sprintf("prepare_data (Seurat clustering): %.1fs\n", proc.time()[3] - t1)) make_structured_training <- function(marker_genes, direction, n_train = 160) { @@ -54,8 +135,12 @@ make_structured_training <- function(marker_genes, direction, n_train = 160) { x_train[g, responder_like] <- pmax(rnorm(half, mean = 8, sd = 3), 0.1) x_train[g, nonresponder_like] <- pmax(rnorm(half, mean = 3, sd = 2), 0.1) } - for (g in setdiff(gene_names, marker_genes)) x_train[g, ] <- runif(n_train, 0.5, 8) - y_train <- direction * colMeans(x_train[marker_genes, , drop = FALSE]) + rnorm(n_train, sd = 0.3) + for (g in setdiff(gene_names, marker_genes)) { + x_train[g, ] <- runif(n_train, 0.5, 8) + } + y_train <- direction * + colMeans(x_train[marker_genes, , drop = FALSE]) + + rnorm(n_train, sd = 0.3) as.data.frame(cbind(y = y_train, t(x_train))) } make_drug_model <- function(drug_name, seed, marker_genes, direction) { @@ -63,22 +148,53 @@ make_drug_model <- function(drug_name, seed, marker_genes, direction) { train_df <- make_structured_training(marker_genes, direction, n_train = 160) t0m <- proc.time()[3] caret_model <- suppressWarnings(caret::train( - y ~ ., data = train_df, method = "glmnet", - trControl = caret::trainControl(method = "cv", number = 3), tuneLength = 3)) + y ~ ., + data = train_df, + method = "glmnet", + trControl = caret::trainControl(method = "cv", number = 3), + tuneLength = 3 + )) cat(sprintf(" %s caret::train: %.1fs\n", drug_name, proc.time()[3] - t0m)) - obj <- list(model = caret_model, - performance_in_scRNA = data.frame(estimate.cor = c(0.45, 0.38), p.value = c(0.001, 0.01)), - performance_in_bulk = data.frame(estimate.cor = c(0.55, 0.48), p.value = c(0.0001, 0.001)), - performance_in_pseudo_bulk = data.frame(estimate.cor = c(0.50, 0.42), p.value = c(0.0005, 0.005)), - predVSgroundTruth = list(pred_gt_scRNA = data.frame(Observed = rnorm(20), Test_pred_sc = rnorm(20))), - single_best = marker_genes[1]) + obj <- list( + model = caret_model, + performance_in_scRNA = data.frame( + estimate.cor = c(0.45, 0.38), + p.value = c(0.001, 0.01) + ), + performance_in_bulk = data.frame( + estimate.cor = c(0.55, 0.48), + p.value = c(0.0001, 0.001) + ), + performance_in_pseudo_bulk = data.frame( + estimate.cor = c(0.50, 0.42), + p.value = c(0.0005, 0.005) + ), + predVSgroundTruth = list( + pred_gt_scRNA = data.frame(Observed = rnorm(20), Test_pred_sc = rnorm(20)) + ), + single_best = marker_genes[1] + ) attr(obj, "drug_name") <- drug_name obj } t2 <- proc.time()[3] models <- list( - abemaciclib = make_drug_model("abemaciclib", 101, abemaciclib_markers, direction = -1), - erlotinib = make_drug_model("erlotinib", 202, erlotinib_markers, direction = +1)) + abemaciclib = make_drug_model( + "abemaciclib", + 101, + abemaciclib_markers, + direction = -1 + ), + erlotinib = make_drug_model( + "erlotinib", + 202, + erlotinib_markers, + direction = +1 + ) +) cat(sprintf("both caret models: %.1fs\n", proc.time()[3] - t2)) -cat(sprintf("TOTAL demo compute (excl. process/package startup): %.1fs\n", proc.time()[3] - t0)) +cat(sprintf( + "TOTAL demo compute (excl. process/package startup): %.1fs\n", + proc.time()[3] - t0 +)) diff --git a/inst/shiny/app/R/async_jobs.R b/inst/shiny/app/R/async_jobs.R index 85c67fd..fa24cac 100644 --- a/inst/shiny/app/R/async_jobs.R +++ b/inst/shiny/app/R/async_jobs.R @@ -33,9 +33,16 @@ # Job id: timestamp + random chars so ids never collide. make_job_id <- function(user_key = "") { - salt <- paste(sample(c(letters, LETTERS, 0:9), 8, replace = TRUE), collapse = "") - paste0("job_", format(Sys.time(), "%Y%m%d_%H%M%S"), "_", - substr(paste0(user_key, salt), 1, 12)) + salt <- paste( + sample(c(letters, LETTERS, 0:9), 8, replace = TRUE), + collapse = "" + ) + paste0( + "job_", + format(Sys.time(), "%Y%m%d_%H%M%S"), + "_", + substr(paste0(user_key, salt), 1, 12) + ) } # Spawn a callr background worker with retries. processx_exec can transiently @@ -53,10 +60,20 @@ make_job_id <- function(user_key = "") { # progressively simpler configs and keep the first one the environment # accepts. Each config gets the full retry budget, and a failed attempt runs # gc() so half-open connections from the failed spawn do not accumulate. -spawn_r_bg_retry <- function(func, args, jobs_dir, retries = 2L, delay_ms = 500L) { +spawn_r_bg_retry <- function( + func, + args, + jobs_dir, + retries = 2L, + delay_ms = 500L +) { configs <- list( # 1. Preferred: supervisor on, stdout discarded, stderr to the job log. - list(supervise = TRUE, stdout = "/dev/null", stderr = file.path(jobs_dir, "worker.log")), + list( + supervise = TRUE, + stdout = "/dev/null", + stderr = file.path(jobs_dir, "worker.log") + ), # 2. Supervisor and stderr file are the two most container-hostile bits; # drop both, keep stdout discarded. (On Windows "/dev/null" does not # exist, so configs 1-2 fail there and 3 below is what runs locally.) @@ -80,30 +97,54 @@ spawn_r_bg_retry <- function(func, args, jobs_dir, retries = 2L, delay_ms = 500L )), error = function(e) { last_err <<- e - if (attempt <= retries) Sys.sleep(delay_ms / 1000) + if (attempt <= retries) { + Sys.sleep(delay_ms / 1000) + } NULL } ) } config_err <- c(config_err, conditionMessage(last_err)) - gc() # release any half-open connections before the next config + gc() # release any half-open connections before the next config } stop( - "Failed to start the background worker after ", length(configs), " configs x ", - retries + 1L, " attempts. ", - "Last errors: ", paste(config_err, collapse = " | "), ". ", - "Diagnostics: R.home(bin)=", R.home("bin"), - "; Rscript exists=", file.exists(file.path(R.home("bin"), "Rscript")), - "; Sys.which(Rscript)=", Sys.which("Rscript"), - "; PATH=", Sys.getenv("PATH"), - "; getwd()=", getwd(), - "; tempdir=", tempdir(), - "; jobs_dir exists=", dir.exists(jobs_dir), - "; jobs_dir writable=", isTRUE(file.access(jobs_dir, 2) == 0), - "; open connections=", length(connections()), - "; R version=", paste(R.version$major, R.version$minor, sep = "."), - "; callr=", tryCatch(as.character(utils::packageVersion("callr")), error = function(e) "?"), - "; processx=", tryCatch(as.character(utils::packageVersion("processx")), error = function(e) "?"), + "Failed to start the background worker after ", + length(configs), + " configs x ", + retries + 1L, + " attempts. ", + "Last errors: ", + paste(config_err, collapse = " | "), + ". ", + "Diagnostics: R.home(bin)=", + R.home("bin"), + "; Rscript exists=", + file.exists(file.path(R.home("bin"), "Rscript")), + "; Sys.which(Rscript)=", + Sys.which("Rscript"), + "; PATH=", + Sys.getenv("PATH"), + "; getwd()=", + getwd(), + "; tempdir=", + tempdir(), + "; jobs_dir exists=", + dir.exists(jobs_dir), + "; jobs_dir writable=", + isTRUE(file.access(jobs_dir, 2) == 0), + "; open connections=", + length(connections()), + "; R version=", + paste(R.version$major, R.version$minor, sep = "."), + "; callr=", + tryCatch(as.character(utils::packageVersion("callr")), error = function(e) { + "?" + }), + "; processx=", + tryCatch( + as.character(utils::packageVersion("processx")), + error = function(e) "?" + ), call. = FALSE ) } @@ -120,15 +161,19 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { # A dir counts as the source tree ONLY with DESCRIPTION + R/*.R — an installed # package dir has DESCRIPTION but no .R sources, and load_all() on it yields # an empty namespace ("X is not an exported object from namespace:PERCEPTIONx"). - pkg_is_src <- !is.null(pkg_root) && nzchar(pkg_root) && dir.exists(pkg_root) && + pkg_is_src <- !is.null(pkg_root) && + nzchar(pkg_root) && + dir.exists(pkg_root) && length(list.files(file.path(pkg_root, "R"), pattern = "\\.R$")) > 0 if (pkg_is_src) { suppressMessages(devtools::load_all(pkg_root, quiet = TRUE)) } else if (requireNamespace("PERCEPTIONx", quietly = TRUE)) { library(PERCEPTIONx) } else { - stop("Package 'PERCEPTIONx' is not installed. Install it with ", - "remotes::install_github(\"WangLabCSU/PERCEPTIONx\"), then restart the app.") + stop( + "Package 'PERCEPTIONx' is not installed. Install it with ", + "remotes::install_github(\"WangLabCSU/PERCEPTIONx\"), then restart the app." + ) } # --- helpers (local to this process) --- @@ -138,13 +183,17 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { strip_model_env <- function(m) { if (is.list(m) && inherits(m$model, "train")) { m$model$call <- NULL - if (!is.null(m$model$terms)) attr(m$model$terms, ".Environment") <- baseenv() + if (!is.null(m$model$terms)) { + attr(m$model$terms, ".Environment") <- baseenv() + } } m } assign_depmap <- function(DepMap) { - depmap_env <- tryCatch(getFromNamespace(".depmap_env", "PERCEPTIONx"), - error = function(e) .GlobalEnv) + depmap_env <- tryCatch( + getFromNamespace(".depmap_env", "PERCEPTIONx"), + error = function(e) .GlobalEnv + ) assign("DepMap", DepMap, envir = depmap_env) assign("DepMap", DepMap, envir = .GlobalEnv) invisible(TRUE) @@ -154,30 +203,40 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { progress_file <- file.path(job_dir, "progress.txt") params <- tryCatch( readRDS(file.path(job_dir, "params.rds")), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(params, "perception_job_error")) { - writeLines(sprintf("error|Failed to read job params: %s", params$message), - status_file) + writeLines( + sprintf("error|Failed to read job params: %s", params$message), + status_file + ) return(invisible(TRUE)) } out <- tryCatch( PERCEPTIONx::train_models( - drug_list = params$drug_list, - cancer_type = params$cancer_type, - exclude_cancer = params$exclude_cancer, - GOI = params$GOI, + drug_list = params$drug_list, + cancer_type = params$cancer_type, + exclude_cancer = params$exclude_cancer, + GOI = params$GOI, k_features_values = params$k_features_values, - model_type = params$model_type, - ncores = params$ncores, - output_dir = params$output_dir, + model_type = params$model_type, + ncores = params$ncores, + output_dir = params$output_dir, progress_cb = function(phase, i, n, drug) { write_progress(progress_file, phase, i, n, drug) } ), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(out, "perception_job_error")) { writeLines(sprintf("error|%s", out$message), status_file) @@ -193,8 +252,13 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { depmap_path <- NULL request_file <- file.path(jobs_dir, "depmap_request.rds") last_activity <- Sys.time() - message("[master] started, polling ", jobs_dir, " (idle release after ", - idle_minutes, " min)") + message( + "[master] started, polling ", + jobs_dir, + " (idle release after ", + idle_minutes, + " min)" + ) while (TRUE) { # 1. DepMap: honour a new request; otherwise reload the last known path @@ -211,17 +275,33 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { # slow saveRDS (e.g. a large expression matrix) could be claimed # mid-write and read as a truncated/corrupt file. pending <- list.dirs(jobs_dir, recursive = FALSE, full.names = TRUE) - pending <- pending[!vapply(pending, function(j) - file.exists(file.path(j, "status.txt")), logical(1))] - pending <- pending[vapply(pending, function(j) - file.exists(file.path(j, "ready")), logical(1))] + pending <- pending[ + !vapply( + pending, + function(j) { + file.exists(file.path(j, "status.txt")) + }, + logical(1) + ) + ] + pending <- pending[vapply( + pending, + function(j) { + file.exists(file.path(j, "ready")) + }, + logical(1) + )] if (!is.null(depmap_path) && is.null(DepMap)) { message("[master] loading DepMap from ", depmap_path) loaded <- tryCatch( readRDS(depmap_path), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(loaded, "perception_job_error")) { # A bad file must never crash the master (that would strand every @@ -229,8 +309,10 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { # job and drop the path so a fresh notify can retry. message("[master] DepMap load FAILED: ", loaded$message) for (j in pending) { - writeLines(sprintf("error|DepMap load failed: %s", loaded$message), - file.path(j, "status.txt")) + writeLines( + sprintf("error|DepMap load failed: %s", loaded$message), + file.path(j, "status.txt") + ) } DepMap <- NULL depmap_path <- NULL @@ -251,11 +333,15 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { } if (length(claimed) > 0) { message("[master] dispatching ", length(claimed), " job(s)") - if (.Platform$OS.type == "unix" && max_parallel > 1L && - length(claimed) > 1L) { + if ( + .Platform$OS.type == "unix" && max_parallel > 1L && length(claimed) > 1L + ) { # Linux: fork — children inherit DepMap copy-on-write, one physical copy - parallel::mclapply(claimed, run_train_job, - mc.cores = min(max_parallel, length(claimed))) + parallel::mclapply( + claimed, + run_train_job, + mc.cores = min(max_parallel, length(claimed)) + ) } else { # Windows (no fork) or a single job: run in-process, serial lapply(claimed, run_train_job) @@ -268,9 +354,16 @@ train_master_main <- function(pkg_root, jobs_dir, max_parallel, idle_minutes) { # back to the server is to EXIT the process. The next submitted job then # re-spawns the master (ensure_master detects !is_alive) and cold-loads # the DepMap from the last known path — shown as "waiting for worker". - if (!is.null(DepMap) && - as.numeric(difftime(Sys.time(), last_activity, units = "mins")) > idle_minutes) { - message("[master] idle for ", idle_minutes, " min - exiting to release memory") + if ( + !is.null(DepMap) && + as.numeric(difftime(Sys.time(), last_activity, units = "mins")) > + idle_minutes + ) { + message( + "[master] idle for ", + idle_minutes, + " min - exiting to release memory" + ) # SAFE here (unlike in the Shiny session): this runs inside the worker's # OWN process, which is about to exit anyway, so closing its leftover # connections only avoids "closing unused connection N" noise in the @@ -294,15 +387,19 @@ train_custom_main <- function(pkg_root, depmap_path, jobs_dir, poll_secs = 1L) { # Source tree check (DESCRIPTION + R/*.R): an installed package dir has # DESCRIPTION but no .R sources, and load_all() on it yields an EMPTY # namespace ("X is not an exported object from namespace:PERCEPTIONx"). - pkg_is_src <- !is.null(pkg_root) && nzchar(pkg_root) && dir.exists(pkg_root) && + pkg_is_src <- !is.null(pkg_root) && + nzchar(pkg_root) && + dir.exists(pkg_root) && length(list.files(file.path(pkg_root, "R"), pattern = "\\.R$")) > 0 if (pkg_is_src) { suppressMessages(devtools::load_all(pkg_root, quiet = TRUE)) } else if (requireNamespace("PERCEPTIONx", quietly = TRUE)) { library(PERCEPTIONx) } else { - stop("Package 'PERCEPTIONx' is not installed. Install it with ", - "remotes::install_github(\"WangLabCSU/PERCEPTIONx\"), then restart the app.") + stop( + "Package 'PERCEPTIONx' is not installed. Install it with ", + "remotes::install_github(\"WangLabCSU/PERCEPTIONx\"), then restart the app." + ) } write_progress <- function(progress_file, phase, i, n, drug) { @@ -311,13 +408,17 @@ train_custom_main <- function(pkg_root, depmap_path, jobs_dir, poll_secs = 1L) { strip_model_env <- function(m) { if (is.list(m) && inherits(m$model, "train")) { m$model$call <- NULL - if (!is.null(m$model$terms)) attr(m$model$terms, ".Environment") <- baseenv() + if (!is.null(m$model$terms)) { + attr(m$model$terms, ".Environment") <- baseenv() + } } m } assign_depmap <- function(DepMap) { - depmap_env <- tryCatch(getFromNamespace(".depmap_env", "PERCEPTIONx"), - error = function(e) .GlobalEnv) + depmap_env <- tryCatch( + getFromNamespace(".depmap_env", "PERCEPTIONx"), + error = function(e) .GlobalEnv + ) assign("DepMap", DepMap, envir = depmap_env) assign("DepMap", DepMap, envir = .GlobalEnv) invisible(TRUE) @@ -327,30 +428,40 @@ train_custom_main <- function(pkg_root, depmap_path, jobs_dir, poll_secs = 1L) { progress_file <- file.path(job_dir, "progress.txt") params <- tryCatch( readRDS(file.path(job_dir, "params.rds")), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(params, "perception_job_error")) { - writeLines(sprintf("error|Failed to read job params: %s", params$message), - status_file) + writeLines( + sprintf("error|Failed to read job params: %s", params$message), + status_file + ) return(invisible(TRUE)) } out <- tryCatch( PERCEPTIONx::train_models( - drug_list = params$drug_list, - cancer_type = params$cancer_type, - exclude_cancer = params$exclude_cancer, - GOI = params$GOI, + drug_list = params$drug_list, + cancer_type = params$cancer_type, + exclude_cancer = params$exclude_cancer, + GOI = params$GOI, k_features_values = params$k_features_values, - model_type = params$model_type, - ncores = params$ncores, - output_dir = params$output_dir, + model_type = params$model_type, + ncores = params$ncores, + output_dir = params$output_dir, progress_cb = function(phase, i, n, drug) { write_progress(progress_file, phase, i, n, drug) } ), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(out, "perception_job_error")) { writeLines(sprintf("error|%s", out$message), status_file) @@ -364,8 +475,12 @@ train_custom_main <- function(pkg_root, depmap_path, jobs_dir, poll_secs = 1L) { message("[custom-worker] loading DepMap from ", depmap_path) DepMap <- tryCatch( readRDS(depmap_path), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(DepMap, "perception_job_error")) { # The uploaded file may already be gone (e.g. its session ended and @@ -379,11 +494,18 @@ train_custom_main <- function(pkg_root, depmap_path, jobs_dir, poll_secs = 1L) { while (TRUE) { # Only claim dirs whose params.rds is fully written (see master note). pending <- list.dirs(jobs_dir, recursive = FALSE, full.names = TRUE) - pending <- pending[vapply(pending, function(j) - file.exists(file.path(j, "ready")), logical(1))] + pending <- pending[vapply( + pending, + function(j) { + file.exists(file.path(j, "ready")) + }, + logical(1) + )] for (j in pending) { - if (!file.exists(file.path(j, "status.txt")) && - file.create(file.path(j, "status.txt"))) { + if ( + !file.exists(file.path(j, "status.txt")) && + file.create(file.path(j, "status.txt")) + ) { run_train_job(j) } } @@ -404,24 +526,39 @@ ensure_master <- function() { jobs_dir <- PERCEPTIONx:::perception_jobs_dir() dir.create(jobs_dir, recursive = TRUE, showWarnings = FALSE) if (!dir.exists(jobs_dir) || file.access(jobs_dir, 2) != 0) { - stop("Cannot use master jobs dir at '", jobs_dir, - "' (unwritable or not creatable). Fix the permission, or unset ", - "PERCEPTIONx.cache_root to fall back to tempdir().") + stop( + "Cannot use master jobs dir at '", + jobs_dir, + "' (unwritable or not creatable). Fix the permission, or unset ", + "PERCEPTIONx.cache_root to fall back to tempdir()." + ) } options(perception.jobs_dir = jobs_dir) - max_par <- suppressWarnings(as.integer(Sys.getenv("PERCEPTION_WORKERS", "16"))) - if (is.na(max_par) || max_par < 1L) max_par <- 16L - idle <- suppressWarnings(as.integer(Sys.getenv("PERCEPTION_WORKER_IDLE_MINUTES", "720"))) - if (is.na(idle) || idle < 1L) idle <- 720L + max_par <- suppressWarnings(as.integer(Sys.getenv( + "PERCEPTION_WORKERS", + "16" + ))) + if (is.na(max_par) || max_par < 1L) { + max_par <- 16L + } + idle <- suppressWarnings(as.integer(Sys.getenv( + "PERCEPTION_WORKER_IDLE_MINUTES", + "720" + ))) + if (is.na(idle) || idle < 1L) { + idle <- 720L + } worker <- spawn_r_bg_retry( train_master_main, # NOTE: pkg_root default must be NULL (not ".") — NULL makes the worker # fall back to library(PERCEPTIONx); "." would trigger devtools::load_all # on an unrelated working directory and crash the worker. - args = list(pkg_root = getOption("perception.pkg_root", NULL), - jobs_dir = jobs_dir, - max_parallel = max_par, - idle_minutes = idle), + args = list( + pkg_root = getOption("perception.pkg_root", NULL), + jobs_dir = jobs_dir, + max_parallel = max_par, + idle_minutes = idle + ), jobs_dir = jobs_dir ) options(perception.master = worker) @@ -432,15 +569,20 @@ ensure_master <- function() { # the standard DepMap via the built-in button; idempotent). notify_master_depmap <- function(depmap_path) { ensure_master() - saveRDS(depmap_path, file.path(getOption("perception.jobs_dir"), - "depmap_request.rds")) + saveRDS( + depmap_path, + file.path(getOption("perception.jobs_dir"), "depmap_request.rds") + ) invisible(TRUE) } # Per-session worker for a user who UPLOADED a custom DepMap file. ensure_custom_worker <- function(shared) { - if (isTRUE(shared$worker_alive) && !is.null(shared$train_worker) && - shared$train_worker$is_alive()) { + if ( + isTRUE(shared$worker_alive) && + !is.null(shared$train_worker) && + shared$train_worker$is_alive() + ) { # The worker already loaded SOME DepMap into memory. If the user has since # uploaded a DIFFERENT file, keep the worker but make it reload: training # must use the current upload, never a stale copy. @@ -450,18 +592,24 @@ ensure_custom_worker <- function(shared) { old_dir <- shared$jobs_dir shared$train_worker$kill() shared$worker_alive <- FALSE - if (!is.null(old_dir) && dir.exists(old_dir)) unlink(old_dir, recursive = TRUE) + if (!is.null(old_dir) && dir.exists(old_dir)) { + unlink(old_dir, recursive = TRUE) + } } if (is.null(shared$depmap_path)) { - stop("DepMap file path is unknown. Please load DepMap data first (Data tab).") + stop( + "DepMap file path is unknown. Please load DepMap data first (Data tab)." + ) } jobs_dir <- file.path(tempdir(), "perception_jobs_custom", make_job_id()) dir.create(jobs_dir, recursive = TRUE, showWarnings = FALSE) worker <- spawn_r_bg_retry( train_custom_main, - args = list(pkg_root = getOption("perception.pkg_root", NULL), - depmap_path = shared$depmap_path, - jobs_dir = jobs_dir), + args = list( + pkg_root = getOption("perception.pkg_root", NULL), + depmap_path = shared$depmap_path, + jobs_dir = jobs_dir + ), jobs_dir = jobs_dir ) shared$jobs_dir <- jobs_dir @@ -507,9 +655,13 @@ read_job_state <- function(shared, jobid) { return(list(status = "queued", phase = "rank", i = 0L, n = 1L, drug = "")) } status <- readLines(status_file, warn = FALSE) - if (length(status) == 0) status <- "running" + if (length(status) == 0) { + status <- "running" + } s <- status[1] - if (s == "done") return(list(status = "done")) + if (s == "done") { + return(list(status = "done")) + } if (startsWith(s, "error")) { return(list(status = "error", message = sub("^error\\|", "", s))) } @@ -519,11 +671,13 @@ read_job_state <- function(shared, jobid) { if (length(lines) > 0) prog <- lines[length(lines)] } parts <- strsplit(prog, "\\|")[[1]] - list(status = "running", - phase = if (length(parts) > 0) parts[1] else "rank", - i = suppressWarnings(as.integer(parts[2])), - n = suppressWarnings(as.integer(parts[3])), - drug = if (length(parts) > 3) parts[4] else "") + list( + status = "running", + phase = if (length(parts) > 0) parts[1] else "rank", + i = suppressWarnings(as.integer(parts[2])), + n = suppressWarnings(as.integer(parts[3])), + drug = if (length(parts) > 3) parts[4] else "" + ) } # --------------------------------------------------------------------------- @@ -550,15 +704,19 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { # Source tree check (DESCRIPTION + R/*.R): an installed package dir has # DESCRIPTION but no .R sources, and load_all() on it yields an EMPTY # namespace ("X is not an exported object from namespace:PERCEPTIONx"). - pkg_is_src <- !is.null(pkg_root) && nzchar(pkg_root) && dir.exists(pkg_root) && + pkg_is_src <- !is.null(pkg_root) && + nzchar(pkg_root) && + dir.exists(pkg_root) && length(list.files(file.path(pkg_root, "R"), pattern = "\\.R$")) > 0 if (pkg_is_src) { suppressMessages(devtools::load_all(pkg_root, quiet = TRUE)) } else if (requireNamespace("PERCEPTIONx", quietly = TRUE)) { library(PERCEPTIONx) } else { - stop("Package 'PERCEPTIONx' is not installed. Install it with ", - "remotes::install_github(\"WangLabCSU/PERCEPTIONx\"), then restart the app.") + stop( + "Package 'PERCEPTIONx' is not installed. Install it with ", + "remotes::install_github(\"WangLabCSU/PERCEPTIONx\"), then restart the app." + ) } write_progress <- function(progress_file, phase, i, n, drug) { @@ -567,45 +725,104 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { run_prepare <- function(a, progress_cb = NULL) { PERCEPTIONx::prepare_data( - method = a$method, + method = a$method, expression_matrix = a$expression_matrix, - patient_mapping = a$patient_mapping, + patient_mapping = a$patient_mapping, seurat_resolution = a$seurat_resolution, - seurat_dims = a$seurat_dims, - seurat_nfeatures = if (!is.null(a$seurat_nfeatures)) a$seurat_nfeatures else 2000, - seurat_seed = 42, - skip_clustering = isTRUE(a$skip_clustering), - progress_cb = progress_cb + seurat_dims = a$seurat_dims, + seurat_nfeatures = if (!is.null(a$seurat_nfeatures)) { + a$seurat_nfeatures + } else { + 2000 + }, + seurat_seed = 42, + skip_clustering = isTRUE(a$skip_clustering), + progress_cb = progress_cb ) } run_demo <- function(a, progress_cb = NULL) { set.seed(42) - gene_names <- c("TP53", "BRCA1", "EGFR", "MYC", "KRAS", "PIK3CA", "PTEN", "RB1", - "APC", "BRAF", "CDH1", "CDKN2A", "ERBB2", "FGFR1", "ALK", - "MET", "RET", "ROS1", "NRAS", "HRAS", "MAP2K1", "MAPK1", - "JAK2", "STAT3", "MTOR", "AKT1", "AKT2", "CTNNB1", "SMAD4", - "VHL", "NF1", "NF2", "STK11", "FBXW7", "ARID1A", "KDM5C", - "KMT2D", "SETD2", "BAP1", "PBRM1", "NOTCH1", "NOTCH2", - "NOTCH3", "JAK1", "JAK3", "SOX9", "IDH1", "IDH2", "FLT3") + gene_names <- c( + "TP53", + "BRCA1", + "EGFR", + "MYC", + "KRAS", + "PIK3CA", + "PTEN", + "RB1", + "APC", + "BRAF", + "CDH1", + "CDKN2A", + "ERBB2", + "FGFR1", + "ALK", + "MET", + "RET", + "ROS1", + "NRAS", + "HRAS", + "MAP2K1", + "MAPK1", + "JAK2", + "STAT3", + "MTOR", + "AKT1", + "AKT2", + "CTNNB1", + "SMAD4", + "VHL", + "NF1", + "NF2", + "STK11", + "FBXW7", + "ARID1A", + "KDM5C", + "KMT2D", + "SETD2", + "BAP1", + "PBRM1", + "NOTCH1", + "NOTCH2", + "NOTCH3", + "JAK1", + "JAK3", + "SOX9", + "IDH1", + "IDH2", + "FLT3" + ) n_cells <- 400 n_patients <- 20 cell_names <- paste0("CELL_", sprintf("%04d", 1:n_cells)) patient_names <- paste0("PAT_", sprintf("%03d", 1:n_patients)) response_labels <- c(rep("Responder", 10), rep("Non-responder", 10)) - clinical_response <- data.frame(patient = patient_names, response = response_labels, - stringsAsFactors = FALSE) + clinical_response <- data.frame( + patient = patient_names, + response = response_labels, + stringsAsFactors = FALSE + ) - patient_assignment <- rep(patient_names, each = ceiling(n_cells / n_patients))[1:n_cells] - patient_mapping <- data.frame(cell_id = cell_names, patient_id = patient_assignment, - stringsAsFactors = FALSE) + patient_assignment <- rep( + patient_names, + each = ceiling(n_cells / n_patients) + )[1:n_cells] + patient_mapping <- data.frame( + cell_id = cell_names, + patient_id = patient_assignment, + stringsAsFactors = FALSE + ) is_responder_cell <- clinical_response$response[ - match(patient_assignment, clinical_response$patient)] == "Responder" + match(patient_assignment, clinical_response$patient) + ] == + "Responder" abemaciclib_markers <- gene_names[1:5] - erlotinib_markers <- gene_names[6:10] - noise_genes <- gene_names[11:length(gene_names)] + erlotinib_markers <- gene_names[6:10] + noise_genes <- gene_names[11:length(gene_names)] expr_matrix <- matrix(0.1, nrow = length(gene_names), ncol = n_cells) rownames(expr_matrix) <- gene_names @@ -615,26 +832,36 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { # coherent. Patient-level means therefore overlap — demo ROC AUC lands in # the realistic ~0.8-0.9 range instead of a perfect 1.0 — while single # cells still show a clear responder/non-responder expression trend. - set.seed(7) # fixed seed: the demo is reproducible across loads + set.seed(7) # fixed seed: the demo is reproducible across loads hi_cell <- runif(n_cells) < ifelse(is_responder_cell, 0.65, 0.35) for (g in abemaciclib_markers) { - expr_matrix[g, hi_cell] <- pmax(rnorm(sum(hi_cell), 6, 3), 0.1) + expr_matrix[g, hi_cell] <- pmax(rnorm(sum(hi_cell), 6, 3), 0.1) expr_matrix[g, !hi_cell] <- pmax(rnorm(sum(!hi_cell), 4, 3), 0.1) } for (g in erlotinib_markers) { - expr_matrix[g, hi_cell] <- pmax(rnorm(sum(hi_cell), 4, 3), 0.1) + expr_matrix[g, hi_cell] <- pmax(rnorm(sum(hi_cell), 4, 3), 0.1) expr_matrix[g, !hi_cell] <- pmax(rnorm(sum(!hi_cell), 6, 3), 0.1) } - for (g in noise_genes) expr_matrix[g, ] <- runif(n_cells, 0.5, 3.5) + for (g in noise_genes) { + expr_matrix[g, ] <- runif(n_cells, 0.5, 3.5) + } storage.mode(expr_matrix) <- "numeric" prepared <- PERCEPTIONx::prepare_data( - method = "umap", expression_matrix = expr_matrix, patient_mapping = patient_mapping, - seurat_resolution = 0.8, seurat_dims = 10, + method = "umap", + expression_matrix = expr_matrix, + patient_mapping = patient_mapping, + seurat_resolution = 0.8, + seurat_dims = 10, seurat_nfeatures = min(2000, length(gene_names)), - progress_cb = progress_cb) + progress_cb = progress_cb + ) - make_structured_training <- function(marker_genes, direction, n_train = 160) { + make_structured_training <- function( + marker_genes, + direction, + n_train = 160 + ) { x_train <- matrix(0, nrow = length(gene_names), ncol = n_train) rownames(x_train) <- gene_names half <- n_train %/% 2 @@ -642,27 +869,54 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { nonresponder_like <- seq.int(half + 1, n_train) for (g in marker_genes) { x_train[g, responder_like] <- pmax(rnorm(half, mean = 8, sd = 3), 0.1) - x_train[g, nonresponder_like] <- pmax(rnorm(half, mean = 3, sd = 2), 0.1) + x_train[g, nonresponder_like] <- pmax( + rnorm(half, mean = 3, sd = 2), + 0.1 + ) + } + for (g in setdiff(gene_names, marker_genes)) { + x_train[g, ] <- runif(n_train, 0.5, 8) } - for (g in setdiff(gene_names, marker_genes)) x_train[g, ] <- runif(n_train, 0.5, 8) y_train <- direction * colMeans(x_train[marker_genes, , drop = FALSE]) y_train <- y_train + rnorm(n_train, sd = 0.3) as.data.frame(cbind(y = y_train, t(x_train))) } make_drug_model <- function(drug_name, seed, marker_genes, direction) { set.seed(seed) - train_df <- make_structured_training(marker_genes, direction, n_train = 160) + train_df <- make_structured_training( + marker_genes, + direction, + n_train = 160 + ) caret_model <- suppressWarnings(caret::train( - y ~ ., data = train_df, method = "glmnet", + y ~ ., + data = train_df, + method = "glmnet", trControl = caret::trainControl(method = "cv", number = 3), - tuneLength = 3)) + tuneLength = 3 + )) obj <- list( model = caret_model, - performance_in_scRNA = data.frame(estimate.cor = c(0.45, 0.38), p.value = c(0.001, 0.01)), - performance_in_bulk = data.frame(estimate.cor = c(0.55, 0.48), p.value = c(0.0001, 0.001)), - performance_in_pseudo_bulk = data.frame(estimate.cor = c(0.50, 0.42), p.value = c(0.0005, 0.005)), - predVSgroundTruth = list(pred_gt_scRNA = data.frame(Observed = rnorm(20), Test_pred_sc = rnorm(20))), - single_best = marker_genes[1]) + performance_in_scRNA = data.frame( + estimate.cor = c(0.45, 0.38), + p.value = c(0.001, 0.01) + ), + performance_in_bulk = data.frame( + estimate.cor = c(0.55, 0.48), + p.value = c(0.0001, 0.001) + ), + performance_in_pseudo_bulk = data.frame( + estimate.cor = c(0.50, 0.42), + p.value = c(0.0005, 0.005) + ), + predVSgroundTruth = list( + pred_gt_scRNA = data.frame( + Observed = rnorm(20), + Test_pred_sc = rnorm(20) + ) + ), + single_best = marker_genes[1] + ) attr(obj, "drug_name") <- drug_name # SIMULATED demo model: trained on random noise, NOT on real drug # response data. UI must label it so users never mistake its output for @@ -672,26 +926,43 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { } models <- list( - abemaciclib = make_drug_model("abemaciclib", 101, abemaciclib_markers, direction = -1), - erlotinib = make_drug_model("erlotinib", 202, erlotinib_markers, direction = +1)) + abemaciclib = make_drug_model( + "abemaciclib", + 101, + abemaciclib_markers, + direction = -1 + ), + erlotinib = make_drug_model( + "erlotinib", + 202, + erlotinib_markers, + direction = +1 + ) + ) list( user_response = clinical_response, - user_mapping = patient_mapping, - user_expr = expr_matrix, + user_mapping = patient_mapping, + user_expr = expr_matrix, prepared_data = prepared, - user_clones = prepared$cell_clone_map, - models = models + user_clones = prepared$cell_clone_map, + models = models ) } run_predict <- function(a) { - clone_pred <- PERCEPTIONx::predict_drugs(model_list = a$model_list, expr = a$expr) + clone_pred <- PERCEPTIONx::predict_drugs( + model_list = a$model_list, + expr = a$expr + ) patient_pred <- NULL if (!is.null(a$patient_input)) { # Standard path: prepared_data-derived template + counts (small). - patient_pred <- PERCEPTIONx::predict_patients(clone_pred, a$patient_input, - mode = a$mode) + patient_pred <- PERCEPTIONx::predict_patients( + clone_pred, + a$patient_input, + mode = a$mode + ) } else if (!is.null(a$legacy_clones)) { # Legacy path (no prepared_data): aggregate from the user clone map. clone_data <- a$legacy_clones @@ -700,20 +971,32 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { clone_to_patient <- lapply(clone_to_patient, unique) clone_viability_list <- lapply(clone_rows, function(cl) { pat <- clone_to_patient[[cl]] - if (is.null(pat) || length(pat) == 0) return(NULL) - if (length(pat) > 1) pat <- pat[1] + if (is.null(pat) || length(pat) == 0) { + return(NULL) + } + if (length(pat) > 1) { + pat <- pat[1] + } df <- data.frame(patient = pat, clone_id = cl, stringsAsFactors = FALSE) - for (drug in colnames(clone_pred)) df[[drug]] <- clone_pred[cl, drug] + for (drug in colnames(clone_pred)) { + df[[drug]] <- clone_pred[cl, drug] + } df }) clone_viability_df <- do.call(rbind, clone_viability_list) if (is.null(clone_viability_df) || nrow(clone_viability_df) == 0) { stop("No matching clones between prediction and annotation") } - clone_counts <- as.data.frame.matrix(table(clone_data$patient, clone_data$clone_id)) + clone_counts <- as.data.frame.matrix(table( + clone_data$patient, + clone_data$clone_id + )) clone_counts$patients <- rownames(clone_counts) - patient_pred <- PERCEPTIONx::predict_patients(clone_viability_df, clone_counts, - mode = a$mode) + patient_pred <- PERCEPTIONx::predict_patients( + clone_viability_df, + clone_counts, + mode = a$mode + ) } list(clone_pred = clone_pred, patient_pred = patient_pred) } @@ -725,85 +1008,161 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { label_resp <- function(x) { y <- tolower(trimws(as.character(x))) - y[y %in% c("responder", "response", "responsive", "r", "sensitive", "sensitivity")] <- "R" - y[y %in% c("non-responder", "nonresponder", "non responder", "non-responsive", - "nonresponsive", "nr", "resistant", "resistance", "progressor", - "progression", "non", "non_responder")] <- "NR" + y[ + y %in% + c( + "responder", + "response", + "responsive", + "r", + "sensitive", + "sensitivity" + ) + ] <- "R" + y[ + y %in% + c( + "non-responder", + "nonresponder", + "non responder", + "non-responsive", + "nonresponsive", + "nr", + "resistant", + "resistance", + "progressor", + "progression", + "non", + "non_responder" + ) + ] <- "NR" keep <- !y %in% c("R", "NR") y[keep] <- toupper(y[keep]) y } safe_range01 <- function(x) { - if (length(x) == 0L) stop("empty input to safe_range01") + if (length(x) == 0L) { + stop("empty input to safe_range01") + } r <- tryCatch(PERCEPTIONx::range01(x), error = function(e) NULL) - if (!is.null(r) && length(r) == length(x)) return(r) + if (!is.null(r) && length(r) == length(x)) { + return(r) + } rng <- range(x, na.rm = TRUE) # Constant vector: map to 0 ("no signal"), not the old 0.5 midpoint. - if (rng[2] == rng[1]) rep(0, length(x)) else (x - rng[1]) / (rng[2] - rng[1]) + if (rng[2] == rng[1]) { + rep(0, length(x)) + } else { + (x - rng[1]) / (rng[2] - rng[1]) + } } get_embedding_xy <- function(coords, cell_ids) { - if (!is.data.frame(coords)) stop("umap_coords is not a data frame") - if (!"cell_id" %in% names(coords)) stop("umap_coords has no 'cell_id' column") + if (!is.data.frame(coords)) { + stop("umap_coords is not a data frame") + } + if (!"cell_id" %in% names(coords)) { + stop("umap_coords has no 'cell_id' column") + } x_col <- intersect(c("dim_1", "umap_1"), names(coords))[1] y_col <- intersect(c("dim_2", "umap_2"), names(coords))[1] - if (is.na(x_col) || is.na(y_col)) + if (is.na(x_col) || is.na(y_col)) { stop("Embedding coordinate columns not found in umap_coords") + } idx <- match(cell_ids, coords$cell_id) - if (all(is.na(idx))) stop("0 matching cell IDs between query and umap_coords") + if (all(is.na(idx))) { + stop("0 matching cell IDs between query and umap_coords") + } list(X = coords[[x_col]][idx], Y = coords[[y_col]][idx]) } combo_clone_frame <- function() { pred_mat <- d$predictions - if (is.null(pred_mat) || ncol(pred_mat) < 1) stop("No clone-level predictions to combine.") + if (is.null(pred_mat) || ncol(pred_mat) < 1) { + stop("No clone-level predictions to combine.") + } pred_mat <- as.matrix(pred_mat) z_mat <- pred_mat for (j in seq_len(ncol(pred_mat))) { col <- pred_mat[, j] s <- stats::sd(col, na.rm = TRUE) - z_mat[, j] <- if (is.na(s) || s == 0) rep(0, nrow(pred_mat)) else + z_mat[, j] <- if (is.na(s) || s == 0) { + rep(0, nrow(pred_mat)) + } else { (col - mean(col, na.rm = TRUE)) / s + } } comb <- apply(z_mat, 1, min, na.rm = TRUE) tmpl <- d$prepared$clone_viability_template if (!is.null(tmpl)) { - clone_viability_df <- data.frame(patient = tmpl$patient, clone_id = tmpl$clone_id, - comb_viability = unname(comb), stringsAsFactors = FALSE) + clone_viability_df <- data.frame( + patient = tmpl$patient, + clone_id = tmpl$clone_id, + comb_viability = unname(comb), + stringsAsFactors = FALSE + ) } else { parsed <- PERCEPTIONx::parse_clone_keys(names(comb)) - clone_viability_df <- data.frame(patient = parsed$patient, clone_id = parsed$clone_id, - comb_viability = unname(comb), stringsAsFactors = FALSE) + clone_viability_df <- data.frame( + patient = parsed$patient, + clone_id = parsed$clone_id, + comb_viability = unname(comb), + stringsAsFactors = FALSE + ) } clone_data <- d$user_clones if (!is.null(clone_data) && nrow(clone_data) > 0) { - clone_viability_df$weights <- vapply(seq_len(nrow(clone_viability_df)), function(i) { - pat <- clone_viability_df$patient[i] - cl <- clone_viability_df$clone_id[i] - n_p <- sum(clone_data$patient == pat, na.rm = TRUE) - if (n_p == 0) NA_real_ else - sum(clone_data$patient == pat & clone_data$clone_id == cl, na.rm = TRUE) / n_p - }, numeric(1)) + clone_viability_df$weights <- vapply( + seq_len(nrow(clone_viability_df)), + function(i) { + pat <- clone_viability_df$patient[i] + cl <- clone_viability_df$clone_id[i] + n_p <- sum(clone_data$patient == pat, na.rm = TRUE) + if (n_p == 0) { + NA_real_ + } else { + sum( + clone_data$patient == pat & clone_data$clone_id == cl, + na.rm = TRUE + ) / + n_p + } + }, + numeric(1) + ) } else { clone_viability_df$weights <- NA_real_ } if (!is.null(d$user_response)) { clone_viability_df$response <- label_resp(d$user_response$response[ - match(clone_viability_df$patient, d$user_response$patient)]) + match(clone_viability_df$patient, d$user_response$patient) + ]) } clone_viability_df } combo_patient_frame <- function(clone_viability_df) { patients <- unique(clone_viability_df$patient) - scores <- vapply(patients, function(p) { - sub <- clone_viability_df[clone_viability_df$patient == p, ] - sub <- sub[!is.na(sub$comb_viability) & !is.na(sub$weights), ] - if (nrow(sub) == 0) return(NA_real_) - max(sub$comb_viability * sub$weights) - }, numeric(1)) - data.frame(patient = patients, combination = scores, stringsAsFactors = FALSE) + scores <- vapply( + patients, + function(p) { + sub <- clone_viability_df[clone_viability_df$patient == p, ] + sub <- sub[!is.na(sub$comb_viability) & !is.na(sub$weights), ] + if (nrow(sub) == 0) { + return(NA_real_) + } + max(sub$comb_viability * sub$weights) + }, + numeric(1) + ) + data.frame( + patient = patients, + combination = scores, + stringsAsFactors = FALSE + ) } response_groups <- function() { cr <- d$user_response - if (is.null(cr) || is.null(cr$response)) return(character(0)) + if (is.null(cr) || is.null(cr$response)) { + return(character(0)) + } grps <- unique(label_resp(cr$response)) grps[!is.na(grps) & nzchar(trimws(grps)) & grps != "NA"] } @@ -819,84 +1178,144 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { p_cells <- clone_data[clone_data$patient == pp, ] p_clones <- unique(p_cells$clone_id) n_p_cells <- nrow(p_cells) - display_clones <- vapply(p_clones, function(cl) { - if (!startsWith(cl, pp)) return(cl) - rest <- sub("^[\\._-]", "", substring(cl, nchar(pp) + 1)) - if (nchar(rest) == 0) cl else rest - }, character(1)) - data.frame(patients = pp, clones = display_clones, - weights = sapply(p_clones, function(cl) sum(p_cells$clone_id == cl) / n_p_cells), - stringsAsFactors = FALSE) + display_clones <- vapply( + p_clones, + function(cl) { + if (!startsWith(cl, pp)) { + return(cl) + } + rest <- sub("^[\\._-]", "", substring(cl, nchar(pp) + 1)) + if (nchar(rest) == 0) cl else rest + }, + character(1) + ) + data.frame( + patients = pp, + clones = display_clones, + weights = sapply(p_clones, function(cl) { + sum(p_cells$clone_id == cl) / n_p_cells + }), + stringsAsFactors = FALSE + ) }) clone_distribution <- do.call(rbind, clone_dist_list) if (!is.null(d$user_response)) { clone_distribution$response <- label_resp(d$user_response$response[ - match(clone_distribution$patients, d$user_response$patient)]) + match(clone_distribution$patients, d$user_response$patient) + ]) clone_distribution$response <- label_resp(clone_distribution$response) - clone_distribution <- clone_distribution[!is.na(clone_distribution$response), ] + clone_distribution <- clone_distribution[ + !is.na(clone_distribution$response), + ] } - plot_obj <- PERCEPTIONx::plot_clone_distribution(clone_distribution, response_var = "response") - + plot_obj <- PERCEPTIONx::plot_clone_distribution( + clone_distribution, + response_var = "response" + ) } else if (pt == "clone_kill") { clone_data <- d$user_clones pred_mat <- d$predictions - drug <- if (!is.null(drug) && nchar(drug) > 0) drug else colnames(pred_mat)[1] + drug <- if (!is.null(drug) && nchar(drug) > 0) { + drug + } else { + colnames(pred_mat)[1] + } if (is_combo) { combo_df <- combo_clone_frame() combo_df <- combo_df[!is.na(combo_df$response), ] - if (nrow(combo_df) == 0) stop("No clones with a valid R/NR response for the combination plot.") - plot_obj <- PERCEPTIONx::plot_clone_viability(combo_df, viability_var = "comb_viability", - weights_var = "weights", response_var = "response", - drug = "Combination") + if (nrow(combo_df) == 0) { + stop("No clones with a valid R/NR response for the combination plot.") + } + plot_obj <- PERCEPTIONx::plot_clone_viability( + combo_df, + viability_var = "comb_viability", + weights_var = "weights", + response_var = "response", + drug = "Combination" + ) } else { clone_viability_df <- NULL tmpl <- d$prepared$clone_viability_template if (!is.null(tmpl)) { clone_viability_df <- data.frame( - patient = tmpl$patient, clone_id = tmpl$clone_id, + patient = tmpl$patient, + clone_id = tmpl$clone_id, comb_viability = pred_mat[rownames(pred_mat), drug], - stringsAsFactors = FALSE) + stringsAsFactors = FALSE + ) if (!is.null(clone_data) && nrow(clone_data) > 0) { - clone_viability_df$weights <- vapply(seq_len(nrow(clone_viability_df)), function(i) { - pat <- clone_viability_df$patient[i] - cl <- clone_viability_df$clone_id[i] - n_p <- sum(clone_data$patient == pat, na.rm = TRUE) - if (n_p == 0) NA_real_ else - sum(clone_data$patient == pat & clone_data$clone_id == cl, na.rm = TRUE) / n_p - }, numeric(1)) + clone_viability_df$weights <- vapply( + seq_len(nrow(clone_viability_df)), + function(i) { + pat <- clone_viability_df$patient[i] + cl <- clone_viability_df$clone_id[i] + n_p <- sum(clone_data$patient == pat, na.rm = TRUE) + if (n_p == 0) { + NA_real_ + } else { + sum( + clone_data$patient == pat & clone_data$clone_id == cl, + na.rm = TRUE + ) / + n_p + } + }, + numeric(1) + ) } } else { parsed <- PERCEPTIONx::parse_clone_keys(rownames(pred_mat)) pred_clone_ids <- parsed$clone_id - pred_patients <- parsed$patient + pred_patients <- parsed$patient clone_kill_list <- lapply(unique(clone_data$patient), function(pp) { p_clones <- unique(clone_data$clone_id[clone_data$patient == pp]) p_clones <- intersect(p_clones, pred_clone_ids) - if (length(p_clones) == 0) return(NULL) + if (length(p_clones) == 0) { + return(NULL) + } n_p_cells <- sum(clone_data$patient == pp) - pred_rows <- which(pred_clone_ids %in% p_clones & pred_patients == pp) - if (length(pred_rows) == 0) pred_rows <- match(p_clones, pred_clone_ids) - data.frame(patient = pp, clone_id = pred_clone_ids[pred_rows], - comb_viability = pred_mat[pred_rows, drug], - weights = sapply(pred_clone_ids[pred_rows], function(cl) sum(clone_data$clone_id == cl) / n_p_cells), - stringsAsFactors = FALSE) + pred_rows <- which( + pred_clone_ids %in% p_clones & pred_patients == pp + ) + if (length(pred_rows) == 0) { + pred_rows <- match(p_clones, pred_clone_ids) + } + data.frame( + patient = pp, + clone_id = pred_clone_ids[pred_rows], + comb_viability = pred_mat[pred_rows, drug], + weights = sapply(pred_clone_ids[pred_rows], function(cl) { + sum(clone_data$clone_id == cl) / n_p_cells + }), + stringsAsFactors = FALSE + ) }) clone_viability_df <- do.call(rbind, clone_kill_list) } if (is.null(clone_viability_df) || nrow(clone_viability_df) == 0) { - stop("No matching clones between prediction matrix and clone annotation.") + stop( + "No matching clones between prediction matrix and clone annotation." + ) } if (!is.null(d$user_response)) { clone_viability_df$response <- label_resp(d$user_response$response[ - match(clone_viability_df$patient, d$user_response$patient)]) - clone_viability_df <- clone_viability_df[!is.na(clone_viability_df$response), ] + match(clone_viability_df$patient, d$user_response$patient) + ]) + clone_viability_df <- clone_viability_df[ + !is.na(clone_viability_df$response), + ] } - clone_viability_df$comb_viability <- as.numeric(scale(clone_viability_df$comb_viability)) - plot_obj <- PERCEPTIONx::plot_clone_viability(clone_viability_df, viability_var = "comb_viability", - weights_var = "weights", response_var = "response", - drug = drug) + clone_viability_df$comb_viability <- as.numeric(scale( + clone_viability_df$comb_viability + )) + plot_obj <- PERCEPTIONx::plot_clone_viability( + clone_viability_df, + viability_var = "comb_viability", + weights_var = "weights", + response_var = "response", + drug = drug + ) } - } else if (pt == "roc") { cr <- d$user_response if (is_combo) { @@ -915,9 +1334,14 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { predictor_vec <- predictor_vec[keep] grps <- response_groups() if (length(grps) > 2) { - a <- p$roc_group_a; b <- p$roc_group_b - if (is.null(a) || !(a %in% grps)) a <- if ("PD" %in% grps) "PD" else grps[1] - if (is.null(b) || !(b %in% grps)) b <- if ("RD" %in% grps) "RD" else grps[2] + a <- p$roc_group_a + b <- p$roc_group_b + if (is.null(a) || !(a %in% grps)) { + a <- if ("PD" %in% grps) "PD" else grps[1] + } + if (is.null(b) || !(b %in% grps)) { + b <- if ("RD" %in% grps) "RD" else grps[2] + } sel <- unique(c(a, b)) } else { sel <- grps @@ -928,10 +1352,15 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { predictor_vec <- predictor_vec[keep2] smooth <- length(response_vec) >= 10 title <- if (is_combo) "Combination" else drug - if (length(grps) > 2) title <- paste0(title, " — ", paste(sel, collapse = " vs ")) - plot_obj <- PERCEPTIONx::plot_roc_curve(response = response_vec, predictor = predictor_vec, - smooth_curve = smooth, title = title) - + if (length(grps) > 2) { + title <- paste0(title, " — ", paste(sel, collapse = " vs ")) + } + plot_obj <- PERCEPTIONx::plot_roc_curve( + response = response_vec, + predictor = predictor_vec, + smooth_curve = smooth, + title = title + ) } else if (pt == "boxplot") { cr <- d$user_response if (is_combo) { @@ -948,20 +1377,31 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { keep <- !is.na(rv) & !is.na(predictor_vec) rv <- rv[keep] predictor_vec <- predictor_vec[keep] - predictor_vec <- if (length(predictor_vec) > 1 && is.finite(sd(predictor_vec)) && sd(predictor_vec) > 0) { + predictor_vec <- if ( + length(predictor_vec) > 1 && + is.finite(sd(predictor_vec)) && + sd(predictor_vec) > 0 + ) { as.numeric(scale(predictor_vec)) - } else predictor_vec - exp_vs_pred <- data.frame(response = factor(rv, levels = unique(rv)), - predicted_viability = predictor_vec, stringsAsFactors = FALSE) + } else { + predictor_vec + } + exp_vs_pred <- data.frame( + response = factor(rv, levels = unique(rv)), + predicted_viability = predictor_vec, + stringsAsFactors = FALSE + ) plot_obj <- PERCEPTIONx::plot_response_boxplot(exp_vs_pred) - plot_obj <- plot_obj + ggplot2::ggtitle(if (is_combo) "Combination" else drug) - + plot_obj <- plot_obj + + ggplot2::ggtitle(if (is_combo) "Combination" else drug) } else if (pt %in% c("umap_gene", "umap_viability", "umap_clone")) { umap_coords <- d$prepared$umap_coords clone_data <- d$user_clones common_cells <- intersect(clone_data$cell_id, umap_coords$cell_id) if (length(common_cells) == 0) { - stop("No matching cells between embedding coordinates and clone annotation.") + stop( + "No matching cells between embedding coordinates and clone annotation." + ) } if (pt == "umap_gene") { gene <- p$umap_gene @@ -973,63 +1413,123 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { } else if (is.null(expr_vec) || length(expr_vec) == 0) { msg <- paste0("Gene '", gene, "' not found in expression matrix.") } else { - cell_expr <- as.numeric(expr_vec[match(common_cells, names(expr_vec))]) + cell_expr <- as.numeric(expr_vec[match( + common_cells, + names(expr_vec) + )]) xy <- get_embedding_xy(umap_coords, common_cells) n <- length(common_cells) - stopifnot(length(xy$X) == n, length(xy$Y) == n, length(cell_expr) == n, - !anyNA(cell_expr)) - umap_data <- data.frame(X = xy$X, Y = xy$Y, expression = safe_range01(cell_expr), - row.names = common_cells) - plot_obj <- PERCEPTIONx::plot_tsne_response(umap_data, color_var = "expression", - title = gene, color_label = "Expression (0-1)", - colors = c("#e0e0e0", "#c13232"), - limits = c(0, 1), base_size = 11) + stopifnot( + length(xy$X) == n, + length(xy$Y) == n, + length(cell_expr) == n, + !anyNA(cell_expr) + ) + umap_data <- data.frame( + X = xy$X, + Y = xy$Y, + expression = safe_range01(cell_expr), + row.names = common_cells + ) + plot_obj <- PERCEPTIONx::plot_tsne_response( + umap_data, + color_var = "expression", + title = gene, + color_label = "Expression (0-1)", + colors = c("#e0e0e0", "#c13232"), + limits = c(0, 1), + base_size = 11 + ) } } else if (pt == "umap_viability") { pred_mat <- d$predictions if (is.null(pred_mat)) { msg <- "No clone-level predictions found. Run predictions first." } else { - drug <- if (!is.null(p$umap_drug) && nchar(p$umap_drug) > 0) p$umap_drug else colnames(pred_mat)[1] - cell_keys <- PERCEPTIONx::build_clone_key(clone_data$patient, clone_data$clone_id) + drug <- if (!is.null(p$umap_drug) && nchar(p$umap_drug) > 0) { + p$umap_drug + } else { + colnames(pred_mat)[1] + } + cell_keys <- PERCEPTIONx::build_clone_key( + clone_data$patient, + clone_data$clone_id + ) pred_keys <- rownames(pred_mat) - cell_viability <- setNames(pred_mat[match(cell_keys, pred_keys), drug], clone_data$cell_id) + cell_viability <- setNames( + pred_mat[match(cell_keys, pred_keys), drug], + clone_data$cell_id + ) kill_common <- intersect(names(cell_viability), umap_coords$cell_id) kill_common <- kill_common[!is.na(cell_viability[kill_common])] if (length(kill_common) == 0) { msg <- "No matching cells between embedding coordinates and prediction data." } else { raw_vals <- cell_viability[kill_common] - scaled_vals <- if (length(raw_vals) > 1 && is.finite(sd(raw_vals)) && sd(raw_vals) > 0) { + scaled_vals <- if ( + length(raw_vals) > 1 && + is.finite(sd(raw_vals)) && + sd(raw_vals) > 0 + ) { as.numeric(scale(raw_vals)) - } else raw_vals + } else { + raw_vals + } xy <- get_embedding_xy(umap_coords, kill_common) n <- length(kill_common) - stopifnot(length(xy$X) == n, length(xy$Y) == n, length(scaled_vals) == n) - umap_data <- data.frame(X = xy$X, Y = xy$Y, viability_scaled = scaled_vals, - row.names = kill_common) - plot_obj <- PERCEPTIONx::plot_tsne_response(umap_data, color_var = "viability_scaled", - title = drug, color_label = "Predicted Viability (z-score)", - palette = "diverging", midpoint = 0, - base_size = 11) + stopifnot( + length(xy$X) == n, + length(xy$Y) == n, + length(scaled_vals) == n + ) + umap_data <- data.frame( + X = xy$X, + Y = xy$Y, + viability_scaled = scaled_vals, + row.names = kill_common + ) + plot_obj <- PERCEPTIONx::plot_tsne_response( + umap_data, + color_var = "viability_scaled", + title = drug, + color_label = "Predicted Viability (z-score)", + palette = "diverging", + midpoint = 0, + base_size = 11 + ) } } - } else { # umap_clone + } else { + # umap_clone idx <- match(common_cells, clone_data$cell_id) xy <- get_embedding_xy(umap_coords, common_cells) n <- length(common_cells) stopifnot(length(xy$X) == n, length(xy$Y) == n, length(idx) == n) - umap_data <- data.frame(X = xy$X, Y = xy$Y, clone_id = clone_data$clone_id[idx], - stringsAsFactors = FALSE) - plot_obj <- PERCEPTIONx::plot_clone_umap(umap_data, title = "Clone Identity") + umap_data <- data.frame( + X = xy$X, + Y = xy$Y, + clone_id = clone_data$clone_id[idx], + stringsAsFactors = FALSE + ) + plot_obj <- PERCEPTIONx::plot_clone_umap( + umap_data, + title = "Clone Identity" + ) } } else { stop("Unknown plot type: ", pt) } - list(plot = plot_obj, - message = if (!is.null(msg)) msg else - if (is.null(plot_obj)) "Selected plot type is not available with current data" else "") + list( + plot = plot_obj, + message = if (!is.null(msg)) { + msg + } else if (is.null(plot_obj)) { + "Selected plot type is not available with current data" + } else { + "" + } + ) } # Download with mirror fallback. Downloading AND parsing (reading the 567 MB @@ -1038,11 +1538,16 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { # process never deserializes the big object either way. run_download <- function(a) { ok <- PERCEPTIONx:::download_with_mirrors( - a$urls, a$destfile, quiet = TRUE, + a$urls, + a$destfile, + quiet = TRUE, timeout_seconds = a$timeout_seconds, retries = a$retries, - expected_size = a$expected_size) - if (!ok) stop("Automatic download failed after trying all mirrors") + expected_size = a$expected_size + ) + if (!ok) { + stop("Automatic download failed after trying all mirrors") + } if (!file.exists(a$destfile) || file.size(a$destfile) == 0) { stop("Downloaded file is missing or empty") } @@ -1069,39 +1574,62 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { while (TRUE) { # Only claim dirs whose params.rds is fully written (see master note). pending <- list.dirs(jobs_dir, recursive = FALSE, full.names = TRUE) - pending <- pending[vapply(pending, function(j) - file.exists(file.path(j, "ready")), logical(1))] + pending <- pending[vapply( + pending, + function(j) { + file.exists(file.path(j, "ready")) + }, + logical(1) + )] for (j in pending) { status_file <- file.path(j, "status.txt") if (!file.exists(status_file) && file.create(status_file)) { params <- tryCatch( readRDS(file.path(j, "params.rds")), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(params, "perception_job_error")) { # A corrupt params file must not crash the worker (that would strand # every later job in this session's queue). - writeLines(sprintf("error|Failed to read job params: %s", params$message), - status_file) + writeLines( + sprintf("error|Failed to read job params: %s", params$message), + status_file + ) next } out <- tryCatch( - switch(params$task, - prepare = run_prepare(params$args, progress_cb = function(phase, i, n, drug) { - write_progress(file.path(j, "progress.txt"), phase, i, n, drug) - }), - demo = run_demo(params$args, progress_cb = function(phase, i, n, drug) { - write_progress(file.path(j, "progress.txt"), phase, i, n, drug) - }), + switch( + params$task, + prepare = run_prepare( + params$args, + progress_cb = function(phase, i, n, drug) { + write_progress(file.path(j, "progress.txt"), phase, i, n, drug) + } + ), + demo = run_demo( + params$args, + progress_cb = function(phase, i, n, drug) { + write_progress(file.path(j, "progress.txt"), phase, i, n, drug) + } + ), predict = run_predict(params$args), - plot = run_plot(params$args), + plot = run_plot(params$args), download = run_download(params$args), extract_meta = run_extract_meta(params$args), - warmup = run_warmup(params$args), - stop("Unknown task: ", params$task)), - error = function(e) structure(list(message = conditionMessage(e)), - class = "perception_job_error") + warmup = run_warmup(params$args), + stop("Unknown task: ", params$task) + ), + error = function(e) { + structure( + list(message = conditionMessage(e)), + class = "perception_job_error" + ) + } ) if (inherits(out, "perception_job_error")) { writeLines(sprintf("error|%s", out$message), status_file) @@ -1119,8 +1647,11 @@ session_task_main <- function(pkg_root, jobs_dir, poll_secs = 0.25) { # Lazily spawn ONE light worker per session for prepare/demo/predict jobs. ensure_session_worker <- function(shared) { - if (isTRUE(shared$task_worker_alive) && !is.null(shared$task_worker) && - shared$task_worker$is_alive()) { + if ( + isTRUE(shared$task_worker_alive) && + !is.null(shared$task_worker) && + shared$task_worker$is_alive() + ) { return(invisible(TRUE)) } jobs_dir <- file.path(tempdir(), "perception_tasks", make_job_id()) @@ -1134,8 +1665,10 @@ ensure_session_worker <- function(shared) { worker <- tryCatch( spawn_r_bg_retry( session_task_main, - args = list(pkg_root = getOption("perception.pkg_root", NULL), - jobs_dir = jobs_dir), + args = list( + pkg_root = getOption("perception.pkg_root", NULL), + jobs_dir = jobs_dir + ), jobs_dir = jobs_dir ), error = function(e) { @@ -1171,11 +1704,20 @@ submit_session_task <- function(shared, task, args) { read_task_state <- function(shared, jobid) { job_dir <- file.path(shared$task_jobs_dir, jobid) status_file <- file.path(job_dir, "status.txt") - if (!file.exists(status_file)) return(list(status = "queued")) + if (!file.exists(status_file)) { + return(list(status = "queued")) + } s <- readLines(status_file, warn = FALSE) - if (length(s) == 0) return(list(status = "running")) + if (length(s) == 0) { + return(list(status = "running")) + } s <- s[1] - if (s == "done") return(list(status = "done", result = readRDS(file.path(job_dir, "result.rds")))) + if (s == "done") { + return(list( + status = "done", + result = readRDS(file.path(job_dir, "result.rds")) + )) + } if (startsWith(s, "error")) { return(list(status = "error", message = sub("^error\\|", "", s))) } @@ -1187,8 +1729,15 @@ read_task_state <- function(shared, jobid) { # so one call per submission is enough (no manual cleanup needed). If the # session worker died mid-task (is_alive == FALSE) the poll gives up with an # actionable error instead of spinning forever. -poll_task <- function(shared, session, jobid, on_done, on_error = NULL, - poll_ms = 250, on_progress = NULL) { +poll_task <- function( + shared, + session, + jobid, + on_done, + on_error = NULL, + poll_ms = 250, + on_progress = NULL +) { obs <- NULL last_progress <- NULL obs <- observe({ @@ -1198,15 +1747,27 @@ poll_task <- function(shared, session, jobid, on_done, on_error = NULL, # current Seurat stage in the overlay. if (!is.null(on_progress)) { tj <- shared$task_jobs_dir - pf <- if (!is.null(tj) && nzchar(tj)) file.path(tj, jobid, "progress.txt") else NULL + pf <- if (!is.null(tj) && nzchar(tj)) { + file.path(tj, jobid, "progress.txt") + } else { + NULL + } if (!is.null(pf) && file.exists(pf)) { l <- readLines(pf, warn = FALSE) if (length(l) > 0 && !identical(l, last_progress)) { last_progress <- l parts <- strsplit(l, "\\|", fixed = FALSE)[[1]] phase <- if (length(parts) >= 1) parts[1] else "" - i <- if (length(parts) >= 2) suppressWarnings(as.integer(parts[2])) else 0L - n <- if (length(parts) >= 3) suppressWarnings(as.integer(parts[3])) else 0L + i <- if (length(parts) >= 2) { + suppressWarnings(as.integer(parts[2])) + } else { + 0L + } + n <- if (length(parts) >= 3) { + suppressWarnings(as.integer(parts[3])) + } else { + 0L + } drug <- if (length(parts) >= 4) parts[4] else "" on_progress(phase, i, n, drug) } @@ -1217,7 +1778,9 @@ poll_task <- function(shared, session, jobid, on_done, on_error = NULL, # degrade to a bare relative path that unlink could resolve in cwd. cleanup_job_dir <- function() { tj <- shared$task_jobs_dir - if (!is.null(tj) && nzchar(tj)) unlink(file.path(tj, jobid), recursive = TRUE) + if (!is.null(tj) && nzchar(tj)) { + unlink(file.path(tj, jobid), recursive = TRUE) + } } if (st$status == "done") { obs$destroy() @@ -1233,8 +1796,11 @@ poll_task <- function(shared, session, jobid, on_done, on_error = NULL, if (!is.null(on_error)) { on_error(st$message) } else { - showNotification(paste("Background task failed:", st$message), - type = "error", duration = 10) + showNotification( + paste("Background task failed:", st$message), + type = "error", + duration = 10 + ) } } else { w <- shared$task_worker @@ -1245,8 +1811,11 @@ poll_task <- function(shared, session, jobid, on_done, on_error = NULL, if (!is.null(on_error)) { on_error("Background worker stopped unexpectedly. Please try again.") } else { - showNotification("Background worker stopped unexpectedly. Please try again.", - type = "error", duration = 10) + showNotification( + "Background worker stopped unexpectedly. Please try again.", + type = "error", + duration = 10 + ) } } else { # NOTE: no explicit session arg here. Inside observe() the default diff --git a/inst/shiny/app/R/mod_data.R b/inst/shiny/app/R/mod_data.R index 0d890df..e39c084 100644 --- a/inst/shiny/app/R/mod_data.R +++ b/inst/shiny/app/R/mod_data.R @@ -27,7 +27,9 @@ read_uploaded_table <- function(file) { # Count fields in a delimited line, ignoring delimiters inside double quotes. count_fields <- function(line, sep) { - if (!nzchar(trimws(line))) return(0L) + if (!nzchar(trimws(line))) { + return(0L) + } pat <- paste0(sep, "(?=([^\"]*\"[^\"]*\")*[^\"]*$)") length(strsplit(line, pat, perl = TRUE)[[1]]) } @@ -35,7 +37,11 @@ read_uploaded_table <- function(file) { # First row with >= 2 non-empty cells = the real header row. first_header_row <- function(rows) { for (i in seq_along(rows)) { - if (sum(!is.na(rows[[i]]) & nzchar(trimws(as.character(rows[[i]])))) >= 2) return(i) + if ( + sum(!is.na(rows[[i]]) & nzchar(trimws(as.character(rows[[i]])))) >= 2 + ) { + return(i) + } } 1L } @@ -60,14 +66,24 @@ read_uploaded_table <- function(file) { con <- open_con() lines <- readLines(con, warn = FALSE) close(con) - hit_all <- which(vapply(lines, count_fields, integer(1), sep = sep) >= 2)[1] + hit_all <- which(vapply(lines, count_fields, integer(1), sep = sep) >= 2)[ + 1 + ] n_skip <- if (is.na(hit_all)) 0L else hit_all - 1L } con <- open_con() - out <- read.table(con, header = TRUE, sep = sep_arg, skip = n_skip, - stringsAsFactors = FALSE, check.names = FALSE, - comment.char = "", quote = "\"", fill = TRUE) + out <- read.table( + con, + header = TRUE, + sep = sep_arg, + skip = n_skip, + stringsAsFactors = FALSE, + check.names = FALSE, + comment.char = "", + quote = "\"", + fill = TRUE + ) close(con) attr(out, "skipped_rows") <- n_skip out @@ -75,37 +91,54 @@ read_uploaded_table <- function(file) { read_excel_tbl <- function(path) { if (!requireNamespace("readxl", quietly = TRUE)) { - stop("Excel upload requires the 'readxl' package. Please run: install.packages('readxl')") + stop( + "Excel upload requires the 'readxl' package. Please run: install.packages('readxl')" + ) } raw <- readxl::read_excel(path, col_names = FALSE, .name_repair = "minimal") - rows <- lapply(seq_len(nrow(raw)), function(i) - as.character(unlist(raw[i, ], use.names = FALSE))) + rows <- lapply(seq_len(nrow(raw)), function(i) { + as.character(unlist(raw[i, ], use.names = FALSE)) + }) header_idx <- first_header_row(rows) - out <- as.data.frame(raw[seq.int(header_idx + 1L, nrow(raw)), , drop = FALSE], - stringsAsFactors = FALSE, check.names = FALSE) + out <- as.data.frame( + raw[seq.int(header_idx + 1L, nrow(raw)), , drop = FALSE], + stringsAsFactors = FALSE, + check.names = FALSE + ) colnames(out) <- rows[[header_idx]] attr(out, "skipped_rows") <- header_idx - 1L out } if (gz && ext %in% c("rds", "xlsx", "xls")) { - stop("Compressed .", ext, ".gz files are not supported. Compress text ", - "matrices as .csv.gz, .tsv.gz or .txt.gz instead.") + stop( + "Compressed .", + ext, + ".gz files are not supported. Compress text ", + "matrices as .csv.gz, .tsv.gz or .txt.gz instead." + ) } - switch(ext, + switch( + ext, rds = { obj <- readRDS(file$datapath) - if (!isS4(obj)) attr(obj, "skipped_rows") <- 0L + if (!isS4(obj)) { + attr(obj, "skipped_rows") <- 0L + } obj }, csv = read_text(file$datapath, ",", gz = gz), tsv = read_text(file$datapath, "\t", gz = gz), txt = read_text(file$datapath, "[ \t]+", gz = gz), xlsx = read_excel_tbl(file$datapath), - xls = read_excel_tbl(file$datapath), - stop("Unsupported file type: .", ext, ". Please use .csv, .tsv, .txt, .xlsx, ", - ".rds, or a gzip-compressed .csv.gz / .tsv.gz / .txt.gz.") + xls = read_excel_tbl(file$datapath), + stop( + "Unsupported file type: .", + ext, + ". Please use .csv, .tsv, .txt, .xlsx, ", + ".rds, or a gzip-compressed .csv.gz / .tsv.gz / .txt.gz." + ) ) } @@ -123,22 +156,45 @@ standardize_columns <- function(df, std_cols) { # Map common response spellings to the canonical two-class labels. normalize_response_labels <- function(x) { y <- tolower(trimws(as.character(x))) - y[y %in% c("responder", "response", "responsive", "r", "sensitive", "sensitivity")] <- "Responder" - y[y %in% c("non-responder", "nonresponder", "non responder", "non-responsive", - "nonresponsive", "nr", "resistant", "resistance", "progressor", - "progression", "non", "non_responder")] <- "Non-responder" + y[ + y %in% + c("responder", "response", "responsive", "r", "sensitive", "sensitivity") + ] <- "Responder" + y[ + y %in% + c( + "non-responder", + "nonresponder", + "non responder", + "non-responsive", + "nonresponsive", + "nr", + "resistant", + "resistance", + "progressor", + "progression", + "non", + "non_responder" + ) + ] <- "Non-responder" # Longitudinal treatment time points (Maynard et al. Cell 2020; PERCEPTION # Fig. 4 lung cohort): kept as canonical 3-group labels rather than being # collapsed into R/NR. - y[y %in% c("tn", "treatment naive", "treatment-naive", "naive", "untreated")] <- "TN" + y[ + y %in% c("tn", "treatment naive", "treatment-naive", "naive", "untreated") + ] <- "TN" y[y %in% c("rd", "residual disease", "residual")] <- "RD" - y[y %in% c("pd", "progressive disease", "progressed", "progression disease")] <- "PD" + y[ + y %in% c("pd", "progressive disease", "progressed", "progression disease") + ] <- "PD" y } # Human-readable suffix for the number of auto-skipped top comment rows. skipped_rows_msg <- function(n) { - if (is.null(n) || n <= 0) return("") + if (is.null(n) || n <= 0) { + return("") + } paste0(" (auto-skipped ", n, " top comment/title row", if (n > 1) "s", ")") } @@ -146,14 +202,16 @@ skipped_rows_msg <- function(n) { # Accepts: data.frame (cell_id/patient_id), named list (patient -> cell ids), # named character vector (cell id -> patient id), or a 2-column matrix. coerce_mapping_df <- function(x) { - if (is.data.frame(x)) return(x) + if (is.data.frame(x)) { + return(x) + } if (is.list(x)) { # Named list: names = patients, elements = cell-id vectors (empty entries dropped) if (!is.null(names(x))) { len <- lengths(x) if (sum(len) > 0) { return(data.frame( - cell_id = unlist(x, use.names = FALSE), + cell_id = unlist(x, use.names = FALSE), patient_id = rep(names(x), len), stringsAsFactors = FALSE )) @@ -162,26 +220,40 @@ coerce_mapping_df <- function(x) { stop("Mapping list must be named, with cell-id vectors per patient.") } if (is.matrix(x)) { - if (ncol(x) == 2) return(as.data.frame(x, stringsAsFactors = FALSE)) + if (ncol(x) == 2) { + return(as.data.frame(x, stringsAsFactors = FALSE)) + } stop("Mapping matrix must have 2 columns (cell_id, patient_id).") } if (is.atomic(x) && !is.null(names(x))) { # Named vector: names = cell ids, values = patient ids - return(data.frame(cell_id = names(x), patient_id = as.character(x), - stringsAsFactors = FALSE)) + return(data.frame( + cell_id = names(x), + patient_id = as.character(x), + stringsAsFactors = FALSE + )) } - stop("Unrecognized mapping format. Upload a table with 'cell_id' and 'patient_id' columns.") + stop( + "Unrecognized mapping format. Upload a table with 'cell_id' and 'patient_id' columns." + ) } # Coerce response input to a patient/response data.frame. # Accepts a data.frame or a named vector (names = patients, values = labels). coerce_response_df <- function(x) { - if (is.data.frame(x)) return(x) + if (is.data.frame(x)) { + return(x) + } if (is.atomic(x) && !is.null(names(x))) { - return(data.frame(patient = names(x), response = as.character(x), - stringsAsFactors = FALSE)) + return(data.frame( + patient = names(x), + response = as.character(x), + stringsAsFactors = FALSE + )) } - stop("Unrecognized response format. Upload a table with 'patient' and 'response' columns.") + stop( + "Unrecognized response format. Upload a table with 'patient' and 'response' columns." + ) } mod_data_ui <- function(id) { @@ -191,20 +263,21 @@ mod_data_ui <- function(id) { # their own data is the main task (DepMap/models are only needed for # training and prediction, so they live in the later "Data Management"). fluidRow( - column(12, - div(class = "section-header", - icon("upload"), - h4("Upload Your Data") - ) + column( + 12, + div(class = "section-header", icon("upload"), h4("Upload Your Data")) ) ), # Demo Data Banner fluidRow( - column(12, - div(class = "demo-banner animate-fade-in-up", + column( + 12, + div( + class = "demo-banner animate-fade-in-up", div(class = "demo-icon", icon("flask")), - div(class = "demo-text", + div( + class = "demo-text", strong("Try it out! "), "Click the button below to load demo data (49 genes × 400 cells, 20 patients) and explore all features without uploading anything." ), @@ -212,117 +285,203 @@ mod_data_ui <- function(id) { # arrives only after a round trip, so the button would flash in a # second late on first load. The server swaps its HTML in place via # the 'set-html' handler when the demo loads / is cleared. - div(id = ns("demo_btn"), - actionButton(ns("load_demo"), "Load Demo Data", - class = "btn-demo btn-sm", icon = icon("play"), - # Instant client-side feedback: disable on click so - # the ~1s Shiny round trip before the waiter overlay - # appears does not look like a dead button. - onclick = "document.getElementById('demo-overlay').style.display='flex'; this.style.opacity='0.6'; var b=this; setTimeout(function(){b.style.opacity='';},2000);")) + div( + id = ns("demo_btn"), + actionButton( + ns("load_demo"), + "Load Demo Data", + class = "btn-demo btn-sm", + icon = icon("play"), + # Instant client-side feedback: disable on click so + # the ~1s Shiny round trip before the waiter overlay + # appears does not look like a dead button. + onclick = "document.getElementById('demo-overlay').style.display='flex'; this.style.opacity='0.6'; var b=this; setTimeout(function(){b.style.opacity='';},2000);" + ) + ) ) ) ), - fluidRow( # Expression Matrix - column(4, - div(class = "card animate-fade-in-up delay-1", - div(class = "card-header", - icon("table"), " Expression Matrix" - ), - div(class = "card-body", - p(class = "text-muted", style = "font-size: 0.82rem;", - "Single-cell expression matrix (genes × cells). Raw counts or normalized values. CSV / TSV / TXT / Excel / RDS format."), - p(style = "font-size: 0.8rem; font-weight: 700; color: var(--text); margin: 0.3rem 0 0.5rem;", - "Header is auto-detected as the first row with ≥2 columns (gene / cell names); single-field title/comment rows above it are skipped. Avoid a multi-column title row above the header."), - div(class = "data-format-hint", - icon("table"), " Format: rows = genes, columns = cells", - tags$pre(class = "data-format-example", - "CELL_001 CELL_002 CELL_003 + column( + 4, + div( + class = "card animate-fade-in-up delay-1", + div(class = "card-header", icon("table"), " Expression Matrix"), + div( + class = "card-body", + p( + class = "text-muted", + style = "font-size: 0.82rem;", + "Single-cell expression matrix (genes × cells). Raw counts or normalized values. CSV / TSV / TXT / Excel / RDS format." + ), + p( + style = "font-size: 0.8rem; font-weight: 700; color: var(--text); margin: 0.3rem 0 0.5rem;", + "Header is auto-detected as the first row with ≥2 columns (gene / cell names); single-field title/comment rows above it are skipped. Avoid a multi-column title row above the header." + ), + div( + class = "data-format-hint", + icon("table"), + " Format: rows = genes, columns = cells", + tags$pre( + class = "data-format-example", + "CELL_001 CELL_002 CELL_003 TP53 2.1 0.0 5.3 BRCA1 0.0 1.8 3.2 -EGFR 4.7 2.1 0.0") +EGFR 4.7 2.1 0.0" + ) + ), + radioButtons( + ns("expr_format"), + "Data format", + choices = c( + "Cell-level — run Seurat clustering to detect clones" = "cell", + "Clone-level — each column is one clone, skip clustering" = "clone" + ), + selected = "cell", + width = "100%" + ), + fileInput( + ns("expr_file"), + "Upload Expression", + accept = c( + ".csv", + ".tsv", + ".txt", + ".xlsx", + ".rds", + ".RDS", + ".gz" + ), + width = "100%" ), - radioButtons(ns("expr_format"), "Data format", - choices = c( - "Cell-level — run Seurat clustering to detect clones" = "cell", - "Clone-level — each column is one clone, skip clustering" = "clone" - ), - selected = "cell", width = "100%"), - fileInput(ns("expr_file"), "Upload Expression", - accept = c(".csv", ".tsv", ".txt", ".xlsx", ".rds", ".RDS", ".gz"), width = "100%"), uiOutput(ns("expr_status")) ) ) ), # Patient-Cell Mapping - column(4, - div(class = "card animate-fade-in-up delay-2", - div(class = "card-header", - icon("users"), " Patient-Cell Mapping" - ), - div(class = "card-body", - p(class = "text-muted", style = "font-size: 0.82rem;", - "File with columns: ", tags$code("cell_id"), " and ", tags$code("patient_id"), - " (case-insensitive). Maps each cell (or clone) to its patient. In Clone-level mode the data is auto-prepared without clustering. CSV / TSV / TXT / Excel / RDS."), - p(style = "font-size: 0.8rem; font-weight: 700; color: var(--text); margin: 0.3rem 0 0.5rem;", - "Header is auto-detected as the first row with ≥2 columns (cell_id / patient_id); single-field title/comment rows above it are skipped."), + column( + 4, + div( + class = "card animate-fade-in-up delay-2", + div(class = "card-header", icon("users"), " Patient-Cell Mapping"), + div( + class = "card-body", + p( + class = "text-muted", + style = "font-size: 0.82rem;", + "File with columns: ", + tags$code("cell_id"), + " and ", + tags$code("patient_id"), + " (case-insensitive). Maps each cell (or clone) to its patient. In Clone-level mode the data is auto-prepared without clustering. CSV / TSV / TXT / Excel / RDS." + ), + p( + style = "font-size: 0.8rem; font-weight: 700; color: var(--text); margin: 0.3rem 0 0.5rem;", + "Header is auto-detected as the first row with ≥2 columns (cell_id / patient_id); single-field title/comment rows above it are skipped." + ), # Cell-level example (default). Clone-level mode swaps to the # count-column example below — the two hints are mutually # exclusive so only the one matching the selected format shows. conditionalPanel( condition = paste0("input['", ns("expr_format"), "'] != 'clone'"), - div(class = "data-format-hint", - icon("users"), " Format: cell_id + patient_id", - tags$pre(class = "data-format-example", - "cell_id patient_id + div( + class = "data-format-hint", + icon("users"), + " Format: cell_id + patient_id", + tags$pre( + class = "data-format-example", + "cell_id patient_id CELL_001 PAT_001 CELL_002 PAT_001 -CELL_003 PAT_002") +CELL_003 PAT_002" + ) ) ), conditionalPanel( condition = paste0("input['", ns("expr_format"), "'] == 'clone'"), - div(class = "data-format-hint", style = "margin-top: 0.4rem;", - icon("users"), " Format: cell_id + patient_id + count", - tags$pre(class = "data-format-example", - "cell_id patient_id count + div( + class = "data-format-hint", + style = "margin-top: 0.4rem;", + icon("users"), + " Format: cell_id + patient_id + count", + tags$pre( + class = "data-format-example", + "cell_id patient_id count CLONE_001 PAT_001 450 CLONE_002 PAT_001 50 -CLONE_003 PAT_002 300"), - tags$small(class = "text-muted", - "count = real cell number per clone; proportions are then shown accurately. Without it, clone proportions fall back to equal (1/n).") +CLONE_003 PAT_002 300" + ), + tags$small( + class = "text-muted", + "count = real cell number per clone; proportions are then shown accurately. Without it, clone proportions fall back to equal (1/n)." + ) ) ), - fileInput(ns("mapping_file"), "Upload Mapping", - accept = c(".csv", ".tsv", ".txt", ".xlsx", ".rds", ".RDS", ".gz"), width = "100%"), + fileInput( + ns("mapping_file"), + "Upload Mapping", + accept = c( + ".csv", + ".tsv", + ".txt", + ".xlsx", + ".rds", + ".RDS", + ".gz" + ), + width = "100%" + ), uiOutput(ns("mapping_status")) ) ) ), # Clinical Response - column(4, - div(class = "card animate-fade-in-up delay-3", - div(class = "card-header", - icon("heartbeat"), " Clinical Response" - ), - div(class = "card-body", - p(class = "text-muted", style = "font-size: 0.82rem;", - "Patient response data for evaluation. File with columns: patient, response (Responder/Non-responder, case-insensitive). CSV / TSV / TXT / Excel / RDS."), - p(style = "font-size: 0.8rem; font-weight: 700; color: var(--text); margin: 0.3rem 0 0.5rem;", - "Header is auto-detected as the first row with ≥2 columns (patient / response); single-field title/comment rows above it are skipped."), - div(class = "data-format-hint", - icon("heartbeat"), " Format: patient + response", - tags$pre(class = "data-format-example", "patient response + column( + 4, + div( + class = "card animate-fade-in-up delay-3", + div(class = "card-header", icon("heartbeat"), " Clinical Response"), + div( + class = "card-body", + p( + class = "text-muted", + style = "font-size: 0.82rem;", + "Patient response data for evaluation. File with columns: patient, response (Responder/Non-responder, case-insensitive). CSV / TSV / TXT / Excel / RDS." + ), + p( + style = "font-size: 0.8rem; font-weight: 700; color: var(--text); margin: 0.3rem 0 0.5rem;", + "Header is auto-detected as the first row with ≥2 columns (patient / response); single-field title/comment rows above it are skipped." + ), + div( + class = "data-format-hint", + icon("heartbeat"), + " Format: patient + response", + tags$pre( + class = "data-format-example", + "patient response PAT_001 Responder PAT_002 Non-responder -PAT_003 Responder") +PAT_003 Responder" + ) + ), + fileInput( + ns("response_file"), + "Upload Response", + accept = c( + ".csv", + ".tsv", + ".txt", + ".xlsx", + ".rds", + ".RDS", + ".gz" + ), + width = "100%" ), - fileInput(ns("response_file"), "Upload Response", - accept = c(".csv", ".tsv", ".txt", ".xlsx", ".rds", ".RDS", ".gz"), width = "100%"), uiOutput(ns("response_status")) ) ) @@ -333,31 +492,47 @@ PAT_003 Responder") # NOTE: deliberately no animate-fade-in-up here — the entrance animation # (opacity/translate fill-mode) intermittently left this card's top half # invisible until a scroll forced a repaint. - fluidRow(style = "margin-top: 1rem;", - column(12, - div(class = "card", - div(class = "card-header", - icon("shapes"), " Clone Detection & Preprocessing" + fluidRow( + style = "margin-top: 1rem;", + column( + 12, + div( + class = "card", + div( + class = "card-header", + icon("shapes"), + " Clone Detection & Preprocessing" ), - div(class = "card-body seurat-body", + div( + class = "card-body seurat-body", # Left: description (always visible) - div(class = "seurat-left", - p(class = "text-muted", style = "font-size: 0.85rem; line-height: 1.5; margin-bottom: 0.6rem;", + div( + class = "seurat-left", + p( + class = "text-muted", + style = "font-size: 0.85rem; line-height: 1.5; margin-bottom: 0.6rem;", "Run Seurat clustering to automatically detect transcriptional subclones, ", "compute clone-level mean expression, rank-normalize the data, and build ", "the clone abundance table required for prediction." ), - p(class = "text-muted", style = "font-size: 0.8rem; line-height: 1.5; margin-bottom: 0;", - strong("Method"), ": UMAP (default) preserves global structure and is faster with large datasets; ", + p( + class = "text-muted", + style = "font-size: 0.8rem; line-height: 1.5; margin-bottom: 0;", + strong("Method"), + ": UMAP (default) preserves global structure and is faster with large datasets; ", "t-SNE emphasizes fine local neighborhoods and may reveal finer substructure at the cost of speed.", br(), - strong("Resolution"), " controls clustering granularity. Higher values produce more clones (finer subclones); ", + strong("Resolution"), + " controls clustering granularity. Higher values produce more clones (finer subclones); ", "lower values produce fewer, broader clones. Default 0.8 suits most datasets.", br(), - strong("PCA Dims"), " sets the number of principal components used for clustering. ", + strong("PCA Dims"), + " sets the number of principal components used for clustering. ", "Higher values capture more biological signal but may include noise. Default 10 is standard for scRNA-seq." ), - div(class = "info-box", style = "margin-top: 0.6rem; margin-bottom: 0; font-size: 0.8rem; padding: 0.5rem 0.7rem;", + div( + class = "info-box", + style = "margin-top: 0.6rem; margin-bottom: 0; font-size: 0.8rem; padding: 0.5rem 0.7rem;", icon("info-circle"), "Requires Expression Matrix and Patient-Cell Mapping loaded first. ", "By default Seurat clusters cells into subclones. ", @@ -367,32 +542,65 @@ PAT_003 Responder") ) ), # Right: clone-level note (vertically centered) + clustering controls - div(class = "seurat-right", - div(id = ns("clone_note"), style = "display: none; flex: 1 1 auto; align-items: center; justify-content: center;", - div(class = "info-box", style = "font-size: 0.8rem; padding: 0.5rem 0.7rem; text-align: left;", + div( + class = "seurat-right", + div( + id = ns("clone_note"), + style = "display: none; flex: 1 1 auto; align-items: center; justify-content: center;", + div( + class = "info-box", + style = "font-size: 0.8rem; padding: 0.5rem 0.7rem; text-align: left;", icon("bolt"), "Clone-level mode: data is prepared automatically after upload — no clustering needed." ) ), - div(id = ns("seurat_controls"), - selectInput(ns("seurat_method"), "Reduction Method", - choices = c("UMAP" = "umap", "t-SNE" = "tsne"), - selected = "umap", width = "100%"), - div(class = "seurat-params", - numericInput(ns("seurat_resolution"), "Resolution", - value = 0.8, min = 0.1, max = 2, step = 0.1, width = "100%"), - numericInput(ns("seurat_dims"), "PCA Dims", - value = 10, min = 2, max = 30, step = 1, width = "100%") + div( + id = ns("seurat_controls"), + selectInput( + ns("seurat_method"), + "Reduction Method", + choices = c("UMAP" = "umap", "t-SNE" = "tsne"), + selected = "umap", + width = "100%" + ), + div( + class = "seurat-params", + numericInput( + ns("seurat_resolution"), + "Resolution", + value = 0.8, + min = 0.1, + max = 2, + step = 0.1, + width = "100%" + ), + numericInput( + ns("seurat_dims"), + "PCA Dims", + value = 10, + min = 2, + max = 30, + step = 1, + width = "100%" + ) ), - actionButton(ns("run_seurat"), "Run Seurat Clustering", - class = "btn-primary seurat-run-btn", - icon = icon("wand-magic-sparkles"), - disabled = "disabled", - title = "Load expression matrix and patient-cell mapping first") + actionButton( + ns("run_seurat"), + "Run Seurat Clustering", + class = "btn-primary seurat-run-btn", + icon = icon("wand-magic-sparkles"), + disabled = "disabled", + title = "Load expression matrix and patient-cell mapping first" + ) ), - tags$script(HTML(paste0(" -Shiny.addCustomMessageHandler('seurat-btn-state-", ns("run_seurat"), "', function(msg) { - var btn = document.getElementById('", ns("run_seurat"), "'); + tags$script(HTML(paste0( + " +Shiny.addCustomMessageHandler('seurat-btn-state-", + ns("run_seurat"), + "', function(msg) { + var btn = document.getElementById('", + ns("run_seurat"), + "'); if (!btn) return; if (msg.enabled) { btn.removeAttribute('disabled'); @@ -402,42 +610,45 @@ Shiny.addCustomMessageHandler('seurat-btn-state-", ns("run_seurat"), "', functio btn.setAttribute('title', 'Load expression matrix and patient-cell mapping first'); } }); -Shiny.addCustomMessageHandler('expr-format-state-", ns("expr_format"), "', function(cloneMode) { - var ctl = document.getElementById('", ns("seurat_controls"), "'); - var note = document.getElementById('", ns("clone_note"), "'); +Shiny.addCustomMessageHandler('expr-format-state-", + ns("expr_format"), + "', function(cloneMode) { + var ctl = document.getElementById('", + ns("seurat_controls"), + "'); + var note = document.getElementById('", + ns("clone_note"), + "'); if (ctl) ctl.style.display = cloneMode ? 'none' : ''; if (note) note.style.display = cloneMode ? 'flex' : 'none'; }); -"))) +" + ))) ) ), - div(class = "seurat-status-bar", - uiOutput(ns("seurat_status")) - ) + div(class = "seurat-status-bar", uiOutput(ns("seurat_status"))) ) ) ), # --- Data Preview --- - fluidRow(style = "margin-top: 1.5rem;", - column(12, - div(class = "section-header", - icon("eye"), - h4("Data Preview") - ) - ) + fluidRow( + style = "margin-top: 1.5rem;", + column(12, div(class = "section-header", icon("eye"), h4("Data Preview"))) ), # Data Overview & Preview (merged). The card is ALWAYS visible so users # see which preview tabs exist; each tab shows a placeholder until its # data is loaded (instead of a blank table after the demo is cleared). - fluidRow(style = "margin-top: 1.5rem;", - column(12, - div(class = "card animate-fade-in", - div(class = "card-header", - icon("eye"), " Data Overview & Preview" - ), - div(class = "card-body", + fluidRow( + style = "margin-top: 1.5rem;", + column( + 12, + div( + class = "card animate-fade-in", + div(class = "card-header", icon("eye"), " Data Overview & Preview"), + div( + class = "card-body", # Status badges at top uiOutput(ns("status_overview")), hr(), @@ -453,106 +664,182 @@ Shiny.addCustomMessageHandler('expr-format-state-", ns("expr_format"), "', funct ), # --- Data Management (DepMap / pre-trained models) --- - fluidRow(style = "margin-top: 1.5rem;", - column(12, - div(class = "section-header", - icon("database"), - h4("Data Management") - ) + fluidRow( + style = "margin-top: 1.5rem;", + column( + 12, + div(class = "section-header", icon("database"), h4("Data Management")) ) ), - fluidRow(class = "data-management-row", + fluidRow( + class = "data-management-row", # DepMap Data - column(6, - div(class = "card animate-fade-in-up delay-1", - div(class = "card-header", - icon("database"), " DepMap Data" - ), - div(class = "card-body", - p(class = "text-muted", style = "font-size: 0.86rem;", - "Load DepMap reference datasets including bulk expression, single-cell expression, drug response (AUC), and cell line annotations. This is a filtered version derived from the original DepMap release used in the PERCEPTION article, with unused tables and objects removed for efficiency."), - tags$small(class = "text-muted", style = "display: block; margin-top: 0.3rem;", + column( + 6, + div( + class = "card animate-fade-in-up delay-1", + div(class = "card-header", icon("database"), " DepMap Data"), + div( + class = "card-body", + p( + class = "text-muted", + style = "font-size: 0.86rem;", + "Load DepMap reference datasets including bulk expression, single-cell expression, drug response (AUC), and cell line annotations. This is a filtered version derived from the original DepMap release used in the PERCEPTION article, with unused tables and objects removed for efficiency." + ), + tags$small( + class = "text-muted", + style = "display: block; margin-top: 0.3rem;", "To download manually, visit ", - tags$a(href = "https://github.com/WangLabCSU/PERCEPTIONx/releases/tag/depmap", - target = "_blank", "GitHub Release", style = "color: var(--primary); text-decoration: underline;"), + tags$a( + href = "https://github.com/WangLabCSU/PERCEPTIONx/releases/tag/depmap", + target = "_blank", + "GitHub Release", + style = "color: var(--primary); text-decoration: underline;" + ), "." ), hr(), - div(class = "inline-form-row", style = "display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;", - actionButton(ns("load_depmap"), "Download & Load", - class = "btn-primary btn-sm", icon = icon("download")), + div( + class = "inline-form-row", + style = "display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;", + actionButton( + ns("load_depmap"), + "Download & Load", + class = "btn-primary btn-sm", + icon = icon("download") + ), checkboxInput(ns("depmap_mirror"), "Use mirror", value = TRUE) ), - div(style = "margin-top: 0.6rem; border-top: 1px dashed var(--border); padding-top: 0.6rem;", - tags$small(class = "text-muted", "Or load a pre-downloaded DepMap.RDS:"), - div(style = "display: flex; gap: 0.5rem; align-items: center; margin-top: 0.3rem;", - fileInput(ns("depmap_file"), NULL, accept = c(".RDS", ".rds"), width = "100%", - placeholder = "Select a .RDS file - loads automatically") + div( + style = "margin-top: 0.6rem; border-top: 1px dashed var(--border); padding-top: 0.6rem;", + tags$small( + class = "text-muted", + "Or load a pre-downloaded DepMap.RDS:" + ), + div( + style = "display: flex; gap: 0.5rem; align-items: center; margin-top: 0.3rem;", + fileInput( + ns("depmap_file"), + NULL, + accept = c(".RDS", ".rds"), + width = "100%", + placeholder = "Select a .RDS file - loads automatically" + ) ) ), - div(style = "margin-top: 0.75rem;", - uiOutput(ns("depmap_status")) - ) + div(style = "margin-top: 0.75rem;", uiOutput(ns("depmap_status"))) ) ) ), # Pre-trained Models - column(6, - div(class = "card animate-fade-in-up delay-2", - div(class = "card-header", - icon("cube"), " Pre-trained Models" - ), - div(class = "card-body", - p(class = "text-muted", style = "font-size: 0.86rem;", - "Load pre-trained drug response models from the PERCEPTIONx GitHub Release repository. 44 models are available, each trained on DepMap bulk expression with Elastic Net regression and 3-fold cross-validation. Models are cached locally after first download."), - tags$small(class = "text-muted", style = "display: block; margin-top: 0.3rem;", + column( + 6, + div( + class = "card animate-fade-in-up delay-2", + div(class = "card-header", icon("cube"), " Pre-trained Models"), + div( + class = "card-body", + p( + class = "text-muted", + style = "font-size: 0.86rem;", + "Load pre-trained drug response models from the PERCEPTIONx GitHub Release repository. 44 models are available, each trained on DepMap bulk expression with Elastic Net regression and 3-fold cross-validation. Models are cached locally after first download." + ), + tags$small( + class = "text-muted", + style = "display: block; margin-top: 0.3rem;", "To download manually, visit ", - tags$a(href = "https://github.com/WangLabCSU/PERCEPTIONx/releases/tag/models-v1", - target = "_blank", "GitHub Release", style = "color: var(--primary); text-decoration: underline;"), + tags$a( + href = "https://github.com/WangLabCSU/PERCEPTIONx/releases/tag/models-v1", + target = "_blank", + "GitHub Release", + style = "color: var(--primary); text-decoration: underline;" + ), "." ), hr(), - div(class = "inline-form-row", style = "display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;", - tags$label(class = "control-label", style = "margin:0; font-size:0.88rem; font-weight:600; white-space:nowrap; line-height:38px;", "Drug"), - selectizeInput(ns("model_name"), label = NULL, width = "300px", - choices = PERCEPTIONx:::perception_all_drugs, - selected = "abemaciclib", - multiple = TRUE, - options = list(placeholder = "Select one or more drugs...", maxOptions = 50, - plugins = list("remove_button"))), - actionButton(ns("load_model"), "Download & Load", - class = "btn-primary", icon = icon("download")), + div( + class = "inline-form-row", + style = "display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;", + tags$label( + class = "control-label", + style = "margin:0; font-size:0.88rem; font-weight:600; white-space:nowrap; line-height:38px;", + "Drug" + ), + selectizeInput( + ns("model_name"), + label = NULL, + width = "300px", + choices = PERCEPTIONx:::perception_all_drugs, + selected = "abemaciclib", + multiple = TRUE, + options = list( + placeholder = "Select one or more drugs...", + maxOptions = 50, + plugins = list("remove_button") + ) + ), + actionButton( + ns("load_model"), + "Download & Load", + class = "btn-primary", + icon = icon("download") + ), checkboxInput(ns("model_mirror"), "Use mirror", value = TRUE) ), - div(style = "margin-top: 0.6rem; border-top: 1px dashed var(--border); padding-top: 0.6rem;", - tags$small(class = "text-muted", "Or load a pre-downloaded model .RDS:"), - div(style = "display: flex; gap: 0.5rem; align-items: center; margin-top: 0.3rem;", - fileInput(ns("model_file"), NULL, accept = c(".RDS", ".rds"), width = "100%", multiple = TRUE, - placeholder = "Select one or more .RDS files - loads automatically, each appears in Loaded Models Management") + div( + style = "margin-top: 0.6rem; border-top: 1px dashed var(--border); padding-top: 0.6rem;", + tags$small( + class = "text-muted", + "Or load a pre-downloaded model .RDS:" + ), + div( + style = "display: flex; gap: 0.5rem; align-items: center; margin-top: 0.3rem;", + fileInput( + ns("model_file"), + NULL, + accept = c(".RDS", ".rds"), + width = "100%", + multiple = TRUE, + placeholder = "Select one or more .RDS files - loads automatically, each appears in Loaded Models Management" + ) ) ), - div(style = "margin-top: 0.75rem;", - uiOutput(ns("model_status")) - ) + div(style = "margin-top: 0.75rem;", uiOutput(ns("model_status"))) ) ) ) ), # --- Loaded Models Management --- - fluidRow(style = "margin-top: 1.5rem;", - column(12, - div(class = "card animate-fade-in-up", - div(class = "card-header", - icon("boxes-stacked"), " Loaded Models Management", - tags$span(style = "margin-left: auto; font-size: 0.78rem; color: var(--text-muted);", - span(class = "status-dot green", style = "display: inline-block; vertical-align: middle; margin-right: 0.2rem;"), "Active ", - span(class = "status-dot gray", style = "display: inline-block; vertical-align: middle; margin-right: 0.2rem;"), "Inactive" + fluidRow( + style = "margin-top: 1.5rem;", + column( + 12, + div( + class = "card animate-fade-in-up", + div( + class = "card-header", + icon("boxes-stacked"), + " Loaded Models Management", + tags$span( + style = "margin-left: auto; font-size: 0.78rem; color: var(--text-muted);", + span( + class = "status-dot green", + style = "display: inline-block; vertical-align: middle; margin-right: 0.2rem;" + ), + "Active ", + span( + class = "status-dot gray", + style = "display: inline-block; vertical-align: middle; margin-right: 0.2rem;" + ), + "Inactive" ) ), - div(class = "card-body", style = "padding: 0.8rem 1.2rem !important;", + div( + class = "card-body", + style = "padding: 0.8rem 1.2rem !important;", uiOutput(ns("models_management")) ) ) @@ -588,65 +875,109 @@ mod_data_server <- function(id, shared) { # the user switches to their own data. observe({ html <- if (isTRUE(shared$demo_loaded)) { - as.character(actionButton(ns("load_demo"), "Clear Demo Data", - class = "btn-accent btn-sm", icon = icon("trash"), - onclick = "document.getElementById('demo-overlay').style.display='flex'; this.style.opacity='0.6'; var b=this; setTimeout(function(){b.style.opacity='';},2000);")) + as.character(actionButton( + ns("load_demo"), + "Clear Demo Data", + class = "btn-accent btn-sm", + icon = icon("trash"), + onclick = "document.getElementById('demo-overlay').style.display='flex'; this.style.opacity='0.6'; var b=this; setTimeout(function(){b.style.opacity='';},2000);" + )) } else { - as.character(actionButton(ns("load_demo"), "Load Demo Data", - class = "btn-demo btn-sm", icon = icon("play"), - onclick = "document.getElementById('demo-overlay').style.display='flex'; this.style.opacity='0.6'; var b=this; setTimeout(function(){b.style.opacity='';},2000);")) + as.character(actionButton( + ns("load_demo"), + "Load Demo Data", + class = "btn-demo btn-sm", + icon = icon("play"), + onclick = "document.getElementById('demo-overlay').style.display='flex'; this.style.opacity='0.6'; var b=this; setTimeout(function(){b.style.opacity='';},2000);" + )) } - session$sendCustomMessage("set-html", list(id = ns("demo_btn"), html = html)) + session$sendCustomMessage( + "set-html", + list(id = ns("demo_btn"), html = html) + ) }) # Auto-prepare in clone-level mode (skip clustering) --- # Runs whenever expression + mapping are both available and the user has # selected "Clone-level" in the Expression Matrix card. No button needed. auto_prepare_if_clone <- function() { - if (!identical(input$expr_format, "clone")) return(invisible(NULL)) - if (is.null(shared$user_expr) || is.null(shared$user_mapping)) return(invisible(NULL)) - if (prep_busy()) return(invisible(NULL)) # a prepare task is already running + if (!identical(input$expr_format, "clone")) { + return(invisible(NULL)) + } + if (is.null(shared$user_expr) || is.null(shared$user_mapping)) { + return(invisible(NULL)) + } + if (prep_busy()) { + return(invisible(NULL)) + } # a prepare task is already running prep_busy(TRUE) w <- Waiter$new( html = tagList( div(class = "spinner-ring"), h4("Preparing clone-level data..."), - p(class = "text-muted", "Mapping cells to patients and rank-normalizing") + p( + class = "text-muted", + "Mapping cells to patients and rank-normalizing" + ) ), color = "rgba(255,255,255,0.85)" ) w$show() jobid <- tryCatch( - submit_session_task(shared, "prepare", list( - expression_matrix = shared$user_expr, - patient_mapping = shared$user_mapping, - skip_clustering = TRUE - )), + submit_session_task( + shared, + "prepare", + list( + expression_matrix = shared$user_expr, + patient_mapping = shared$user_mapping, + skip_clustering = TRUE + ) + ), error = function(e) { prep_busy(FALSE) w$hide() - showNotification(paste("Failed to start the background task:", e$message), - type = "error", duration = 12) + showNotification( + paste("Failed to start the background task:", e$message), + type = "error", + duration = 12 + ) NULL } ) - if (is.null(jobid)) return(invisible(NULL)) - poll_task(shared, session, jobid, + if (is.null(jobid)) { + return(invisible(NULL)) + } + poll_task( + shared, + session, + jobid, on_done = function(prepared) { prep_busy(FALSE) w$hide() shared$prepared_data <- prepared shared$user_clones <- prepared$cell_clone_map - showNotification(paste0("Data ready (clone-level): ", - ncol(prepared$clone_expression_rnorm), - " clones across ", nrow(prepared$clone_counts), " patients"), - type = "message", duration = 5) + showNotification( + paste0( + "Data ready (clone-level): ", + ncol(prepared$clone_expression_rnorm), + " clones across ", + nrow(prepared$clone_counts), + " patients" + ), + type = "message", + duration = 5 + ) }, on_error = function(msg) { prep_busy(FALSE) w$hide() - showNotification(paste("Auto-prepare error:", msg), type = "error", duration = 10) - }) + showNotification( + paste("Auto-prepare error:", msg), + type = "error", + duration = 10 + ) + } + ) } # --- Enable/disable Run Seurat button based on required data (#10) --- @@ -666,33 +997,46 @@ mod_data_server <- function(id, shared) { if (isTRUE(shared$demo_busy)) { # Overlay was shown by onclick — hide it again since nothing new starts. session$sendCustomMessage("hide-demo-overlay", list()) - showNotification("Demo data is already being prepared...", type = "warning", duration = 5) + showNotification( + "Demo data is already being prepared...", + type = "warning", + duration = 5 + ) return() } shared$demo_busy <- TRUE # Toggle: once the demo is loaded, the button becomes "Clear Demo Data". if (isTRUE(shared$demo_loaded)) { shared$user_response <- NULL - shared$user_mapping <- NULL - shared$user_expr <- NULL + shared$user_mapping <- NULL + shared$user_expr <- NULL shared$prepared_data <- NULL - shared$user_clones <- NULL - shared$predictions <- NULL - shared$patient_pred <- NULL - shared$models <- NULL - shared$model_cache <- list() - shared$model_active <- list() + shared$user_clones <- NULL + shared$predictions <- NULL + shared$patient_pred <- NULL + shared$models <- NULL + shared$model_cache <- list() + shared$model_active <- list() shared$demo_loaded <- FALSE shared$demo_busy <- FALSE session$sendCustomMessage("hide-demo-overlay", list()) - showNotification("Demo data cleared. Upload your own data or load the demo again.", - type = "message", duration = 5) + showNotification( + "Demo data cleared. Upload your own data or load the demo again.", + type = "message", + duration = 5 + ) return() } # Shared demo pipeline (also used by the Home "Load Demo" button). - run_demo_pipeline(shared, session, - on_success = function() { shared$demo_loaded <- TRUE; shared$demo_busy <- FALSE }, - on_error = function() shared$demo_busy <- FALSE) + run_demo_pipeline( + shared, + session, + on_success = function() { + shared$demo_loaded <- TRUE + shared$demo_busy <- FALSE + }, + on_error = function() shared$demo_busy <- FALSE + ) }) # --- Load DepMap (download) --- @@ -702,7 +1046,11 @@ mod_data_server <- function(id, shared) { # styled like the training overlay (mod_train.R). observeEvent(input$load_depmap, { if (!is.null(download_progress())) { - showNotification("A DepMap download is already in progress.", type = "warning", duration = 5) + showNotification( + "A DepMap download is already in progress.", + type = "warning", + duration = 5 + ) return() } use_mirror <- isTRUE(input$depmap_mirror) @@ -729,8 +1077,11 @@ mod_data_server <- function(id, shared) { # A partial file from an interrupted download must never be treated as a # cache hit (it would fail at readRDS). Only files that reach the full # release size count as a valid cache. - if (file.exists(destfile) && - is.finite(file.size(destfile)) && file.size(destfile) >= depmap_release_size) { + if ( + file.exists(destfile) && + is.finite(file.size(destfile)) && + file.size(destfile) >= depmap_release_size + ) { meta_cache <- file.path(cache_dir, "DepMap_meta.RDS") meta <- read_cached_meta(destfile, meta_cache) if (!is.null(meta)) { @@ -754,14 +1105,26 @@ mod_data_server <- function(id, shared) { ) ew$show() jobid <- tryCatch( - submit_session_task(shared, "extract_meta", list( - depmap_path = destfile, - cache_file = meta_cache - )), - error = function(e) { ew$hide(); NULL } + submit_session_task( + shared, + "extract_meta", + list( + depmap_path = destfile, + cache_file = meta_cache + ) + ), + error = function(e) { + ew$hide() + NULL + } ) - if (is.null(jobid)) return() - poll_task(shared, session, jobid, + if (is.null(jobid)) { + return() + } + poll_task( + shared, + session, + jobid, on_done = function(meta) { shared$depmap_meta <- meta shared$depmap_path <- destfile @@ -772,10 +1135,18 @@ mod_data_server <- function(id, shared) { }, on_error = function(msg) { ew$hide() - showNotification(paste("Error:", msg), type = "error", duration = 10) - showNotification("Tip: Try enabling 'Use mirror' or download DepMap.RDS manually and use the 'Load' button below.", - type = "warning", duration = 15) - }) + showNotification( + paste("Error:", msg), + type = "error", + duration = 10 + ) + showNotification( + "Tip: Try enabling 'Use mirror' or download DepMap.RDS manually and use the 'Load' button below.", + type = "warning", + duration = 15 + ) + } + ) return() } @@ -786,13 +1157,21 @@ mod_data_server <- function(id, shared) { div(class = "spinner-ring"), h4("Downloading DepMap data..."), p(id = ns("dwn_stage"), class = "text-muted", "Starting download..."), - p(id = ns("dwn_detail"), class = "text-muted", + p( + id = ns("dwn_detail"), + class = "text-muted", style = "font-size: 0.82rem; opacity: 0.75;", - if (use_mirror) "567 MB via mirror (mirrors tried in order)" - else "567 MB from GitHub"), + if (use_mirror) { + "567 MB via mirror (mirrors tried in order)" + } else { + "567 MB from GitHub" + } + ), # The id sits on the TRACK (see mod_train.R note): set-html replaces # the bar inside it with a fresh .train-progress-bar. - div(id = ns("dwn_bar"), class = "train-progress-track", + div( + id = ns("dwn_bar"), + class = "train-progress-track", div(class = "train-progress-bar", style = "width: 2%;") ) ), @@ -800,26 +1179,49 @@ mod_data_server <- function(id, shared) { ) w$show() - base_urls <- if (use_mirror) PERCEPTIONx::get_mirrors() else "https://github.com" - urls <- paste0(base_urls, "/WangLabCSU/PERCEPTIONx/releases/download/depmap/DepMap.RDS") + base_urls <- if (use_mirror) { + PERCEPTIONx::get_mirrors() + } else { + "https://github.com" + } + urls <- paste0( + base_urls, + "/WangLabCSU/PERCEPTIONx/releases/download/depmap/DepMap.RDS" + ) jobid <- tryCatch( - submit_session_task(shared, "download", list( - urls = urls, - destfile = destfile, - timeout_seconds = 600, - retries = 2 - )), - error = function(e) { w$hide(); NULL } + submit_session_task( + shared, + "download", + list( + urls = urls, + destfile = destfile, + timeout_seconds = 600, + retries = 2 + ) + ), + error = function(e) { + w$hide() + NULL + } ) - if (is.null(jobid)) return() + if (is.null(jobid)) { + return() + } # Expected size of the official DepMap.RDS release asset (bytes) — used # only as the progress-bar denominator. The real file is validated by # the parsing step below, so a wrong estimate can never corrupt data. - download_progress(list(jobid = jobid, destfile = destfile, expected = depmap_release_size)) + download_progress(list( + jobid = jobid, + destfile = destfile, + expected = depmap_release_size + )) - poll_task(shared, session, jobid, + poll_task( + shared, + session, + jobid, on_done = function(path) { download_progress(NULL) # Download hit 100%: close the download overlay, then immediately @@ -831,24 +1233,43 @@ mod_data_server <- function(id, shared) { html = tagList( div(class = "spinner-ring"), h4("Parsing DepMap data..."), - p(class = "text-muted", "Reading the file and extracting metadata (a few seconds)") + p( + class = "text-muted", + "Reading the file and extracting metadata (a few seconds)" + ) ), color = "rgba(255,255,255,0.85)" ) pw$show() jobid2 <- tryCatch( - submit_session_task(shared, "extract_meta", list( - depmap_path = path, - cache_file = file.path(cache_dir, "DepMap_meta.RDS") - )), - error = function(e) { pw$hide(); e } + submit_session_task( + shared, + "extract_meta", + list( + depmap_path = path, + cache_file = file.path(cache_dir, "DepMap_meta.RDS") + ) + ), + error = function(e) { + pw$hide() + e + } ) if (inherits(jobid2, "error")) { - showNotification(paste("Download finished but parsing failed to start:", conditionMessage(jobid2)), - type = "error", duration = 10) + showNotification( + paste( + "Download finished but parsing failed to start:", + conditionMessage(jobid2) + ), + type = "error", + duration = 10 + ) return() } - poll_task(shared, session, jobid2, + poll_task( + shared, + session, + jobid2, on_done = function(meta) { shared$depmap_meta <- meta shared$depmap_path <- path @@ -856,7 +1277,10 @@ mod_data_server <- function(id, shared) { shared$depmap_is_standard <- TRUE notify_master_depmap(path) pw$hide() - showNotification("DepMap data loaded successfully", type = "message") + showNotification( + "DepMap data loaded successfully", + type = "message" + ) }, on_error = function(msg) { pw$hide() @@ -864,9 +1288,15 @@ mod_data_server <- function(id, shared) { # otherwise poison EVERY later session. Detect and delete it so # the next click re-downloads a clean copy. Memory errors must # NOT delete anything — the file may be fine. - corrupt <- grepl(paste0("error reading from connection|unknown input format|", - "cannot open the connection|not a list|", - "missing required components"), msg, ignore.case = TRUE) + corrupt <- grepl( + paste0( + "error reading from connection|unknown input format|", + "cannot open the connection|not a list|", + "missing required components" + ), + msg, + ignore.case = TRUE + ) if (corrupt) { # Distinguish an INCOMPLETE download (file smaller than the # release asset — safe to delete, the next click re-downloads) @@ -875,51 +1305,97 @@ mod_data_server <- function(id, shared) { # Deleting the full-size file would force a pointless 567 MB # re-download that fails the same way. full_size <- file.exists(destfile) && - is.finite(file.size(destfile)) && file.size(destfile) >= depmap_release_size + is.finite(file.size(destfile)) && + file.size(destfile) >= depmap_release_size if (full_size) { - showNotification(paste0("DepMap.RDS is complete but could not be read: ", msg, - ". This is usually insufficient RAM (reading the file needs ~2-4x its size). ", - "The file was kept — close other applications and try again."), - type = "error", duration = 12) + showNotification( + paste0( + "DepMap.RDS is complete but could not be read: ", + msg, + ". This is usually insufficient RAM (reading the file needs ~2-4x its size). ", + "The file was kept — close other applications and try again." + ), + type = "error", + duration = 12 + ) } else { unlink(destfile) unlink(file.path(cache_dir, "DepMap_meta.RDS")) - showNotification("Downloaded DepMap.RDS is incomplete/corrupt (interrupted download?) — it was deleted. Please click 'Download & Load' again.", - type = "error", duration = 10) + showNotification( + "Downloaded DepMap.RDS is incomplete/corrupt (interrupted download?) — it was deleted. Please click 'Download & Load' again.", + type = "error", + duration = 10 + ) } } else { - showNotification(paste("Error:", msg), type = "error", duration = 10) + showNotification( + paste("Error:", msg), + type = "error", + duration = 10 + ) } - showNotification("Tip: Try enabling 'Use mirror' or download DepMap.RDS manually and use the 'Load' button below.", - type = "warning", duration = 15) - }) + showNotification( + "Tip: Try enabling 'Use mirror' or download DepMap.RDS manually and use the 'Load' button below.", + type = "warning", + duration = 15 + ) + } + ) }, on_error = function(msg) { download_progress(NULL) w$hide() - showNotification(paste("Download failed:", msg), type = "error", duration = 10) - showNotification("Tip: Try enabling 'Use mirror' or download DepMap.RDS manually and use the 'Load' button below.", - type = "warning", duration = 15) - }) + showNotification( + paste("Download failed:", msg), + type = "error", + duration = 10 + ) + showNotification( + "Tip: Try enabling 'Use mirror' or download DepMap.RDS manually and use the 'Load' button below.", + type = "warning", + duration = 15 + ) + } + ) }) # Drive the download progress bar: poll the growing file once per second. # Stops as soon as the job finishes (download_progress -> NULL). observe({ st <- download_progress() - if (is.null(st)) return() + if (is.null(st)) { + return() + } tw <- shared$task_worker - if (!is.null(tw) && !tw$is_alive()) { download_progress(NULL); return() } + if (!is.null(tw) && !tw$is_alive()) { + download_progress(NULL) + return() + } invalidateLater(1000) size <- if (file.exists(st$destfile)) file.size(st$destfile) else 0 expected <- max(1, st$expected) pct <- round(100 * pmin(1, size / expected)) - stage <- sprintf("Downloaded %.0f MB of %.0f MB (%d%%)", - size / 1024^2, expected / 1024^2, pct) - session$sendCustomMessage("set-html", list(id = ns("dwn_stage"), html = stage)) - session$sendCustomMessage("set-html", - list(id = ns("dwn_bar"), - html = paste0("
"))) + stage <- sprintf( + "Downloaded %.0f MB of %.0f MB (%d%%)", + size / 1024^2, + expected / 1024^2, + pct + ) + session$sendCustomMessage( + "set-html", + list(id = ns("dwn_stage"), html = stage) + ) + session$sendCustomMessage( + "set-html", + list( + id = ns("dwn_bar"), + html = paste0( + "
" + ) + ) + ) }) # --- Load DepMap (local file) --- @@ -933,9 +1409,13 @@ mod_data_server <- function(id, shared) { fsize_mb <- file.size(file$datapath) / 1024^2 if (is.finite(fsize_mb) && fsize_mb > 700) { showNotification( - sprintf("Large file (%.0f MB). Loading needs roughly 2-4x that in free RAM. Close other applications first, or use the built-in 567 MB 'Download & Load' above.", - fsize_mb), - type = "warning", duration = 12) + sprintf( + "Large file (%.0f MB). Loading needs roughly 2-4x that in free RAM. Close other applications first, or use the built-in 567 MB 'Download & Load' above.", + fsize_mb + ), + type = "warning", + duration = 12 + ) } w <- Waiter$new( @@ -948,19 +1428,31 @@ mod_data_server <- function(id, shared) { ) w$show() jobid <- tryCatch( - submit_session_task(shared, "extract_meta", list( - depmap_path = file$datapath, - cache_file = NULL - )), + submit_session_task( + shared, + "extract_meta", + list( + depmap_path = file$datapath, + cache_file = NULL + ) + ), error = function(e) { w$hide() - showNotification(paste("Failed to start the background task:", e$message), - type = "error", duration = 12) + showNotification( + paste("Failed to start the background task:", e$message), + type = "error", + duration = 12 + ) NULL } ) - if (is.null(jobid)) return() - poll_task(shared, session, jobid, + if (is.null(jobid)) { + return() + } + poll_task( + shared, + session, + jobid, on_done = function(meta) { # Record the source file so the background training worker (callr) # can load the identical DepMap from disk in its own process. @@ -970,33 +1462,66 @@ mod_data_server <- function(id, shared) { # never the shared pool (a wrong upload must not affect others). shared$depmap_is_standard <- FALSE w$hide() - showNotification(paste("DepMap loaded from file:", - length(meta$components), "datasets"), - type = "message") + showNotification( + paste( + "DepMap loaded from file:", + length(meta$components), + "datasets" + ), + type = "message" + ) }, on_error = function(msg) { w$hide() - if (grepl("cannot allocate|failed to allocate|Error in readRDS", - msg, ignore.case = TRUE)) { - showNotification("Failed to read the file (possible out of memory in the worker).", - type = "error", duration = 15) - showNotification("Tips: close other applications; re-save the RDS containing only the components PERCEPTIONx needs; or use the built-in 567 MB 'Download & Load' instead.", - type = "warning", duration = 20) + if ( + grepl( + "cannot allocate|failed to allocate|Error in readRDS", + msg, + ignore.case = TRUE + ) + ) { + showNotification( + "Failed to read the file (possible out of memory in the worker).", + type = "error", + duration = 15 + ) + showNotification( + "Tips: close other applications; re-save the RDS containing only the components PERCEPTIONx needs; or use the built-in 567 MB 'Download & Load' instead.", + type = "warning", + duration = 20 + ) } else { - showNotification(paste("Error reading file:", msg), type = "error", duration = 10) + showNotification( + paste("Error reading file:", msg), + type = "error", + duration = 10 + ) } - }) + } + ) }) output$depmap_status <- renderUI({ if (is.null(shared$depmap_meta)) { - tagList(span(class = "status-badge unloaded", span(class = "status-dot gray"), "Not loaded")) + tagList(span( + class = "status-badge unloaded", + span(class = "status-dot gray"), + "Not loaded" + )) } else { n_datasets <- length(shared$depmap_meta$components) tagList( - span(class = "status-badge loaded", span(class = "status-dot green"), "Loaded"), - br(), br(), - tags$small(class = "text-muted", paste(n_datasets, "datasets available")) + span( + class = "status-badge loaded", + span(class = "status-dot green"), + "Loaded" + ), + br(), + br(), + tags$small( + class = "text-muted", + paste(n_datasets, "datasets available") + ) ) } }) @@ -1006,7 +1531,9 @@ mod_data_server <- function(id, shared) { req(input$model_name) drug_list <- trimws(input$model_name) drug_list <- drug_list[nzchar(drug_list)] - if (length(drug_list) == 0) return() + if (length(drug_list) == 0) { + return() + } use_mirror <- isTRUE(input$model_mirror) w <- Waiter$new( html = tagList( @@ -1017,42 +1544,77 @@ mod_data_server <- function(id, shared) { color = "rgba(255,255,255,0.85)" ) w$show() - tryCatch({ - if (is.null(shared$models)) shared$models <- list() - # Pre-trained models live in a persistent cache dir when - # options(PERCEPTIONx.cache_root) is set; otherwise tempdir() keeps the - # historical behaviour. load_model() skips drugs already on disk, so a - # cached model is not downloaded again on the next app session. - model_dir <- PERCEPTIONx:::perception_model_dir() - if (is.null(model_dir)) model_dir <- tempdir() - loaded_count <- 0 - failed_drugs <- c() - for (drug in drug_list) { - tryCatch({ - new_model <- PERCEPTIONx::load_model(drug, dest = model_dir, read = TRUE, mirror = use_mirror, - timeout_seconds = 120, retries = 2) - shared$models[[drug]] <- new_model[[drug]] - shared$model_cache[[drug]] <- new_model[[drug]] - shared$model_active[[drug]] <- TRUE - loaded_count <- loaded_count + 1 - }, error = function(e) { - failed_drugs <<- c(failed_drugs, paste0(drug, " (", conditionMessage(e), ")")) - }) - } - w$hide() - if (loaded_count > 0) { - showNotification(sprintf("Loaded %d model(s): %s", loaded_count, - paste(drug_list[1:min(loaded_count, length(drug_list))], collapse = ", ")), - type = "message", duration = 5) - } - if (length(failed_drugs) > 0) { - showNotification(paste("Failed to load:", paste(failed_drugs, collapse = "; ")), - type = "error", duration = 10) + tryCatch( + { + if (is.null(shared$models)) { + shared$models <- list() + } + # Pre-trained models live in a persistent cache dir when + # options(PERCEPTIONx.cache_root) is set; otherwise tempdir() keeps the + # historical behaviour. load_model() skips drugs already on disk, so a + # cached model is not downloaded again on the next app session. + model_dir <- PERCEPTIONx:::perception_model_dir() + if (is.null(model_dir)) { + model_dir <- tempdir() + } + loaded_count <- 0 + failed_drugs <- c() + for (drug in drug_list) { + tryCatch( + { + new_model <- PERCEPTIONx::load_model( + drug, + dest = model_dir, + read = TRUE, + mirror = use_mirror, + timeout_seconds = 120, + retries = 2 + ) + shared$models[[drug]] <- new_model[[drug]] + shared$model_cache[[drug]] <- new_model[[drug]] + shared$model_active[[drug]] <- TRUE + loaded_count <- loaded_count + 1 + }, + error = function(e) { + failed_drugs <<- c( + failed_drugs, + paste0(drug, " (", conditionMessage(e), ")") + ) + } + ) + } + w$hide() + if (loaded_count > 0) { + showNotification( + sprintf( + "Loaded %d model(s): %s", + loaded_count, + paste( + drug_list[1:min(loaded_count, length(drug_list))], + collapse = ", " + ) + ), + type = "message", + duration = 5 + ) + } + if (length(failed_drugs) > 0) { + showNotification( + paste("Failed to load:", paste(failed_drugs, collapse = "; ")), + type = "error", + duration = 10 + ) + } + }, + error = function(e) { + w$hide() + showNotification( + paste("Error:", e$message), + type = "error", + duration = 10 + ) } - }, error = function(e) { - w$hide() - showNotification(paste("Error:", e$message), type = "error", duration = 10) - }) + ) }) # --- Load Model (local file) - one or more, each lands in the cache and @@ -1072,41 +1634,71 @@ mod_data_server <- function(id, shared) { ok_names <- character(0) errs <- character(0) for (k in seq_len(nrow(files))) { - tryCatch({ - model_obj <- readRDS(files$datapath[k]) - drug_name <- tools::file_path_sans_ext(basename(files$name[k])) - attr_drug <- attr(model_obj, "drug_name") - if (!is.null(attr_drug) && nzchar(attr_drug)) drug_name <- attr_drug - if (is.null(shared$models)) shared$models <- list() - if (is.null(shared$model_cache)) shared$model_cache <- list() - shared$models[[drug_name]] <- model_obj - shared$model_cache[[drug_name]] <- model_obj - shared$model_active[[drug_name]] <- TRUE - ok_names <- c(ok_names, drug_name) - }, error = function(e) { - errs <<- c(errs, paste0(basename(files$name[k]), ": ", conditionMessage(e))) - }) + tryCatch( + { + model_obj <- readRDS(files$datapath[k]) + drug_name <- tools::file_path_sans_ext(basename(files$name[k])) + attr_drug <- attr(model_obj, "drug_name") + if (!is.null(attr_drug) && nzchar(attr_drug)) { + drug_name <- attr_drug + } + if (is.null(shared$models)) { + shared$models <- list() + } + if (is.null(shared$model_cache)) { + shared$model_cache <- list() + } + shared$models[[drug_name]] <- model_obj + shared$model_cache[[drug_name]] <- model_obj + shared$model_active[[drug_name]] <- TRUE + ok_names <- c(ok_names, drug_name) + }, + error = function(e) { + errs <<- c( + errs, + paste0(basename(files$name[k]), ": ", conditionMessage(e)) + ) + } + ) } w$hide() if (length(ok_names) > 0) { - showNotification(paste("Model(s) loaded:", paste(ok_names, collapse = ", "), - "| now listed in Loaded Models Management"), - type = "message", duration = 6) + showNotification( + paste( + "Model(s) loaded:", + paste(ok_names, collapse = ", "), + "| now listed in Loaded Models Management" + ), + type = "message", + duration = 6 + ) } if (length(errs) > 0) { - showNotification(paste("Failed to read:", paste(errs, collapse = " | ")), - type = "error", duration = 10) + showNotification( + paste("Failed to read:", paste(errs, collapse = " | ")), + type = "error", + duration = 10 + ) } }) output$model_status <- renderUI({ if (is.null(shared$models)) { - span(class = "status-badge unloaded", span(class = "status-dot gray"), "No model loaded") + span( + class = "status-badge unloaded", + span(class = "status-dot gray"), + "No model loaded" + ) } else { n_drugs <- length(shared$models) tagList( - span(class = "status-badge loaded", span(class = "status-dot green"), "Loaded"), - br(), br(), + span( + class = "status-badge loaded", + span(class = "status-dot green"), + "Loaded" + ), + br(), + br(), tags$small(class = "text-muted", paste(n_drugs, "drug model(s)")) ) } @@ -1116,8 +1708,13 @@ mod_data_server <- function(id, shared) { output$models_management <- renderUI({ cache <- shared$model_cache if (is.null(cache) || length(cache) == 0) { - div(class = "text-muted", style = "text-align: center; padding: 1.5rem;", - icon("inbox", style = "font-size: 1.8rem; opacity: 0.3; display: block; margin-bottom: 0.5rem;"), + div( + class = "text-muted", + style = "text-align: center; padding: 1.5rem;", + icon( + "inbox", + style = "font-size: 1.8rem; opacity: 0.3; display: block; margin-bottom: 0.5rem;" + ), "No models in cache. Use the Pre-trained Models card above to load a model,", "or train one in the Train tab." ) @@ -1133,19 +1730,24 @@ mod_data_server <- function(id, shared) { dot_class <- if (is_active) "green" else "gray" label <- if (is_active) "Active" else "Inactive" display_name <- if (d %in% demo_names) paste0(d, " [demo]") else d - div(class = "model-mgmt-card", - div(class = "model-mgmt-status", - strong(display_name) - ), + div( + class = "model-mgmt-card", + div(class = "model-mgmt-status", strong(display_name)), # NOTE: the status dot must go in `label`, not `icon` — Shiny >= 1.10 # validates the icon arg (validateIcon) and errors "Invalid icon" # for any non-icon() tag. - actionButton(ns(btn_id), tagList( - tags$span(class = "status-dot", class = dot_class, - style = "width:8px;height:8px;border-radius:50%;display:inline-block;"), - label - ), - class = paste("btn-model-toggle btn-sm", state_class)) + actionButton( + ns(btn_id), + tagList( + tags$span( + class = "status-dot", + class = dot_class, + style = "width:8px;height:8px;border-radius:50%;display:inline-block;" + ), + label + ), + class = paste("btn-model-toggle btn-sm", state_class) + ) ) }) div(class = "model-mgmt-grid", cards) @@ -1158,29 +1760,41 @@ mod_data_server <- function(id, shared) { local({ drug_local <- d btn_id <- paste0("toggle_", gsub("[^A-Za-z0-9]", "_", drug_local)) - observeEvent(input[[btn_id]], { - is_active <- isTRUE(shared$model_active[[drug_local]]) - if (is_active) { - # Deactivate: remove from active models but keep in cache - shared$models[[drug_local]] <- NULL - shared$model_active[[drug_local]] <- FALSE - showNotification(paste("Model deactivated:", drug_local, "(kept in cache)"), type = "message") - } else { - # Activate: restore from cache - if (!is.null(shared$model_cache[[drug_local]])) { - if (is.null(shared$models)) shared$models <- list() - shared$models[[drug_local]] <- shared$model_cache[[drug_local]] - shared$model_active[[drug_local]] <- TRUE - showNotification(paste("Model activated:", drug_local), type = "message") + observeEvent( + input[[btn_id]], + { + is_active <- isTRUE(shared$model_active[[drug_local]]) + if (is_active) { + # Deactivate: remove from active models but keep in cache + shared$models[[drug_local]] <- NULL + shared$model_active[[drug_local]] <- FALSE + showNotification( + paste("Model deactivated:", drug_local, "(kept in cache)"), + type = "message" + ) + } else { + # Activate: restore from cache + if (!is.null(shared$model_cache[[drug_local]])) { + if (is.null(shared$models)) { + shared$models <- list() + } + shared$models[[drug_local]] <- shared$model_cache[[drug_local]] + shared$model_active[[drug_local]] <- TRUE + showNotification( + paste("Model activated:", drug_local), + type = "message" + ) + } } - } - }, ignoreInit = TRUE) + }, + ignoreInit = TRUE + ) }) } # --- Upload Expression --- observeEvent(input$expr_file, { - shared$demo_loaded <- FALSE # user switched to their own data + shared$demo_loaded <- FALSE # user switched to their own data file <- input$expr_file w <- Waiter$new( html = tagList( @@ -1191,40 +1805,68 @@ mod_data_server <- function(id, shared) { color = "rgba(255,255,255,0.85)" ) w$show() - res <- tryCatch({ - mat <- read_uploaded_table(file) - n_skip <- attr(mat, "skipped_rows"); if (is.null(n_skip)) n_skip <- 0L - # RDS may be a matrix; text/Excel uploads come in as a data.frame - if (!is.matrix(mat)) { - mat <- as.matrix(mat) - # First column holding gene names (e.g. from Excel/csv export) -> rownames - if (ncol(mat) > 1 && is.character(mat[, 1]) && - anyNA(suppressWarnings(as.numeric(mat[, 1])))) { - rownames(mat) <- mat[, 1] - mat <- mat[, -1, drop = FALSE] + res <- tryCatch( + { + mat <- read_uploaded_table(file) + n_skip <- attr(mat, "skipped_rows") + if (is.null(n_skip)) { + n_skip <- 0L } + # RDS may be a matrix; text/Excel uploads come in as a data.frame + if (!is.matrix(mat)) { + mat <- as.matrix(mat) + # First column holding gene names (e.g. from Excel/csv export) -> rownames + if ( + ncol(mat) > 1 && + is.character(mat[, 1]) && + anyNA(suppressWarnings(as.numeric(mat[, 1]))) + ) { + rownames(mat) <- mat[, 1] + mat <- mat[, -1, drop = FALSE] + } + } + # Ensure numeric (Seurat LogMap requires numeric, not integer) + if (is.integer(mat)) { + mat <- matrix( + as.numeric(mat), + nrow = nrow(mat), + ncol = ncol(mat), + dimnames = dimnames(mat) + ) + } + storage.mode(mat) <- "numeric" + # Sanity check: a real expression matrix needs a plausible number of + # genes x cells. A stray text file (e.g. a gene list) would otherwise + # "parse" into a tiny matrix and silently load with no error at all. + if (nrow(mat) < 10 || ncol(mat) < 3) { + stop(sprintf( + paste0( + "Expression matrix looks invalid: %d genes x %d cells. ", + "A matrix needs at least ~10 genes and 3 cells — ", + "check you uploaded the expression file, not a gene list or response file." + ), + nrow(mat), + ncol(mat) + )) + } + shared$user_expr <- mat + shared$prepared_data <- NULL # Reset prepared data when expression changes + list( + ok = TRUE, + msg = paste0( + "Expression matrix loaded: ", + nrow(mat), + " genes x ", + ncol(mat), + " cells", + skipped_rows_msg(n_skip) + ) + ) + }, + error = function(e) { + list(ok = FALSE, msg = conditionMessage(e)) } - # Ensure numeric (Seurat LogMap requires numeric, not integer) - if (is.integer(mat)) mat <- matrix(as.numeric(mat), nrow = nrow(mat), ncol = ncol(mat), - dimnames = dimnames(mat)) - storage.mode(mat) <- "numeric" - # Sanity check: a real expression matrix needs a plausible number of - # genes x cells. A stray text file (e.g. a gene list) would otherwise - # "parse" into a tiny matrix and silently load with no error at all. - if (nrow(mat) < 10 || ncol(mat) < 3) { - stop(sprintf(paste0("Expression matrix looks invalid: %d genes x %d cells. ", - "A matrix needs at least ~10 genes and 3 cells — ", - "check you uploaded the expression file, not a gene list or response file."), - nrow(mat), ncol(mat))) - } - shared$user_expr <- mat - shared$prepared_data <- NULL # Reset prepared data when expression changes - list(ok = TRUE, - msg = paste0("Expression matrix loaded: ", nrow(mat), " genes x ", - ncol(mat), " cells", skipped_rows_msg(n_skip))) - }, error = function(e) { - list(ok = FALSE, msg = conditionMessage(e)) - }) + ) w$hide() if (isTRUE(res$ok)) { showNotification(res$msg, type = "message") @@ -1235,66 +1877,101 @@ mod_data_server <- function(id, shared) { }) output$expr_status <- renderUI({ - if (is.null(shared$user_expr)) return(NULL) + if (is.null(shared$user_expr)) { + return(NULL) + } tagList( - span(class = "status-badge loaded", span(class = "status-dot green"), "Loaded"), - tags$small(class = "text-muted", - paste0(nrow(shared$user_expr), " genes x ", ncol(shared$user_expr), " cells") + span( + class = "status-badge loaded", + span(class = "status-dot green"), + "Loaded" + ), + tags$small( + class = "text-muted", + paste0( + nrow(shared$user_expr), + " genes x ", + ncol(shared$user_expr), + " cells" + ) ) ) }) # --- Upload Patient-Cell Mapping --- observeEvent(input$mapping_file, { - shared$demo_loaded <- FALSE # user switched to their own data + shared$demo_loaded <- FALSE # user switched to their own data file <- input$mapping_file - tryCatch({ - df <- coerce_mapping_df(read_uploaded_table(file)) - n_skip <- attr(df, "skipped_rows"); if (is.null(n_skip)) n_skip <- 0L - df <- standardize_columns(df, c("cell_id", "patient_id")) - if (!all(c("cell_id", "patient_id") %in% names(df))) { - stop("Mapping must contain columns 'cell_id' and 'patient_id' (case-insensitive). Found: ", - paste(names(df), collapse = ", ")) - } - df$cell_id <- as.character(df$cell_id) - df$patient_id <- as.character(df$patient_id) - - # Optional per-clone abundance column (count / cells / n_cells / - # abundance): if present, expand each row to that many cells so clone - # proportions reflect TRUE cell counts (matching the paper's figures) - # instead of equal 1/n per clone. The abundance column is consumed here - # and not passed downstream. - count_col <- intersect(c("count", "cells", "n_cells", "n_cells_per_clone", - "abundance"), tolower(names(df))) - shared$mapping_has_count <- length(count_col) > 0 - if (length(count_col) > 0) { - cnt_col <- names(df)[tolower(names(df)) == count_col[1]][1] - cnt <- suppressWarnings(as.numeric(df[[cnt_col]])) - cnt[is.na(cnt) | cnt < 1] <- 1L - df <- df[rep(seq_len(nrow(df)), cnt), , drop = FALSE] - df[[cnt_col]] <- NULL - rownames(df) <- NULL - } + tryCatch( + { + df <- coerce_mapping_df(read_uploaded_table(file)) + n_skip <- attr(df, "skipped_rows") + if (is.null(n_skip)) { + n_skip <- 0L + } + df <- standardize_columns(df, c("cell_id", "patient_id")) + if (!all(c("cell_id", "patient_id") %in% names(df))) { + stop( + "Mapping must contain columns 'cell_id' and 'patient_id' (case-insensitive). Found: ", + paste(names(df), collapse = ", ") + ) + } + df$cell_id <- as.character(df$cell_id) + df$patient_id <- as.character(df$patient_id) + + # Optional per-clone abundance column (count / cells / n_cells / + # abundance): if present, expand each row to that many cells so clone + # proportions reflect TRUE cell counts (matching the paper's figures) + # instead of equal 1/n per clone. The abundance column is consumed here + # and not passed downstream. + count_col <- intersect( + c("count", "cells", "n_cells", "n_cells_per_clone", "abundance"), + tolower(names(df)) + ) + shared$mapping_has_count <- length(count_col) > 0 + if (length(count_col) > 0) { + cnt_col <- names(df)[tolower(names(df)) == count_col[1]][1] + cnt <- suppressWarnings(as.numeric(df[[cnt_col]])) + cnt[is.na(cnt) | cnt < 1] <- 1L + df <- df[rep(seq_len(nrow(df)), cnt), , drop = FALSE] + df[[cnt_col]] <- NULL + rownames(df) <- NULL + } - shared$user_mapping <- df - shared$prepared_data <- NULL # Reset prepared data when mapping changes - showNotification(paste0("Patient-cell mapping loaded: ", nrow(shared$user_mapping), - " cells", skipped_rows_msg(n_skip)), type = "message") - auto_prepare_if_clone() - }, error = function(e) { - showNotification(paste("Error:", e$message), type = "error") - }) + shared$user_mapping <- df + shared$prepared_data <- NULL # Reset prepared data when mapping changes + showNotification( + paste0( + "Patient-cell mapping loaded: ", + nrow(shared$user_mapping), + " cells", + skipped_rows_msg(n_skip) + ), + type = "message" + ) + auto_prepare_if_clone() + }, + error = function(e) { + showNotification(paste("Error:", e$message), type = "error") + } + ) }) output$mapping_status <- renderUI({ - if (is.null(shared$user_mapping)) return(NULL) + if (is.null(shared$user_mapping)) { + return(NULL) + } n_patients <- length(unique(shared$user_mapping$patient_id)) clone_mode <- identical(input$expr_format, "clone") # In clone-level mode without a count column there are no per-clone cell # counts, so clone proportions fall back to equal 1/n per clone. Be # explicit about this so users know what the plots actually show. - equal_weight_note <- if (clone_mode && !isTRUE(shared$mapping_has_count)) { - div(class = "info-box", style = "border-left-color: var(--warning, #d97706); margin-top: 0.4rem; font-size: 0.78rem; padding: 0.4rem 0.6rem;", + equal_weight_note <- if ( + clone_mode && !isTRUE(shared$mapping_has_count) + ) { + div( + class = "info-box", + style = "border-left-color: var(--warning, #d97706); margin-top: 0.4rem; font-size: 0.78rem; padding: 0.4rem 0.6rem;", icon("triangle-exclamation"), " No count column — clone proportions are shown as equal (1/n per clone). Add a count column with real cell numbers to show true proportions." ) @@ -1302,8 +1979,13 @@ mod_data_server <- function(id, shared) { NULL } tagList( - span(class = "status-badge loaded", span(class = "status-dot green"), "Loaded"), - tags$small(class = "text-muted", + span( + class = "status-badge loaded", + span(class = "status-dot green"), + "Loaded" + ), + tags$small( + class = "text-muted", paste0(nrow(shared$user_mapping), " cells, ", n_patients, " patients") ), equal_weight_note @@ -1313,7 +1995,10 @@ mod_data_server <- function(id, shared) { # --- Expression format (cell-level vs clone-level) --- observeEvent(input$expr_format, { clone_mode <- identical(input$expr_format, "clone") - session$sendCustomMessage(paste0("expr-format-state-", ns("expr_format")), clone_mode) + session$sendCustomMessage( + paste0("expr-format-state-", ns("expr_format")), + clone_mode + ) # Mode switch invalidates any previous preparation; in clone-level mode # the data is re-prepared automatically. shared$prepared_data <- NULL @@ -1325,7 +2010,11 @@ mod_data_server <- function(id, shared) { observeEvent(input$run_seurat, { req(shared$user_expr, shared$user_mapping) if (prep_busy()) { - showNotification("A preparation task is already running", type = "warning", duration = 5) + showNotification( + "A preparation task is already running", + type = "warning", + duration = 5 + ) return() } prep_busy(TRUE) @@ -1339,51 +2028,78 @@ mod_data_server <- function(id, shared) { ) w$show() jobid <- tryCatch( - submit_session_task(shared, "prepare", list( - method = input$seurat_method, - expression_matrix = shared$user_expr, - patient_mapping = shared$user_mapping, - seurat_resolution = input$seurat_resolution, - seurat_dims = input$seurat_dims - )), + submit_session_task( + shared, + "prepare", + list( + method = input$seurat_method, + expression_matrix = shared$user_expr, + patient_mapping = shared$user_mapping, + seurat_resolution = input$seurat_resolution, + seurat_dims = input$seurat_dims + ) + ), error = function(e) { prep_busy(FALSE) w$hide() # Make a failed worker spawn VISIBLE — otherwise the overlay just # vanishes after ~0.5s with no error and the status never changes. - showNotification(paste("Failed to start the background task:", e$message), - type = "error", duration = 12) + showNotification( + paste("Failed to start the background task:", e$message), + type = "error", + duration = 12 + ) NULL } ) - if (is.null(jobid)) return() - poll_task(shared, session, jobid, + if (is.null(jobid)) { + return() + } + poll_task( + shared, + session, + jobid, on_done = function(res) { prep_busy(FALSE) w$hide() shared$prepared_data <- res shared$user_clones <- res$cell_clone_map # Keep shared$user_expr as cell-level expression for biomarker plots - showNotification(paste0("Clustering complete: ", ncol(res$clone_expression_rnorm), - " clones detected across ", nrow(res$clone_counts), " patients"), - type = "message", duration = 5) + showNotification( + paste0( + "Clustering complete: ", + ncol(res$clone_expression_rnorm), + " clones detected across ", + nrow(res$clone_counts), + " patients" + ), + type = "message", + duration = 5 + ) }, on_error = function(msg) { prep_busy(FALSE) w$hide() - showNotification(paste("Clustering error:", msg), type = "error", duration = 10) - }) + showNotification( + paste("Clustering error:", msg), + type = "error", + duration = 10 + ) + } + ) }) output$seurat_status <- renderUI({ if (is.null(shared$prepared_data)) { if (identical(input$expr_format, "clone")) { - tags$span(class = "status-badge unloaded", + tags$span( + class = "status-badge unloaded", span(class = "status-dot gray"), "Clone-level mode. Will auto-prepare once expression and mapping are loaded" ) } else { - tags$span(class = "status-badge unloaded", + tags$span( + class = "status-badge unloaded", span(class = "status-dot gray"), "Not run yet. Upload expression and mapping, then click Run Seurat Clustering" ) @@ -1391,13 +2107,26 @@ mod_data_server <- function(id, shared) { } else { pd <- shared$prepared_data tagList( - span(class = "status-badge loaded", span(class = "status-dot green"), "Complete"), - tags$small(class = "text-muted", - if (identical(pd$reduction_method, "none")) - "(clone-level, clustering skipped) " else "", - paste0(ncol(pd$clone_expression_rnorm), " clones, ", - nrow(pd$clone_counts), " patients, ", - nrow(pd$clone_expression_rnorm), " genes (rank-normalized)") + span( + class = "status-badge loaded", + span(class = "status-dot green"), + "Complete" + ), + tags$small( + class = "text-muted", + if (identical(pd$reduction_method, "none")) { + "(clone-level, clustering skipped) " + } else { + "" + }, + paste0( + ncol(pd$clone_expression_rnorm), + " clones, ", + nrow(pd$clone_counts), + " patients, ", + nrow(pd$clone_expression_rnorm), + " genes (rank-normalized)" + ) ) ) } @@ -1405,39 +2134,69 @@ mod_data_server <- function(id, shared) { # --- Upload Clinical Response --- observeEvent(input$response_file, { - shared$demo_loaded <- FALSE # user switched to their own data + shared$demo_loaded <- FALSE # user switched to their own data file <- input$response_file - tryCatch({ - df <- coerce_response_df(read_uploaded_table(file)) - n_skip <- attr(df, "skipped_rows"); if (is.null(n_skip)) n_skip <- 0L - df <- standardize_columns(df, c("patient", "response")) - if (!all(c("patient", "response") %in% names(df))) { - stop("Response file must contain columns 'patient' and 'response' (case-insensitive). Found: ", - paste(names(df), collapse = ", ")) - } - df$patient <- as.character(df$patient) - df$response <- normalize_response_labels(df$response) - shared$user_response <- df - # Warn if patient IDs do not overlap with the loaded mapping - if (!is.null(shared$user_mapping)) { - mapped_patients <- unique(as.character(shared$user_mapping$patient_id)) - overlap <- intersect(as.character(df$patient), mapped_patients) - if (length(overlap) == 0) { - showNotification("Warning: no patient IDs in the response file match the mapping's patient_id. Predictions cannot be validated.", type = "warning", duration = 10) + tryCatch( + { + df <- coerce_response_df(read_uploaded_table(file)) + n_skip <- attr(df, "skipped_rows") + if (is.null(n_skip)) { + n_skip <- 0L } + df <- standardize_columns(df, c("patient", "response")) + if (!all(c("patient", "response") %in% names(df))) { + stop( + "Response file must contain columns 'patient' and 'response' (case-insensitive). Found: ", + paste(names(df), collapse = ", ") + ) + } + df$patient <- as.character(df$patient) + df$response <- normalize_response_labels(df$response) + shared$user_response <- df + # Warn if patient IDs do not overlap with the loaded mapping + if (!is.null(shared$user_mapping)) { + mapped_patients <- unique(as.character( + shared$user_mapping$patient_id + )) + overlap <- intersect(as.character(df$patient), mapped_patients) + if (length(overlap) == 0) { + showNotification( + "Warning: no patient IDs in the response file match the mapping's patient_id. Predictions cannot be validated.", + type = "warning", + duration = 10 + ) + } + } + showNotification( + paste0( + "Clinical response loaded: ", + nrow(shared$user_response), + " patients", + skipped_rows_msg(n_skip) + ), + type = "message" + ) + }, + error = function(e) { + showNotification(paste("Error:", e$message), type = "error") } - showNotification(paste0("Clinical response loaded: ", nrow(shared$user_response), - " patients", skipped_rows_msg(n_skip)), type = "message") - }, error = function(e) { - showNotification(paste("Error:", e$message), type = "error") - }) + ) }) output$response_status <- renderUI({ - if (is.null(shared$user_response)) return(NULL) + if (is.null(shared$user_response)) { + return(NULL) + } tagList( - span(class = "status-badge loaded", span(class = "status-dot green"), "Loaded"), - tags$small(class = "text-muted", paste(nrow(shared$user_response), "patients")) + span( + class = "status-badge loaded", + span(class = "status-dot green"), + "Loaded" + ), + tags$small( + class = "text-muted", + paste(nrow(shared$user_response), "patients") + ) ) }) @@ -1445,9 +2204,18 @@ mod_data_server <- function(id, shared) { output$status_overview <- renderUI({ items <- list( list(name = "Expression Matrix", loaded = !is.null(shared$user_expr)), - list(name = "Patient-Cell Mapping", loaded = !is.null(shared$user_mapping)), - list(name = "Clone Map (Seurat)", loaded = !is.null(shared$prepared_data)), - list(name = "Clinical Response", loaded = !is.null(shared$user_response)), + list( + name = "Patient-Cell Mapping", + loaded = !is.null(shared$user_mapping) + ), + list( + name = "Clone Map (Seurat)", + loaded = !is.null(shared$prepared_data) + ), + list( + name = "Clinical Response", + loaded = !is.null(shared$user_response) + ), list(name = "Trained Model", loaded = !is.null(shared$models)), # NO trailing comma on the last element: renderUI captures the # expression with rlang, which turns a trailing comma into an empty @@ -1456,11 +2224,23 @@ mod_data_server <- function(id, shared) { ) tagList( - div(style = "display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 0.8rem;", + div( + style = "display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 0.8rem;", lapply(items, function(item) { - div(class = if (item$loaded) "status-badge loaded" else "status-badge unloaded", + div( + class = if (item$loaded) { + "status-badge loaded" + } else { + "status-badge unloaded" + }, style = "justify-content: center; padding: 0.5rem 0.8rem; font-size: 0.82rem;", - span(class = if (item$loaded) "status-dot green" else "status-dot gray"), + span( + class = if (item$loaded) { + "status-dot green" + } else { + "status-dot gray" + } + ), strong(item$name) ) }) @@ -1473,16 +2253,16 @@ mod_data_server <- function(id, shared) { # Known members of the DepMap.RDS reference object, with short plain-English # descriptions so users know what each table actually contains. depmap_help <- c( - expression_20q4 = "Bulk RNA expression (TPM) of CCLE cell lines (DepMap 20Q4). Rows = genes, columns = cell lines.", - expression_rnorm = "Rank-normalized bulk expression (genes x cell lines). The main input used to build drug response models.", - scrna_complete = "Single-cell RNA expression of CCLE cell lines (genes x cells). Used to tune models at single-cell resolution.", - scrna_subset_rnorm = "Rank-normalized subset of single-cell expression (genes x cells), aligned with the model feature space.", - cpm_scrna_ccle_rnorm = "Rank-normalized single-cell CPM expression (cells x genes). The full single-cell reference used for clone-level prediction.", - metadata_cpm_scrna = "Cell-level metadata for the single-cell reference (cell barcodes, cell line, quality metrics, etc.).", - mutations_matrix = "Binarized mutation matrix (genes x cell lines): 1 = non-silent mutation, 0 = wild type.", - annotation_20q4 = "Cell line annotations (DepMap 20Q4): lineage, primary disease, growth conditions, etc.", - drugcategory = "Drug classification table: drug name, target pathway, mechanism of action, etc.", - secondary_prism = "PRISM secondary-screen drug response values (viability/AUC) across cell lines.", + expression_20q4 = "Bulk RNA expression (TPM) of CCLE cell lines (DepMap 20Q4). Rows = genes, columns = cell lines.", + expression_rnorm = "Rank-normalized bulk expression (genes x cell lines). The main input used to build drug response models.", + scrna_complete = "Single-cell RNA expression of CCLE cell lines (genes x cells). Used to tune models at single-cell resolution.", + scrna_subset_rnorm = "Rank-normalized subset of single-cell expression (genes x cells), aligned with the model feature space.", + cpm_scrna_ccle_rnorm = "Rank-normalized single-cell CPM expression (cells x genes). The full single-cell reference used for clone-level prediction.", + metadata_cpm_scrna = "Cell-level metadata for the single-cell reference (cell barcodes, cell line, quality metrics, etc.).", + mutations_matrix = "Binarized mutation matrix (genes x cell lines): 1 = non-silent mutation, 0 = wild type.", + annotation_20q4 = "Cell line annotations (DepMap 20Q4): lineage, primary disease, growth conditions, etc.", + drugcategory = "Drug classification table: drug name, target pathway, mechanism of action, etc.", + secondary_prism = "PRISM secondary-screen drug response values (viability/AUC) across cell lines.", secondary_screen_drugannotation = "Annotations for the PRISM secondary-screen drugs." ) # Safe lookup: names not in depmap_help return NULL instead of an error. @@ -1494,11 +2274,17 @@ mod_data_server <- function(id, shared) { # Placeholder shown in a preview tab until its data is loaded (so the tab # is never a blank area — e.g. right after the demo is cleared). preview_placeholder <- function(msg) { - div(style = paste("padding: 1.2rem; text-align: center;", - "color: var(--text-muted);", - "border: 1px dashed var(--border);", - "border-radius: 0.5rem; font-size: 0.88rem;"), - icon("table"), " ", msg) + div( + style = paste( + "padding: 1.2rem; text-align: center;", + "color: var(--text-muted);", + "border: 1px dashed var(--border);", + "border-radius: 0.5rem; font-size: 0.88rem;" + ), + icon("table"), + " ", + msg + ) } output$depmap_preview <- renderUI({ @@ -1511,19 +2297,34 @@ mod_data_server <- function(id, shared) { Dataset = nms, Rows = vapply(comps, function(x) x$nrow, numeric(1)), Cols = vapply(comps, function(x) x$ncol, numeric(1)), - Description = vapply(tolower(nms), function(n) { - d <- depmap_lookup(n) - if (is.null(d)) "Click View to inspect details." else d - }, character(1)), - View = vapply(nms, function(n) { - sprintf('View', - ns("depmap_view"), n) - }, character(1)), + Description = vapply( + tolower(nms), + function(n) { + d <- depmap_lookup(n) + if (is.null(d)) "Click View to inspect details." else d + }, + character(1) + ), + View = vapply( + nms, + function(n) { + sprintf( + 'View', + ns("depmap_view"), + n + ) + }, + character(1) + ), stringsAsFactors = FALSE ) - datatable(summary_df, options = list(pageLength = 10, dom = "tp"), - rownames = FALSE, class = "display", - escape = c(TRUE, TRUE, TRUE, TRUE, FALSE)) + datatable( + summary_df, + options = list(pageLength = 10, dom = "tp"), + rownames = FALSE, + class = "display", + escape = c(TRUE, TRUE, TRUE, TRUE, FALSE) + ) }) # Clicking "View" shows a modal with the description, dimensions, and the @@ -1534,11 +2335,17 @@ mod_data_server <- function(id, shared) { req(shared$depmap_meta, input$depmap_view) nm <- input$depmap_view comp <- shared$depmap_meta$components[[nm]] - if (is.null(comp)) return(NULL) + if (is.null(comp)) { + return(NULL) + } desc <- depmap_lookup(tolower(nm)) - if (is.null(desc)) desc <- paste0("R object '", nm, "'.") + if (is.null(desc)) { + desc <- paste0("R object '", nm, "'.") + } col_head <- paste(comp$cols_preview, collapse = ", ") - if (!is.na(comp$ncol) && comp$ncol > 12) col_head <- paste0(col_head, ", ...") + if (!is.na(comp$ncol) && comp$ncol > 12) { + col_head <- paste0(col_head, ", ...") + } showModal(modalDialog( title = tags$strong(icon("database"), nm), size = "l", @@ -1546,12 +2353,18 @@ mod_data_server <- function(id, shared) { footer = modalButton("Close"), tags$div( p(style = "margin-bottom: 0.6rem;", desc), - p(class = "text-muted", style = "font-size: 0.82rem; margin-bottom: 0.8rem;", + p( + class = "text-muted", + style = "font-size: 0.82rem; margin-bottom: 0.8rem;", sprintf("Dimensions: %s rows x %s columns.", comp$nrow, comp$ncol), " | Columns: ", - if (length(col_head) == 0 || !nzchar(col_head)) "—" else col_head), - p(class = "text-muted", style = "font-size: 0.78rem;", - "No data preview — the main process keeps only DepMap metadata; the full object lives in the background training worker.") + if (length(col_head) == 0 || !nzchar(col_head)) "—" else col_head + ), + p( + class = "text-muted", + style = "font-size: 0.78rem;", + "No data preview — the main process keeps only DepMap metadata; the full object lives in the background training worker." + ) ) )) }) @@ -1560,26 +2373,35 @@ mod_data_server <- function(id, shared) { if (is.null(shared$user_expr)) { return(preview_placeholder("Expression matrix not loaded yet")) } - datatable(shared$user_expr[, 1:min(10, ncol(shared$user_expr)), drop = FALSE], - options = list(pageLength = 10, dom = "tp", scrollX = TRUE), - class = "display") + datatable( + shared$user_expr[, 1:min(10, ncol(shared$user_expr)), drop = FALSE], + options = list(pageLength = 10, dom = "tp", scrollX = TRUE), + class = "display" + ) }) output$clone_preview <- renderUI({ if (is.null(shared$user_clones)) { return(preview_placeholder("Clone map not available yet")) } - datatable(shared$user_clones, options = list(pageLength = 10, dom = "tp"), - rownames = FALSE, class = "display") + datatable( + shared$user_clones, + options = list(pageLength = 10, dom = "tp"), + rownames = FALSE, + class = "display" + ) }) output$response_preview <- renderUI({ if (is.null(shared$user_response)) { return(preview_placeholder("Clinical response not loaded yet")) } - datatable(shared$user_response, options = list(pageLength = 10, dom = "tp"), - rownames = FALSE, class = "display") + datatable( + shared$user_response, + options = list(pageLength = 10, dom = "tp"), + rownames = FALSE, + class = "display" + ) }) - }) -} \ No newline at end of file +} diff --git a/inst/shiny/app/R/mod_help.R b/inst/shiny/app/R/mod_help.R index 559b526..83bc45b 100644 --- a/inst/shiny/app/R/mod_help.R +++ b/inst/shiny/app/R/mod_help.R @@ -3,238 +3,462 @@ mod_help_ui <- function(id) { ns <- NS(id) # Keep the in-app citation in sync with the installed package version # (falls back to the current release when running from source). - pkg_ver <- tryCatch(as.character(utils::packageVersion("PERCEPTIONx")), - error = function(e) "0.3.0") + pkg_ver <- tryCatch( + as.character(utils::packageVersion("PERCEPTIONx")), + error = function(e) "0.3.0" + ) tagList( fluidRow( - column(12, - div(class = "section-header", + column( + 12, + div( + class = "section-header", icon("circle-question"), h4("Reference Documentation") ), - div(class = "info-box", - icon("book"), " Detailed reference for data formats, parameters, and interpretation." + div( + class = "info-box", + icon("book"), + " Detailed reference for data formats, parameters, and interpretation." ) ) ), - fluidRow(style = "margin-top: 1rem;", + fluidRow( + style = "margin-top: 1rem;", # Left sidebar: section navigation - column(3, - div(class = "card help-nav-card", - div(class = "card-header", - icon("list-ul"), " Sections" - ), - div(class = "card-body", style = "padding: 0.6rem 0.5rem !important;", - div(class = "help-nav-list", - actionButton(ns("nav_overview"), "Walkthroughs", class = "help-nav-btn"), - actionButton(ns("nav_drugs"), "Supported Drugs", class = "help-nav-btn"), - actionButton(ns("nav_data_req"), "Data Requirements", class = "help-nav-btn"), - actionButton(ns("nav_training"), "Training Parameters", class = "help-nav-btn"), - actionButton(ns("nav_prediction"), "Aggregation Modes", class = "help-nav-btn"), - actionButton(ns("nav_viz_guide"), "Visualization Guide", class = "help-nav-btn"), + column( + 3, + div( + class = "card help-nav-card", + div(class = "card-header", icon("list-ul"), " Sections"), + div( + class = "card-body", + style = "padding: 0.6rem 0.5rem !important;", + div( + class = "help-nav-list", + actionButton( + ns("nav_overview"), + "Walkthroughs", + class = "help-nav-btn" + ), + actionButton( + ns("nav_drugs"), + "Supported Drugs", + class = "help-nav-btn" + ), + actionButton( + ns("nav_data_req"), + "Data Requirements", + class = "help-nav-btn" + ), + actionButton( + ns("nav_training"), + "Training Parameters", + class = "help-nav-btn" + ), + actionButton( + ns("nav_prediction"), + "Aggregation Modes", + class = "help-nav-btn" + ), + actionButton( + ns("nav_viz_guide"), + "Visualization Guide", + class = "help-nav-btn" + ), actionButton(ns("nav_faq"), "FAQ", class = "help-nav-btn"), - actionButton(ns("nav_citation"), "Citation", class = "help-nav-btn") + actionButton( + ns("nav_citation"), + "Citation", + class = "help-nav-btn" + ) ) ) ) ), # Main content - column(9, + column( + 9, # Walkthroughs — pick Demo or Advanced; each opens a centered, # slide-style guided tour (game-tutorial style prev/next paging). - div(id = ns("section_overview"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_overview"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("graduation-cap")), div( h5("Guided Walkthroughs"), - p(class = "help-subtitle", "New to the app? Pick a tour below. It opens as an interactive slideshow in the center of the screen.") + p( + class = "help-subtitle", + "New to the app? Pick a tour below. It opens as an interactive slideshow in the center of the screen." + ) ) ), - div(class = "tw-entry-grid", - div(class = "tw-entry tw-entry-demo", - div(class = "tw-entry-top", + div( + class = "tw-entry-grid", + div( + class = "tw-entry tw-entry-demo", + div( + class = "tw-entry-top", div(class = "tw-entry-ic", icon("wand-magic-sparkles")), - div(class = "tw-entry-title", + div( + class = "tw-entry-title", strong("Try the demo"), span("~1 minute \u00b7 no files needed") ) ), - p("Load the built-in demo data, run the predictions, then draw and export the plots - nothing to upload or train."), - actionButton(ns("tour_demo"), "Start the Demo Tour", class = "btn-tw btn-tw-demo", width = "100%") + p( + "Load the built-in demo data, run the predictions, then draw and export the plots - nothing to upload or train." + ), + actionButton( + ns("tour_demo"), + "Start the Demo Tour", + class = "btn-tw btn-tw-demo", + width = "100%" + ) ), - div(class = "tw-entry tw-entry-adv", - div(class = "tw-entry-top", + div( + class = "tw-entry tw-entry-adv", + div( + class = "tw-entry-top", div(class = "tw-entry-ic", icon("flask-vial")), - div(class = "tw-entry-title", + div( + class = "tw-entry-title", strong("Analyze your own data"), span("~2 minutes \u00b7 uploads required") ) ), - p("Walk through uploading expression / mapping / response files, (optional) training, prediction and how to read the plots."), - actionButton(ns("tour_advanced"), "Start the Advanced Tour", class = "btn-tw btn-tw-adv", width = "100%") + p( + "Walk through uploading expression / mapping / response files, (optional) training, prediction and how to read the plots." + ), + actionButton( + ns("tour_advanced"), + "Start the Advanced Tour", + class = "btn-tw btn-tw-adv", + width = "100%" + ) ) ), - p(class = "text-muted", style = "font-size: 0.8rem; margin-top: 0.6rem; margin-bottom: 0;", - icon("book"), " Detailed reference for every parameter and format sits in the sections below.") + p( + class = "text-muted", + style = "font-size: 0.8rem; margin-top: 0.6rem; margin-bottom: 0;", + icon("book"), + " Detailed reference for every parameter and format sits in the sections below." + ) ), # Supported Drugs - searchable catalogue with the pre-trained 44 marked - div(id = ns("section_drugs"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_drugs"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("pills")), div( h5("Supported Drugs"), - p(class = "help-subtitle", "Find a compound, see if a model is ready, or train it yourself") + p( + class = "help-subtitle", + "Find a compound, see if a model is ready, or train it yourself" + ) ) ), - p("This is the drug screen shipped with our DepMap data (PRISM): ", - strong("1448 compounds"), ", most of them research tool molecules rather than clinical drugs. ", - strong("142 are FDA-approved cancer drugs"), " (green), and the ", strong("44 pre-trained"), - " ones come with ready-made models. Any other compound can be trained on the Train tab once DepMap is loaded."), - div(class = "help-drug-legend", + p( + "This is the drug screen shipped with our DepMap data (PRISM): ", + strong("1448 compounds"), + ", most of them research tool molecules rather than clinical drugs. ", + strong("142 are FDA-approved cancer drugs"), + " (green), and the ", + strong("44 pre-trained"), + " ones come with ready-made models. Any other compound can be trained on the Train tab once DepMap is loaded." + ), + div( + class = "help-drug-legend", span(class = "help-drug-chip", "compound in the DepMap screen"), span(class = "help-drug-badge help-drug-badge-fda", "FDA"), span(class = "help-drug-badge", "PRE"), span(class = "help-drug-badge help-drug-badge-demo", "demo") ), - p(class = "text-muted", style = "font-size: 0.72rem; margin: 0.3rem 0 0;", - "PRE = pre-trained model available \u00b7 FDA = FDA-approved cancer drug \u00b7 demo = used by the demo dataset."), - div(class = "help-drug-controls", - textInput(ns("drug_search"), NULL, placeholder = "Search compounds...", - width = "260px"), - radioButtons(ns("drug_filter"), NULL, inline = TRUE, - choices = c("Pre-trained (44)" = "pt", - "FDA (142)" = "fda", - "Demo" = "demo", - "All compounds" = "all"), - selected = "pt") + p( + class = "text-muted", + style = "font-size: 0.72rem; margin: 0.3rem 0 0;", + "PRE = pre-trained model available \u00b7 FDA = FDA-approved cancer drug \u00b7 demo = used by the demo dataset." + ), + div( + class = "help-drug-controls", + textInput( + ns("drug_search"), + NULL, + placeholder = "Search compounds...", + width = "260px" + ), + radioButtons( + ns("drug_filter"), + NULL, + inline = TRUE, + choices = c( + "Pre-trained (44)" = "pt", + "FDA (142)" = "fda", + "Demo" = "demo", + "All compounds" = "all" + ), + selected = "pt" + ) ), uiOutput(ns("drug_results")) ), # Data Requirements - div(id = ns("section_data_req"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_data_req"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("database")), div( h5("Data Requirements"), - p(class = "help-subtitle", "What data you need and how to prepare it") + p( + class = "help-subtitle", + "What data you need and how to prepare it" + ) ) ), - div(class = "help-data-grid", - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--primary);", icon("layer-group")), + div( + class = "help-data-grid", + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--primary);", + icon("layer-group") + ), strong("DepMap Data"), - p("Downloaded and loaded via the ", code("Download & Load"), " button on the Data tab (or a pre-downloaded .RDS upload). Includes bulk expression, single-cell expression, and drug response (AUC) data from DepMap."), + p( + "Downloaded and loaded via the ", + code("Download & Load"), + " button on the Data tab (or a pre-downloaded .RDS upload). Includes bulk expression, single-cell expression, and drug response (AUC) data from DepMap." + ), tags$span(class = "status-badge unloaded", "Click & load") ), - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--accent);", icon("table")), + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--accent);", + icon("table") + ), strong("Expression Matrix"), - p("A gene x cell single-cell expression matrix. Raw counts or normalized values. Rank normalization is applied automatically during Seurat clustering."), + p( + "A gene x cell single-cell expression matrix. Raw counts or normalized values. Rank normalization is applied automatically during Seurat clustering." + ), tags$span(class = "status-badge unloaded", "User upload") ), - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--success);", icon("users")), + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--success);", + icon("users") + ), strong("Patient-Cell Mapping"), - p("File with columns: ", code("cell_id"), " and ", code("patient_id"), " (case-insensitive). Maps each cell to its patient. Clones are auto-detected via Seurat clustering. Accepts CSV / TSV / TXT / Excel / RDS."), + p( + "File with columns: ", + code("cell_id"), + " and ", + code("patient_id"), + " (case-insensitive). Maps each cell to its patient. Clones are auto-detected via Seurat clustering. Accepts CSV / TSV / TXT / Excel / RDS." + ), tags$span(class = "status-badge unloaded", "User upload") ), - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--primary-light);", icon("stethoscope")), + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--primary-light);", + icon("stethoscope") + ), strong("Clinical Response"), - p("(Optional) File with columns: ", code("patient"), ", ", code("response"), " (Responder/Non-responder, case-insensitive). Required for ROC curves and boxplots. Accepts CSV / TSV / TXT / Excel / RDS."), + p( + "(Optional) File with columns: ", + code("patient"), + ", ", + code("response"), + " (Responder/Non-responder, case-insensitive). Required for ROC curves and boxplots. Accepts CSV / TSV / TXT / Excel / RDS." + ), tags$span(class = "status-badge unloaded", "Optional") ) ) ), # Training Parameters - div(id = ns("section_training"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_training"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("sliders-h")), div( h5("Training Parameters"), p(class = "help-subtitle", "Configure your model training") ) ), - div(class = "help-param-grid", - div(class = "help-param-item", + div( + class = "help-param-grid", + div( + class = "help-param-item", div(class = "help-param-name", icon("tag"), " Drug Name"), - p("Must match a drug in DepMap secondary_prism data (e.g. abemaciclib, erlotinib). Use the dropdown on the Data tab for the full list of 44 supported drugs.") + p( + "Must match a drug in DepMap secondary_prism data (e.g. abemaciclib, erlotinib). Use the dropdown on the Data tab for the full list of 44 supported drugs." + ) ), - div(class = "help-param-item", + div( + class = "help-param-item", div(class = "help-param-name", icon("filter"), " Cancer Type"), - p("Filter cell lines by cancer type. Use ", code("PanCan"), " for all cancer types, or specify e.g. ", code("Breast"), ", ", code("Lung"), ".") + p( + "Filter cell lines by cancer type. Use ", + code("PanCan"), + " for all cancer types, or specify e.g. ", + code("Breast"), + ", ", + code("Lung"), + "." + ) ), - div(class = "help-param-item", + div( + class = "help-param-item", div(class = "help-param-name", icon("ban"), " Exclude Cancer"), - p("Exclude specific cancer types from training. Set to ", code("PanCan"), " to exclude none.") + p( + "Exclude specific cancer types from training. Set to ", + code("PanCan"), + " to exclude none." + ) ), - div(class = "help-param-item", + div( + class = "help-param-item", div(class = "help-param-name", icon("dna"), " Genes of Interest"), - p("Gene symbols for feature selection. Leave ", strong("empty to use all genes"), " from DepMap (~15K). Should overlap with your scRNA data for prediction.") + p( + "Gene symbols for feature selection. Leave ", + strong("empty to use all genes"), + " from DepMap (~15K). Should overlap with your scRNA data for prediction." + ) ), - div(class = "help-param-item", - div(class = "help-param-name", icon("sort-numeric-down"), " k_features"), - p("Number of top-ranked features (by Pearson correlation) to use. Default: 100. Higher = more features but slower.") + div( + class = "help-param-item", + div( + class = "help-param-name", + icon("sort-numeric-down"), + " k_features" + ), + p( + "Number of top-ranked features (by Pearson correlation) to use. Default: 100. Higher = more features but slower." + ) ), - div(class = "help-param-item", + div( + class = "help-param-item", div(class = "help-param-name", icon("cog"), " Model Type"), - p(code("glmnet"), " (elastic net, recommended) with 3-fold CV, or ", code("rf"), " (random forest).") + p( + code("glmnet"), + " (elastic net, recommended) with 3-fold CV, or ", + code("rf"), + " (random forest)." + ) ) ) ), # Aggregation Modes - div(id = ns("section_prediction"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_prediction"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("layer-group")), div( h5("Patient Aggregation Modes"), - p(class = "help-subtitle", "How clone-level predictions become patient-level") + p( + class = "help-subtitle", + "How clone-level predictions become patient-level" + ) ) ), - div(class = "help-data-grid", - div(class = "help-data-card", style = "border-left: 3px solid var(--success);", - div(class = "help-data-icon", style = "color: var(--success);", icon("star")), + div( + class = "help-data-grid", + div( + class = "help-data-card", + style = "border-left: 3px solid var(--success);", + div( + class = "help-data-icon", + style = "color: var(--success);", + icon("star") + ), strong("weighted_max"), tags$span(class = "status-badge loaded", "Recommended"), - p("Weighted maximum across clones, emphasizing the most resistant clones (recommended).") + p( + "Weighted maximum across clones, emphasizing the most resistant clones (recommended)." + ) ), - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--primary);", icon("balance-scale")), + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--primary);", + icon("balance-scale") + ), strong("weighted_average"), - p("Weighted average across all clones, weighted by clone proportion.") + p( + "Weighted average across all clones, weighted by clone proportion." + ) ), - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--error);", icon("arrow-down")), + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--error);", + icon("arrow-down") + ), strong("min"), - p("Takes the most sensitive clone's prediction (lowest viability, pessimistic).") + p( + "Takes the most sensitive clone's prediction (lowest viability, pessimistic)." + ) ), - div(class = "help-data-card", - div(class = "help-data-icon", style = "color: var(--success-light);", icon("arrow-up")), + div( + class = "help-data-card", + div( + class = "help-data-icon", + style = "color: var(--success-light);", + icon("arrow-up") + ), strong("max"), - p("Takes the most resistant clone's prediction (highest viability, optimistic).") + p( + "Takes the most resistant clone's prediction (highest viability, optimistic)." + ) ) ) ), # Visualization Guide - div(id = ns("section_viz_guide"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_viz_guide"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("chart-line")), div( h5("Visualization Guide"), - p(class = "help-subtitle", "Available plot types and their data requirements") + p( + class = "help-subtitle", + "Available plot types and their data requirements" + ) ) ), - div(class = "help-viz-grid", - div(class = "help-viz-card", + div( + class = "help-viz-grid", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("chart-pie")), div( strong("Clone Distribution"), @@ -242,135 +466,239 @@ mod_help_ui <- function(id) { tags$span(class = "status-badge unloaded", "Needs: Clones") ) ), - div(class = "help-viz-card", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("chart-column")), div( strong("Clone Viability Lollipop"), p("Lollipop chart of predicted viability per clone."), - tags$span(class = "status-badge unloaded", "Needs: Predictions + Clones") + tags$span( + class = "status-badge unloaded", + "Needs: Predictions + Clones" + ) ) ), - div(class = "help-viz-card", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("chart-line")), div( strong("ROC Curve"), - p("Receiver Operating Characteristic curve for response prediction."), - tags$span(class = "status-badge unloaded", "Needs: Patient Pred + Response") + p( + "Receiver Operating Characteristic curve for response prediction." + ), + tags$span( + class = "status-badge unloaded", + "Needs: Patient Pred + Response" + ) ) ), - div(class = "help-viz-card", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("chart-gantt")), div( strong("Response Boxplot"), - p("Boxplot comparing predicted viability between responders and non-responders."), - tags$span(class = "status-badge unloaded", "Needs: Patient Pred + Response") + p( + "Boxplot comparing predicted viability between responders and non-responders." + ), + tags$span( + class = "status-badge unloaded", + "Needs: Patient Pred + Response" + ) ) ), - div(class = "help-viz-card", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("map")), div( strong("Clone Identity"), p("2D embedding (UMAP/t-SNE) colored by clone membership."), - tags$span(class = "status-badge unloaded", "Needs: Clones + Embedding") + tags$span( + class = "status-badge unloaded", + "Needs: Clones + Embedding" + ) ) ), - div(class = "help-viz-card", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("flask")), div( strong("Drug Viability"), - p("2D embedding (UMAP/t-SNE) colored by predicted drug viability."), - tags$span(class = "status-badge unloaded", "Needs: Predictions + Embedding") + p( + "2D embedding (UMAP/t-SNE) colored by predicted drug viability." + ), + tags$span( + class = "status-badge unloaded", + "Needs: Predictions + Embedding" + ) ) ), - div(class = "help-viz-card", + div( + class = "help-viz-card", div(class = "help-viz-icon", icon("dna")), div( strong("Gene Expression"), - p("2D embedding (UMAP/t-SNE) colored by selected gene expression."), - tags$span(class = "status-badge unloaded", "Needs: Predictions + Expression + Embedding") + p( + "2D embedding (UMAP/t-SNE) colored by selected gene expression." + ), + tags$span( + class = "status-badge unloaded", + "Needs: Predictions + Expression + Embedding" + ) ) ) ) ), # FAQ - div(id = ns("section_faq"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_faq"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("comment-dots")), div( h5("Frequently Asked Questions"), p(class = "help-subtitle", "Common questions and answers") ) ), - div(class = "help-faq-list", - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " How long does training take?"), - div(class = "help-faq-a", + div( + class = "help-faq-list", + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " How long does training take?" + ), + div( + class = "help-faq-a", "Training a single drug model typically takes 30 seconds to 5 minutes depending on the number of features and cores used. Using all genes (~15K) with k_features=100 is the default and works well." ) ), - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " Can I use my own bulk expression data?"), - div(class = "help-faq-a", + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " Can I use my own bulk expression data?" + ), + div( + class = "help-faq-a", "Currently, PERCEPTIONx trains on DepMap data. You can use the trained model to predict on your own single-cell data after rank normalization." ) ), - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " What if my gene names don't match?"), - div(class = "help-faq-a", - "Gene symbols must match between training and prediction data. The app automatically intersects genes between DepMap and your expression matrix. Check for hyphen vs dot formatting (e.g. ", code("BRCA1"), " vs ", code("BRCA.1"), ")." + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " What if my gene names don't match?" + ), + div( + class = "help-faq-a", + "Gene symbols must match between training and prediction data. The app automatically intersects genes between DepMap and your expression matrix. Check for hyphen vs dot formatting (e.g. ", + code("BRCA1"), + " vs ", + code("BRCA.1"), + ")." ) ), - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " How do I preprocess my data?"), - div(class = "help-faq-a", - "Use ", code("rank_normalization_mat()"), " to rank-normalize your expression matrix. This is the same preprocessing applied to DepMap data." + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " How do I preprocess my data?" + ), + div( + class = "help-faq-a", + "Use ", + code("rank_normalization_mat()"), + " to rank-normalize your expression matrix. This is the same preprocessing applied to DepMap data." ) ), - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " Should I specify Genes of Interest?"), - div(class = "help-faq-a", - "Leave it ", strong("empty"), " to use all ~15K genes from DepMap (recommended for most users). Specify a subset only if you want to restrict feature selection to known biomarkers." + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " Should I specify Genes of Interest?" + ), + div( + class = "help-faq-a", + "Leave it ", + strong("empty"), + " to use all ~15K genes from DepMap (recommended for most users). Specify a subset only if you want to restrict feature selection to known biomarkers." ) ), - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " Download fails for DepMap or models?"), - div(class = "help-faq-a", - "Enable the ", strong("Mirror"), " checkbox (default ON) to use mirror download. If still failing, download the files manually from GitHub Releases and use the file upload option." + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " Download fails for DepMap or models?" + ), + div( + class = "help-faq-a", + "Enable the ", + strong("Mirror"), + " checkbox (default ON) to use mirror download. If still failing, download the files manually from GitHub Releases and use the file upload option." ) ), - div(class = "help-faq-item", - div(class = "help-faq-q", icon("question-circle"), " Why doesn't the interface freeze during training / clustering / prediction?"), - div(class = "help-faq-a", - "All heavy computation (model training, Seurat clustering, prediction, plot math) runs in ", strong("background worker processes"), ", not in the interface. The UI polls and shows progress, so other pages stay responsive. If a worker ever stops unexpectedly, the app shows \"Background worker stopped\" instead of spinning forever — just submit again." + div( + class = "help-faq-item", + div( + class = "help-faq-q", + icon("question-circle"), + " Why doesn't the interface freeze during training / clustering / prediction?" + ), + div( + class = "help-faq-a", + "All heavy computation (model training, Seurat clustering, prediction, plot math) runs in ", + strong("background worker processes"), + ", not in the interface. The UI polls and shows progress, so other pages stay responsive. If a worker ever stops unexpectedly, the app shows \"Background worker stopped\" instead of spinning forever — just submit again." ) ) ) ), # Citation - div(id = ns("section_citation"), class = "help-ref-section", - div(class = "help-section-header", + div( + id = ns("section_citation"), + class = "help-ref-section", + div( + class = "help-section-header", div(class = "help-section-icon", icon("book-open")), div( h5("Citation"), - p(class = "help-subtitle", "If you use this package, please cite both the package and the original PERCEPTION study:") + p( + class = "help-subtitle", + "If you use this package, please cite both the package and the original PERCEPTION study:" + ) ) ), - div(class = "citation-box", + div( + class = "citation-box", strong("Jia Ding."), " PERCEPTIONx: Personalized Drug Response Prediction from Single-Cell Transcriptomics. R package version ", - pkg_ver, ". ", - a("https://github.com/WangLabCSU/PERCEPTIONx", + pkg_ver, + ". ", + a( + "https://github.com/WangLabCSU/PERCEPTIONx", href = "https://github.com/WangLabCSU/PERCEPTIONx", - target = "_blank"), - br(), br(), + target = "_blank" + ), + br(), + br(), strong("Sinha, S., Vegesna, R., Mukherjee, S."), " et al. PERCEPTION predicts patient response and resistance to treatment using single-cell transcriptomics of their tumors. ", - em("Nat Cancer"), " 5, 938-952 (2024). ", - a("DOI: 10.1038/s43018-024-00756-7", + em("Nat Cancer"), + " 5, 938-952 (2024). ", + a( + "DOI: 10.1038/s43018-024-00756-7", href = "https://doi.org/10.1038/s43018-024-00756-7", - target = "_blank") + target = "_blank" + ) ) ) ) @@ -385,13 +713,16 @@ mod_help_server <- function(id, main_session, shared) { # --- Supported Drugs: searchable catalogue (44 pre-trained marked) ---- # Debounce the search box so the (possibly 1,448-entry) grid is only # re-rendered after the user pauses typing. - search_q <- debounce(reactive({ - if (is.null(input$drug_search)) { - "" - } else { - trimws(input$drug_search) - } - }), 250) + search_q <- debounce( + reactive({ + if (is.null(input$drug_search)) { + "" + } else { + trimws(input$drug_search) + } + }), + 250 + ) output$drug_results <- renderUI({ pt_all <- tolower(PERCEPTIONx:::perception_all_drugs) @@ -410,16 +741,24 @@ mod_help_server <- function(id, main_session, shared) { ftype <- if (is.null(input$drug_filter)) "pt" else input$drug_filter q <- search_q() - sel <- switch(ftype, - pt = all[tolower(all) %in% pt_all], - fda = all[tolower(all) %in% fda_all], + sel <- switch( + ftype, + pt = all[tolower(all) %in% pt_all], + fda = all[tolower(all) %in% fda_all], demo = all[tolower(all) %in% demo], - all = all) - if (nzchar(q)) sel <- sel[grepl(tolower(q), tolower(sel), fixed = TRUE)] + all = all + ) + if (nzchar(q)) { + sel <- sel[grepl(tolower(q), tolower(sel), fixed = TRUE)] + } if (length(sel) == 0) { - return(div(class = "text-muted", style = "text-align: center; padding: 1.2rem;", - icon("magnifying-glass"), " No compound matches your search.")) + return(div( + class = "text-muted", + style = "text-align: center; padding: 1.2rem;", + icon("magnifying-glass"), + " No compound matches your search." + )) } mk_badges <- function(d) { @@ -430,25 +769,43 @@ mod_help_server <- function(id, main_session, shared) { # reads at a glance (e.g. which FDA drugs already have a model). bd <- list() if (is_fda) { - bd <- c(bd, list(tags$span(class = "help-drug-badge help-drug-badge-fda", "FDA"))) + bd <- c( + bd, + list(tags$span( + class = "help-drug-badge help-drug-badge-fda", + "FDA" + )) + ) } if (is_pt) { bd <- c(bd, list(tags$span(class = "help-drug-badge", "PRE"))) } if (is_demo) { - bd <- c(bd, list(tags$span(class = "help-drug-badge help-drug-badge-demo", "demo"))) + bd <- c( + bd, + list(tags$span( + class = "help-drug-badge help-drug-badge-demo", + "demo" + )) + ) } if (length(bd)) div(class = "help-drug-cell-badges", bd) } items <- lapply(sel, function(d) { - div(class = "help-drug-cell", title = d, + div( + class = "help-drug-cell", + title = d, span(class = "help-drug-cell-name", d), - mk_badges(d)) + mk_badges(d) + ) }) count_note <- if (ftype == "all" && !nzchar(q)) { - sprintf("%s compounds in the DepMap screen (%d pre-trained).", - prettyNum(length(sel), big.mark = ","), sum(tolower(sel) %in% pt_all)) + sprintf( + "%s compounds in the DepMap screen (%d pre-trained).", + prettyNum(length(sel), big.mark = ","), + sum(tolower(sel) %in% pt_all) + ) } else { if (length(sel) == 1) { plural <- "" @@ -460,8 +817,7 @@ mod_help_server <- function(id, main_session, shared) { tagList( div(class = "help-drug-count", icon("filter"), " ", count_note), - div(class = "help-drug-list", - div(class = "help-drug-grid", items)) + div(class = "help-drug-list", div(class = "help-drug-grid", items)) ) }) @@ -486,7 +842,8 @@ mod_help_server <- function(id, main_session, shared) { } # Small example table card (mimics the Data-tab previews) tw_tbl <- function(title, note, headers, rows) { - div(class = "tw-tbl-card", + div( + class = "tw-tbl-card", strong(title), tags$table( tags$thead(tags$tr(lapply(headers, tags$th))), @@ -496,9 +853,18 @@ mod_help_server <- function(id, main_session, shared) { ) } - tw_slide <- function(img, kicker, title, paras, points = NULL, - note = NULL, warn = NULL, chips = NULL, - layout = c("lr", "tb"), big = NA) { + tw_slide <- function( + img, + kicker, + title, + paras, + points = NULL, + note = NULL, + warn = NULL, + chips = NULL, + layout = c("lr", "tb"), + big = NA + ) { layout <- match.arg(layout) imgs <- if (is.null(img)) character(0) else img imgs <- imgs[nzchar(imgs)] @@ -512,18 +878,27 @@ mod_help_server <- function(id, main_session, shared) { # Header is a fixed zone ABOVE the body so every slide keeps its # step caption + title pinned to the same top-left spot (no vertical # drift between sparse and dense pages). - slide_head <- div(class = "tw-slide-head", + slide_head <- div( + class = "tw-slide-head", div(class = "tw-slide-kicker", kicker), h4(title) ) body_text <- tagList( lapply(paras, function(t) if (is.character(t)) p(t) else t), - if (!is.null(chips)) div(class = "tw-chips", - lapply(chips, function(cp) { - if (is.character(cp)) tags$span(class = "tw-chip", cp) else cp - })), - if (!is.null(points)) tags$ul(class = "tw-points", - lapply(points, function(x) if (is.character(x)) tags$li(x) else x)), + if (!is.null(chips)) { + div( + class = "tw-chips", + lapply(chips, function(cp) { + if (is.character(cp)) tags$span(class = "tw-chip", cp) else cp + }) + ) + }, + if (!is.null(points)) { + tags$ul( + class = "tw-points", + lapply(points, function(x) if (is.character(x)) tags$li(x) else x) + ) + }, # A quiet bottom line (no boxed "warning" component). if (!is.null(warn)) div(class = "tw-warn", icon("circle-info"), warn) ) @@ -535,13 +910,19 @@ mod_help_server <- function(id, main_session, shared) { } else { "tw-slide-body" } - body_children <- if (has_img && layout == "tb") list(figs, text_col) else list(text_col, figs) + body_children <- if (has_img && layout == "tb") { + list(figs, text_col) + } else { + list(text_col, figs) + } # Only slides explicitly marked `big` get the enlarged base font (the # auto word-count heuristic is disabled to avoid any runtime surprises). is_big <- !is.na(big) && isTRUE(big) - div(class = if (is_big) "tw-slide tw-big" else "tw-slide", + div( + class = if (is_big) "tw-slide tw-big" else "tw-slide", slide_head, - div(class = body_class, body_children)) + div(class = body_class, body_children) + ) } # Builds and opens the centered slideshow modal. @@ -555,27 +936,42 @@ mod_help_server <- function(id, main_session, shared) { }) close_req <- ns("tw_close") body <- div( - id = root_id, class = "tw-root", - div(class = "tw-topbar", + id = root_id, + class = "tw-root", + div( + class = "tw-topbar", div(class = "tw-topbar-title", icon("graduation-cap"), header), - span(class = "tw-close", title = "Close", - onclick = sprintf("Shiny.setInputValue('%s', 1, {priority:'event'});", close_req), - icon("xmark")) - ), - div(class = "tw-stages", - div(class = "tw-count", ""), - slides_html + span( + class = "tw-close", + title = "Close", + onclick = sprintf( + "Shiny.setInputValue('%s', 1, {priority:'event'});", + close_req + ), + icon("xmark") + ) ), - div(class = "tw-nav", - tags$button(type = "button", class = "tw-btn tw-prev", - icon("chevron-left"), " Back"), - div(class = "tw-dots", + div(class = "tw-stages", div(class = "tw-count", ""), slides_html), + div( + class = "tw-nav", + tags$button( + type = "button", + class = "tw-btn tw-prev", + icon("chevron-left"), + " Back" + ), + div( + class = "tw-dots", lapply(seq_along(pages), function(k) { span(class = "tw-dot", `data-i` = k - 1L) }) ), - tags$button(type = "button", class = "tw-btn tw-next tw-btn-primary", - "Next ", icon("chevron-right")) + tags$button( + type = "button", + class = "tw-btn tw-next tw-btn-primary", + "Next ", + icon("chevron-right") + ) ), tags$script(HTML(sprintf( "(function(){\n @@ -609,117 +1005,276 @@ mod_help_server <- function(id, main_session, shared) { while((nn=walker.nextNode())){ if(nn.nodeValue.trim()==='') drop.push(nn); }\n for(var d=0;d Pre-trained Models > select drugs (multi-select) > Download & Load.")), - div(class = "tw-choice", + p( + "Data tab > Pre-trained Models > select drugs (multi-select) > Download & Load." + ) + ), + div( + class = "tw-choice", div(class = "tw-choice-title", icon("hammer"), "Not in the 44"), - p(tw_r("Download & Load DepMap"), " > train it on the Train tab."))), - p("Every model you download or train lands in ", tw_r("Loaded Models Management"), " on the Data tab, where you can tick which ones stay active."), - p("Supported Drugs on the Help page lists the full catalogue, with the 44 marked.")), - layout = "lr"), - tw_slide("figures/model_roc.png", - "Step 4 of 7 \u00b7 Train tab (outside the 44)", "Train and Evaluate Your Own Model", - list(p("If your drug is not in the 44 pre-trained models, check the Supported Drugs list in the Help page. If it is there, download the DepMap data we provide and train the drug on the Train tab."), - p("Training generates a ", tw_b("Validation ROC"), " and a ", tw_b("Model Performance"), " plot, so you can judge how accurate the model is.")), - layout = "tb"), - tw_slide("figures/predict.png", - "Step 5 of 7 \u00b7 Predict tab", "Run Prediction: Your Result is Here", - list(p("On the Predict tab, click ", tw_r("Run Prediction"), ". You get a clone-level table and heatmap, plus patient-level predictions."), - p("Prediction uses the active models and prepared expression from the Loaded Models Management."), - p("For the Aggregation Mode, use ", tw_b("Weighted Max (recommended)"), ". The other modes are explained in the Help page."))), - tw_slide("figures/plot_gallery.png", - "Step 6 of 7 \u00b7 Visualize tab", "Dive Deeper with More Plots", - list(p("Click any plot card to draw it."), - p("Every plot shows its explanation in the ", tw_b("About This Plot"), " card above it."), - p("Adjust the figure size, text and DPI before exporting."), - p("Plots that compare drugs come with a drug switcher, set to ", tw_r("Combination"), - " by default (the ensemble prediction across all drugs)."))), - tw_slide("figures/help.png", - "Step 7 of 7 \u00b7 Help & resources", "More details live in the Help page", - list(p("The Help page still has more for you: aggregation modes, data formats, every parameter, the full drug list and the FAQ."), - p("Explore at your own pace, and have fun with your data! 🎉")), + p(tw_r("Download & Load DepMap"), " > train it on the Train tab.") + ) + ), + p( + "Every model you download or train lands in ", + tw_r("Loaded Models Management"), + " on the Data tab, where you can tick which ones stay active." + ), + p( + "Supported Drugs on the Help page lists the full catalogue, with the 44 marked." + ) + ), + layout = "lr" + ), + tw_slide( + "figures/model_roc.png", + "Step 4 of 7 \u00b7 Train tab (outside the 44)", + "Train and Evaluate Your Own Model", + list( + p( + "If your drug is not in the 44 pre-trained models, check the Supported Drugs list in the Help page. If it is there, download the DepMap data we provide and train the drug on the Train tab." + ), + p( + "Training generates a ", + tw_b("Validation ROC"), + " and a ", + tw_b("Model Performance"), + " plot, so you can judge how accurate the model is." + ) + ), + layout = "tb" + ), + tw_slide( + "figures/predict.png", + "Step 5 of 7 \u00b7 Predict tab", + "Run Prediction: Your Result is Here", + list( + p( + "On the Predict tab, click ", + tw_r("Run Prediction"), + ". You get a clone-level table and heatmap, plus patient-level predictions." + ), + p( + "Prediction uses the active models and prepared expression from the Loaded Models Management." + ), + p( + "For the Aggregation Mode, use ", + tw_b("Weighted Max (recommended)"), + ". The other modes are explained in the Help page." + ) + ) + ), + tw_slide( + "figures/plot_gallery.png", + "Step 6 of 7 \u00b7 Visualize tab", + "Dive Deeper with More Plots", + list( + p("Click any plot card to draw it."), + p( + "Every plot shows its explanation in the ", + tw_b("About This Plot"), + " card above it." + ), + p("Adjust the figure size, text and DPI before exporting."), + p( + "Plots that compare drugs come with a drug switcher, set to ", + tw_r("Combination"), + " by default (the ensemble prediction across all drugs)." + ) + ) + ), + tw_slide( + "figures/help.png", + "Step 7 of 7 \u00b7 Help & resources", + "More details live in the Help page", + list( + p( + "The Help page still has more for you: aggregation modes, data formats, every parameter, the full drug list and the FAQ." + ), + p("Explore at your own pace, and have fun with your data! 🎉") + ), big = TRUE ) ) @@ -728,10 +1283,16 @@ mod_help_server <- function(id, main_session, shared) { tw_walkthrough(ns("tour_demo_root"), "Demo walkthrough", demo_pages) }) observeEvent(input$tour_advanced, { - tw_walkthrough(ns("tour_adv_root"), "Your own data walkthrough", adv_pages) + tw_walkthrough( + ns("tour_adv_root"), + "Your own data walkthrough", + adv_pages + ) }) # Close (X button or "Finish" on the last slide) of either walkthrough. - observeEvent(input$tw_close, { removeModal() }) + observeEvent(input$tw_close, { + removeModal() + }) # Section navigation scroll - use namespaced IDs observeEvent(input$nav_overview, { diff --git a/inst/shiny/app/R/mod_home.R b/inst/shiny/app/R/mod_home.R index 246cfe4..1464583 100644 --- a/inst/shiny/app/R/mod_home.R +++ b/inst/shiny/app/R/mod_home.R @@ -7,54 +7,85 @@ mod_home_ui <- function(id) { empty_state <- list() tagList( # Hero Section — Lightweight ERV-Atlas-Style Banner - div(class = "hero", - div(class = "hero-inner", - div(class = "hero-text", - div(class = "hero-title-row", + div( + class = "hero", + div( + class = "hero-inner", + div( + class = "hero-text", + div( + class = "hero-title-row", h1(class = "hero-title", "PERCEPTION-shiny") ), - p(class = "hero-tagline", + p( + class = "hero-tagline", "From single-cell transcriptomics to precision oncology." ), - p(class = "hero-desc", + p( + class = "hero-desc", "PERCEPTION (PERsonalized single-Cell Expression-based Planning for Treatments In ONcology) ", "predicts patient response and resistance to cancer treatment using single-cell expression profiles. ", "It trains elastic-net models on DepMap cell-line data, then applies them to patient single-cell data ", "for clone-level drug sensitivity and patient-level response stratification." ), - div(class = "hero-actions", - actionButton(ns("go_data"), "Quick Start", class = "btn-hero-primary", icon = icon("rocket")), - actionButton(ns("go_demo"), "Load Demo", class = "btn-hero-secondary", icon = icon("flask"), - onclick = "document.getElementById('demo-overlay').style.display='flex';"), - tags$a(href = "https://wanglabcsu.github.io/PERCEPTIONx/articles/shiny_app.html", - target = "_blank", class = "btn-hero-secondary", - icon("book-open"), " Tutorial") + div( + class = "hero-actions", + actionButton( + ns("go_data"), + "Quick Start", + class = "btn-hero-primary", + icon = icon("rocket") + ), + actionButton( + ns("go_demo"), + "Load Demo", + class = "btn-hero-secondary", + icon = icon("flask"), + onclick = "document.getElementById('demo-overlay').style.display='flex';" + ), + tags$a( + href = "https://wanglabcsu.github.io/PERCEPTIONx/articles/shiny_app.html", + target = "_blank", + class = "btn-hero-secondary", + icon("book-open"), + " Tutorial" + ) ) ), - div(class = "hero-brand", - div(class = "hero-logo", + div( + class = "hero-brand", + div( + class = "hero-logo", # Inlined data URI — see perception_favicon_uri() in app.R (no # external asset requests, works under Shiny Server without www/). - tags$img(src = perception_favicon_uri(), alt = "PERCEPTION-shiny logo") + tags$img( + src = perception_favicon_uri(), + alt = "PERCEPTION-shiny logo" + ) ) ) ) ), # Stat Cards — aligned with hero-inner (max-width 1200px, centered) - fluidRow(style = "padding: 1.5rem 0 0.5rem;", - div(class = "stat-grid", - div(class = "stat-card stat-blue animate-fade-in-up delay-1", + fluidRow( + style = "padding: 1.5rem 0 0.5rem;", + div( + class = "stat-grid", + div( + class = "stat-card stat-blue animate-fade-in-up delay-1", div(class = "stat-icon", icon("dna")), div(class = "stat-value", "15K+"), div(class = "stat-label", "DepMap Genes") ), - div(class = "stat-card stat-teal animate-fade-in-up delay-2", + div( + class = "stat-card stat-teal animate-fade-in-up delay-2", div(class = "stat-icon", icon("table-cells")), div(class = "stat-value", "Single-Cell"), div(class = "stat-label", "Resolution") ), - div(class = "stat-card stat-amber animate-fade-in-up delay-3", + div( + class = "stat-card stat-amber animate-fade-in-up delay-3", div(class = "stat-icon", icon("pills")), div(class = "stat-value", "44"), div(class = "stat-label", "Pretrained Drug Models") @@ -65,111 +96,156 @@ mod_home_ui <- function(id) { hr(class = "section-divider"), # Guided Workflow — live pipeline stepper (state derives from shared data) - fluidRow(style = "padding: 0 2rem;", - div(class = "section-header animate-fade-in", + fluidRow( + style = "padding: 0 2rem;", + div( + class = "section-header animate-fade-in", icon("route"), h4("Pipeline — Where You Are"), - p(class = "text-muted animate-fade-in", style = "font-size: 0.88rem; margin: 0.2rem 0 0 auto;", - "Status updates live as you load data, train and predict. Click any step to jump to it.") + p( + class = "text-muted animate-fade-in", + style = "font-size: 0.88rem; margin: 0.2rem 0 0 auto;", + "Status updates live as you load data, train and predict. Click any step to jump to it." + ) ), - div(class = "card animate-fade-in-up", - div(id = ns("workflow_stepper"), - workflow_stepper_html(empty_state, ns)) + div( + class = "card animate-fade-in-up", + div(id = ns("workflow_stepper"), workflow_stepper_html(empty_state, ns)) ) ), hr(class = "section-divider"), # Data Status Dashboard — real-time overview - div(class = "data-status-section", - div(class = "section-header animate-fade-in", + div( + class = "data-status-section", + div( + class = "section-header animate-fade-in", icon("dashboard"), h4("Data Status"), - p(class = "text-muted animate-fade-in", style = "font-size: 0.88rem; margin: 0.2rem 0 0 auto;", - "Real-time overview of loaded data.") + p( + class = "text-muted animate-fade-in", + style = "font-size: 0.88rem; margin: 0.2rem 0 0 auto;", + "Real-time overview of loaded data." + ) ), - div(id = ns("data_dashboard"), - data_dashboard_html(empty_state)) + div(id = ns("data_dashboard"), data_dashboard_html(empty_state)) ), hr(class = "section-divider"), # Key Features - fluidRow(style = "padding: 0 2rem 1rem;", - div(class = "section-header animate-fade-in", + fluidRow( + style = "padding: 0 2rem 1rem;", + div( + class = "section-header animate-fade-in", icon("star"), h4("Key Features") ), - div(class = "feature-grid", - div(class = "feature-card card-red animate-fade-in-up delay-1", + div( + class = "feature-grid", + div( + class = "feature-card card-red animate-fade-in-up delay-1", div(class = "feature-icon icon-red", icon("cloud-arrow-down")), h5("DepMap Integration"), - p("Seamlessly load and cache DepMap cell line expression and drug response data for model training.") + p( + "Seamlessly load and cache DepMap cell line expression and drug response data for model training." + ) ), - div(class = "feature-card card-purple animate-fade-in-up delay-2", + div( + class = "feature-card card-purple animate-fade-in-up delay-2", div(class = "feature-icon icon-purple", icon("code-branch")), h5("Elastic Net & Random Forest"), - p("Train drug response models using glmnet (elastic net) or random forest with cross-validated hyperparameter tuning.") + p( + "Train drug response models using glmnet (elastic net) or random forest with cross-validated hyperparameter tuning." + ) ), - div(class = "feature-card card-blue animate-fade-in-up delay-3", + div( + class = "feature-card card-blue animate-fade-in-up delay-3", div(class = "feature-icon icon-blue", icon("dna")), h5("Clone-Level Prediction"), - p("Predict drug sensitivity at single-cell clone resolution, then aggregate to patient-level response.") + p( + "Predict drug sensitivity at single-cell clone resolution, then aggregate to patient-level response." + ) ), - div(class = "feature-card card-amber animate-fade-in-up delay-4", + div( + class = "feature-card card-amber animate-fade-in-up delay-4", div(class = "feature-icon icon-amber", icon("palette")), h5("Rich Visualization"), - p("Generate UMAP plots, clone distribution stacks, ROC curves, and comprehensive patient response panels.") + p( + "Generate UMAP plots, clone distribution stacks, ROC curves, and comprehensive patient response panels." + ) ) ) ), # Citation & Repository - fluidRow(style = "padding: 0 2rem 3rem;", - div(class = "section-header animate-fade-in", + fluidRow( + style = "padding: 0 2rem 3rem;", + div( + class = "section-header animate-fade-in", icon("book-open"), h4("Citation & Repository") ), - div(class = "citation-box animate-fade-in", - div(class = "citation-row", - div(class = "citation-col", - div(class = "citation-item", + div( + class = "citation-box animate-fade-in", + div( + class = "citation-row", + div( + class = "citation-col", + div( + class = "citation-item", h6(icon("file-lines"), " Original Paper"), p( strong("Sinha, S., Vegesna, R., Mukherjee, S."), " et al. PERCEPTION predicts patient response and resistance to treatment using single-cell transcriptomics of their tumors. ", - em("Nat Cancer"), " 5, 938-952 (2024). ", + em("Nat Cancer"), + " 5, 938-952 (2024). ", br(), - a("DOI: 10.1038/s43018-024-00756-7", + a( + "DOI: 10.1038/s43018-024-00756-7", href = "https://doi.org/10.1038/s43018-024-00756-7", - target = "_blank") + target = "_blank" + ) ) ), - div(class = "citation-item", + div( + class = "citation-item", h6(icon("code-branch"), " Original Codebase"), p( icon("github"), " ", - a("github.com/ruppinlab/PERCEPTION", + a( + "github.com/ruppinlab/PERCEPTION", href = "https://github.com/ruppinlab/PERCEPTION", - target = "_blank"), - tags$small(" (original Python implementation by Sinha et al.)", - class = "text-muted") + target = "_blank" + ), + tags$small( + " (original Python implementation by Sinha et al.)", + class = "text-muted" + ) ) ) ), - div(class = "citation-col", - div(class = "citation-item", + div( + class = "citation-col", + div( + class = "citation-item", h6(icon("box-open"), " R Package Repository"), p( icon("github"), " ", - a("github.com/WangLabCSU/PERCEPTIONx", + a( + "github.com/WangLabCSU/PERCEPTIONx", href = "https://github.com/WangLabCSU/PERCEPTIONx", - target = "_blank"), + target = "_blank" + ), br(), - tags$small("Install with: ", code("remotes::install_github('WangLabCSU/PERCEPTIONx')"), - class = "text-muted") + tags$small( + "Install with: ", + code("remotes::install_github('WangLabCSU/PERCEPTIONx')"), + class = "text-muted" + ) ) ) ) @@ -183,11 +259,30 @@ mod_home_server <- function(id, shared, main_session) { moduleServer(id, function(input, output, session) { ns <- session$ns # Navigation buttons — use main session for cross-module nav - observeEvent(input$go_data, bslib::nav_select("navbar", selected = "data", session = main_session)) - observeEvent(input$wf_1, bslib::nav_select("navbar", selected = "data", session = main_session)) - observeEvent(input$wf_2, bslib::nav_select("navbar", selected = "train", session = main_session)) - observeEvent(input$wf_3, bslib::nav_select("navbar", selected = "predict", session = main_session)) - observeEvent(input$wf_4, bslib::nav_select("navbar", selected = "visualize", session = main_session)) + observeEvent( + input$go_data, + bslib::nav_select("navbar", selected = "data", session = main_session) + ) + observeEvent( + input$wf_1, + bslib::nav_select("navbar", selected = "data", session = main_session) + ) + observeEvent( + input$wf_2, + bslib::nav_select("navbar", selected = "train", session = main_session) + ) + observeEvent( + input$wf_3, + bslib::nav_select("navbar", selected = "predict", session = main_session) + ) + observeEvent( + input$wf_4, + bslib::nav_select( + "navbar", + selected = "visualize", + session = main_session + ) + ) # Live workflow stepper — step states are derived directly from the shared # data so the pipeline tracker updates the moment anything is loaded. @@ -195,10 +290,13 @@ mod_home_server <- function(id, shared, main_session) { # shared state changes (no initial server round trip on first paint). observe({ state <- reactiveValuesToList(shared) - session$sendCustomMessage("set-html", list( - id = ns("workflow_stepper"), - html = as.character(workflow_stepper_html(state, ns)) - )) + session$sendCustomMessage( + "set-html", + list( + id = ns("workflow_stepper"), + html = as.character(workflow_stepper_html(state, ns)) + ) + ) }) # Load Demo Data — full pipeline, via the shared helper (same code path @@ -207,24 +305,36 @@ mod_home_server <- function(id, shared, main_session) { if (isTRUE(shared$demo_busy)) { # Overlay was shown by onclick — hide it again since nothing new starts. session$sendCustomMessage("hide-demo-overlay", list()) - showNotification("Demo data is already being prepared...", type = "warning", duration = 5) + showNotification( + "Demo data is already being prepared...", + type = "warning", + duration = 5 + ) return() } shared$demo_busy <- TRUE - run_demo_pipeline(shared, session, on_success = function() { - shared$demo_loaded <- TRUE - shared$demo_busy <- FALSE - bslib::nav_select("navbar", selected = "data", session = main_session) - }, on_error = function() shared$demo_busy <- FALSE) + run_demo_pipeline( + shared, + session, + on_success = function() { + shared$demo_loaded <- TRUE + shared$demo_busy <- FALSE + bslib::nav_select("navbar", selected = "data", session = main_session) + }, + on_error = function() shared$demo_busy <- FALSE + ) }) # Data Status Dashboard — real-time overview observe({ state <- reactiveValuesToList(shared) - session$sendCustomMessage("set-html", list( - id = ns("data_dashboard"), - html = as.character(data_dashboard_html(state)) - )) + session$sendCustomMessage( + "set-html", + list( + id = ns("data_dashboard"), + html = as.character(data_dashboard_html(state)) + ) + ) }) }) } diff --git a/inst/shiny/app/R/mod_predict.R b/inst/shiny/app/R/mod_predict.R index fbca250..b7adbab 100644 --- a/inst/shiny/app/R/mod_predict.R +++ b/inst/shiny/app/R/mod_predict.R @@ -5,18 +5,27 @@ # round trip). The server just clears — or restores — them via the 'set-html' # handler once predictions exist. clone_desc_html <- function() { - div(class = "card-desc", - icon("fire", style = "font-size: 2rem; opacity: 0.3; display: block; margin-bottom: 0.35rem;"), + div( + class = "card-desc", + icon( + "fire", + style = "font-size: 2rem; opacity: 0.3; display: block; margin-bottom: 0.35rem;" + ), "Predicted viability of every clone per drug (higher = more resistant).", br(), "Select model & expression sources, then click ", - strong("Run Prediction"), "." + strong("Run Prediction"), + "." ) } patient_desc_html <- function() { - div(class = "card-desc", - icon("user", style = "font-size: 2rem; opacity: 0.3; display: block; margin-bottom: 0.35rem;"), + div( + class = "card-desc", + icon( + "user", + style = "font-size: 2rem; opacity: 0.3; display: block; margin-bottom: 0.35rem;" + ), "Clone viabilities aggregated per patient (weighted_max).", br(), "Appears here after running prediction." @@ -27,43 +36,54 @@ mod_predict_ui <- function(id) { ns <- NS(id) tagList( fluidRow( - column(12, - div(class = "section-header", + column( + 12, + div( + class = "section-header", icon("microscope"), h4("Drug Response Prediction") ), - div(class = "info-box", - icon("info-circle"), " Predict drug sensitivity at clone level using trained models, ", + div( + class = "info-box", + icon("info-circle"), + " Predict drug sensitivity at clone level using trained models, ", "then aggregate to patient-level response using weighted averaging strategies. ", - strong("Viability semantics:"), " higher viability = more resistant (less sensitive); ", + strong("Viability semantics:"), + " higher viability = more resistant (less sensitive); ", "lower viability = more sensitive (stronger drug killing)." ) ) ), # Prerequisites check - fluidRow(style = "margin-top: 1rem;", - column(12, - uiOutput(ns("prereq_check")) - ) + fluidRow( + style = "margin-top: 1rem;", + column(12, uiOutput(ns("prereq_check"))) ), - fluidRow(style = "margin-top: 0.5rem;", + fluidRow( + style = "margin-top: 0.5rem;", # Configuration - column(4, class = "predict-config-col", - div(class = "card", - div(class = "card-header", - icon("cog"), " Configuration" - ), - div(class = "card-body", + column( + 4, + class = "predict-config-col", + div( + class = "card", + div(class = "card-header", icon("cog"), " Configuration"), + div( + class = "card-body", # Sources — single source of truth: models & expression come from # the Data tab (management-integrated), never uploaded here. - div(class = "param-section", + div( + class = "param-section", h6(class = "param-section-title", icon("link"), " Sources"), - div(class = "info-box", style = "margin-top: 0.2rem; font-size: 0.78rem;", + div( + class = "info-box", + style = "margin-top: 0.2rem; font-size: 0.78rem;", icon("circle-info"), " Prediction runs on the ", - strong("active models"), " from the Data tab (Loaded Models Management) ", + strong("active models"), + " from the Data tab (Loaded Models Management) ", "and the expression data prepared there. Load, upload or train ", "models on the Data / Train tabs - every uploaded .RDS appears ", "in the management list automatically." @@ -71,50 +91,76 @@ mod_predict_ui <- function(id) { ), # Aggregation mode - div(class = "param-section", - h6(class = "param-section-title", icon("layer-group"), " Patient Aggregation"), - selectInput(ns("agg_mode"), "Aggregation Mode", - choices = c( - "Weighted Max (recommended)" = "weighted_max", - "Weighted Average" = "weighted_average", - "Min (Most Sensitive)" = "min", - "Max (Most Resistant)" = "max" - ), - selected = "weighted_max"), - div(class = "info-box", style = "margin-top: 0.5rem; font-size: 0.78rem;", - strong("weighted_max"), ": maximum clone viability weighted by clone proportion (recommended)", - br(), strong("weighted_average"), ": weighted average across all clones", - br(), strong("min/max"), ": most sensitive/resistant clone" + div( + class = "param-section", + h6( + class = "param-section-title", + icon("layer-group"), + " Patient Aggregation" + ), + selectInput( + ns("agg_mode"), + "Aggregation Mode", + choices = c( + "Weighted Max (recommended)" = "weighted_max", + "Weighted Average" = "weighted_average", + "Min (Most Sensitive)" = "min", + "Max (Most Resistant)" = "max" + ), + selected = "weighted_max" + ), + div( + class = "info-box", + style = "margin-top: 0.5rem; font-size: 0.78rem;", + strong("weighted_max"), + ": maximum clone viability weighted by clone proportion (recommended)", + br(), + strong("weighted_average"), + ": weighted average across all clones", + br(), + strong("min/max"), + ": most sensitive/resistant clone" ) ), hr(), - actionButton(ns("predict"), "Run Prediction", - class = "btn-primary", icon = icon("play")) + actionButton( + ns("predict"), + "Run Prediction", + class = "btn-primary", + icon = icon("play") + ) ) ) ), # Results - column(8, class = "predict-results-col", + column( + 8, + class = "predict-results-col", # Clone-level heatmap - div(class = "card", - div(class = "card-header", - icon("fire"), " Clone-Level Predictions" - ), - div(class = "card-body", + div( + class = "card", + div(class = "card-header", icon("fire"), " Clone-Level Predictions"), + div( + class = "card-body", div(id = ns("clone_desc"), clone_desc_html()), uiOutput(ns("clone_heatmap_area")) ) ), # Patient-level table - div(class = "card", style = "margin-top: 1rem;", - div(class = "card-header", - icon("user"), " Patient-Level Predictions" + div( + class = "card", + style = "margin-top: 1rem;", + div( + class = "card-header", + icon("user"), + " Patient-Level Predictions" ), - div(class = "card-body", + div( + class = "card-body", div(id = ns("patient_desc"), patient_desc_html()), uiOutput(ns("patient_table_area")), uiOutput(ns("patient_download")) @@ -135,23 +181,39 @@ mod_predict_server <- function(id, shared, main_session) { # Prerequisites check output$prereq_check <- renderUI({ missing <- c() - if (is.null(shared$models)) missing <- c(missing, "Trained Model") + if (is.null(shared$models)) { + missing <- c(missing, "Trained Model") + } if (is.null(shared$prepared_data) && is.null(shared$user_expr)) { missing <- c(missing, "Expression Data") } if (is.null(shared$prepared_data) && is.null(shared$user_clones)) { - missing <- c(missing, "Clone Annotation (run Seurat clustering in Data tab)") + missing <- c( + missing, + "Clone Annotation (run Seurat clustering in Data tab)" + ) } if (length(missing) > 0) { - div(class = "info-box", style = "border-left-color: var(--accent);", - icon("exclamation-triangle"), " Missing prerequisites: ", + div( + class = "info-box", + style = "border-left-color: var(--accent);", + icon("exclamation-triangle"), + " Missing prerequisites: ", strong(paste(missing, collapse = ", ")), ". Please load data first (Data tab) or use 'Load Demo Data'.", - actionButton(ns("go_data"), "Go to Data", class = "btn-accent btn-sm", style = "margin-left: 0.5rem;") + actionButton( + ns("go_data"), + "Go to Data", + class = "btn-accent btn-sm", + style = "margin-left: 0.5rem;" + ) ) } else { - div(class = "info-box", style = "border-left-color: var(--success);", - icon("check-circle"), " All prerequisites loaded. Ready to predict!" + div( + class = "info-box", + style = "border-left-color: var(--success);", + icon("check-circle"), + " All prerequisites loaded. Ready to predict!" ) } }) @@ -168,7 +230,11 @@ mod_predict_server <- function(id, shared, main_session) { # Data tab. The raw cell-level user_expr is NOT rank-normalized and would # produce unreliable predictions. current_expr <- reactive({ - if (is.null(shared$prepared_data)) NULL else shared$prepared_data$clone_expression_rnorm + if (is.null(shared$prepared_data)) { + NULL + } else { + shared$prepared_data$clone_expression_rnorm + } }) # Run prediction — submitted to the background per-session worker. The @@ -184,8 +250,12 @@ mod_predict_server <- function(id, shared, main_session) { # or the Predict tab keeps showing stale results that contradict the # global state (e.g. "Predictions Not loaded" in the sidebar). observe({ - if (is.null(shared$predictions) && !is.null(clone_pred())) clone_pred(NULL) - if (is.null(shared$patient_pred) && !is.null(patient_pred())) patient_pred(NULL) + if (is.null(shared$predictions) && !is.null(clone_pred())) { + clone_pred(NULL) + } + if (is.null(shared$patient_pred) && !is.null(patient_pred())) { + patient_pred(NULL) + } }) observeEvent(input$predict, { @@ -195,20 +265,35 @@ mod_predict_server <- function(id, shared, main_session) { # Completely empty state: point the user somewhere actionable instead of # a generic "no model" / "no data" pair. if (is.null(model) && is.null(expr)) { - showNotification("No model or expression data loaded yet — use 'Load Demo Data' or upload your data in the Data tab first.", - type = "warning", duration = 8) + showNotification( + "No model or expression data loaded yet — use 'Load Demo Data' or upload your data in the Data tab first.", + type = "warning", + duration = 8 + ) return() } if (is.null(model)) { - showNotification("No model available. Train or upload a model first.", type = "error", duration = 8) + showNotification( + "No model available. Train or upload a model first.", + type = "error", + duration = 8 + ) return() } if (is.null(expr)) { - showNotification("No expression data available. Load or upload data first.", type = "error", duration = 8) + showNotification( + "No expression data available. Load or upload data first.", + type = "error", + duration = 8 + ) return() } if (pred_busy()) { - showNotification("A prediction is already running", type = "warning", duration = 5) + showNotification( + "A prediction is already running", + type = "warning", + duration = 5 + ) return() } @@ -220,7 +305,9 @@ mod_predict_server <- function(id, shared, main_session) { extract_features <- function(m) { if (inherits(m, "train")) { feats <- setdiff(colnames(m$trainingData), ".outcome") - if (length(feats) > 0) return(feats) + if (length(feats) > 0) { + return(feats) + } feats <- colnames(m$trainingData) if (length(feats) > 1) return(feats[-1]) } @@ -248,15 +335,26 @@ mod_predict_server <- function(id, shared, main_session) { showModal(modalDialog( title = "Data incompatibility — prediction blocked", tags$div( - div(style = "text-align: center; margin-bottom: 0.6rem;", - icon("exclamation-triangle", style = "color: #e08a3c; font-size: 1.8rem;")), - p(paste0("None of the model's ", length(all_features), - " features were found in the expression data (", - nrow(expr), " genes available).")), - p("The model was trained on the DepMap gene space; the current ", + div( + style = "text-align: center; margin-bottom: 0.6rem;", + icon( + "exclamation-triangle", + style = "color: #e08a3c; font-size: 1.8rem;" + ) + ), + p(paste0( + "None of the model's ", + length(all_features), + " features were found in the expression data (", + nrow(expr), + " genes available)." + )), + p( + "The model was trained on the DepMap gene space; the current ", "expression data shares no genes with it. Check gene name formats ", "(hyphens vs dots, e.g. MIF-1 vs MIF.1) between training and ", - "prediction data.") + "prediction data." + ) ), footer = modalButton("OK"), easyClose = TRUE @@ -265,9 +363,16 @@ mod_predict_server <- function(id, shared, main_session) { } if (length(overlap) < length(all_features) * 0.5) { showNotification( - paste0("Note: ", length(overlap), "/", length(all_features), - " model features found in data. Predictions may be less reliable."), - type = "warning", duration = 8) + paste0( + "Note: ", + length(overlap), + "/", + length(all_features), + " model features found in data. Predictions may be less reliable." + ), + type = "warning", + duration = 8 + ) } } @@ -276,8 +381,11 @@ mod_predict_server <- function(id, shared, main_session) { pred_busy(TRUE) w <- Waiter$new( - html = tagList(div(class = "spinner-ring"), h4("Predicting..."), - p(class = "text-muted", "Running prediction...")), + html = tagList( + div(class = "spinner-ring"), + h4("Predicting..."), + p(class = "text-muted", "Running prediction...") + ), color = "rgba(255,255,255,0.85)" ) w$show() @@ -297,18 +405,31 @@ mod_predict_server <- function(id, shared, main_session) { } jobid <- tryCatch( - submit_session_task(shared, "predict", list( - model_list = model, - expr = expr, - patient_input = patient_input, - legacy_clones = legacy_clones, - mode = input$agg_mode - )), - error = function(e) { pred_busy(FALSE); w$hide(); NULL } + submit_session_task( + shared, + "predict", + list( + model_list = model, + expr = expr, + patient_input = patient_input, + legacy_clones = legacy_clones, + mode = input$agg_mode + ) + ), + error = function(e) { + pred_busy(FALSE) + w$hide() + NULL + } ) - if (is.null(jobid)) return() + if (is.null(jobid)) { + return() + } - poll_task(shared, session, jobid, + poll_task( + shared, + session, + jobid, on_done = function(res) { pred_busy(FALSE) w$hide() @@ -321,8 +442,13 @@ mod_predict_server <- function(id, shared, main_session) { on_error = function(msg) { pred_busy(FALSE) w$hide() - showNotification(paste("Prediction error:", msg), type = "error", duration = 10) - }) + showNotification( + paste("Prediction error:", msg), + type = "error", + duration = 10 + ) + } + ) }) # Patient-level aggregation now happens inside the background worker @@ -363,25 +489,35 @@ mod_predict_server <- function(id, shared, main_session) { # old heatmap survived "Clear Demo Data". output$clone_heatmap_area <- renderUI({ mat <- clone_pred() - if (is.null(mat)) return(div()) + if (is.null(mat)) { + return(div()) + } n_rows <- nrow(mat) - h <- if (is.null(n_rows) || n_rows <= 0) 400 - else min(700, max(240, 140 + 16 * n_rows)) + h <- if (is.null(n_rows) || n_rows <= 0) { + 400 + } else { + min(700, max(240, 140 + 16 * n_rows)) + } # Demo models are SIMULATED (trained on random noise, not real drug # response data) but carry real drug names — the results must carry a # visible banner whenever any of them appear in the prediction. demo <- intersect(colnames(mat), demo_models(shared$models)) banner <- if (length(demo) > 0) { - div(class = "info-box", - style = "border-left-color: var(--warning); margin-bottom: 0.6rem;", - icon("exclamation-triangle"), - strong("Demo simulation: "), - "Demo models are SIMULATED placeholders, not trained on real drug response data. ", - "These predictions demonstrate the workflow only and must NOT be interpreted as real drug response.") + div( + class = "info-box", + style = "border-left-color: var(--warning); margin-bottom: 0.6rem;", + icon("exclamation-triangle"), + strong("Demo simulation: "), + "Demo models are SIMULATED placeholders, not trained on real drug response data. ", + "These predictions demonstrate the workflow only and must NOT be interpreted as real drug response." + ) } else { NULL } - tagList(banner, plotlyOutput(ns("clone_heatmap"), height = paste0(h, "px"))) + tagList( + banner, + plotlyOutput(ns("clone_heatmap"), height = paste0(h, "px")) + ) }) # Card annotations (icon + description + hint) are statically pre-rendered @@ -389,12 +525,20 @@ mod_predict_server <- function(id, shared, main_session) { # and restore them if a later run produces no result again. observe({ has_res <- !is.null(clone_pred()) - session$sendCustomMessage("set-html", - list(id = ns("clone_desc"), - html = if (has_res) "" else as.character(clone_desc_html()))) - session$sendCustomMessage("set-html", - list(id = ns("patient_desc"), - html = if (has_res) "" else as.character(patient_desc_html()))) + session$sendCustomMessage( + "set-html", + list( + id = ns("clone_desc"), + html = if (has_res) "" else as.character(clone_desc_html()) + ) + ) + session$sendCustomMessage( + "set-html", + list( + id = ns("patient_desc"), + html = if (has_res) "" else as.character(patient_desc_html()) + ) + ) }) # Patient table @@ -404,14 +548,16 @@ mod_predict_server <- function(id, shared, main_session) { df$patient <- rownames(df) df <- df[, c("patient", setdiff(names(df), "patient"))] - datatable(df, - options = list( - pageLength = 15, - dom = "ftip", - columnDefs = list(list(className = "dt-center", targets = "_all")) - ), - rownames = FALSE, - class = "display") %>% + datatable( + df, + options = list( + pageLength = 15, + dom = "ftip", + columnDefs = list(list(className = "dt-center", targets = "_all")) + ), + rownames = FALSE, + class = "display" + ) %>% formatRound(names(df)[sapply(df, is.numeric)], 4) }) @@ -424,9 +570,13 @@ mod_predict_server <- function(id, shared, main_session) { # Patient download output$patient_download <- renderUI({ req(patient_pred()) - div(style = "margin-top: 0.75rem;", - downloadButton(ns("download_pred"), "Download Predictions (.csv)", - class = "btn-outline-primary btn-sm") + div( + style = "margin-top: 0.75rem;", + downloadButton( + ns("download_pred"), + "Download Predictions (.csv)", + class = "btn-outline-primary btn-sm" + ) ) }) @@ -441,4 +591,4 @@ mod_predict_server <- function(id, shared, main_session) { } ) }) -} \ No newline at end of file +} diff --git a/inst/shiny/app/R/mod_train.R b/inst/shiny/app/R/mod_train.R index 0e44e85..e1b47b7 100644 --- a/inst/shiny/app/R/mod_train.R +++ b/inst/shiny/app/R/mod_train.R @@ -3,13 +3,13 @@ mod_train_ui <- function(id) { ns <- NS(id) tagList( fluidRow( - column(12, - div(class = "section-header", - icon("brain"), - h4("Model Training") - ), - div(class = "info-box", - icon("info-circle"), " Train drug response models on DepMap bulk expression data. ", + column( + 12, + div(class = "section-header", icon("brain"), h4("Model Training")), + div( + class = "info-box", + icon("info-circle"), + " Train drug response models on DepMap bulk expression data. ", "Models are built using elastic net (glmnet) or random forest with cross-validated hyperparameter tuning. ", "Each candidate is validated on held-out bulk, pseudo-bulk, and single-cell expression; the best configuration is selected by single-cell validation performance." ) @@ -17,90 +17,168 @@ mod_train_ui <- function(id) { ), # Prerequisites check - fluidRow(style = "margin-top: 1rem;", - column(12, - uiOutput(ns("prereq_check")) - ) + fluidRow( + style = "margin-top: 1rem;", + column(12, uiOutput(ns("prereq_check"))) ), - fluidRow(style = "margin-top: 0.5rem;", + fluidRow( + style = "margin-top: 0.5rem;", # Parameters Panel — align-self:flex-start keeps it at natural height # when the results column grows after training (see styles.css). # Width 4 matches Predict/Visualize so the sidebar ratio is consistent # across the three analysis tabs. - column(4, class = "train-config-col", - div(class = "card train-params-card animate-fade-in-up", - div(class = "card-header", - icon("sliders-h"), " Parameters" - ), - div(class = "card-body", + column( + 4, + class = "train-config-col", + div( + class = "card train-params-card animate-fade-in-up", + div(class = "card-header", icon("sliders-h"), " Parameters"), + div( + class = "card-body", # Section: Drug & Cancer Type - div(class = "param-section", - h6(class = "param-section-title", icon("tag"), " Drug & Cancer Type"), - textAreaInput(ns("drug"), "Drug Names (one per line or comma-separated)", - value = "abemaciclib", rows = 3, height = "90px", - width = "100%", - placeholder = "e.g.\nabemaciclib\nerlotinib\nAny drug with response data in your DepMap upload can be trained."), + div( + class = "param-section", + h6( + class = "param-section-title", + icon("tag"), + " Drug & Cancer Type" + ), + textAreaInput( + ns("drug"), + "Drug Names (one per line or comma-separated)", + value = "abemaciclib", + rows = 3, + height = "90px", + width = "100%", + placeholder = "e.g.\nabemaciclib\nerlotinib\nAny drug with response data in your DepMap upload can be trained." + ), uiOutput(ns("drug_hint")), - selectizeInput(ns("cancer_type"), "Cancer Type (include)", - choices = NULL, selected = "PanCan", width = "100%", - options = list(maxItems = 1, placeholder = "Select cancer type")), - selectizeInput(ns("exclude_cancer"), "Cancer Type (exclude)", - choices = NULL, selected = "PanCan", width = "100%", - options = list(maxItems = 1, placeholder = "Select cancer type to exclude")) + selectizeInput( + ns("cancer_type"), + "Cancer Type (include)", + choices = NULL, + selected = "PanCan", + width = "100%", + options = list(maxItems = 1, placeholder = "Select cancer type") + ), + selectizeInput( + ns("exclude_cancer"), + "Cancer Type (exclude)", + choices = NULL, + selected = "PanCan", + width = "100%", + options = list( + maxItems = 1, + placeholder = "Select cancer type to exclude" + ) + ) ), # Section: Genes of Interest - div(class = "param-section", - h6(class = "param-section-title", icon("dna"), " Genes of Interest"), - div(class = "info-box", style = "margin-bottom: 0.6rem; font-size: 0.78rem; padding: 0.6rem 0.8rem;", + div( + class = "param-section", + h6( + class = "param-section-title", + icon("dna"), + " Genes of Interest" + ), + div( + class = "info-box", + style = "margin-bottom: 0.6rem; font-size: 0.78rem; padding: 0.6rem 0.8rem;", icon("info-circle"), - " Leave empty to use ", strong("all genes"), " from DepMap data (recommended for most users). ", + " Leave empty to use ", + strong("all genes"), + " from DepMap data (recommended for most users). ", "Or enter specific gene symbols to restrict feature selection to a subset." ), - textAreaInput(ns("goi"), "Gene Symbols (optional, empty = all genes)", - placeholder = "Enter gene symbols, one per line or comma-separated.\nLeave empty to use all genes.", - rows = 8, - height = "120px", - width = "100%"), - fileInput(ns("goi_file"), "Or Upload Gene List (.txt, .csv)", - accept = c(".txt", ".csv")), - numericInput(ns("k_features"), "Top k Features", - value = 100, min = 10, max = 5000, step = 10, - width = "100%") + textAreaInput( + ns("goi"), + "Gene Symbols (optional, empty = all genes)", + placeholder = "Enter gene symbols, one per line or comma-separated.\nLeave empty to use all genes.", + rows = 8, + height = "120px", + width = "100%" + ), + fileInput( + ns("goi_file"), + "Or Upload Gene List (.txt, .csv)", + accept = c(".txt", ".csv") + ), + numericInput( + ns("k_features"), + "Top k Features", + value = 100, + min = 10, + max = 5000, + step = 10, + width = "100%" + ) ), # Section: Model Configuration - div(class = "param-section", - h6(class = "param-section-title", icon("cog"), " Model Configuration"), - selectInput(ns("model_type"), "Algorithm", - choices = c("Elastic Net (glmnet)" = "glmnet", "Random Forest" = "rf"), - selected = "glmnet", width = "100%"), - selectInput(ns("ncores"), "CPU Cores", - choices = 1:max(1L, min(4L, parallel::detectCores(), na.rm = TRUE)), - selected = 1, width = "100%"), - tags$small(class = "text-muted", - "Maximum 4 cores — hard cap for shared-server safety.") + div( + class = "param-section", + h6( + class = "param-section-title", + icon("cog"), + " Model Configuration" + ), + selectInput( + ns("model_type"), + "Algorithm", + choices = c( + "Elastic Net (glmnet)" = "glmnet", + "Random Forest" = "rf" + ), + selected = "glmnet", + width = "100%" + ), + selectInput( + ns("ncores"), + "CPU Cores", + choices = 1:max( + 1L, + min(4L, parallel::detectCores(), na.rm = TRUE) + ), + selected = 1, + width = "100%" + ), + tags$small( + class = "text-muted", + "Maximum 4 cores — hard cap for shared-server safety." + ) ), - div(class = "train-action-row", - actionButton(ns("train"), "Start Training", - class = "btn-primary", icon = icon("play")), - actionButton(ns("reset"), "Reset", - class = "btn-reset btn-sm", icon = icon("undo")) + div( + class = "train-action-row", + actionButton( + ns("train"), + "Start Training", + class = "btn-primary", + icon = icon("play") + ), + actionButton( + ns("reset"), + "Reset", + class = "btn-reset btn-sm", + icon = icon("undo") + ) ) ) ) ), # Results Panel - column(8, class = "train-results-col", - div(class = "card", - div(class = "card-header", - icon("chart-bar"), " Training Results" - ), - div(class = "card-body", + column( + 8, + class = "train-results-col", + div( + class = "card", + div(class = "card-header", icon("chart-bar"), " Training Results"), + div( + class = "card-body", # Progress uiOutput(ns("progress")), @@ -134,17 +212,30 @@ mod_train_server <- function(id, shared, main_session) { # Prerequisites check output$prereq_check <- renderUI({ missing <- c() - if (is.null(shared$depmap_meta)) missing <- c(missing, "DepMap Data") + if (is.null(shared$depmap_meta)) { + missing <- c(missing, "DepMap Data") + } if (length(missing) > 0) { - div(class = "info-box", style = "border-left-color: var(--accent);", - icon("exclamation-triangle"), " Missing prerequisites: ", + div( + class = "info-box", + style = "border-left-color: var(--accent);", + icon("exclamation-triangle"), + " Missing prerequisites: ", strong(paste(missing, collapse = ", ")), ". Please go to the Data tab first to load the required data.", - actionButton(ns("go_data"), "Go to Data", class = "btn-accent btn-sm", style = "margin-left: 0.5rem;") + actionButton( + ns("go_data"), + "Go to Data", + class = "btn-accent btn-sm", + style = "margin-left: 0.5rem;" + ) ) } else { - div(class = "info-box", style = "border-left-color: var(--success);", - icon("check-circle"), " All prerequisites loaded. Ready to train!" + div( + class = "info-box", + style = "border-left-color: var(--success);", + icon("check-circle"), + " All prerequisites loaded. Ready to train!" ) } }) @@ -162,18 +253,36 @@ mod_train_server <- function(id, shared, main_session) { # recommended subset, not a limitation. available <- meta$drugs output$drug_hint <- renderUI({ - if (length(available) == 0) return(NULL) - tags$small(class = "text-muted", - paste0(length(available), " drugs with response data in the loaded DepMap — ", - "any of them can be trained, beyond the 44 recommended ones. ", - "Matching is case-insensitive.") + if (length(available) == 0) { + return(NULL) + } + tags$small( + class = "text-muted", + paste0( + length(available), + " drugs with response data in the loaded DepMap — ", + "any of them can be trained, beyond the 44 recommended ones. ", + "Matching is case-insensitive." + ) ) }) # Cancer type choices: PanCan + unique lineages from DepMap annotation cancer_choices <- c("PanCan", meta$lineages) - updateSelectizeInput(session, "cancer_type", choices = cancer_choices, selected = "PanCan", server = TRUE) - updateSelectizeInput(session, "exclude_cancer", choices = cancer_choices, selected = "PanCan", server = TRUE) + updateSelectizeInput( + session, + "cancer_type", + choices = cancer_choices, + selected = "PanCan", + server = TRUE + ) + updateSelectizeInput( + session, + "exclude_cancer", + choices = cancer_choices, + selected = "PanCan", + server = TRUE + ) } }) @@ -200,7 +309,9 @@ mod_train_server <- function(id, shared, main_session) { # Parse drug text input (one per line or comma/space separated) drug_parsed <- reactive({ - if (is.null(input$drug)) return(character(0)) + if (is.null(input$drug)) { + return(character(0)) + } d <- unlist(strsplit(input$drug, "[,\r\n\t ]+")) d <- trimws(d) d <- d[nchar(d) > 0] @@ -213,11 +324,25 @@ mod_train_server <- function(id, shared, main_session) { train_waiter <- reactiveVal(NULL) set_train_overlay <- function(stage, detail, value) { pct <- round(100 * max(0, min(1, value))) - session$sendCustomMessage("set-html", list(id = ns("trn_stage"), html = stage)) - session$sendCustomMessage("set-html", list(id = ns("trn_detail"), html = detail)) - session$sendCustomMessage("set-html", - list(id = ns("trn_bar"), - html = paste0("
"))) + session$sendCustomMessage( + "set-html", + list(id = ns("trn_stage"), html = stage) + ) + session$sendCustomMessage( + "set-html", + list(id = ns("trn_detail"), html = detail) + ) + session$sendCustomMessage( + "set-html", + list( + id = ns("trn_bar"), + html = paste0( + "
" + ) + ) + ) } # Actual training entry — shared by the Train button and the demo-mode @@ -228,7 +353,10 @@ mod_train_server <- function(id, shared, main_session) { goi <- goi_parsed() if (is.null(goi) || length(goi) == 0) { goi <- shared$depmap_meta$genes - showNotification(paste0("Using all ", length(goi), " genes from DepMap data"), type = "message") + showNotification( + paste0("Using all ", length(goi), " genes from DepMap data"), + type = "message" + ) } drugs <- drug_parsed() if (length(drugs) == 0) { @@ -244,15 +372,23 @@ mod_train_server <- function(id, shared, main_session) { matched <- match(norm_key(drugs), norm_key(available)) missing <- drugs[is.na(matched)] if (length(missing) > 0) { - showNotification(paste0("Not found in DepMap response data (skipped): ", - paste(missing, collapse = ", "), - ". Drugs outside DepMap (e.g. daratumumab) cannot be trained here — ", - "load a pre-trained model instead (Predict tab)."), - type = "warning", duration = 8) + showNotification( + paste0( + "Not found in DepMap response data (skipped): ", + paste(missing, collapse = ", "), + ". Drugs outside DepMap (e.g. daratumumab) cannot be trained here — ", + "load a pre-trained model instead (Predict tab)." + ), + type = "warning", + duration = 8 + ) drugs <- available[matched[!is.na(matched)]] } if (length(drugs) == 0) { - showNotification("No valid drug names left — check spellings", type = "error") + showNotification( + "No valid drug names left — check spellings", + type = "error" + ) return() } } @@ -277,15 +413,24 @@ mod_train_server <- function(id, shared, main_session) { html = tagList( div(class = "spinner-ring"), h4("Training model..."), - p(id = ns("trn_stage"), class = "text-muted", "Submitting background job..."), - p(id = ns("trn_detail"), class = "text-muted", + p( + id = ns("trn_stage"), + class = "text-muted", + "Submitting background job..." + ), + p( + id = ns("trn_detail"), + class = "text-muted", style = "font-size: 0.82rem; opacity: 0.75;", - "Elastic net tuning + single-cell refinement"), + "Elastic net tuning + single-cell refinement" + ), # NB: the id sits on the TRACK. set-html replaces the bar inside it # with a fresh .train-progress-bar whose width % is therefore relative # to the full track. (Putting the id on the bar itself caused a bar # nested inside a 5%-wide bar — the visible fill never moved.) - div(id = ns("trn_bar"), class = "train-progress-track", + div( + id = ns("trn_bar"), + class = "train-progress-track", div(class = "train-progress-bar", style = "width: 5%;") ) ), @@ -297,28 +442,40 @@ mod_train_server <- function(id, shared, main_session) { # Training runs in a SEPARATE R process (callr worker, see async_jobs.R): # the main Shiny thread is never blocked, so the UI / other users stay # responsive. We submit a job, then the polling observer below tracks it. - tryCatch({ - params <- list( - drug_list = drugs, - cancer_type = input$cancer_type, - exclude_cancer = input$exclude_cancer, - GOI = goi, - k_features_values = input$k_features, - model_type = input$model_type, - ncores = input$ncores, - output_dir = tempdir() - ) - jobid <- submit_train_job(shared, params) - shared$active_job <- jobid - shared$active_job_drugs <- drugs - showNotification(sprintf("Training job %s running in the background — you can keep using the app.", - jobid), - type = "message", duration = 6) - }, error = function(e) { - w$hide() - train_waiter(NULL) - showNotification(paste("Failed to start training job:", e$message), type = "error", duration = 10) - }) + tryCatch( + { + params <- list( + drug_list = drugs, + cancer_type = input$cancer_type, + exclude_cancer = input$exclude_cancer, + GOI = goi, + k_features_values = input$k_features, + model_type = input$model_type, + ncores = input$ncores, + output_dir = tempdir() + ) + jobid <- submit_train_job(shared, params) + shared$active_job <- jobid + shared$active_job_drugs <- drugs + showNotification( + sprintf( + "Training job %s running in the background — you can keep using the app.", + jobid + ), + type = "message", + duration = 6 + ) + }, + error = function(e) { + w$hide() + train_waiter(NULL) + showNotification( + paste("Failed to start training job:", e$message), + type = "error", + duration = 10 + ) + } + ) } # Train @@ -326,12 +483,18 @@ mod_train_server <- function(id, shared, main_session) { # Guard against double-submitting: a second click would overwrite # active_job, orphan the first job and leak its waiter overlay. if (!is.null(shared$active_job)) { - showNotification("A training job is already running — wait for it to finish.", - type = "warning", duration = 6) + showNotification( + "A training job is already running — wait for it to finish.", + type = "warning", + duration = 6 + ) return() } if (is.null(shared$depmap_meta)) { - showNotification("Please load DepMap data first (Data tab)", type = "error") + showNotification( + "Please load DepMap data first (Data tab)", + type = "error" + ) return() } # In demo mode, warn BEFORE any overlay appears: the demo ships its own @@ -343,19 +506,32 @@ mod_train_server <- function(id, shared, main_session) { showModal(modalDialog( title = "Heads up — demo mode", tags$div( - div(style = "text-align: center; margin-bottom: 0.6rem;", - icon("lightbulb", style = "color: #e08a3c; font-size: 1.8rem;")), - p("You are on the demo dataset (49 genes). The demo already ships ", - strong("simulated"), " abemaciclib / erlotinib models for walking ", - "through the workflow — you can predict with them directly."), - p("Training now builds a ", strong("real"), " DepMap-space model whose ", + div( + style = "text-align: center; margin-bottom: 0.6rem;", + icon("lightbulb", style = "color: #e08a3c; font-size: 1.8rem;") + ), + p( + "You are on the demo dataset (49 genes). The demo already ships ", + strong("simulated"), + " abemaciclib / erlotinib models for walking ", + "through the workflow — you can predict with them directly." + ), + p( + "Training now builds a ", + strong("real"), + " DepMap-space model whose ", "features will NOT match the demo data, so prediction with it will fail. ", - "If you want real models, use your own full expression data instead of the demo.") + "If you want real models, use your own full expression data instead of the demo." + ) ), footer = tagList( modalButton("Cancel"), - actionButton(ns("confirm_train_demo"), "Continue training", - class = "btn-primary", icon = icon("play")) + actionButton( + ns("confirm_train_demo"), + "Continue training", + class = "btn-primary", + icon = icon("play") + ) ), easyClose = FALSE )) @@ -366,10 +542,14 @@ mod_train_server <- function(id, shared, main_session) { # Demo-mode confirmation: the user clicked "Continue training" in the # dialog — now (and only now) the overlay + background job start. - observeEvent(input$confirm_train_demo, { - removeModal() - start_training() - }, ignoreInit = TRUE) + observeEvent( + input$confirm_train_demo, + { + removeModal() + start_training() + }, + ignoreInit = TRUE + ) # Poll the background training job every second; drive the overlay and # finalize when the worker reports done / error. Also detects a DEAD @@ -377,10 +557,12 @@ mod_train_server <- function(id, shared, main_session) { # job would spin "queued" forever because status.txt never appears. observe({ jobid <- shared$active_job - if (is.null(jobid)) return() + if (is.null(jobid)) { + return() + } worker_alive <- if (isTRUE(shared$depmap_is_standard)) { m <- getOption("perception.master") - is.null(m) || m$is_alive() # NULL = not yet spawned = still recoverable + is.null(m) || m$is_alive() # NULL = not yet spawned = still recoverable } else { w <- shared$train_worker is.null(w) || w$is_alive() @@ -388,43 +570,70 @@ mod_train_server <- function(id, shared, main_session) { if (!worker_alive) { shared$active_job <- NULL shared$active_job_drugs <- NULL - if (!is.null(train_waiter())) { train_waiter()$hide(); train_waiter(NULL) } - showNotification("The background training worker stopped unexpectedly (it may have run out of memory or been killed). Please try again.", - type = "error", duration = 12) + if (!is.null(train_waiter())) { + train_waiter()$hide() + train_waiter(NULL) + } + showNotification( + "The background training worker stopped unexpectedly (it may have run out of memory or been killed). Please try again.", + type = "error", + duration = 12 + ) return() } - st <- tryCatch(read_job_state(shared, jobid), - error = function(e) list(status = "error", message = conditionMessage(e))) + st <- tryCatch(read_job_state(shared, jobid), error = function(e) { + list(status = "error", message = conditionMessage(e)) + }) w <- train_waiter() if (st$status == "done") { job_dir <- file.path(shared$jobs_dir, jobid) - result <- tryCatch(readRDS(file.path(job_dir, "result.rds")), error = function(e) NULL) - requested_drugs <- if (is.null(shared$active_job_drugs)) character(0) else shared$active_job_drugs + result <- tryCatch( + readRDS(file.path(job_dir, "result.rds")), + error = function(e) NULL + ) + requested_drugs <- if (is.null(shared$active_job_drugs)) { + character(0) + } else { + shared$active_job_drugs + } shared$active_job <- NULL shared$active_job_drugs <- NULL # Result is in memory now — drop the on-disk job dir (models can be # large) so the shared jobs pool does not accumulate GBs over time. unlink(job_dir, recursive = TRUE) - if (!is.null(w)) { w$hide(); train_waiter(NULL) } + if (!is.null(w)) { + w$hide() + train_waiter(NULL) + } if (is.null(result)) { - showNotification("Background job finished but produced no result (see console).", - type = "error", duration = 10) + showNotification( + "Background job finished but produced no result (see console).", + type = "error", + duration = 10 + ) return() } trained(result) shared$models <- result - if (is.null(shared$model_cache)) shared$model_cache <- list() + if (is.null(shared$model_cache)) { + shared$model_cache <- list() + } for (nm in names(result)) { shared$model_cache[[nm]] <- result[[nm]] shared$model_active[[nm]] <- TRUE } failed_drugs <- setdiff(requested_drugs, names(result)) if (length(failed_drugs) > 0) { - showNotification(paste0("No model produced for: ", - paste(failed_drugs, collapse = ", "), - " (feature ranking or model building failed — see console warnings)."), - type = "warning", duration = 10) + showNotification( + paste0( + "No model produced for: ", + paste(failed_drugs, collapse = ", "), + " (feature ranking or model building failed — see console warnings)." + ), + type = "warning", + duration = 10 + ) } # Feature-compatibility check against the CURRENT expression data. # A freshly trained model lives in the DepMap feature space (top-k of @@ -445,16 +654,29 @@ mod_train_server <- function(id, shared, main_session) { showModal(modalDialog( title = "Training finished — incompatible models", tags$div( - div(style = "text-align: center; margin-bottom: 0.6rem;", - icon("exclamation-triangle", style = "color: #e08a3c; font-size: 1.8rem;")), - p(paste0("Training completed, but ", length(compat$incompatible), - " model(s) share NO genes with the current expression data (", - compat$n_genes, " genes available):")), - p(style = "font-weight: 600;", - paste(compat$incompatible, collapse = ", ")), - p("Their features come from the DepMap gene space, so prediction with ", + div( + style = "text-align: center; margin-bottom: 0.6rem;", + icon( + "exclamation-triangle", + style = "color: #e08a3c; font-size: 1.8rem;" + ) + ), + p(paste0( + "Training completed, but ", + length(compat$incompatible), + " model(s) share NO genes with the current expression data (", + compat$n_genes, + " genes available):" + )), + p( + style = "font-weight: 600;", + paste(compat$incompatible, collapse = ", ") + ), + p( + "Their features come from the DepMap gene space, so prediction with ", "them will fail. Use the demo's built-in models, clear the demo, ", - "or upload a pre-trained model instead.") + "or upload a pre-trained model instead." + ) ), footer = modalButton("OK"), easyClose = TRUE @@ -468,25 +690,41 @@ mod_train_server <- function(id, shared, main_session) { shared$active_job <- NULL shared$active_job_drugs <- NULL unlink(file.path(shared$jobs_dir, jobid), recursive = TRUE) - if (!is.null(w)) { w$hide(); train_waiter(NULL) } - showNotification(paste("Training job failed:", st$message), type = "error", duration = 12) + if (!is.null(w)) { + w$hide() + train_waiter(NULL) + } + showNotification( + paste("Training job failed:", st$message), + type = "error", + duration = 12 + ) return() } # running / queued → keep the overlay in sync if (!is.null(w)) { if (st$status == "queued") { - set_train_overlay("Waiting for background worker", - "Loading DepMap in the worker process (first run only)...", 0.02) + set_train_overlay( + "Waiting for background worker", + "Loading DepMap in the worker process (first run only)...", + 0.02 + ) } else if (identical(st$phase, "rank")) { - set_train_overlay("Feature ranking", "Elastic net tuning + single-cell refinement", 0.05) + set_train_overlay( + "Feature ranking", + "Elastic net tuning + single-cell refinement", + 0.05 + ) } else if (identical(st$phase, "done")) { set_train_overlay("All drugs trained", "Saving model files...", 1) } else { n <- if (is.null(st$n) || !is.finite(st$n) || st$n <= 0) 1 else st$n i <- if (is.null(st$i) || is.na(st$i)) 0 else st$i - set_train_overlay(sprintf("Training %d/%d: %s", i, n, st$drug), - "Elastic net tuning + single-cell validation", - max(0.05, (i - 1) / n)) + set_train_overlay( + sprintf("Training %d/%d: %s", i, n, st$drug), + "Elastic net tuning + single-cell validation", + max(0.05, (i - 1) / n) + ) } } # no explicit session arg: inside observe() the default reactive domain @@ -510,15 +748,24 @@ mod_train_server <- function(id, shared, main_session) { # Progress UI output$progress <- renderUI({ if (is.null(trained())) { - div(class = "text-muted", style = "text-align: center; padding: 3rem;", - icon("brain", style = "font-size: 3rem; opacity: 0.15; display: block; margin-bottom: 0.8rem;"), + div( + class = "text-muted", + style = "text-align: center; padding: 3rem;", + icon( + "brain", + style = "font-size: 3rem; opacity: 0.15; display: block; margin-bottom: 0.8rem;" + ), "Enter drug names, configure parameters, and click ", strong("Start Training"), br(), - span(style = "font-size: 0.82rem; opacity: 0.7;", "Check the prerequisites above for available data") + span( + style = "font-size: 0.82rem; opacity: 0.7;", + "Check the prerequisites above for available data" + ) ) } else { - div(class = "status-badge loaded", + div( + class = "status-badge loaded", span(class = "status-dot green"), "Training complete" ) @@ -538,13 +785,21 @@ mod_train_server <- function(id, shared, main_session) { model_method <- m$model$method if (model_method == "glmnet") { bt <- m$model$bestTune - info <- paste0("glmnet, alpha=", round(bt$alpha, 3), - ", lambda=", signif(bt$lambda, 4)) + info <- paste0( + "glmnet, alpha=", + round(bt$alpha, 3), + ", lambda=", + signif(bt$lambda, 4) + ) } else if (model_method == "rf") { fm <- m$model$finalModel best_rmse <- min(m$model$results$RMSE, na.rm = TRUE) - info <- paste0("rf, ntree=", fm$ntree, - ", RMSE=", signif(best_rmse, 4)) + info <- paste0( + "rf, ntree=", + fm$ntree, + ", RMSE=", + signif(best_rmse, 4) + ) } else { info <- paste("method:", model_method) } @@ -560,8 +815,13 @@ mod_train_server <- function(id, shared, main_session) { }) tagList( - h6(style = "font-weight: 700; color: var(--primary-dark);", icon("info-circle"), " Model Summary"), - tags$table(class = "table table-sm", + h6( + style = "font-weight: 700; color: var(--primary-dark);", + icon("info-circle"), + " Model Summary" + ), + tags$table( + class = "table table-sm", tags$thead(tags$tr(tags$th("Drug"), tags$th("Parameters"))), tags$tbody(summary_rows) ) @@ -592,9 +852,15 @@ mod_train_server <- function(id, shared, main_session) { } else { paste(dropped, collapse = ", ") } - showNotification(paste0("ROC not drawn for: ", detail, - " — held-out cell lines have too few or non-varied drug responses in your DepMap data."), - type = "warning", duration = 12) + showNotification( + paste0( + "ROC not drawn for: ", + detail, + " — held-out cell lines have too few or non-varied drug responses in your DepMap data." + ), + type = "warning", + duration = 12 + ) } ggplotly(p) %>% layout(font = list(family = "Inter, sans-serif", size = 12)) @@ -613,36 +879,65 @@ mod_train_server <- function(id, shared, main_session) { }) output$download_roc_png <- downloadHandler( - filename = function() paste0("validation_roc_", format(Sys.Date(), "%Y%m%d"), ".png"), + filename = function() { + paste0("validation_roc_", format(Sys.Date(), "%Y%m%d"), ".png") + }, content = function(file) { p <- roc_gg() if (is.null(p)) { showNotification("Generate the ROC plot first.", type = "warning") return() } - PERCEPTIONx::export_plot_cairo(file, p, format = "png", width = 12, height = 10, res = 600) + PERCEPTIONx::export_plot_cairo( + file, + p, + format = "png", + width = 12, + height = 10, + res = 600 + ) } ) output$download_roc_pdf <- downloadHandler( - filename = function() paste0("validation_roc_", format(Sys.Date(), "%Y%m%d"), ".pdf"), + filename = function() { + paste0("validation_roc_", format(Sys.Date(), "%Y%m%d"), ".pdf") + }, content = function(file) { p <- roc_gg() if (is.null(p)) { showNotification("Generate the ROC plot first.", type = "warning") return() } - PERCEPTIONx::export_plot_cairo(file, p, format = "pdf", width = 12, height = 10) + PERCEPTIONx::export_plot_cairo( + file, + p, + format = "pdf", + width = 12, + height = 10 + ) } ) output$download_perf_png <- downloadHandler( - filename = function() paste0("performance_curve_", format(Sys.Date(), "%Y%m%d"), ".png"), + filename = function() { + paste0("performance_curve_", format(Sys.Date(), "%Y%m%d"), ".png") + }, content = function(file) { p <- perf_gg() if (is.null(p)) { - showNotification("Generate the performance plot first.", type = "warning") + showNotification( + "Generate the performance plot first.", + type = "warning" + ) return() } - PERCEPTIONx::export_plot_cairo(file, p, format = "png", width = 10, height = 7, res = 600) + PERCEPTIONx::export_plot_cairo( + file, + p, + format = "png", + width = 10, + height = 7, + res = 600 + ) } ) @@ -657,29 +952,63 @@ mod_train_server <- function(id, shared, main_session) { # instead of squashing them into the single-drug 340px frame. n_models <- length(trained()) roc_ncol <- if (n_models <= 4) 1 else 2 - roc_h <- if (n_models > 1) min(1500, 150 + 240 * ceiling(n_models / roc_ncol)) else 340 - div(class = "viz-plot-wrapper", + roc_h <- if (n_models > 1) { + min(1500, 150 + 240 * ceiling(n_models / roc_ncol)) + } else { + 340 + } + div( + class = "viz-plot-wrapper", tabsetPanel( - tabPanel("Validation ROC", + tabPanel( + "Validation ROC", plotlyOutput(ns("perf_roc_plot"), height = paste0(roc_h, "px")), - tags$small(class = "text-muted", style = "display: block; margin-top: 0.3rem;", - "ROC of the predicted viability in stratifying the top vs bottom 50% observed response by rank (paper's convention), one curve per validation dataset with AUC annotated in a box. 0.5 = random."), - tags$small(class = "text-muted", style = "display: block; margin-top: 0.3rem;", - strong("Validation sets are built-in:"), " each model was validated on DepMap data it never trained on — ", - strong("bulk"), " = cell-line bulk expression, ", - strong("pseudo-bulk"), " = single-cell expression aggregated to simulate bulk, ", - strong("single-cell"), " = DepMap single-cell expression. A curve shows whether the model's predicted viability correctly separates the most vs least responsive cell lines on that validation set."), - div(style = "margin-top: 0.4rem;", - downloadButton(ns("download_roc_png"), "PNG", class = "btn-outline-primary btn-sm"), - downloadButton(ns("download_roc_pdf"), "PDF", class = "btn-outline-primary btn-sm") + tags$small( + class = "text-muted", + style = "display: block; margin-top: 0.3rem;", + "ROC of the predicted viability in stratifying the top vs bottom 50% observed response by rank (paper's convention), one curve per validation dataset with AUC annotated in a box. 0.5 = random." + ), + tags$small( + class = "text-muted", + style = "display: block; margin-top: 0.3rem;", + strong("Validation sets are built-in:"), + " each model was validated on DepMap data it never trained on — ", + strong("bulk"), + " = cell-line bulk expression, ", + strong("pseudo-bulk"), + " = single-cell expression aggregated to simulate bulk, ", + strong("single-cell"), + " = DepMap single-cell expression. A curve shows whether the model's predicted viability correctly separates the most vs least responsive cell lines on that validation set." + ), + div( + style = "margin-top: 0.4rem;", + downloadButton( + ns("download_roc_png"), + "PNG", + class = "btn-outline-primary btn-sm" + ), + downloadButton( + ns("download_roc_pdf"), + "PDF", + class = "btn-outline-primary btn-sm" + ) ) ), - tabPanel("Performance Curve", + tabPanel( + "Performance Curve", plotlyOutput(ns("perf_plot"), height = "320px"), - tags$small(class = "text-muted", style = "display: block; margin-top: 0.3rem;", - "For each threshold, the proportion of trained drugs whose predicted-observed Pearson correlation exceeds it (per dataset). Most informative when several drugs are trained together; with a single drug the curve is a simple step."), - div(style = "margin-top: 0.4rem;", - downloadButton(ns("download_perf_png"), "PNG", class = "btn-outline-primary btn-sm") + tags$small( + class = "text-muted", + style = "display: block; margin-top: 0.3rem;", + "For each threshold, the proportion of trained drugs whose predicted-observed Pearson correlation exceeds it (per dataset). Most informative when several drugs are trained together; with a single drug the curve is a simple step." + ), + div( + style = "margin-top: 0.4rem;", + downloadButton( + ns("download_perf_png"), + "PNG", + class = "btn-outline-primary btn-sm" + ) ) ) ) @@ -696,13 +1025,20 @@ mod_train_server <- function(id, shared, main_session) { m <- models[[d]] # Helper to safely extract cor & p-value from named vector or data.frame extract_metrics <- function(perf) { - if (is.null(perf)) return(list(cor = NA, p = NA)) + if (is.null(perf)) { + return(list(cor = NA, p = NA)) + } if (is.data.frame(perf)) { list(cor = perf$estimate.cor[1], p = perf$p.value[1]) } else if (is.numeric(perf)) { # Named vector from unlist(cor.test(...)) - cor_val <- if ("estimate.cor" %in% names(perf)) perf["estimate.cor"] else - if ("cor" %in% names(perf)) perf["cor"] else NA + cor_val <- if ("estimate.cor" %in% names(perf)) { + perf["estimate.cor"] + } else if ("cor" %in% names(perf)) { + perf["cor"] + } else { + NA + } p_val <- if ("p.value" %in% names(perf)) perf["p.value"] else NA list(cor = unname(cor_val), p = unname(p_val)) } else { @@ -715,31 +1051,67 @@ mod_train_server <- function(id, shared, main_session) { sc <- extract_metrics(m$performance_in_scRNA) fmt <- function(v, digits = 3) { - if (is.na(v)) return("—") + if (is.na(v)) { + return("—") + } format(round(v, digits), nsmall = digits) } # p-value: always show the number (scientific notation when very # small), never an abbreviated "< 0.001". fmt_p <- function(v) { - if (is.na(v)) return("—") - if (v < 0.001) format(v, scientific = TRUE, digits = 2) - else format(round(v, 3), nsmall = 3) + if (is.na(v)) { + return("—") + } + if (v < 0.001) { + format(v, scientific = TRUE, digits = 2) + } else { + format(round(v, 3), nsmall = 3) + } } tags$tr( tags$td(strong(d)), - tags$td(fmt(bulk$cor), tags$span(class = "text-muted", style = "font-size:0.72rem; display:block;", "p = ", fmt_p(bulk$p))), - tags$td(fmt(pseudo$cor), tags$span(class = "text-muted", style = "font-size:0.72rem; display:block;", "p = ", fmt_p(pseudo$p))), - tags$td(fmt(sc$cor), tags$span(class = "text-muted", style = "font-size:0.72rem; display:block;", "p = ", fmt_p(sc$p))) + tags$td( + fmt(bulk$cor), + tags$span( + class = "text-muted", + style = "font-size:0.72rem; display:block;", + "p = ", + fmt_p(bulk$p) + ) + ), + tags$td( + fmt(pseudo$cor), + tags$span( + class = "text-muted", + style = "font-size:0.72rem; display:block;", + "p = ", + fmt_p(pseudo$p) + ) + ), + tags$td( + fmt(sc$cor), + tags$span( + class = "text-muted", + style = "font-size:0.72rem; display:block;", + "p = ", + fmt_p(sc$p) + ) + ) ) }) tagList( - h6(style = "font-weight: 700; color: var(--primary-dark); margin-top: 1rem;", - icon("ruler"), " Performance Metrics (Pearson correlation)"), - div(class = "table-responsive", - tags$table(class = "table table-sm", + h6( + style = "font-weight: 700; color: var(--primary-dark); margin-top: 1rem;", + icon("ruler"), + " Performance Metrics (Pearson correlation)" + ), + div( + class = "table-responsive", + tags$table( + class = "table table-sm", tags$thead(tags$tr( tags$th("Drug"), tags$th("Bulk"), @@ -749,7 +1121,8 @@ mod_train_server <- function(id, shared, main_session) { tags$tbody(rows) ) ), - tags$small(class = "text-muted", + tags$small( + class = "text-muted", "Correlation between predicted and observed drug response. Higher correlation + lower p-value = better model." ) ) @@ -758,17 +1131,25 @@ mod_train_server <- function(id, shared, main_session) { # Download output$download_btn <- renderUI({ req(trained()) - div(style = "margin-top: 1rem;", - downloadButton(ns("download_model"), "Download Model (.RDS)", - class = "btn-outline-primary btn-sm"), - tags$hr(style = "margin-top: 1rem; margin-bottom: 1rem; border-top: 1px solid var(--border-light);") + div( + style = "margin-top: 1rem;", + downloadButton( + ns("download_model"), + "Download Model (.RDS)", + class = "btn-outline-primary btn-sm" + ), + tags$hr( + style = "margin-top: 1rem; margin-bottom: 1rem; border-top: 1px solid var(--border-light);" + ) ) }) output$download_model <- downloadHandler( filename = function() { drug_str <- paste(drug_parsed(), collapse = "_") - if (nchar(drug_str) > 80) drug_str <- substr(drug_str, 1, 80) + if (nchar(drug_str) > 80) { + drug_str <- substr(drug_str, 1, 80) + } paste0(drug_str, "_model_", format(Sys.Date(), "%Y%m%d"), ".RDS") }, content = function(file) { diff --git a/inst/shiny/app/R/mod_visualize.R b/inst/shiny/app/R/mod_visualize.R index 1b58f27..d4ff481 100644 --- a/inst/shiny/app/R/mod_visualize.R +++ b/inst/shiny/app/R/mod_visualize.R @@ -25,7 +25,8 @@ mod_visualize_ui <- function(id) { ns <- NS(id) tagList( - fluidRow(column(12, + fluidRow(column( + 12, div(class = "section-header", icon("chart-line"), h4("Visualization")) )), @@ -34,15 +35,21 @@ mod_visualize_ui <- function(id) { fluidRow( # LEFT column: plot gallery + parameters. - column(4, class = "viz-sidebar-col", - div(class = "card animate-fade-in-up viz-gallery-card", - div(class = "card-header", - icon("images"), " Plot Gallery" - ), - div(class = "card-body", + column( + 4, + class = "viz-sidebar-col", + div( + class = "card animate-fade-in-up viz-gallery-card", + div(class = "card-header", icon("images"), " Plot Gallery"), + div( + class = "card-body", uiOutput(ns("gallery_grid")), - tags$small(class = "text-muted", style = "display: block; margin-top: 0.5rem;", - icon("lightbulb"), " Grey = required data not loaded yet.") + tags$small( + class = "text-muted", + style = "display: block; margin-top: 0.5rem;", + icon("lightbulb"), + " Grey = required data not loaded yet." + ) ) ), # Parameters appear here once a card is clicked. @@ -51,36 +58,80 @@ mod_visualize_ui <- function(id) { # RIGHT column: "About this plot" card sits ABOVE the Output card, then # the Output card (size/export controls → status → interactive plot). - column(8, class = "viz-main-col", + column( + 8, + class = "viz-main-col", uiOutput(ns("plot_explanation")), - div(class = "card animate-fade-in-up delay-1 viz-output-card", - div(class = "card-header", - icon("image"), " Output", - tags$span(class = "viz-output-header-info", + div( + class = "card animate-fade-in-up delay-1 viz-output-card", + div( + class = "card-header", + icon("image"), + " Output", + tags$span( + class = "viz-output-header-info", uiOutput(ns("plot_info_inline")), - tags$span(style = "margin-left: 0.5rem;", + tags$span( + style = "margin-left: 0.5rem;", uiOutput(ns("plot_download_inline")) ) ) ), - div(class = "card-body", - div(class = "viz-size-controls", style = "margin-top: 0; margin-bottom: 0.6rem;", - tags$label(class = "viz-size-label", icon("arrows-alt"), " Plot Size & Export"), - div(class = "viz-size-row", - div(class = "viz-size-col", + div( + class = "card-body", + div( + class = "viz-size-controls", + style = "margin-top: 0; margin-bottom: 0.6rem;", + tags$label( + class = "viz-size-label", + icon("arrows-alt"), + " Plot Size & Export" + ), + div( + class = "viz-size-row", + div( + class = "viz-size-col", tags$span(class = "viz-size-mini-label", "Width (%)"), - numericInput(ns("plot_width"), NULL, value = 100, min = 50, max = 200, step = 10)), - div(class = "viz-size-col", + numericInput( + ns("plot_width"), + NULL, + value = 100, + min = 50, + max = 200, + step = 10 + ) + ), + div( + class = "viz-size-col", tags$span(class = "viz-size-mini-label", "Height (%)"), - numericInput(ns("plot_height"), NULL, value = 100, min = 50, max = 200, step = 10)), - div(class = "viz-size-col", + numericInput( + ns("plot_height"), + NULL, + value = 100, + min = 50, + max = 200, + step = 10 + ) + ), + div( + class = "viz-size-col", tags$span(class = "viz-size-mini-label", "DPI (100-1200)"), - numericInput(ns("plot_dpi"), NULL, value = 300, step = 50)) + numericInput(ns("plot_dpi"), NULL, value = 300, step = 50) + ) ), - div(class = "viz-size-row", - sliderInput(ns("plot_text_size"), "Text size", - min = 60, max = 160, value = 100, step = 10, - post = "%", ticks = TRUE, width = "100%") + div( + class = "viz-size-row", + sliderInput( + ns("plot_text_size"), + "Text size", + min = 60, + max = 160, + value = 100, + step = 10, + post = "%", + ticks = TRUE, + width = "100%" + ) ) ), uiOutput(ns("plot_status")), @@ -128,8 +179,10 @@ mod_visualize_server <- function(id, shared, main_session) { # cached plot and the selection so the Output area collapses back to the # placeholder instead of a stale blank block. observe({ - no_data <- is.null(shared$predictions) && is.null(shared$models) && - is.null(shared$user_clones) && is.null(shared$user_expr) + no_data <- is.null(shared$predictions) && + is.null(shared$models) && + is.null(shared$user_clones) && + is.null(shared$user_expr) if (no_data && !is.null(current_plot())) { current_plot(NULL) current_plot_type(NULL) @@ -141,11 +194,21 @@ mod_visualize_server <- function(id, shared, main_session) { # Any source-object change (demo load/clear, uploads, new predictions) # makes every cached plot stale — drop both caches. observe({ - invisible(list(shared$predictions, shared$user_clones, shared$user_expr, - shared$user_response, shared$patient_pred, - shared$models, shared$prepared_data)) - if (length(ls(plot_cache)) > 0) rm(list = ls(plot_cache), envir = plot_cache) - if (length(ls(widget_cache)) > 0) rm(list = ls(widget_cache), envir = widget_cache) + invisible(list( + shared$predictions, + shared$user_clones, + shared$user_expr, + shared$user_response, + shared$patient_pred, + shared$models, + shared$prepared_data + )) + if (length(ls(plot_cache)) > 0) { + rm(list = ls(plot_cache), envir = plot_cache) + } + if (length(ls(widget_cache)) > 0) { + rm(list = ls(widget_cache), envir = widget_cache) + } }) # Map response labels to canonical short classes: R/NR spellings collapse @@ -153,10 +216,34 @@ mod_visualize_server <- function(id, shared, main_session) { # as-is (uppercased) so multi-group response data is not silently dropped. label_resp <- function(x) { y <- tolower(trimws(as.character(x))) - y[y %in% c("responder", "response", "responsive", "r", "sensitive", "sensitivity")] <- "R" - y[y %in% c("non-responder", "nonresponder", "non responder", "non-responsive", - "nonresponsive", "nr", "resistant", "resistance", "progressor", - "progression", "non", "non_responder")] <- "NR" + y[ + y %in% + c( + "responder", + "response", + "responsive", + "r", + "sensitive", + "sensitivity" + ) + ] <- "R" + y[ + y %in% + c( + "non-responder", + "nonresponder", + "non responder", + "non-responsive", + "nonresponsive", + "nr", + "resistant", + "resistance", + "progressor", + "progression", + "non", + "non_responder" + ) + ] <- "NR" keep <- !y %in% c("R", "NR") y[keep] <- toupper(y[keep]) y @@ -164,7 +251,9 @@ mod_visualize_server <- function(id, shared, main_session) { response_groups <- reactive({ cr <- shared$user_response - if (is.null(cr) || is.null(cr$response)) return(character(0)) + if (is.null(cr) || is.null(cr$response)) { + return(character(0)) + } grps <- unique(label_resp(cr$response)) grps[!is.na(grps) & nzchar(trimws(grps)) & grps != "NA"] }) @@ -182,16 +271,24 @@ mod_visualize_server <- function(id, shared, main_session) { hp <- if (is.null(hp) || !is.finite(hp)) 100 else hp dp <- if (is.null(dp) || !is.finite(dp) || dp < 72) 300 else dp base_h <- 750 - if (identical(current_plot_type(), "clone_kill")) base_h <- 975 - list(w = round(1000 * wp / 100), - h = round(base_h * hp / 100), - dpi = round(dp)) + if (identical(current_plot_type(), "clone_kill")) { + base_h <- 975 + } + list( + w = round(1000 * wp / 100), + h = round(base_h * hp / 100), + dpi = round(dp) + ) }) # Debounced preview dims: typing in the width/height boxes re-renders the # interactive SVG only after the input settles (each rebuild costs ~1 s). preview_size <- reactive(plot_size()) |> debounce(300) text_scale <- reactive({ - if (is.null(input$plot_text_size)) 100 else as.numeric(input$plot_text_size) / 100 + if (is.null(input$plot_text_size)) { + 100 + } else { + as.numeric(input$plot_text_size) / 100 + } }) # DPI bounds are enforced server-side (the input itself has no min/max, so # the browser never pops its locale-dependent "value cannot exceed" tooltip). @@ -200,12 +297,17 @@ mod_visualize_server <- function(id, shared, main_session) { dpi_clamp <- reactive(input$plot_dpi) |> debounce(1000) observeEvent(dpi_clamp(), { d <- dpi_clamp() - if (is.null(d) || !is.finite(d)) return() + if (is.null(d) || !is.finite(d)) { + return() + } d2 <- min(max(round(d), 100), 1200) if (d2 != round(d)) { updateNumericInput(session, "plot_dpi", value = d2) - showNotification(sprintf("DPI must be between 100 and 1200. Reset to %d.", d2), - type = "warning", duration = 4) + showNotification( + sprintf("DPI must be between 100 and 1200. Reset to %d.", d2), + type = "warning", + duration = 4 + ) } }) reduction_method <- reactive({ @@ -214,32 +316,73 @@ mod_visualize_server <- function(id, shared, main_session) { }) reduction_label <- reactive({ m <- reduction_method() - if (m == "none") "no embedding" else if (m == "tsne") "t-SNE" else "UMAP" + if (m == "none") { + "no embedding" + } else if (m == "tsne") { + "t-SNE" + } else { + "UMAP" + } }) # ---- Gallery metadata (single source for cards, requirements, labels) ---- gallery_items <- list( - list(id = "clone_dist", icon = "chart-pie", title = "Clone Distribution", - tagline = "Clone proportions within each patient", - req = c("user_clones"), spatial = FALSE), - list(id = "clone_kill", icon = "chart-column", title = "Clone Viability Lollipop", - tagline = "Predicted viability per clone", - req = c("predictions", "user_clones"), spatial = FALSE), - list(id = "roc", icon = "chart-line", title = "ROC Curve", - tagline = "How well scores separate responders from non-responders", - req = c("patient_pred", "user_response"), spatial = FALSE), - list(id = "boxplot", icon = "chart-gantt", title = "Response Boxplot", - tagline = "Predicted viability by clinical response group", - req = c("patient_pred", "user_response"), spatial = FALSE), - list(id = "umap_clone", icon = "map", title = "Clone Identity", - tagline = "Where each clone sits in the embedding", - req = c("user_clones"), spatial = TRUE), - list(id = "umap_viability", icon = "flask", title = "Drug Viability", - tagline = "Predicted drug viability across cells", - req = c("predictions"), spatial = TRUE), - list(id = "umap_gene", icon = "dna", title = "Gene Expression", - tagline = "Expression of one gene across cells", - req = c("predictions", "user_expr"), spatial = TRUE) + list( + id = "clone_dist", + icon = "chart-pie", + title = "Clone Distribution", + tagline = "Clone proportions within each patient", + req = c("user_clones"), + spatial = FALSE + ), + list( + id = "clone_kill", + icon = "chart-column", + title = "Clone Viability Lollipop", + tagline = "Predicted viability per clone", + req = c("predictions", "user_clones"), + spatial = FALSE + ), + list( + id = "roc", + icon = "chart-line", + title = "ROC Curve", + tagline = "How well scores separate responders from non-responders", + req = c("patient_pred", "user_response"), + spatial = FALSE + ), + list( + id = "boxplot", + icon = "chart-gantt", + title = "Response Boxplot", + tagline = "Predicted viability by clinical response group", + req = c("patient_pred", "user_response"), + spatial = FALSE + ), + list( + id = "umap_clone", + icon = "map", + title = "Clone Identity", + tagline = "Where each clone sits in the embedding", + req = c("user_clones"), + spatial = TRUE + ), + list( + id = "umap_viability", + icon = "flask", + title = "Drug Viability", + tagline = "Predicted drug viability across cells", + req = c("predictions"), + spatial = TRUE + ), + list( + id = "umap_gene", + icon = "dna", + title = "Gene Expression", + tagline = "Expression of one gene across cells", + req = c("predictions", "user_expr"), + spatial = TRUE + ) ) plot_requirements <- setNames( @@ -255,34 +398,55 @@ mod_visualize_server <- function(id, shared, main_session) { paste(reduction_label(), plot_labels[[pt]]) } plot_label <- function(pt) { - if (isTRUE(pt %in% c("umap_gene", "umap_viability", "umap_clone"))) spatial_plot_label(pt) else plot_labels[[pt]] + if (isTRUE(pt %in% c("umap_gene", "umap_viability", "umap_clone"))) { + spatial_plot_label(pt) + } else { + plot_labels[[pt]] + } } # Requirements check helpers req_missing <- function(reqs) { missing <- c() - if ("user_clones" %in% reqs && is.null(shared$user_clones)) missing <- c(missing, "Clone Annotation") - if ("predictions" %in% reqs && is.null(shared$predictions)) missing <- c(missing, "Predictions") - if ("patient_pred" %in% reqs && is.null(shared$patient_pred)) missing <- c(missing, "Patient Predictions") - if ("user_response" %in% reqs && is.null(shared$user_response)) missing <- c(missing, "Clinical Response") - if ("models" %in% reqs && is.null(shared$models)) missing <- c(missing, "Trained Model") - if ("user_expr" %in% reqs && is.null(shared$user_expr)) missing <- c(missing, "Expression") + if ("user_clones" %in% reqs && is.null(shared$user_clones)) { + missing <- c(missing, "Clone Annotation") + } + if ("predictions" %in% reqs && is.null(shared$predictions)) { + missing <- c(missing, "Predictions") + } + if ("patient_pred" %in% reqs && is.null(shared$patient_pred)) { + missing <- c(missing, "Patient Predictions") + } + if ("user_response" %in% reqs && is.null(shared$user_response)) { + missing <- c(missing, "Clinical Response") + } + if ("models" %in% reqs && is.null(shared$models)) { + missing <- c(missing, "Trained Model") + } + if ("user_expr" %in% reqs && is.null(shared$user_expr)) { + missing <- c(missing, "Expression") + } missing } # boxplot/ROC are satisfiable through the Combination route (predictions + # clones + response) even without per-drug patient_pred. card_ready <- function(pt) { if (pt %in% c("boxplot", "roc")) { - return(!is.null(shared$user_response) && - ((!is.null(shared$patient_pred)) || - (!is.null(shared$predictions) && !is.null(shared$user_clones)))) + return( + !is.null(shared$user_response) && + ((!is.null(shared$patient_pred)) || + (!is.null(shared$predictions) && !is.null(shared$user_clones))) + ) } length(req_missing(plot_requirements[[pt]])) == 0 } effective_reqs <- function(pt) { reqs <- plot_requirements[[pt]] - if (pt %in% c("boxplot", "roc") && - identical(input$drug_name_common, "Combination")) { + if ( + pt %in% + c("boxplot", "roc") && + identical(input$drug_name_common, "Combination") + ) { reqs <- c("predictions", "user_clones", "user_response") } reqs @@ -291,30 +455,59 @@ mod_visualize_server <- function(id, shared, main_session) { # ---- Data readiness bar ---- output$readiness_bar <- renderUI({ items <- list( - list(key = "Expression", ok = !is.null(shared$user_expr), tab = "data"), - list(key = "Clones", ok = !is.null(shared$user_clones), tab = "data"), - list(key = "Response", ok = !is.null(shared$user_response), tab = "data"), - list(key = "Models", ok = !is.null(shared$models), tab = "train"), - list(key = "Predictions", ok = !is.null(shared$predictions), tab = "predict") + list(key = "Expression", ok = !is.null(shared$user_expr), tab = "data"), + list(key = "Clones", ok = !is.null(shared$user_clones), tab = "data"), + list( + key = "Response", + ok = !is.null(shared$user_response), + tab = "data" + ), + list(key = "Models", ok = !is.null(shared$models), tab = "train"), + list( + key = "Predictions", + ok = !is.null(shared$predictions), + tab = "predict" + ) ) - div(class = "viz-readiness-bar", - span(class = "viz-readiness-title", icon("clipboard-check"), " Data readiness:"), + div( + class = "viz-readiness-bar", + span( + class = "viz-readiness-title", + icon("clipboard-check"), + " Data readiness:" + ), lapply(items, function(it) { - div(class = paste("readiness-pill", if (it$ok) "ok" else "missing"), - span(class = paste("readiness-dot", if (it$ok) "green" else "gray")), + div( + class = paste("readiness-pill", if (it$ok) "ok" else "missing"), + span( + class = paste("readiness-dot", if (it$ok) "green" else "gray") + ), it$key, - if (it$ok) tags$span(class = "readiness-badge", "ready") - else tags$button( - class = "readiness-go", - onclick = sprintf("Shiny.setInputValue('%s', '%s');", - ns("go_tab"), it$tab), - "load \u2192") + if (it$ok) { + tags$span(class = "readiness-badge", "ready") + } else { + tags$button( + class = "readiness-go", + onclick = sprintf( + "Shiny.setInputValue('%s', '%s');", + ns("go_tab"), + it$tab + ), + "load \u2192" + ) + } ) }) ) }) observeEvent(input$go_tab, { - if (nzchar(input$go_tab)) bslib::nav_select("navbar", selected = input$go_tab, session = main_session) + if (nzchar(input$go_tab)) { + bslib::nav_select( + "navbar", + selected = input$go_tab, + session = main_session + ) + } }) # ---- Plot gallery grid ---- @@ -322,37 +515,62 @@ mod_visualize_server <- function(id, shared, main_session) { cards <- lapply(gallery_items, function(it) { ready <- card_ready(it$id) missing <- req_missing(plot_requirements[[it$id]]) - div(class = paste("viz-card", if (ready) "ready" else "missing"), - title = if (ready) paste(it$title, "- click to draw") else - paste0("Missing: ", paste(missing, collapse = ", ")), - onclick = sprintf("Shiny.setInputValue('%s', '%s');", - ns("pick_plot"), it$id), + div( + class = paste("viz-card", if (ready) "ready" else "missing"), + title = if (ready) { + paste(it$title, "- click to draw") + } else { + paste0("Missing: ", paste(missing, collapse = ", ")) + }, + onclick = sprintf( + "Shiny.setInputValue('%s', '%s');", + ns("pick_plot"), + it$id + ), div(class = "viz-card-icon", icon(it$icon)), div(class = "viz-card-title", it$title), div(class = "viz-card-tagline", it$tagline), - div(class = "viz-card-status", - if (ready) tags$span(class = "viz-card-ready", icon("check-circle"), " Ready") - else tags$span(class = "viz-card-missing", - icon("circle-exclamation"), - paste("Needs:", paste(missing, collapse = ", "))) + div( + class = "viz-card-status", + if (ready) { + tags$span( + class = "viz-card-ready", + icon("check-circle"), + " Ready" + ) + } else { + tags$span( + class = "viz-card-missing", + icon("circle-exclamation"), + paste("Needs:", paste(missing, collapse = ", ")) + ) + } ) ) }) div(class = "viz-gallery-grid", cards) }) - # Clicking a card selects it and draws immediately. When the required # data is missing, do NOT select it — otherwise the parameter panel would # appear for a plot that cannot be drawn. observeEvent(input$pick_plot, { pt <- input$pick_plot - if (is.null(pt) || !nzchar(pt)) return() + if (is.null(pt) || !nzchar(pt)) { + return() + } missing <- req_missing(effective_reqs(pt)) if (length(missing) > 0) { - showNotification(paste0(plot_labels[[pt]], " needs: ", - paste(missing, collapse = ", "), - ". Load them first."), type = "warning", duration = 6) + showNotification( + paste0( + plot_labels[[pt]], + " needs: ", + paste(missing, collapse = ", "), + ". Load them first." + ), + type = "warning", + duration = 6 + ) return() } viz_selected(pt) @@ -362,20 +580,43 @@ mod_visualize_server <- function(id, shared, main_session) { # ROC pair picker (only meaningful when response has >2 groups). output$roc_pair_picker <- renderUI({ grps <- response_groups() - if (length(grps) <= 2) return(NULL) + if (length(grps) <= 2) { + return(NULL) + } def <- if (all(c("PD", "RD") %in% grps)) c("PD", "RD") else grps[1:2] tagList( - tags$small(class = "text-muted", style = "display: block; margin: 0.4rem 0 0.2rem;", - icon("info-circle"), " Response has ", length(grps), " groups. Pick two for ROC:"), - div(class = "viz-size-row", - div(class = "viz-size-col", - selectInput(ns("roc_group_a"), "ROC Group A", - choices = grps, selected = def[1], width = "100%", - selectize = FALSE)), - div(class = "viz-size-col", - selectInput(ns("roc_group_b"), "ROC Group B", - choices = grps, selected = def[2], width = "100%", - selectize = FALSE)) + tags$small( + class = "text-muted", + style = "display: block; margin: 0.4rem 0 0.2rem;", + icon("info-circle"), + " Response has ", + length(grps), + " groups. Pick two for ROC:" + ), + div( + class = "viz-size-row", + div( + class = "viz-size-col", + selectInput( + ns("roc_group_a"), + "ROC Group A", + choices = grps, + selected = def[1], + width = "100%", + selectize = FALSE + ) + ), + div( + class = "viz-size-col", + selectInput( + ns("roc_group_b"), + "ROC Group B", + choices = grps, + selected = def[2], + width = "100%", + selectize = FALSE + ) + ) ) ) }) @@ -389,54 +630,108 @@ mod_visualize_server <- function(id, shared, main_session) { # re-freshes them whenever shared data changes (renderUI re-evaluates). output$param_panel <- renderUI({ pt <- viz_selected() - if (is.null(pt)) return(NULL) - has_drug <- pt %in% c("clone_kill", "boxplot", "roc", "umap_viability") - has_gene <- pt == "umap_gene" - has_roc <- pt == "roc" + if (is.null(pt)) { + return(NULL) + } + has_drug <- pt %in% c("clone_kill", "boxplot", "roc", "umap_viability") + has_gene <- pt == "umap_gene" + has_roc <- pt == "roc" # Plots that need NO user parameters (clone_dist, umap_clone) get no # parameter panel at all — an empty box would only confuse. - if (!has_drug && !has_gene && !has_roc) return(NULL) + if (!has_drug && !has_gene && !has_roc) { + return(NULL) + } drug_choices <- NULL - if (!is.null(shared$models)) drug_choices <- names(shared$models) - else if (!is.null(shared$predictions)) drug_choices <- colnames(shared$predictions) + if (!is.null(shared$models)) { + drug_choices <- names(shared$models) + } else if (!is.null(shared$predictions)) { + drug_choices <- colnames(shared$predictions) + } combo_choices <- if (length(drug_choices) > 0) { c("Combination" = "Combination", setNames(drug_choices, drug_choices)) - } else NULL - gene_choices <- if (!is.null(shared$user_expr)) rownames(shared$user_expr) else NULL + } else { + NULL + } + gene_choices <- if (!is.null(shared$user_expr)) { + rownames(shared$user_expr) + } else { + NULL + } tagList( - div(class = "card animate-fade-in-up viz-param-card", - div(class = "card-header", icon("sliders"), " Plot Parameters", - tags$span(class = "text-muted", style = "font-size: 0.78rem; margin-left: 0.6rem;", - "Changes redraw the plot automatically.") + div( + class = "card animate-fade-in-up viz-param-card", + div( + class = "card-header", + icon("sliders"), + " Plot Parameters", + tags$span( + class = "text-muted", + style = "font-size: 0.78rem; margin-left: 0.6rem;", + "Changes redraw the plot automatically." + ) ), - div(class = "card-body", + div( + class = "card-body", fluidRow( - if (has_drug && pt != "umap_viability") column(6, - selectizeInput(ns("drug_name_common"), "Drug", - choices = combo_choices, selected = "Combination", - width = "100%", - options = list(maxItems = 1, placeholder = "Select a drug")) - ), - if (pt == "umap_viability") column(6, - selectizeInput(ns("umap_drug"), "Drug", - choices = if (length(drug_choices) > 0) setNames(drug_choices, drug_choices) else NULL, - selected = if (length(drug_choices) > 0) drug_choices[1] else NULL, - width = "100%", - options = list(maxItems = 1, placeholder = "Select a drug")) - ), - if (has_gene) column(6, - # Only a head of the gene list is shipped with the panel; the - # rest is handed over in the background by load_full_gene_list() - # so that opening this card never waits on the browser building - # a 15-20k-entry widget. - selectizeInput(ns("umap_gene"), "Gene", - choices = utils::head(gene_choices, 1000L), - selected = if (!is.null(gene_choices) && length(gene_choices) > 0) gene_choices[1] else NULL, - width = "100%", - options = list(maxItems = 1, placeholder = "Select a gene")) - ), + if (has_drug && pt != "umap_viability") { + column( + 6, + selectizeInput( + ns("drug_name_common"), + "Drug", + choices = combo_choices, + selected = "Combination", + width = "100%", + options = list(maxItems = 1, placeholder = "Select a drug") + ) + ) + }, + if (pt == "umap_viability") { + column( + 6, + selectizeInput( + ns("umap_drug"), + "Drug", + choices = if (length(drug_choices) > 0) { + setNames(drug_choices, drug_choices) + } else { + NULL + }, + selected = if (length(drug_choices) > 0) { + drug_choices[1] + } else { + NULL + }, + width = "100%", + options = list(maxItems = 1, placeholder = "Select a drug") + ) + ) + }, + if (has_gene) { + column( + 6, + # Only a head of the gene list is shipped with the panel; the + # rest is handed over in the background by load_full_gene_list() + # so that opening this card never waits on the browser building + # a 15-20k-entry widget. + selectizeInput( + ns("umap_gene"), + "Gene", + choices = utils::head(gene_choices, 1000L), + selected = if ( + !is.null(gene_choices) && length(gene_choices) > 0 + ) { + gene_choices[1] + } else { + NULL + }, + width = "100%", + options = list(maxItems = 1, placeholder = "Select a gene") + ) + ) + }, if (has_roc) column(12, uiOutput(ns("roc_pair_picker"))) ), if (has_drug && pt != "umap_viability") uiOutput(ns("combo_hint")) @@ -450,12 +745,18 @@ mod_visualize_server <- function(id, shared, main_session) { # Rendered as its own output so switching the dropdown never rebuilds the # panel (which would reset the selectize). output$combo_hint <- renderUI({ - if (!isTRUE(identical(input$drug_name_common, "Combination"))) return(NULL) + if (!isTRUE(identical(input$drug_name_common, "Combination"))) { + return(NULL) + } pt <- viz_selected() - if (is.null(pt) || !pt %in% c("clone_kill", "boxplot", "roc")) return(NULL) - div(class = "viz-combo-hint", + if (is.null(pt) || !pt %in% c("clone_kill", "boxplot", "roc")) { + return(NULL) + } + div( + class = "viz-combo-hint", icon("info-circle"), - " Combination = ensemble model: clone-level predictions aggregated across all drugs.") + " Combination = ensemble model: clone-level predictions aggregated across all drugs." + ) }) # The Gene dropdown must list every gene so the whole list stays browsable, @@ -470,34 +771,52 @@ mod_visualize_server <- function(id, shared, main_session) { observeEvent(shared$user_expr, gene_list_loaded(FALSE), ignoreNULL = FALSE) load_full_gene_list <- function() { - if (isTRUE(gene_list_loaded())) return(invisible(NULL)) - genes <- if (!is.null(shared$user_expr)) rownames(shared$user_expr) else NULL - if (is.null(genes) || length(genes) == 0) return(invisible(NULL)) + if (isTRUE(gene_list_loaded())) { + return(invisible(NULL)) + } + genes <- if (!is.null(shared$user_expr)) { + rownames(shared$user_expr) + } else { + NULL + } + if (is.null(genes) || length(genes) == 0) { + return(invisible(NULL)) + } gene_list_loaded(TRUE) # onFlushed: the selectize has to exist in the browser before it can be # updated. Sent without `server = TRUE`, so the whole list stays client # side and remains fully browsable. - session$onFlushed(function() { - updateSelectizeInput(session, "umap_gene", choices = genes) - }, once = TRUE) + session$onFlushed( + function() { + updateSelectizeInput(session, "umap_gene", choices = genes) + }, + once = TRUE + ) invisible(NULL) } # Parameter changes redraw the current plot automatically (debounced so # fast typing/sliding does not fire a plot per keystroke). auto_redraw <- reactive({ - list(pt = viz_selected(), - drug = input$drug_name_common, - gene = input$umap_gene, - udrug = input$umap_drug, - ra = input$roc_group_a, - rb = input$roc_group_b) - }) |> debounce(300) + list( + pt = viz_selected(), + drug = input$drug_name_common, + gene = input$umap_gene, + udrug = input$umap_drug, + ra = input$roc_group_a, + rb = input$roc_group_b + ) + }) |> + debounce(300) observeEvent(auto_redraw(), { pt <- viz_selected() - if (is.null(pt)) return() + if (is.null(pt)) { + return() + } missing <- req_missing(effective_reqs(pt)) - if (length(missing) > 0) return() + if (length(missing) > 0) { + return() + } generate_plot(pt) }) @@ -509,9 +828,13 @@ mod_visualize_server <- function(id, shared, main_session) { # click, so input$drug_name_common can still be NULL then — fall back to # the panel's default "Combination" so the plot matches what the # dropdown shows (otherwise the first drug leaks in as a silent default). - drug_sel <- if (!is.null(input$drug_name_common) && nzchar(input$drug_name_common)) { + drug_sel <- if ( + !is.null(input$drug_name_common) && nzchar(input$drug_name_common) + ) { input$drug_name_common - } else "Combination" + } else { + "Combination" + } is_combo <- identical(drug_sel, "Combination") # umap_gene: the parameter panel may not have rendered on the FIRST card @@ -522,24 +845,43 @@ mod_visualize_server <- function(id, shared, main_session) { input$umap_gene } else if (!is.null(shared$user_expr) && nrow(shared$user_expr) > 0) { rownames(shared$user_expr)[1] - } else "" - } else "" + } else { + "" + } + } else { + "" + } # A gene plot is about to be requested either way, so hand the browser the # rest of the gene list now — it builds it while the plot is being # computed instead of blocking the first render. No-op after the first call. - if (pt == "umap_gene") load_full_gene_list() + if (pt == "umap_gene") { + load_full_gene_list() + } # Cache hit: identical request was generated before — reuse instantly. - ck <- if (is_spatial) paste(pt, gene_sel, input$umap_drug, sep = "\u0001") - else paste(pt, is_combo, drug_sel, - input$roc_group_a, input$roc_group_b, sep = "\u0001") + ck <- if (is_spatial) { + paste(pt, gene_sel, input$umap_drug, sep = "\u0001") + } else { + paste( + pt, + is_combo, + drug_sel, + input$roc_group_a, + input$roc_group_b, + sep = "\u0001" + ) + } cached <- get0(ck, envir = plot_cache, inherits = FALSE) if (!is.null(cached)) { current_plot(cached$plot) current_plot_type(pt) current_plot_key(ck) - showNotification(paste0(plot_label(pt), " loaded from cache"), type = "message", duration = 3) + showNotification( + paste0(plot_label(pt), " loaded from cache"), + type = "message", + duration = 3 + ) return() } @@ -549,8 +891,14 @@ mod_visualize_server <- function(id, shared, main_session) { # finishes (flush_pending below). if (viz_busy()) { pending_plot(pt) - showNotification(paste0(plot_label(pt), " queued — it will draw when the current plot finishes"), - type = "message", duration = 2) + showNotification( + paste0( + plot_label(pt), + " queued — it will draw when the current plot finishes" + ), + type = "message", + duration = 2 + ) return() } viz_busy(TRUE) @@ -560,99 +908,158 @@ mod_visualize_server <- function(id, shared, main_session) { if (is_spatial) { umap_coords <- pd$umap_coords if (is.null(umap_coords)) { - viz_busy(FALSE); viz_waiter$hide() - showNotification("No 2D embedding available (clustering was skipped or not run). Re-run with Seurat clustering to enable spatial plots.", type = "warning", duration = 8) + viz_busy(FALSE) + viz_waiter$hide() + showNotification( + "No 2D embedding available (clustering was skipped or not run). Re-run with Seurat clustering to enable spatial plots.", + type = "warning", + duration = 8 + ) return() } if (is.null(shared$user_clones)) { - viz_busy(FALSE); viz_waiter$hide() - showNotification("No clone annotation found. Run Seurat clustering first.", type = "warning") + viz_busy(FALSE) + viz_waiter$hide() + showNotification( + "No clone annotation found. Run Seurat clustering first.", + type = "warning" + ) return() } # umap_gene: ship only the selected gene's per-cell vector (small), # never the whole expression matrix. gene_vec <- NULL - if (pt == "umap_gene" && nzchar(gene_sel) && - !is.null(shared$user_expr) && gene_sel %in% rownames(shared$user_expr)) { - gene_vec <- setNames(as.numeric(shared$user_expr[gene_sel, ]), - colnames(shared$user_expr)) + if ( + pt == "umap_gene" && + nzchar(gene_sel) && + !is.null(shared$user_expr) && + gene_sel %in% rownames(shared$user_expr) + ) { + gene_vec <- setNames( + as.numeric(shared$user_expr[gene_sel, ]), + colnames(shared$user_expr) + ) } jobid <- tryCatch( - submit_session_task(shared, "plot", list( - plot_type = pt, - data = list( - # Spatial plots need only the slices listed here — carrying the - # full predictions/response matrices made params.rds serialize - # slowly (Gene Expression felt slow for no reason). - predictions = if (pt == "umap_viability") shared$predictions else NULL, - user_clones = shared$user_clones, - user_response = NULL, - patient_pred = NULL, - umap_gene_expr = gene_vec, - prepared = list( - umap_coords = umap_coords, - clone_viability_template = if (!is.null(pd)) pd$clone_viability_template else NULL + submit_session_task( + shared, + "plot", + list( + plot_type = pt, + data = list( + # Spatial plots need only the slices listed here — carrying the + # full predictions/response matrices made params.rds serialize + # slowly (Gene Expression felt slow for no reason). + predictions = if (pt == "umap_viability") { + shared$predictions + } else { + NULL + }, + user_clones = shared$user_clones, + user_response = NULL, + patient_pred = NULL, + umap_gene_expr = gene_vec, + prepared = list( + umap_coords = umap_coords, + clone_viability_template = if (!is.null(pd)) { + pd$clone_viability_template + } else { + NULL + } + ) + ), + params = list( + drug = "", + combo = FALSE, + roc_group_a = NULL, + roc_group_b = NULL, + umap_gene = gene_sel, + umap_drug = input$umap_drug ) - ), - params = list( - drug = "", - combo = FALSE, - roc_group_a = NULL, - roc_group_b = NULL, - umap_gene = gene_sel, - umap_drug = input$umap_drug ) - )), - error = function(e) { viz_busy(FALSE); viz_waiter$hide(); NULL } + ), + error = function(e) { + viz_busy(FALSE) + viz_waiter$hide() + NULL + } ) } else { jobid <- tryCatch( - submit_session_task(shared, "plot", list( - plot_type = pt, - data = list( - predictions = shared$predictions, - user_clones = shared$user_clones, - user_response = shared$user_response, - patient_pred = shared$patient_pred, - prepared = list( - umap_coords = NULL, - clone_viability_template = if (!is.null(pd)) pd$clone_viability_template else NULL + submit_session_task( + shared, + "plot", + list( + plot_type = pt, + data = list( + predictions = shared$predictions, + user_clones = shared$user_clones, + user_response = shared$user_response, + patient_pred = shared$patient_pred, + prepared = list( + umap_coords = NULL, + clone_viability_template = if (!is.null(pd)) { + pd$clone_viability_template + } else { + NULL + } + ) + ), + params = list( + drug = drug_sel, + combo = is_combo, + roc_group_a = input$roc_group_a, + roc_group_b = input$roc_group_b ) - ), - params = list( - drug = drug_sel, - combo = is_combo, - roc_group_a = input$roc_group_a, - roc_group_b = input$roc_group_b ) - )), - error = function(e) { viz_busy(FALSE); viz_waiter$hide(); NULL } + ), + error = function(e) { + viz_busy(FALSE) + viz_waiter$hide() + NULL + } ) } - if (is.null(jobid)) return() + if (is.null(jobid)) { + return() + } # After this generation settles (success or error), draw the newest # queued request, if any. Only the last queued request is kept. flush_pending <- function() { pt2 <- pending_plot() - if (is.null(pt2)) return() + if (is.null(pt2)) { + return() + } pending_plot(NULL) generate_plot(pt2) } - poll_task(shared, session, jobid, + poll_task( + shared, + session, + jobid, on_done = function(res) { viz_busy(FALSE) viz_waiter$hide() if (!is.null(res$plot)) { - assign(ck, list(plot = res$plot, message = res$message), envir = plot_cache) + assign( + ck, + list(plot = res$plot, message = res$message), + envir = plot_cache + ) current_plot(res$plot) current_plot_type(pt) current_plot_key(ck) - showNotification(paste0(plot_label(pt), " generated successfully"), type = "message") + showNotification( + paste0(plot_label(pt), " generated successfully"), + type = "message" + ) } else { msg <- res$message - if (is.null(msg) || !nzchar(msg)) msg <- "Selected plot type is not available with current data" + if (is.null(msg) || !nzchar(msg)) { + msg <- "Selected plot type is not available with current data" + } showNotification(msg, type = "warning") } flush_pending() @@ -660,41 +1067,71 @@ mod_visualize_server <- function(id, shared, main_session) { on_error = function(msg) { viz_busy(FALSE) viz_waiter$hide() - showNotification(paste("Plot error:", msg), type = "error", duration = 8) + showNotification( + paste("Plot error:", msg), + type = "error", + duration = 8 + ) flush_pending() - }) + } + ) } # --- Interactive rendering via ggiraph (unchanged) --- scaled_plot <- reactive({ req(current_plot()) p_obj <- current_plot() - if (inherits(p_obj, "gtable") || inherits(p_obj, "grob") || inherits(p_obj, "gTree") || - inherits(p_obj, "plotly") || inherits(p_obj, "htmlwidget")) { + if ( + inherits(p_obj, "gtable") || + inherits(p_obj, "grob") || + inherits(p_obj, "gTree") || + inherits(p_obj, "plotly") || + inherits(p_obj, "htmlwidget") + ) { p_obj <- ggplot2::ggplot() + - ggplot2::annotate("text", x = 0.5, y = 0.5, - label = "This plot type cannot be shown interactively.", - size = 5, color = "#5a6a8a") + + ggplot2::annotate( + "text", + x = 0.5, + y = 0.5, + label = "This plot type cannot be shown interactively.", + size = 5, + color = "#5a6a8a" + ) + ggplot2::theme_void() } scale <- text_scale() base <- p_obj$theme$text$size - if (is.null(base) || length(base) == 0 || !is.finite(base)) base <- 11 - if (scale == 1) return(p_obj) + if (is.null(base) || length(base) == 0 || !is.finite(base)) { + base <- 11 + } + if (scale == 1) { + return(p_obj) + } p_obj + - theme(text = element_text(size = base * scale), - plot.title = element_text(size = (base + 1) * scale, hjust = 0, vjust = 0, - face = "plain", margin = margin(b = 6)), - plot.subtitle = element_text(size = base * scale), - axis.title = element_text(size = base * scale), - axis.text = element_text(size = (base - 1) * scale), - legend.text = element_text(size = (base - 2) * scale), - legend.title = element_text(size = (base - 1) * scale), - strip.text = element_text(size = (base - 1) * scale)) + theme( + text = element_text(size = base * scale), + plot.title = element_text( + size = (base + 1) * scale, + hjust = 0, + vjust = 0, + face = "plain", + margin = margin(b = 6) + ), + plot.subtitle = element_text(size = base * scale), + axis.title = element_text(size = base * scale), + axis.text = element_text(size = (base - 1) * scale), + legend.text = element_text(size = (base - 2) * scale), + legend.title = element_text(size = (base - 1) * scale), + strip.text = element_text(size = (base - 1) * scale) + ) }) output$main_plot_host <- renderUI({ - if (is.null(current_plot())) NULL else ggiraph::girafeOutput(ns("main_plot")) + if (is.null(current_plot())) { + NULL + } else { + ggiraph::girafeOutput(ns("main_plot")) + } }) output$main_plot <- ggiraph::renderGirafe({ @@ -702,9 +1139,17 @@ mod_visualize_server <- function(id, shared, main_session) { ps <- preview_size() # Interactive SVG keeps the SAME aspect as the physical export size # (container-width responsive via opts_sizing) — WYSIWYG for downloads. - wkey <- paste(current_plot_key(), text_scale(), ps$w, ps$h, sep = "\u0001") + wkey <- paste( + current_plot_key(), + text_scale(), + ps$w, + ps$h, + sep = "\u0001" + ) cached_w <- get0(wkey, envir = widget_cache, inherits = FALSE) - if (!is.null(cached_w)) return(cached_w) + if (!is.null(cached_w)) { + return(cached_w) + } w <- ggiraph::girafe( ggobj = scaled_plot(), width_svg = max(ps$w / 100, 4), @@ -712,7 +1157,10 @@ mod_visualize_server <- function(id, shared, main_session) { options = list( ggiraph::opts_sizing(rescale = TRUE, width = 1), ggiraph::opts_tooltip( - use_cursor = TRUE, opacity = 0.92, offx = 14, offy = 14, + use_cursor = TRUE, + opacity = 0.92, + offx = 14, + offy = 14, css = "background-color:#1e2a4a;color:#ffffff;border-radius:5px; padding:7px 11px;font-size:12px;line-height:1.45; box-shadow:0 3px 10px rgba(0,0,0,0.30);" @@ -732,18 +1180,42 @@ mod_visualize_server <- function(id, shared, main_session) { # Instant feedback on the very first draw (before a plot exists the # card body would otherwise sit empty while the background worker runs). target <- pending_plot() - if (is.null(target)) target <- viz_selected() - div(class = "viz-gen-pending", - span(icon("spinner", class = "fa-spin", style = "margin-right: 0.35rem;")), - span(" Generating ", strong(if (!is.null(target) && nzchar(target)) plot_label(target) else "plot"), " …") + if (is.null(target)) { + target <- viz_selected() + } + div( + class = "viz-gen-pending", + span(icon( + "spinner", + class = "fa-spin", + style = "margin-right: 0.35rem;" + )), + span( + " Generating ", + strong( + if (!is.null(target) && nzchar(target)) { + plot_label(target) + } else { + "plot" + } + ), + " …" + ) ) } else if (is.null(current_plot())) { - div(class = "text-muted", style = "text-align: center; padding: 3rem;", - icon("chart-area", style = "font-size: 3rem; opacity: 0.15; display: block; margin-bottom: 0.8rem;"), + div( + class = "text-muted", + style = "text-align: center; padding: 3rem;", + icon( + "chart-area", + style = "font-size: 3rem; opacity: 0.15; display: block; margin-bottom: 0.8rem;" + ), "Click a card in the Plot Gallery to draw it.", br(), - span(style = "font-size: 0.82rem; opacity: 0.7;", - "Check the data readiness bar above for what is loaded") + span( + style = "font-size: 0.82rem; opacity: 0.7;", + "Check the data readiness bar above for what is loaded" + ) ) } else { NULL @@ -754,12 +1226,19 @@ mod_visualize_server <- function(id, shared, main_session) { output$plot_info_inline <- renderUI({ req(current_plot()) pt <- current_plot_type() - if (is.null(pt)) return(NULL) + if (is.null(pt)) { + return(NULL) + } utc_now <- format(Sys.time(), tz = "UTC", "%Y-%m-%d %H:%M UTC") - tags$span(class = "viz-info-inline", + tags$span( + class = "viz-info-inline", strong(plot_label(pt)), - tags$span(class = "text-muted", style = "margin-left: 0.5rem; font-size: 0.78rem;", - "Generated at ", utc_now) + tags$span( + class = "text-muted", + style = "margin-left: 0.5rem; font-size: 0.78rem;", + "Generated at ", + utc_now + ) ) }) @@ -768,9 +1247,16 @@ mod_visualize_server <- function(id, shared, main_session) { # knows what the figure means. No hover toggling — simple and stable. output$plot_explanation <- renderUI({ pt <- viz_selected() - if (is.null(pt) || !nzchar(pt)) return(NULL) - item <- gallery_items[[match(pt, vapply(gallery_items, function(x) x$id, ""))]] - if (is.null(item)) return(NULL) + if (is.null(pt) || !nzchar(pt)) { + return(NULL) + } + item <- gallery_items[[match( + pt, + vapply(gallery_items, function(x) x$id, "") + )]] + if (is.null(item)) { + return(NULL) + } info <- list( clone_dist = "Shows clone proportions within each patient. With global clustering, the same clone (color) genuinely spans patients. With clone-level input using per-patient labels (e.g. c1/c2/c3), the same color across patients does not imply the same clone origin — it is a shared category label.", clone_kill = "Displays predicted drug viability scores for each clone within each patient. Taller = higher viability = more resistant; shorter = lower viability = more sensitive. Use this to identify which subclones are most affected by treatment.", @@ -790,25 +1276,37 @@ mod_visualize_server <- function(id, shared, main_session) { umap_clone = "Clone annotation + 2D embedding coordinates (auto-generated by Seurat)" ) equal_weight_note <- NULL - if (pt == "clone_dist" && !is.null(shared$prepared_data) && + if ( + pt == "clone_dist" && + !is.null(shared$prepared_data) && identical(shared$prepared_data$reduction_method, "none") && - !isTRUE(shared$mapping_has_count)) { - equal_weight_note <- div(class = "info-box", + !isTRUE(shared$mapping_has_count) + ) { + equal_weight_note <- div( + class = "info-box", style = "border-left-color: var(--warning, #d97706); margin: 0.6rem 0 0.8rem 0; font-size: 0.82rem; line-height: 1.5;", icon("triangle-exclamation"), - " Clone-level input without a count column: proportions are equal (1/n per clone). Add a count column with real cell numbers in the mapping file to show true proportions.") + " Clone-level input without a count column: proportions are equal (1/n per clone). Add a count column with real cell numbers in the mapping file to show true proportions." + ) } - div(class = "card viz-explanation-card", - div(class = "card-header", - icon("circle-info"), " About This Plot" - ), - div(class = "card-body", + div( + class = "card viz-explanation-card", + div(class = "card-header", icon("circle-info"), " About This Plot"), + div( + class = "card-body", h6(strong(if (item$spatial) spatial_plot_label(pt) else item$title)), - p(class = "text-muted", style = "font-size: 0.85rem; line-height: 1.5; margin-bottom: 0.4rem;", - info[[pt]]), - tags$span(class = "viz-explanation-req", + p( + class = "text-muted", + style = "font-size: 0.85rem; line-height: 1.5; margin-bottom: 0.4rem;", + info[[pt]] + ), + tags$span( + class = "viz-explanation-req", icon("clipboard-check", style = "font-size: 0.75rem;"), - tags$span(style = "font-size: 0.78rem; font-weight: 600;", "Requires: "), + tags$span( + style = "font-size: 0.78rem; font-weight: 600;", + "Requires: " + ), tags$span(style = "font-size: 0.78rem;", requires_map[[pt]]) ), equal_weight_note @@ -820,18 +1318,37 @@ mod_visualize_server <- function(id, shared, main_session) { output$plot_download_inline <- renderUI({ req(current_plot()) tagList( - downloadButton(ns("download_png"), "PNG", class = "btn-outline-primary btn-sm"), - downloadButton(ns("download_pdf"), "PDF", class = "btn-outline-primary btn-sm") + downloadButton( + ns("download_png"), + "PNG", + class = "btn-outline-primary btn-sm" + ), + downloadButton( + ns("download_pdf"), + "PDF", + class = "btn-outline-primary btn-sm" + ) ) }) output$download_png <- downloadHandler( - filename = function() paste0("perceptionx_plot_", gsub("[-: ]", "", format(Sys.time(), tz = "UTC")), ".png"), + filename = function() { + paste0( + "perceptionx_plot_", + gsub("[-: ]", "", format(Sys.time(), tz = "UTC")), + ".png" + ) + }, content = function(file) { p <- scaled_plot() sz <- plot_size() - if (inherits(p, "gtable") || inherits(p, "grob") || inherits(p, "gTree") || - inherits(p, "plotly") || inherits(p, "htmlwidget")) { + if ( + inherits(p, "gtable") || + inherits(p, "grob") || + inherits(p, "gTree") || + inherits(p, "plotly") || + inherits(p, "htmlwidget") + ) { writeLines("This plot type cannot be exported as PNG.", file) return() } @@ -840,15 +1357,32 @@ mod_visualize_server <- function(id, shared, main_session) { # density on top of that, e.g. 100 % × 300 dpi → 3000 × 2250 px. w_in <- sz$w / 100 h_in <- sz$h / 100 - ok <- tryCatch({ - ragg::agg_png(file, width = w_in, height = h_in, units = "in", res = sz$dpi) - print(p) - dev.off() - TRUE - }, error = function(e) FALSE) + ok <- tryCatch( + { + ragg::agg_png( + file, + width = w_in, + height = h_in, + units = "in", + res = sz$dpi + ) + print(p) + dev.off() + TRUE + }, + error = function(e) FALSE + ) if (!ok) { - if (grDevices::dev.cur() > 1) grDevices::dev.off() - grDevices::png(file, width = w_in, height = h_in, units = "in", res = sz$dpi) + if (grDevices::dev.cur() > 1) { + grDevices::dev.off() + } + grDevices::png( + file, + width = w_in, + height = h_in, + units = "in", + res = sz$dpi + ) print(p) dev.off() } @@ -856,12 +1390,23 @@ mod_visualize_server <- function(id, shared, main_session) { ) output$download_pdf <- downloadHandler( - filename = function() paste0("perceptionx_plot_", gsub("[-: ]", "", format(Sys.time(), tz = "UTC")), ".pdf"), + filename = function() { + paste0( + "perceptionx_plot_", + gsub("[-: ]", "", format(Sys.time(), tz = "UTC")), + ".pdf" + ) + }, content = function(file) { p <- scaled_plot() sz <- plot_size() - if (inherits(p, "gtable") || inherits(p, "grob") || inherits(p, "gTree") || - inherits(p, "plotly") || inherits(p, "htmlwidget")) { + if ( + inherits(p, "gtable") || + inherits(p, "grob") || + inherits(p, "gTree") || + inherits(p, "plotly") || + inherits(p, "htmlwidget") + ) { writeLines("This plot type cannot be exported as PDF.", file) return() } @@ -879,9 +1424,16 @@ mod_visualize_server <- function(id, shared, main_session) { # These outputs are cheap when empty (gallery grid, status placeholder, # NULL param panel), so computing them eagerly costs nothing and makes # the tab appear fully rendered the moment it is activated. - for (out_name in c("readiness_bar", "gallery_grid", "param_panel", - "plot_status", "main_plot_host", "plot_info_inline", - "plot_download_inline", "plot_explanation")) { + for (out_name in c( + "readiness_bar", + "gallery_grid", + "param_panel", + "plot_status", + "main_plot_host", + "plot_info_inline", + "plot_download_inline", + "plot_explanation" + )) { outputOptions(output, out_name, suspendWhenHidden = FALSE) } }) diff --git a/inst/shiny/app/R/shiny_helpers.R b/inst/shiny/app/R/shiny_helpers.R index f20a243..2d3cb61 100644 --- a/inst/shiny/app/R/shiny_helpers.R +++ b/inst/shiny/app/R/shiny_helpers.R @@ -9,8 +9,12 @@ # background job so the full read happens in the worker, never the main # Shiny process. read_cached_meta <- function(depmap_path, cache_file) { - if (!file.exists(cache_file) || !file.exists(depmap_path)) return(NULL) - if (file.mtime(cache_file) < file.mtime(depmap_path)) return(NULL) + if (!file.exists(cache_file) || !file.exists(depmap_path)) { + return(NULL) + } + if (file.mtime(cache_file) < file.mtime(depmap_path)) { + return(NULL) + } tryCatch(readRDS(cache_file), error = function(e) NULL) } @@ -28,15 +32,17 @@ read_cached_meta <- function(depmap_path, cache_file) { # no namespacing is needed). # --------------------------------------------------------------------------- workflow_stepper_html <- function(shared, ns = identity) { - data_ok <- !is.null(shared$prepared_data) || - (!is.null(shared$user_expr) && !is.null(shared$user_clones)) - train_ok <- !is.null(shared$models) && length(shared$models) > 0 + data_ok <- !is.null(shared$prepared_data) || + (!is.null(shared$user_expr) && !is.null(shared$user_clones)) + train_ok <- !is.null(shared$models) && length(shared$models) > 0 predict_ok <- !is.null(shared$predictions) done <- c(data_ok, train_ok, predict_ok, FALSE) # "Active" = the first incomplete step (the user's next action). active_idx <- which(!done)[1] - if (is.na(active_idx)) active_idx <- 4L + if (is.na(active_idx)) { + active_idx <- 4L + } # Red "blocked" state — used SPARINGLY (red reads as error). Only for # Train when the user has data but no DepMap reference and no models: @@ -52,35 +58,55 @@ workflow_stepper_html <- function(shared, ns = identity) { ) status_done <- c("Data ready", "Model ready", "Predictions ready", "Complete") status_next <- c("Start here", "Next step", "Next step", "Next step") - status_todo <- c("Pending", "Pending", "Pending", "Pending") + status_todo <- c("Pending", "Pending", "Pending", "Pending") step_html <- lapply(seq_along(step_defs), function(i) { - st <- if (done[i]) "done" - else if (i == 2L && blocked2) "blocked" - else if (i == active_idx) "active" - else "todo" - label <- if (done[i]) status_done[i] - else if (i == 2L && blocked2) "Needs DepMap" - else if (i == active_idx) status_next[i] - else status_todo[i] - node <- if (done[i]) icon("check", style = "font-size: 1.05rem;") - else if (i == 2L && blocked2) icon("triangle-exclamation", style = "font-size: 1rem;") - else tags$span(i) - tags$div(class = paste("wf-step", st), + st <- if (done[i]) { + "done" + } else if (i == 2L && blocked2) { + "blocked" + } else if (i == active_idx) { + "active" + } else { + "todo" + } + label <- if (done[i]) { + status_done[i] + } else if (i == 2L && blocked2) { + "Needs DepMap" + } else if (i == active_idx) { + status_next[i] + } else { + status_todo[i] + } + node <- if (done[i]) { + icon("check", style = "font-size: 1.05rem;") + } else if (i == 2L && blocked2) { + icon("triangle-exclamation", style = "font-size: 1rem;") + } else { + tags$span(i) + } + tags$div( + class = paste("wf-step", st), # NOTE: child divs must go in `label`, NOT in `...` — Shiny >= 1.10 # validates `...` tag elements as icons (actionLink -> tags$a) and # errors with "Invalid icon" when a plain div is passed positionally. - actionLink(ns(step_defs[[i]]$id), label = tagList( - div(class = "wf-node", node), - div(class = "wf-step-title", step_defs[[i]]$title), - div(class = "wf-step-status", label) - ), class = "wf-step-link") + actionLink( + ns(step_defs[[i]]$id), + label = tagList( + div(class = "wf-node", node), + div(class = "wf-step-title", step_defs[[i]]$title), + div(class = "wf-step-status", label) + ), + class = "wf-step-link" + ) ) }) # Connector lines between steps — filled once the NEXT step is done. - lines <- lapply(seq_len(length(step_defs) - 1), function(i) - div(class = paste("wf-line", if (done[i + 1]) "filled" else ""))) + lines <- lapply(seq_len(length(step_defs) - 1), function(i) { + div(class = paste("wf-line", if (done[i + 1]) "filled" else "")) + }) children <- list() for (i in seq_along(step_defs)) { @@ -90,18 +116,24 @@ workflow_stepper_html <- function(shared, ns = identity) { hint <- if (blocked2) { "Data is ready, but training needs the DepMap reference — load it in the Data tab (or load pre-trained models) first." - } else switch(active_idx, - "1" = "Start: load data — or click Load Demo to try the whole pipeline instantly.", - "2" = "Data ready -> next: train (or load) a drug response model.", - "3" = "Model ready -> next: run clone- and patient-level prediction.", - "4" = "Predictions ready -> go to Visualize to generate plots.", - "All steps complete -> everything is ready. Explore the tabs!" - ) + } else { + switch( + active_idx, + "1" = "Start: load data — or click Load Demo to try the whole pipeline instantly.", + "2" = "Data ready -> next: train (or load) a drug response model.", + "3" = "Model ready -> next: run clone- and patient-level prediction.", + "4" = "Predictions ready -> go to Visualize to generate plots.", + "All steps complete -> everything is ready. Explore the tabs!" + ) + } tagList( div(class = "wf-steps", children), - div(class = if (blocked2) "wf-hint wf-hint-warn" else "wf-hint", - icon(if (blocked2) "triangle-exclamation" else "circle-info"), hint) + div( + class = if (blocked2) "wf-hint wf-hint-warn" else "wf-hint", + icon(if (blocked2) "triangle-exclamation" else "circle-info"), + hint + ) ) } @@ -115,61 +147,136 @@ data_dashboard_html <- function(shared) { # DepMap stats come from the lightweight metadata (the main process never # holds the full multi-GB object; the training master does). dm <- shared$depmap_meta - depmap_cell_lines <- if (!is.null(dm) && !is.null(dm$components$expression_rnorm)) - dm$components$expression_rnorm$ncol else NULL - depmap_drugs <- if (!is.null(dm) && !is.null(dm$components$secondary_prism)) - dm$components$secondary_prism$nrow else NULL - depmap_sc_models <- if (!is.null(dm) && !is.null(dm$components$scRNA_complete)) - dm$components$scRNA_complete$ncol else NULL + depmap_cell_lines <- if ( + !is.null(dm) && !is.null(dm$components$expression_rnorm) + ) { + dm$components$expression_rnorm$ncol + } else { + NULL + } + depmap_drugs <- if (!is.null(dm) && !is.null(dm$components$secondary_prism)) { + dm$components$secondary_prism$nrow + } else { + NULL + } + depmap_sc_models <- if ( + !is.null(dm) && !is.null(dm$components$scRNA_complete) + ) { + dm$components$scRNA_complete$ncol + } else { + NULL + } items <- list( - list(name = "DepMap Reference", icon_name = "database", - loaded = !is.null(dm), - detail = if (!is.null(dm)) - paste0(if (!is.null(depmap_cell_lines)) paste0(depmap_cell_lines, " cell lines, "), - if (!is.null(depmap_drugs)) paste0(depmap_drugs, " drugs"), - if (!is.null(depmap_sc_models)) paste0(", ", depmap_sc_models, " scRNA-seq profiles")) - else "Not loaded"), - list(name = "Expression Matrix", icon_name = "table", - loaded = !is.null(shared$user_expr), - detail = if (!is.null(shared$user_expr)) - paste0(nrow(shared$user_expr), " genes x ", ncol(shared$user_expr), " clones") - else "Not loaded"), - list(name = "Clone Map (Seurat)", icon_name = "layer-group", - loaded = !is.null(shared$prepared_data), - detail = if (!is.null(shared$prepared_data)) - paste0(ncol(shared$prepared_data$clone_expression_rnorm), " clones, ", - nrow(shared$prepared_data$clone_counts), " patients") - else "Not loaded"), - list(name = "Clinical Response", icon_name = "heartbeat", - loaded = !is.null(shared$user_response), - detail = if (!is.null(shared$user_response)) - paste0(nrow(shared$user_response), " patients") - else "Not loaded"), - list(name = "Drug Models", icon_name = "cube", - loaded = !is.null(shared$models), - detail = if (!is.null(shared$models)) - paste0(length(shared$models), " model(s): ", - paste(names(shared$models), collapse = ", ")) - else "Not loaded"), - list(name = "Predictions", icon_name = "microscope", - loaded = !is.null(shared$predictions), - detail = if (!is.null(shared$predictions)) - paste0(nrow(shared$predictions), " clones x ", ncol(shared$predictions), " drugs") - else "Not loaded") + list( + name = "DepMap Reference", + icon_name = "database", + loaded = !is.null(dm), + detail = if (!is.null(dm)) { + paste0( + if (!is.null(depmap_cell_lines)) { + paste0(depmap_cell_lines, " cell lines, ") + }, + if (!is.null(depmap_drugs)) paste0(depmap_drugs, " drugs"), + if (!is.null(depmap_sc_models)) { + paste0(", ", depmap_sc_models, " scRNA-seq profiles") + } + ) + } else { + "Not loaded" + } + ), + list( + name = "Expression Matrix", + icon_name = "table", + loaded = !is.null(shared$user_expr), + detail = if (!is.null(shared$user_expr)) { + paste0( + nrow(shared$user_expr), + " genes x ", + ncol(shared$user_expr), + " clones" + ) + } else { + "Not loaded" + } + ), + list( + name = "Clone Map (Seurat)", + icon_name = "layer-group", + loaded = !is.null(shared$prepared_data), + detail = if (!is.null(shared$prepared_data)) { + paste0( + ncol(shared$prepared_data$clone_expression_rnorm), + " clones, ", + nrow(shared$prepared_data$clone_counts), + " patients" + ) + } else { + "Not loaded" + } + ), + list( + name = "Clinical Response", + icon_name = "heartbeat", + loaded = !is.null(shared$user_response), + detail = if (!is.null(shared$user_response)) { + paste0(nrow(shared$user_response), " patients") + } else { + "Not loaded" + } + ), + list( + name = "Drug Models", + icon_name = "cube", + loaded = !is.null(shared$models), + detail = if (!is.null(shared$models)) { + paste0( + length(shared$models), + " model(s): ", + paste(names(shared$models), collapse = ", ") + ) + } else { + "Not loaded" + } + ), + list( + name = "Predictions", + icon_name = "microscope", + loaded = !is.null(shared$predictions), + detail = if (!is.null(shared$predictions)) { + paste0( + nrow(shared$predictions), + " clones x ", + ncol(shared$predictions), + " drugs" + ) + } else { + "Not loaded" + } + ) ) tagList( - div(class = "dashboard-grid", + div( + class = "dashboard-grid", lapply(items, function(item) { - div(class = paste("dashboard-card", if (item$loaded) "card-loaded" else "card-empty"), + div( + class = paste( + "dashboard-card", + if (item$loaded) "card-loaded" else "card-empty" + ), div(class = "dashboard-card-icon", icon(item$icon_name)), - div(class = "dashboard-card-body", + div( + class = "dashboard-card-body", div(class = "dashboard-card-name", item$name), div(class = "dashboard-card-detail", item$detail) ), - div(class = "dashboard-card-status", - span(class = paste("status-dot", if (item$loaded) "green" else "gray")) + div( + class = "dashboard-card-status", + span( + class = paste("status-dot", if (item$loaded) "green" else "gray") + ) ) ) }) @@ -194,25 +301,32 @@ data_dashboard_html <- function(shared) { # Human-readable stage text for the demo overlay, mapping the worker's # progress phases (prepare_data / Seurat step callbacks) to short labels. stage_text <- function(phase) { - switch(phase, - "seurat" = "Running Seurat clustering...", - "seurat-normalizing" = "Normalizing expression data...", + switch( + phase, + "seurat" = "Running Seurat clustering...", + "seurat-normalizing" = "Normalizing expression data...", "seurat-variable-features" = "Finding variable genes...", - "seurat-scaling" = "Scaling expression data...", - "seurat-pca" = "Running PCA...", - "seurat-neighbors" = "Building cell graph...", - "seurat-clustering" = "Clustering cells...", - "seurat-umap" = "Computing UMAP embedding...", - "seurat-tsne" = "Computing t-SNE embedding...", - "clones" = "Reading clone-level input...", - "mapping" = "Mapping cells to patients...", - "clone-expression" = "Computing clone-level expression...", - "rank-normalizing" = "Rank-normalizing expression...", - "clone-counts" = "Building clone abundance table...", - "Running Seurat clustering...") + "seurat-scaling" = "Scaling expression data...", + "seurat-pca" = "Running PCA...", + "seurat-neighbors" = "Building cell graph...", + "seurat-clustering" = "Clustering cells...", + "seurat-umap" = "Computing UMAP embedding...", + "seurat-tsne" = "Computing t-SNE embedding...", + "clones" = "Reading clone-level input...", + "mapping" = "Mapping cells to patients...", + "clone-expression" = "Computing clone-level expression...", + "rank-normalizing" = "Rank-normalizing expression...", + "clone-counts" = "Building clone abundance table...", + "Running Seurat clustering..." + ) } -run_demo_pipeline <- function(shared, session, on_success = NULL, on_error = NULL) { +run_demo_pipeline <- function( + shared, + session, + on_success = NULL, + on_error = NULL +) { # The whole demo (structured data + Seurat clustering + 2 demo models) runs # in the per-session background worker (task "demo", see async_jobs.R), so # the main Shiny thread never blocks other users while it prepares. @@ -231,40 +345,75 @@ run_demo_pipeline <- function(shared, session, on_success = NULL, on_error = NUL # and if it still failed the caller (mod_data / mod_home) would otherwise # leave demo_busy = TRUE forever, making every later click report # "Demo data is already being prepared..." without ever loading. - if (!is.null(on_error)) on_error() - showNotification(paste("Demo failed to start:", e$message), type = "error", duration = 12) + if (!is.null(on_error)) { + on_error() + } + showNotification( + paste("Demo failed to start:", e$message), + type = "error", + duration = 12 + ) NULL } ) - if (is.null(jobid)) return(invisible(NULL)) - poll_task(shared, session, jobid, + if (is.null(jobid)) { + return(invisible(NULL)) + } + poll_task( + shared, + session, + jobid, # Live Seurat stage text in the demo overlay (normalizing / PCA / # clustering / UMAP / ...). on_progress = function(phase, i, n, drug) { - session$sendCustomMessage("set-demo-stage", list(text = stage_text(phase))) + session$sendCustomMessage( + "set-demo-stage", + list(text = stage_text(phase)) + ) }, on_done = function(res) { hide_overlay() shared$user_response <- res$user_response - shared$user_mapping <- res$user_mapping - shared$user_expr <- res$user_expr # stays CELL-level for spatial plots + shared$user_mapping <- res$user_mapping + shared$user_expr <- res$user_expr # stays CELL-level for spatial plots shared$prepared_data <- res$prepared_data - shared$user_clones <- res$user_clones - shared$models <- res$models - shared$model_cache <- res$models - shared$model_active <- setNames(rep(TRUE, length(res$models)), names(res$models)) + shared$user_clones <- res$user_clones + shared$models <- res$models + shared$model_cache <- res$models + shared$model_active <- setNames( + rep(TRUE, length(res$models)), + names(res$models) + ) n_clones <- ncol(res$prepared_data$clone_expression_rnorm) - if (!is.null(on_success)) on_success() - showNotification(paste0("Demo data loaded: ", nrow(res$user_expr), " genes x ", - ncol(res$user_expr), " cells, ", nrow(res$user_response), - " patients, ", n_clones, " clones detected. Models ready!"), - type = "message", duration = 6) + if (!is.null(on_success)) { + on_success() + } + showNotification( + paste0( + "Demo data loaded: ", + nrow(res$user_expr), + " genes x ", + ncol(res$user_expr), + " cells, ", + nrow(res$user_response), + " patients, ", + n_clones, + " clones detected. Models ready!" + ), + type = "message", + duration = 6 + ) }, on_error = function(msg) { hide_overlay() - showNotification(paste("Demo data preparation error:", msg), type = "error", duration = 10) + showNotification( + paste("Demo data preparation error:", msg), + type = "error", + duration = 10 + ) if (!is.null(on_error)) on_error() - }) + } + ) invisible(NULL) } @@ -284,7 +433,9 @@ run_demo_pipeline <- function(shared, session, on_success = NULL, on_error = NUL extract_model_features <- function(m) { if (inherits(m, "train")) { feats <- setdiff(colnames(m$trainingData), ".outcome") - if (length(feats) > 0) return(feats) + if (length(feats) > 0) { + return(feats) + } feats <- colnames(m$trainingData) if (length(feats) > 1) return(feats[-1]) } @@ -304,19 +455,30 @@ extract_model_features <- function(m) { # $overlaps: named integer vector of overlap counts (NA = no features # could be extracted from the model). check_model_expression_compat <- function(models, expr_genes) { - empty <- list(incompatible = character(0), n_genes = 0, - overlaps = setNames(integer(0), character(0))) - if (is.null(models) || length(models) == 0) return(empty) + empty <- list( + incompatible = character(0), + n_genes = 0, + overlaps = setNames(integer(0), character(0)) + ) + if (is.null(models) || length(models) == 0) { + return(empty) + } if (is.null(expr_genes) || length(expr_genes) == 0) { # No expression data to compare against -> nothing to warn about. - return(list(incompatible = character(0), n_genes = 0, - overlaps = setNames(rep(NA_integer_, length(models)), names(models)))) + return(list( + incompatible = character(0), + n_genes = 0, + overlaps = setNames(rep(NA_integer_, length(models)), names(models)) + )) } expr_made <- make.names(expr_genes, unique = TRUE) overlaps <- setNames(integer(length(models)), names(models)) for (nm in names(models)) { feats <- extract_model_features(models[[nm]]$model) - if (length(feats) == 0) { overlaps[[nm]] <- NA_integer_; next } + if (length(feats) == 0) { + overlaps[[nm]] <- NA_integer_ + next + } ov <- intersect(feats, expr_genes) # Hyphen-vs-dot fallback (same rule as the prediction pre-check). if (length(ov) == 0) { @@ -324,9 +486,11 @@ check_model_expression_compat <- function(models, expr_genes) { } overlaps[[nm]] <- length(ov) } - list(incompatible = names(overlaps)[!is.na(overlaps) & overlaps == 0], - n_genes = length(expr_genes), - overlaps = overlaps) + list( + incompatible = names(overlaps)[!is.na(overlaps) & overlaps == 0], + n_genes = length(expr_genes), + overlaps = overlaps + ) } # Names of the SIMULATED demo models (attr model_source == "demo") in a model @@ -334,10 +498,16 @@ check_model_expression_compat <- function(models, expr_genes) { # visibly labelled wherever they appear so their output is never mistaken for # a real drug-response prediction. demo_models <- function(models) { - if (is.null(models) || length(models) == 0) return(character(0)) - src <- vapply(models, function(m) { - s <- attr(m, "model_source") - if (is.null(s)) NA_character_ else as.character(s) - }, character(1)) + if (is.null(models) || length(models) == 0) { + return(character(0)) + } + src <- vapply( + models, + function(m) { + s <- attr(m, "model_source") + if (is.null(s)) NA_character_ else as.character(s) + }, + character(1) + ) names(models)[!is.na(src) & src == "demo"] } diff --git a/inst/shiny/app/app.R b/inst/shiny/app/app.R index 32ab052..98a16cb 100644 --- a/inst/shiny/app/app.R +++ b/inst/shiny/app/app.R @@ -11,14 +11,14 @@ library(ggplot2) # Allow large uploads: single-cell matrices / RDS reference files can far # exceed Shiny's default 5 MB limit. -options(shiny.maxRequestSize = 1 * 1024^3) # 1 GB (DepMap.RDS is ~567 MB) +options(shiny.maxRequestSize = 1 * 1024^3) # 1 GB (DepMap.RDS is ~567 MB) # Long synchronous tasks (model training, large uploads/parsing) block the # single R thread, so the browser heartbeat cannot be answered while they run. # The default heartbeat timeout is 60s — multi-drug training can exceed that, # the browser drops the WebSocket, and the "hiding" messages (waiter, progress) # are lost, leaving spinners stuck on screen. Raise it so sessions survive. -options(shiny.heartbeat.timeout = 1800) # 30 minutes, then consider dead +options(shiny.heartbeat.timeout = 1800) # 30 minutes, then consider dead # --------------------------------------------------------------------------- # sass/bslib compile cache. On hosted deployments (Shiny Server) sass defaults @@ -43,11 +43,17 @@ options(sass.cache = file.path(tempdir(check = TRUE), "sass-cache")) # a data URI (both in and inside styles.css backgrounds). # --------------------------------------------------------------------------- perception_asset <- function(name) { - paste(readLines(file.path(perception_www_dir, name), warn = FALSE), collapse = "\n") + paste( + readLines(file.path(perception_www_dir, name), warn = FALSE), + collapse = "\n" + ) } perception_favicon_uri <- function() { svg <- perception_asset("favicon.svg") - paste0("data:image/svg+xml;charset=utf-8,", utils::URLencode(svg, reserved = TRUE)) + paste0( + "data:image/svg+xml;charset=utf-8,", + utils::URLencode(svg, reserved = TRUE) + ) } # Auto-detect package root robustly, regardless of how the app is launched @@ -66,10 +72,10 @@ pkg_root <- NULL script_dir <- tryCatch(dirname(sys.frame(1)$ofile), error = function(e) NULL) candidates <- c( if (!is.null(script_dir)) file.path(script_dir, "..", "..", ".."), - file.path(getwd(), "..", "..", ".."), # cwd = inst/shiny/app - file.path(getwd(), "..", ".."), # cwd = inst/shiny - file.path(getwd(), ".."), # cwd = inst - file.path(getwd()) # cwd = repo root + file.path(getwd(), "..", "..", ".."), # cwd = inst/shiny/app + file.path(getwd(), "..", ".."), # cwd = inst/shiny + file.path(getwd(), ".."), # cwd = inst + file.path(getwd()) # cwd = repo root ) for (cand in candidates) { if (is_src_root(cand)) { @@ -95,7 +101,9 @@ if (!is.null(pkg_root)) { # the normal, expected path for deployments. library(PERCEPTIONx) } else { - stop("Neither devtools (with repo) nor PERCEPTIONx is available. Please install PERCEPTIONx.") + stop( + "Neither devtools (with repo) nor PERCEPTIONx is available. Please install PERCEPTIONx." + ) } # Tutorial screenshots are referenced with relative srcs ("figures/x.png"). @@ -147,9 +155,14 @@ perception_theme <- bs_theme( ui <- page_navbar( theme = perception_theme, title = tagList( - tags$span(class = "brand-icon", - tags$img(src = perception_favicon_uri(), height = "28", alt = "PERCEPTION-shiny", - style = "vertical-align: middle; margin-right: 0.3rem;") + tags$span( + class = "brand-icon", + tags$img( + src = perception_favicon_uri(), + height = "28", + alt = "PERCEPTION-shiny", + style = "vertical-align: middle; margin-right: 0.3rem;" + ) ), tags$span(class = "brand-text", "PERCEPTION-shiny") ), @@ -162,21 +175,34 @@ ui <- page_navbar( # buttons show it instantly from their onclick (no ~1s round trip before # feedback); the server hides it via 'hide-demo-overlay' when the demo # task finishes or fails. - div(id = "demo-overlay", class = "demo-overlay", style = "display: none;", + div( + id = "demo-overlay", + class = "demo-overlay", + style = "display: none;", div(class = "spinner-ring"), h4("Preparing demo data..."), - p(id = "demo-stage", class = "text-muted", "Running Seurat clustering...")), + p(id = "demo-stage", class = "text-muted", "Running Seurat clustering...") + ), # Assets are inlined (see the perception_asset block above) — no external # file requests, so no www/ directory is needed on the server. The # favicon.svg references inside styles.css are swapped for the data URI. tags$head(tags$style(HTML( - gsub("url('favicon.svg')", paste0("url(\"", perception_favicon_uri(), "\")"), - perception_asset("styles.css"), fixed = TRUE)))), + gsub( + "url('favicon.svg')", + paste0("url(\"", perception_favicon_uri(), "\")"), + perception_asset("styles.css"), + fixed = TRUE + ) + ))), tags$head(tags$style(HTML(perception_asset("tour.css")))), tags$head(tags$script(HTML(perception_asset("tour.js")))), - tags$head(tags$link(rel = "icon", href = perception_favicon_uri(), - type = "image/svg+xml")), - tags$head(tags$script(HTML(" + tags$head(tags$link( + rel = "icon", + href = perception_favicon_uri(), + type = "image/svg+xml" + )), + tags$head(tags$script(HTML( + " Shiny.addCustomMessageHandler('scroll-to', function(id) { var el = document.getElementById(id); if (el) el.scrollIntoView({behavior: 'smooth', block: 'start'}); @@ -244,7 +270,8 @@ ui <- page_navbar( setTimeout(function() { window.scrollTo(0, y); }, ms); }); }); - "))) + " + ))) ), nav_spacer(), nav_item(tagList( @@ -311,7 +338,7 @@ ui <- page_navbar( server <- function(input, output, session) { # Shared reactive values shared <- reactiveValues( - depmap_meta = NULL, # lightweight DepMap metadata only (genes/drugs/dims) + depmap_meta = NULL, # lightweight DepMap metadata only (genes/drugs/dims) depmap_path = NULL, depmap_is_standard = FALSE, models = NULL, @@ -335,7 +362,9 @@ server <- function(input, output, session) { # heavy Seurat / caret / glmnet namespaces are already loaded when the user # first runs Seurat clustering / the demo — that ~3-4 s load no longer sits # inside the first prepare/demo task. - tryCatch(submit_session_task(shared, "warmup", list()), error = function(e) NULL) + tryCatch(submit_session_task(shared, "warmup", list()), error = function(e) { + NULL + }) # Modules — pass main session for cross-module navigation mod_home_server("home", shared, session) @@ -380,8 +409,11 @@ server <- function(input, output, session) { # mid-flight has been aborted by the kill above. for (dir_key in c("task_jobs_dir", "jobs_dir")) { d <- isolate(shared[[dir_key]]) - if (!is.null(d) && nzchar(d) && - grepl("perception_tasks|perception_jobs_custom", d, fixed = FALSE)) { + if ( + !is.null(d) && + nzchar(d) && + grepl("perception_tasks|perception_jobs_custom", d, fixed = FALSE) + ) { unlink(d, recursive = TRUE) } } diff --git a/man/PERCEPTIONx-package.Rd b/man/PERCEPTIONx-package.Rd index bdc5d49..87b8475 100644 --- a/man/PERCEPTIONx-package.Rd +++ b/man/PERCEPTIONx-package.Rd @@ -34,5 +34,10 @@ Authors: \item Jia Ding \email{jiading682@qq.com} (\href{https://orcid.org/0009-0002-2530-0897}{ORCID}) } +Other contributors: +\itemize{ + \item Yuxi Yang \email{15364051195@163.com} (\href{https://orcid.org/0009-0006-1329-1224}{ORCID}) [contributor] +} + } \keyword{internal} diff --git a/man/annotate_clones.Rd b/man/annotate_clones.Rd index 98fa062..c50ce9c 100644 --- a/man/annotate_clones.Rd +++ b/man/annotate_clones.Rd @@ -7,14 +7,14 @@ annotate_clones( method = c("umap", "tsne"), expression_matrix, - min_cells = 3, - min_features = 200, - nfeatures = 2000, - dims = 10, + min_cells = 3L, + min_features = 200L, + nfeatures = 2000L, + dims = 10L, resolution = 0.8, - seed = 42, + seed = 42L, progress_cb = NULL, - cluster_algorithm = 1, + cluster_algorithm = 1L, variable_selection = c("vst", "dispersion", "mvp") ) } diff --git a/man/build_on_BULK_v2.Rd b/man/build_on_BULK_v2.Rd index 9574702..dcb6f8d 100644 --- a/man/build_on_BULK_v2.Rd +++ b/man/build_on_BULK_v2.Rd @@ -9,16 +9,16 @@ build_on_BULK_v2( infunc_cancerType = "PanCan", exclude_cancer = "PanCan", infunc_features, - single_best = infunc_features[1], - k_features = 100, - infunc_alpha = 1, + single_best = infunc_features[1L], + k_features = 100L, + infunc_alpha = 1L, model_type = "glmnet", - num_folds = 3, - num_tree = 500, - seed = 1, + num_folds = 3L, + num_tree = 500L, + seed = 1L, alpha_gradient = 0.05, - lambda_gradient = 20, - lambda_range = c(1e-04, 1), + lambda_gradient = 20L, + lambda_range = c(1e-04, 1L), cv_method = "cv" ) } diff --git a/man/combine_drugs.Rd b/man/combine_drugs.Rd index ec56df3..4fee4a2 100644 --- a/man/combine_drugs.Rd +++ b/man/combine_drugs.Rd @@ -14,11 +14,12 @@ combine_drugs( ) } \arguments{ -\item{pred}{Matrix or data.frame of clone-level drug viability predictions. -Typically the output of \code{\link[=predict_drugs]{predict_drugs()}}. Rows = clones, columns = drugs. -Row names must be canonical PERCEPTION clone keys -(\code{"patient@clone_id"}). Alternatively, pass a \code{data.frame} with -an explicit \code{patient} column and a \code{clone_id} column.} +\item{pred}{Matrix, data.frame, or data.table of clone-level drug viability +predictions. Typically the output of \code{\link[=predict_drugs]{predict_drugs()}}. Rows = clones, +columns = drugs. Row names must be canonical PERCEPTION clone keys +(\code{"patient@clone_id"}). Alternatively, pass a \code{data.frame} / +\code{data.table} with an explicit \code{patient} column and a +\code{clone_id} column.} \item{patient}{Optional character vector of patient IDs, length equal to \code{nrow(pred)}. Required only when \code{pred} row names are NOT diff --git a/man/each_patient_pseudo_bulk.Rd b/man/each_patient_pseudo_bulk.Rd index 9341c8f..6024c30 100644 --- a/man/each_patient_pseudo_bulk.Rd +++ b/man/each_patient_pseudo_bulk.Rd @@ -5,7 +5,7 @@ \title{Compute pseudo-bulk expression for a patient} \usage{ each_patient_pseudo_bulk( - x = 1, + x = 1L, comb_viability_df, Clone_Counts_per_patients, clone_Level_z_expression_df diff --git a/man/export_plot_cairo.Rd b/man/export_plot_cairo.Rd index 208ea0a..075fc95 100644 --- a/man/export_plot_cairo.Rd +++ b/man/export_plot_cairo.Rd @@ -8,9 +8,9 @@ export_plot_cairo( file, plot, format = "png", - width = 7, - height = 5, - res = 600, + width = 7L, + height = 5L, + res = 600L, draw_fun = NULL ) } diff --git a/man/load_depmap.Rd b/man/load_depmap.Rd index 34c2f93..edf2c8d 100644 --- a/man/load_depmap.Rd +++ b/man/load_depmap.Rd @@ -9,8 +9,8 @@ load_depmap( read = FALSE, mirror = FALSE, mirror_url = NULL, - timeout_seconds = 300, - retries = 1, + timeout_seconds = 300L, + retries = 1L, force = FALSE ) } diff --git a/man/load_model.Rd b/man/load_model.Rd index d2fdf01..91552bf 100644 --- a/man/load_model.Rd +++ b/man/load_model.Rd @@ -10,8 +10,8 @@ load_model( read = FALSE, mirror = FALSE, mirror_url = NULL, - timeout_seconds = 30, - retries = 0, + timeout_seconds = 30L, + retries = 0L, force = FALSE, all = FALSE ) diff --git a/man/perception_depmap_drugs.Rd b/man/perception_depmap_drugs.Rd new file mode 100644 index 0000000..d7cbb70 --- /dev/null +++ b/man/perception_depmap_drugs.Rd @@ -0,0 +1,19 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/drugs.R +\name{perception_depmap_drugs} +\alias{perception_depmap_drugs} +\title{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.} +\usage{ +perception_depmap_drugs +} +\description{ +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. +} diff --git a/man/perception_fda_approved_drugs.Rd b/man/perception_fda_approved_drugs.Rd new file mode 100644 index 0000000..d3dce75 --- /dev/null +++ b/man/perception_fda_approved_drugs.Rd @@ -0,0 +1,15 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/drugs.R +\name{perception_fda_approved_drugs} +\alias{perception_fda_approved_drugs} +\title{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.} +\usage{ +perception_fda_approved_drugs +} +\description{ +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. +} diff --git a/man/plot_clone_distribution.Rd b/man/plot_clone_distribution.Rd index 9cc33f5..bb1d628 100644 --- a/man/plot_clone_distribution.Rd +++ b/man/plot_clone_distribution.Rd @@ -7,7 +7,7 @@ plot_clone_distribution( clone_distribution, response_var = NULL, - base_size = 15, + base_size = 15L, tooltip = TRUE, tooltip_col = NULL ) diff --git a/man/plot_clone_umap.Rd b/man/plot_clone_umap.Rd index 68a869d..519e17d 100644 --- a/man/plot_clone_umap.Rd +++ b/man/plot_clone_umap.Rd @@ -10,7 +10,7 @@ plot_clone_umap( title = NULL, color_label = "Clone", point_size = NULL, - base_size = 11, + base_size = 11L, tooltip = TRUE, tooltip_col = NULL ) diff --git a/man/plot_clone_viability.Rd b/man/plot_clone_viability.Rd index 068bec5..a6c66a7 100644 --- a/man/plot_clone_viability.Rd +++ b/man/plot_clone_viability.Rd @@ -10,8 +10,8 @@ plot_clone_viability( weights_var = NULL, response_var = NULL, drug = NULL, - base_size = 11, - y_limits = c(-3, 1.2), + base_size = 11L, + y_limits = c(-3L, 1.2), viridis_scale = FALSE, tooltip = TRUE, tooltip_col = NULL diff --git a/man/plot_model_performance.Rd b/man/plot_model_performance.Rd index 79e1306..03a5a7f 100644 --- a/man/plot_model_performance.Rd +++ b/man/plot_model_performance.Rd @@ -7,7 +7,7 @@ plot_model_performance( performance_list, threshold_range = NULL, - base_size = 20, + base_size = 20L, highlight_threshold = 0.3, tooltip = TRUE ) diff --git a/man/plot_model_roc.Rd b/man/plot_model_roc.Rd index b1a359e..495ad48 100644 --- a/man/plot_model_roc.Rd +++ b/man/plot_model_roc.Rd @@ -4,7 +4,7 @@ \alias{plot_model_roc} \title{Plot validation ROC curves for trained models} \usage{ -plot_model_roc(performance_list, base_size = 13) +plot_model_roc(performance_list, base_size = 13L) } \arguments{ \item{performance_list}{Named list of model objects from \code{train_models()}, diff --git a/man/plot_response_boxplot.Rd b/man/plot_response_boxplot.Rd index 5ac941f..ac05d08 100644 --- a/man/plot_response_boxplot.Rd +++ b/man/plot_response_boxplot.Rd @@ -9,7 +9,7 @@ plot_response_boxplot( response_var = "response", predicted_var = "predicted_viability", y_label = "Predicted Viability (z-score)", - base_size = 15, + base_size = 15L, compare_method = "wilcox.test", alternative = "less", tooltip = TRUE diff --git a/man/plot_roc_curve.Rd b/man/plot_roc_curve.Rd index c661a5b..7876a5a 100644 --- a/man/plot_roc_curve.Rd +++ b/man/plot_roc_curve.Rd @@ -8,8 +8,8 @@ plot_roc_curve( response, predictor, smooth_curve = TRUE, - base_size = 15, - auc_digits = 3, + base_size = 15L, + auc_digits = 3L, title = NULL, tooltip = TRUE ) diff --git a/man/plot_seurat_clustering.Rd b/man/plot_seurat_clustering.Rd index ce68f19..2107824 100644 --- a/man/plot_seurat_clustering.Rd +++ b/man/plot_seurat_clustering.Rd @@ -7,12 +7,12 @@ plot_seurat_clustering( method = c("umap", "tsne"), expression_matrix, - min_cells = 3, - min_features = 200, - nfeatures = 2000, - dims = 10, + min_cells = 3L, + min_features = 200L, + nfeatures = 2000L, + dims = 10L, resolution = 0.8, - seed = 1 + seed = 1L ) } \arguments{ diff --git a/man/plot_tsne_biomarker_viability.Rd b/man/plot_tsne_biomarker_viability.Rd index 5d82174..cc30957 100644 --- a/man/plot_tsne_biomarker_viability.Rd +++ b/man/plot_tsne_biomarker_viability.Rd @@ -10,8 +10,8 @@ plot_tsne_biomarker_viability( viability_var = "viability_scaled", biomarker_label = "Biomarker Exp", viability_label = "Drug Viability", - nrow = 1, - base_size = 8 + nrow = 1L, + base_size = 8L ) } \arguments{ diff --git a/man/plot_tsne_response.Rd b/man/plot_tsne_response.Rd index e7b51cc..4d27a81 100644 --- a/man/plot_tsne_response.Rd +++ b/man/plot_tsne_response.Rd @@ -12,9 +12,9 @@ plot_tsne_response( point_size = NULL, colors = NULL, palette = c("viridis", "diverging"), - midpoint = 0, + midpoint = 0L, limits = NULL, - base_size = 11, + base_size = 11L, tooltip = TRUE, tooltip_col = NULL ) diff --git a/man/predict_drugs.Rd b/man/predict_drugs.Rd index b18997e..991d668 100644 --- a/man/predict_drugs.Rd +++ b/man/predict_drugs.Rd @@ -10,8 +10,10 @@ predict_drugs(model_list, expr) \item{model_list}{A named list of model objects (each with a \code{$model} element), or a single model object. From \code{train_models()} or \code{load_model()}.} -\item{expr}{Matrix or data frame. Rank-normalized expression matrix with -genes as rows and cells/samples as columns.} +\item{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.} } \value{ A matrix with cells/samples as rows and drugs as columns, diff --git a/man/predict_patients.Rd b/man/predict_patients.Rd index d09fc54..3d61e0a 100644 --- a/man/predict_patients.Rd +++ b/man/predict_patients.Rd @@ -19,11 +19,12 @@ and drugs as columns. Row names should match clone column names from \item{prepared_data}{List from \code{prepare_data()}, containing \code{$clone_viability_template} and \code{$clone_counts}. Alternatively, -you can pass \code{clone_counts} directly as a data frame (legacy mode).} +you can pass \code{clone_counts} directly as a data frame or data.table +(legacy mode).} -\item{clone_counts}{Optional. Data frame with patients as rows and clone IDs -as columns. Only needed if \code{prepared_data} is not a list from -\code{prepare_data()}.} +\item{clone_counts}{Optional. Data frame or data.table with patients as rows +and clone IDs as columns. Only needed if \code{prepared_data} is not a +list from \code{prepare_data()}.} \item{mode}{Character. Aggregation method: \describe{ diff --git a/man/prepare_data.Rd b/man/prepare_data.Rd index 5c58a4b..b3ca48c 100644 --- a/man/prepare_data.Rd +++ b/man/prepare_data.Rd @@ -12,14 +12,14 @@ prepare_data( patient_col = "patient_id", parse_patient = FALSE, patient_sep = "_", - patient_pos = 1, + patient_pos = 1L, genes_to_use = NULL, seurat_resolution = 0.8, - seurat_dims = 10, - seurat_nfeatures = 2000, - seurat_min_cells = 3, - seurat_min_features = 200, - seurat_seed = 42, + seurat_dims = 10L, + seurat_nfeatures = 2000L, + seurat_min_cells = 3L, + seurat_min_features = 200L, + seurat_seed = 42L, skip_clustering = FALSE, progress_cb = NULL ) diff --git a/man/run_parallel_feature_ranking_bulk.Rd b/man/run_parallel_feature_ranking_bulk.Rd index de2382d..9457d06 100644 --- a/man/run_parallel_feature_ranking_bulk.Rd +++ b/man/run_parallel_feature_ranking_bulk.Rd @@ -9,7 +9,7 @@ run_parallel_feature_ranking_bulk( id_cancerType = "PanCan", infunc_exclude_cancer = "PanCan", infunc_GOI, - ncores = 4 + ncores = 4L ) } \arguments{ diff --git a/man/train_models.Rd b/man/train_models.Rd index 6ae7df4..79f11a3 100644 --- a/man/train_models.Rd +++ b/man/train_models.Rd @@ -10,15 +10,15 @@ train_models( exclude_cancer = "PanCan", GOI = NULL, k_features_values = NULL, - ncores = 4, + ncores = 4L, output_dir = "./models", model_type = "glmnet", - num_folds = 3, - num_tree = 500, - seed = 1, + num_folds = 3L, + num_tree = 500L, + seed = 1L, alpha_gradient = 0.05, - lambda_gradient = 20, - lambda_range = c(1e-04, 1), + lambda_gradient = 20L, + lambda_range = c(1e-04, 1L), cv_method = "cv", progress_cb = NULL ) From 1eb2f8865d9968ee89675ff978256730c33ede31 Mon Sep 17 00:00:00 2001 From: Exceret <15364051195@163.com> Date: Thu, 5 Nov 2026 02:59:34 -0500 Subject: [PATCH 3/4] refactor: standardize progress reporting, CLI messaging, and drug list export --- .Rbuildignore | 2 + .gitignore | 4 +- DESCRIPTION | 3 +- NAMESPACE | 1 + R/PERCEPTIONx-package.R | 41 +++------ R/annotate.R | 1 + R/load.R | 106 +++++++++-------------- R/plot.R | 36 ++++---- R/train.R | 150 ++++++++++++++++---------------- R/utils.R | 1 - _pkgdown.yml | 1 + dev/e2e_concurrent.R | 9 +- dev/e2e_session.R | 9 +- dev/test_edge.R | 9 +- dev/test_unit.R | 13 +-- dev/verify_fixes.R | 11 +-- dev/verify_install.R | 11 +-- inst/shiny/app/R/async_jobs.R | 21 ++--- inst/shiny/app/R/mod_data.R | 22 ++--- man/feature_ranking_bulk.Rd | 5 +- man/perception_all_drugs.Rd | 17 ++++ tools/test_parse_patient.R | 32 ++++--- tools/test_pipeline.R | 158 +++++++++++++++++++++++----------- tools/test_pipeline_v2.R | 98 ++++++++++++++------- 24 files changed, 432 insertions(+), 329 deletions(-) create mode 100644 man/perception_all_drugs.Rd diff --git a/.Rbuildignore b/.Rbuildignore index faba5e2..aa80659 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -21,3 +21,5 @@ ^jarl\.toml$ \.qs2$ ^README\.Rmd$ +^test_pipeline_output$ +^test_pipeline_v2_output$ \ No newline at end of file diff --git a/.gitignore b/.gitignore index 62b3a74..39ebb30 100644 --- a/.gitignore +++ b/.gitignore @@ -46,4 +46,6 @@ inst/testdata/ # pkgdown site output (built by CI, deployed to gh-pages) docs/ -*.qs2 \ No newline at end of file +*.qs2 +test_pipeline_output/ +test_pipeline_v2_output/ \ No newline at end of file diff --git a/DESCRIPTION b/DESCRIPTION index 8ae9a29..394b347 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -50,7 +50,8 @@ Suggests: WGCNA, matrixStats, glmnet, - randomForest + randomForest, + kableExtra Config/testthat/edition: 3 Language: en-US Config/roxygen2/version: 8.1.0 diff --git a/NAMESPACE b/NAMESPACE index 06206ac..262d0c1 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -26,6 +26,7 @@ export(list_mirrors) export(load_depmap) export(load_model) export(parse_clone_keys) +export(perception_all_drugs) export(perception_depmap_drugs) export(perception_fda_approved_drugs) export(plot_clone_distribution) diff --git a/R/PERCEPTIONx-package.R b/R/PERCEPTIONx-package.R index bb0a44f..9716474 100644 --- a/R/PERCEPTIONx-package.R +++ b/R/PERCEPTIONx-package.R @@ -21,19 +21,21 @@ .onAttach <- function(libname, pkgname) { if (startup_message_allowed()) { - pkg_version <- utils::packageVersion(pkgname) - end <- Sys.time() - elapsed <- cli_timestamp_formatter(as.numeric(end - .time_record$start)) - cli::cli_alert_success(sprintf( - "{.pkg {pkgname}} v{pkg_version} loaded {cli::col_grey('[%s]')}", - elapsed - )) + cli::cli_process_done(.envir = .time_record) } } .onLoad <- function(libname, pkgname) { if (startup_message_allowed()) { - .time_record$start <- Sys.time() + pkg_version <- utils::packageVersion(pkgname) + .time_record$pkgname <- pkgname + .time_record$pkg_version <- pkg_version + cli::cli_progress_step( + msg = "Loading {.pkg {pkgname}} v{pkg_version}", + msg_done = "{.pkg {pkgname}} v{pkg_version} loaded", + spinner = TRUE, + .envir = .time_record + ) } invisible() @@ -41,29 +43,6 @@ .time_record <- new.env() -cli_timestamp_formatter <- function(x) { - stopifnot( - length(x) == 1L, - is.numeric(x), - !is.na(x), - x >= 0L - ) - - if (x < 1L) { - sprintf("%d ms", as.integer(x * 1000L)) - } else if (x < 60L) { - sprintf("%d s", as.integer(x)) - } else if (x < 3600L) { - sprintf("%d min %d s", floor(x / 60L), as.integer(x %% 60L)) - } else { - sprintf( - "%d h %02d min %d s", - floor(x / 3600L), - floor((x %% 3600L) / 60L), - as.integer(x %% 60L) - ) - } -} startup_message_allowed <- function() { allowed <- FALSE diff --git a/R/annotate.R b/R/annotate.R index 48bac9f..9d89a02 100644 --- a/R/annotate.R +++ b/R/annotate.R @@ -736,6 +736,7 @@ prepare_data <- function( # Row order matches clone_expression_rnorm column order clone_viability_template <- parse_clone_keys(colnames(clone_expression_rnorm)) + cli::cli_progress_done() cli::cli_h2("Preparation complete") cli::cli_ul("Genes: {.val {nrow(clone_expression_rnorm)}}") cli::cli_ul("Clones: {.val {ncol(clone_expression_rnorm)}}") diff --git a/R/load.R b/R/load.R index b666243..3800483 100644 --- a/R/load.R +++ b/R/load.R @@ -112,10 +112,9 @@ download_with_mirrors <- function( start_time <- Sys.time() success <- FALSE - timeout_occurred <- FALSE incomplete <- FALSE - tryCatch( + download_status <- tryCatch( { suppressWarnings({ curl_extra <- if (attempt > 0L) { @@ -133,29 +132,30 @@ download_with_mirrors <- function( ) }) success <- TRUE + "success" }, error = function(e) { - if ( - grepl( - "Timeout|timed out|reached elapsed time", - e$message, - ignore.case = TRUE - ) - ) { - timeout_occurred <<- TRUE - if (!quiet && attempt == retries) { + timed_out <- grepl( + "Timeout|timed out|reached elapsed time", + e$message, + ignore.case = TRUE + ) + if (!quiet && attempt == retries) { + if (timed_out) { cli::cli_alert_warning( "Mirror {i} timed out after {timeout_seconds} seconds." ) - } - } else { - if (!quiet && attempt == retries) { + } else { cli::cli_alert_warning("Mirror {i} failed: {e$message}") } } - if (file.exists(destfile)) file.remove(destfile) + if (file.exists(destfile)) { + file.remove(destfile) + } + if (timed_out) "timeout" else "error" } ) + timeout_occurred <- identical(download_status, "timeout") # A "successful" transfer can still be truncated by a flaky connection # or a misbehaving proxy: verify the size against the known release @@ -310,55 +310,35 @@ reset_mirrors <- function() { } -# 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. +#' 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. +#' @export +# fmt:table perception_all_drugs <- c( - "abemaciclib", - "afatinib", - "axitinib", - "azacitidine", - "cladribine", - "clofarabine", - "cobimetinib", - "dabrafenib", - "dasatinib", - "daunorubicin", - "decitabine", - "docetaxel", - "doxorubicin", - "epirubicin", - "erlotinib", - "etoposide", - "gefitinib", - "gemcitabine", - "homoharringtonine", - "ibrutinib", - "icotinib", - "ixabepilone", - "lapatinib", - "lenvatinib", - "midostaurin", - "niraparib", - "osimertinib", - "paclitaxel", - "palbociclib", - "ponatinib", - "romidepsin", - "sunitinib", - "temsirolimus", - "teniposide", - "thioguanine", - "topotecan", - "trametinib", - "vandetanib", - "vemurafenib", - "vinblastine", - "vincristine", - "vindesine", - "vinflunine", - "vinorelbine" + "abemaciclib" , "afatinib" , + "axitinib" , "azacitidine" , + "cladribine" , "clofarabine" , + "cobimetinib" , "dabrafenib" , + "dasatinib" , "daunorubicin" , + "decitabine" , "docetaxel" , + "doxorubicin" , "epirubicin" , + "erlotinib" , "etoposide" , + "gefitinib" , "gemcitabine" , + "homoharringtonine" , "ibrutinib" , + "icotinib" , "ixabepilone" , + "lapatinib" , "lenvatinib" , + "midostaurin" , "niraparib" , + "osimertinib" , "paclitaxel" , + "palbociclib" , "ponatinib" , + "romidepsin" , "sunitinib" , + "temsirolimus" , "teniposide" , + "thioguanine" , "topotecan" , + "trametinib" , "vandetanib" , + "vemurafenib" , "vinblastine" , + "vincristine" , "vindesine" , + "vinflunine" , "vinorelbine" ) #' Load pre-built model of provided drugs diff --git a/R/plot.R b/R/plot.R index 837a36c..e08da3a 100644 --- a/R/plot.R +++ b/R/plot.R @@ -1841,14 +1841,13 @@ plot_model_roc <- function(performance_list, base_size = 13L) { # Per-drug collection. A drug is only dropped when NONE of its three # validation datasets can produce a curve; the reason is recorded (with # counts) so the app can tell the user exactly what happened. - dropped_reasons <- character() - curve_rows <- lapply(names(performance_list), function(d) { + curve_specs <- lapply(names(performance_list), function(d) { m <- performance_list[[d]] if (is.null(m$predVSgroundTruth)) { - dropped_reasons[[ - d - ]] <<- "no prediction-vs-observed data stored in the model" - return(NULL) + return(list( + rows = NULL, + why = "no prediction-vs-observed data stored in the model" + )) } ds_out <- lapply(names(ds_map), function(k) { df <- m$predVSgroundTruth[[k]] @@ -1944,16 +1943,22 @@ plot_model_roc <- function(performance_list, base_size = 13L) { reasons <- reasons[nzchar(reasons)] ok_rows <- do.call(rbind, lapply(ds_out, function(x) x$rows)) if (is.null(ok_rows)) { - dropped_reasons[[d]] <<- paste(reasons, collapse = "; ") - return(NULL) + return(list(rows = NULL, why = paste(reasons, collapse = "; "))) } - ok_rows + list(rows = ok_rows, why = NULL) }) - names(curve_rows) <- names(performance_list) + names(curve_specs) <- names(performance_list) # Drugs that produced no ROC data at all -- record them so the app can tell # the user instead of silently showing fewer panels. - dropped_drugs <- names(curve_rows)[vapply(curve_rows, is.null, logical(1L))] - curve_rows <- curve_rows[!vapply(curve_rows, is.null, logical(1L))] + no_rows <- vapply(curve_specs, function(x) is.null(x$rows), logical(1L)) + dropped_drugs <- names(curve_specs)[no_rows] + dropped_reasons <- vapply( + curve_specs[no_rows], + function(x) if (is.null(x$why)) "" else x$why, + character(1L) + ) + curve_rows <- lapply(curve_specs, function(x) x$rows) + curve_rows <- curve_rows[!no_rows] if (length(curve_rows) == 0L) { cli::cli_abort( "No prediction-vs-observed data available to compute validation ROC." @@ -2217,12 +2222,7 @@ plot_seurat_clustering <- function( ) { method <- rlang::arg_match(method) - if (!requireNamespace("Seurat", quietly = TRUE)) { - cli::cli_abort(c( - "Package {.pkg Seurat} is required.", - "i" = "Install with {.run utils::install.packages('Seurat')}." - )) - } + rlang::check_installed("Seurat") # Shared pipeline (also used by annotate_clones) includes the PCA-dimension # safeguard for small datasets. diff --git a/R/train.R b/R/train.R index b468aca..fce0830 100644 --- a/R/train.R +++ b/R/train.R @@ -44,17 +44,14 @@ get_response_matrix <- function(infunc_drugName) { 3L ) - if ( - sum(infunc_drugName_screenID_trimmed == 'HTS') == 1L && - sum(infunc_drugName_screenID_trimmed == 'MTS') == 1L - ) { + sum_hts <- sum(infunc_drugName_screenID_trimmed == 'HTS') + sum_mts <- sum(infunc_drugName_screenID_trimmed == 'MTS') + + if (sum_hts == 1L && sum_mts == 1L) { infunc_response <- infunc_response[ infunc_drugName_screenID_trimmed == 'MTS', ] - } else if ( - sum(infunc_drugName_screenID_trimmed == 'HTS') == 1L && - sum(infunc_drugName_screenID_trimmed == 'MTS') > 1L - ) { + } else if (sum_hts == 1L && sum_mts > 1L) { infunc_response <- infunc_response[ infunc_drugName_screenID_trimmed == 'MTS', ] @@ -64,10 +61,7 @@ get_response_matrix <- function(infunc_drugName) { # Fall through to the colMeans() below: when several MTS batches tie on # NA count they are averaged ACROSS cell lines. (rowMeans here would # collapse to one scalar per batch and destroy cell-line granularity.) - } else if ( - sum(infunc_drugName_screenID_trimmed == 'HTS') == 0L && - sum(infunc_drugName_screenID_trimmed == 'MTS') > 1L - ) { + } else if (sum_hts == 0L && sum_mts > 1L) { infunc_response <- infunc_response[ count_row_NAs(infunc_response) == min(count_row_NAs(infunc_response)), ] @@ -76,7 +70,6 @@ get_response_matrix <- function(infunc_drugName) { infunc_response <- colMeans(infunc_response, na.rm = TRUE) } } - return(infunc_response) } @@ -177,6 +170,7 @@ get_cellLine_list <- function( #' @param infunc_cancerType Character. Cancer type for training. Default = "PanCan". #' @param exclude_cancer Character. Cancer type to exclude. Default = "PanCan". #' @param infunc_GOI Character vector. Genes of Interest to rank. +#' @param ncores Number of cores to use for parallelization. Default = 4. #' #' @return Matrix of ranked features with columns: p.value, estimate.cor (sorted by abs(cor) descending) #' @export @@ -184,7 +178,8 @@ feature_ranking_bulk <- function( infunc_drugName, infunc_cancerType = "PanCan", exclude_cancer = "PanCan", - infunc_GOI + infunc_GOI, + ncores = 4L ) { if (!exists("DepMap")) { cli::cli_abort( @@ -259,7 +254,12 @@ feature_ranking_bulk <- function( ok <- !is.na(X) # per-gene complete-cell mask n_eff <- rowSums(ok) r <- if (rlang::is_installed("WGCNA")) { - as.numeric(WGCNA::cor(t(X), y, use = "pairwise.complete.obs")) + as.numeric(WGCNA::cor( + t(X), + y, + use = "pairwise.complete.obs", + nThreads = ncores + )) } else { as.numeric(stats::cor(t(X), y, use = "pairwise.complete.obs")) } @@ -313,11 +313,12 @@ run_parallel_feature_ranking_bulk <- function( infunc_GOI = infunc_GOI, exclude_cancer = infunc_exclude_cancer )) + # matrix/NA } ) names(featuresRank_fromBulk) <- infunc_DrugsToUse - featuresRank_fromBulk + featuresRank_fromBulk # a list of matrices } @@ -368,21 +369,17 @@ build_on_BULK_v2 <- function( infunc_response <- get_response_matrix(infunc_drugName = infunc_drugName) # Get training cell lines - common_cellLines <- get_cellLine_list( + cellLine_list <- get_cellLine_list( infunc_cancerType = infunc_cancerType, infunc_drugName = infunc_drugName, exclude_cancer = exclude_cancer, infunc_response = infunc_response, force_add_cellLines = TRUE - )[[1L]] + ) + common_cellLines <- cellLine_list[[1L]] # Get test cell lines (excluded from training) - cellLines2remove <- get_cellLine_list( - infunc_cancerType = infunc_cancerType, - infunc_drugName = infunc_drugName, - exclude_cancer = exclude_cancer, - infunc_response = infunc_response - )[[2L]] + cellLines2remove <- cellLine_list[[2L]] # Check consistency between rnorm matrices if (nrow(DepMap$expression_rnorm) != nrow(DepMap$scRNA_subset_rnorm)) { @@ -531,7 +528,7 @@ build_on_BULK_v2 <- function( model_performance_cv <- max(sqrt(cv.out$results$Rsquared), na.rm = TRUE) # Test on bulk (test 2) - Test_pred_bulk <- predict(cv.out, Test2_features) + Test_pred_bulk <- stats::predict(cv.out, Test2_features) performance_in_bulk <- unlist(stats::cor.test( Test_pred_bulk, Test2_Target_Label, @@ -585,7 +582,7 @@ build_on_BULK_v2 <- function( ############ # Return ########## - toreturn <- list( + list( model = cv.out, single_best = single_best, model_performance_during_cv = model_performance_cv, @@ -594,7 +591,6 @@ build_on_BULK_v2 <- function( performance_in_scRNA = performance_in_scRNA, predVSgroundTruth = predVSgroundTruth ) - toreturn } @@ -684,7 +680,7 @@ train_models <- function( rownames(DepMap$scRNA_complete) ) cli::cli_alert_info( - "Using all {length(GOI)} intersecting genes as features." + "Using all {.val {length(GOI)}} intersecting genes as features." ) } else { available_genes <- intersect(GOI, rownames(DepMap$expression_20Q4)) @@ -694,9 +690,8 @@ train_models <- function( ) } if (length(available_genes) < length(GOI)) { - warning( - "Some GOI genes not found in DepMap: ", - paste(setdiff(GOI, available_genes), collapse = ", ") + cli::cli_warn( + "Some GOI genes not found in DepMap: {toString(setdiff(GOI, available_genes))}" ) } GOI <- available_genes @@ -720,7 +715,7 @@ train_models <- function( k_features_values <- n_genes_total * seq(0.0005, 0.02, length = 5L) k_features_values <- round(k_features_values) cli::cli_alert_info( - "Testing feature counts: {paste(k_features_values, collapse = ', ')}" + "Testing feature counts: {.val {toString(k_features_values)}}" ) } @@ -758,7 +753,7 @@ train_models <- function( "Step 2/2: Training models with hyperparameter tuning..." ) - for_output_lung_Test_vglm <- list() + for_output_lung_Test_vglm <- vector("list", length(drug_list)) Performance_by_features <- list() for (i in seq_along(drug_list)) { @@ -771,7 +766,7 @@ train_models <- function( # Check if feature ranking succeeded features <- features_list[[i]] if (is.null(features) || (length(features) == 1L && is.na(features))) { - warning(" Skipping ", drug, " - feature ranking failed.") + cli::cli_warn("Skipping {drug} - feature ranking failed.") for_output_lung_Test_vglm[i] <- list(NULL) next } @@ -784,48 +779,47 @@ train_models <- function( stripall2match(drug) ) if (length(drug_match) == 0L) { - warning(" Skipping ", drug, " - drug not found in DepMap response data.") + cli::cli_warn("Skipping {drug} - drug not found in DepMap response data.") for_output_lung_Test_vglm[i] <- list(NULL) next } # Iterate over k_features values (exactly like original script) - Raw_models_output <- list() - id_counter <- 1L - build_failed <- FALSE - - for (infunc_k_features_grid in k_features_values) { - Raw_models_output[[id_counter]] <- tryCatch( - build_on_BULK_v2( - infunc_drugName = drug, - infunc_cancerType = cancer_type, - exclude_cancer = exclude_cancer, - infunc_features = rownames(features), - single_best = rownames(features)[1L], - k_features = infunc_k_features_grid, - model_type = model_type, - num_folds = num_folds, - num_tree = num_tree, - seed = seed, - alpha_gradient = alpha_gradient, - lambda_gradient = lambda_gradient, - lambda_range = lambda_range, - cv_method = cv_method - ), - error = function(e) { - cli::cli_warn( - "build_on_BULK_v2 failed for {drug} (k = {infunc_k_features_grid}): {e$message}" - ) - NULL - } - ) - id_counter <- id_counter + 1L - } + Raw_models_output <- lapply( + seq_along(k_features_values), + function(id_counter) { + infunc_k_features_grid <- k_features_values[id_counter] + tryCatch( + build_on_BULK_v2( + infunc_drugName = drug, + infunc_cancerType = cancer_type, + exclude_cancer = exclude_cancer, + infunc_features = rownames(features), + single_best = rownames(features)[1L], + k_features = infunc_k_features_grid, + model_type = model_type, + num_folds = num_folds, + num_tree = num_tree, + seed = seed, + alpha_gradient = alpha_gradient, + lambda_gradient = lambda_gradient, + lambda_range = lambda_range, + cv_method = cv_method + ), + error = function(e) { + cli::cli_warn( + "build_on_BULK_v2 failed for {drug} (k = {infunc_k_features_grid}): {e$message}" + ) + NULL + } + ) + } + ) # Check if any models were successfully built if ( length(Raw_models_output) == 0L || - all(sapply(Raw_models_output, base::is.null)) + all(vapply(Raw_models_output, base::is.null, logical(1L))) ) { cli::cli_warn("Skipping {drug} - all model builds failed.") for_output_lung_Test_vglm[i] <- list(NULL) @@ -850,21 +844,25 @@ train_models <- function( } # Print and store the performance (rows: p-value, correlation) - perf <- sapply(Raw_models_output[valid], function(x) x$performance_in_scRNA) - print(perf) - Performance_by_features[[i]] <- lapply( + perf <- vapply( Raw_models_output[valid], - function(x) x$performance_in_scRNA + function(x) x$performance_in_scRNA, + numeric(2L) ) + if (rlang::is_installed("kableExtra")) { + kableExtra::kable(perf) + } else { + print(perf) + } + Performance_by_features[[i]] <- perf # Store the Tuned model (select based on highest correlation estimate) best_pos <- which.max(perf[2L, ]) for_output_lung_Test_vglm[[i]] <- Raw_models_output[valid][[best_pos]] - - # Clean up - rm(Raw_models_output) - gc(verbose = FALSE) + cli::cli_progress_done() } + # Clean up + gc(verbose = FALSE) # All drugs processed — final tick so a progress bar reaches 100%. if (!is.null(progress_cb)) { @@ -874,7 +872,7 @@ train_models <- function( # Assign names and filter out NULL entries (failed drugs) names(for_output_lung_Test_vglm) <- drug_list for_output_lung_Test_vglm <- for_output_lung_Test_vglm[ - !sapply(for_output_lung_Test_vglm, is.null) + !vapply(for_output_lung_Test_vglm, base::is.null, logical(1L)) ] Tuned_models_output <- for_output_lung_Test_vglm diff --git a/R/utils.R b/R/utils.R index 34a88ac..d5225ab 100644 --- a/R/utils.R +++ b/R/utils.R @@ -23,7 +23,6 @@ err_handle <- function(x) { }) } - # Lowercase and strip non-alphanumeric characters (keep underscores) — used # to make inconsistent drug / gene names comparable (e.g. "Drug-1" vs "Drug_1"). stripall2match <- function(x) { diff --git a/_pkgdown.yml b/_pkgdown.yml index 48d19f5..00856c2 100644 --- a/_pkgdown.yml +++ b/_pkgdown.yml @@ -100,6 +100,7 @@ reference: - export_plot_cairo - perception_depmap_drugs - perception_fda_approved_drugs + - perception_all_drugs articles: - title: Tutorials diff --git a/dev/e2e_concurrent.R b/dev/e2e_concurrent.R index 623c2c0..30a8d5b 100644 --- a/dev/e2e_concurrent.R +++ b/dev/e2e_concurrent.R @@ -19,11 +19,12 @@ s1 <- mk_session() s2 <- mk_session() cat('[e2e-conc] session1 pid:', s1$worker$get_pid(), '| session2 pid:', s2$worker$get_pid(), '\n') -fails <- 0L +counters <- new.env(parent = emptyenv()) +counters$fails <- 0L t <- function(name, ok, detail = '') { cat(sprintf('[%s] %s%s\n', if (ok) 'PASS' else 'FAIL', name, if (nzchar(detail)) paste0(' -> ', detail) else '')) - if (!ok) fails <<- fails + 1L + if (!ok) counters$fails <- counters$fails + 1L } t('two sessions have distinct workers', s1$worker$get_pid() != s2$worker$get_pid()) t('distinct jobs dirs', !identical(s1$dir, s2$dir)) @@ -64,5 +65,5 @@ pid_before <- s1$worker$get_pid() r3 <- submit_wait(s1) t('session1 worker reused (same pid)', s1$worker$get_pid() == pid_before && r3$status == 'done') -cat('\n==== CONCURRENCY TEST SUMMARY: FAIL =', fails, '====\n') -quit(status = if (fails == 0L) 0L else 1L) +cat('\n==== CONCURRENCY TEST SUMMARY: FAIL =', counters$fails, '====\n') +quit(status = if (counters$fails == 0L) 0L else 1L) diff --git a/dev/e2e_session.R b/dev/e2e_session.R index ecb509b..b2a8724 100644 --- a/dev/e2e_session.R +++ b/dev/e2e_session.R @@ -12,11 +12,12 @@ options(perception.pkg_root = NULL) # environment = reference semantics (reactiveValues stand-in, see e2e_train.R) shared <- new.env(parent = emptyenv()) -fails <- 0L +counters <- new.env(parent = emptyenv()) +counters$fails <- 0L t <- function(name, ok, detail = '') { cat(sprintf('[%s] %s%s\n', if (ok) 'PASS' else 'FAIL', name, if (nzchar(detail)) paste0(' -> ', detail) else '')) - if (!ok) fails <<- fails + 1L + if (!ok) counters$fails <- counters$fails + 1L } ensure_session_worker(shared) @@ -101,5 +102,5 @@ cat('[e2e-session] bad task submitted:', jid, '\n') r <- wait_done(jid) t('unknown task errors cleanly', r$status == 'error' && nzchar(r$message), r$message) -cat('\n==== SESSION WORKER TEST SUMMARY: FAIL =', fails, '====\n') -quit(status = if (fails == 0L) 0L else 1L) +cat('\n==== SESSION WORKER TEST SUMMARY: FAIL =', counters$fails, '====\n') +quit(status = if (counters$fails == 0L) 0L else 1L) diff --git a/dev/test_edge.R b/dev/test_edge.R index 8f7145b..3208cc9 100644 --- a/dev/test_edge.R +++ b/dev/test_edge.R @@ -9,11 +9,12 @@ source('/data/home/dingjia/R/library/PERCEPTIONx/shiny/app/R/async_jobs.R') options(perception.pkg_root = NULL) suppressMessages(library(PERCEPTIONx)) -fails <- 0L +counters <- new.env(parent = emptyenv()) +counters$fails <- 0L t <- function(name, ok, detail = '') { cat(sprintf('[%s] %s%s\n', if (ok) 'PASS' else 'FAIL', name, if (nzchar(detail)) paste0(' -> ', detail) else '')) - if (!ok) fails <<- fails + 1L + if (!ok) counters$fails <- counters$fails + 1L } # --- 1. corrupt DepMap file -> extract_depmap_meta errors (app deletes it) --- @@ -57,5 +58,5 @@ t('task stays running (not fake done/error) after worker death', st$status == 'r alive <- worker$is_alive() t('poll can detect dead worker (alive=FALSE)', isFALSE(alive)) -cat('\n==== EDGE TEST SUMMARY: FAIL =', fails, '====\n') -quit(status = if (fails == 0L) 0L else 1L) +cat('\n==== EDGE TEST SUMMARY: FAIL =', counters$fails, '====\n') +quit(status = if (counters$fails == 0L) 0L else 1L) diff --git a/dev/test_unit.R b/dev/test_unit.R index a223f67..c9890bc 100644 --- a/dev/test_unit.R +++ b/dev/test_unit.R @@ -20,13 +20,14 @@ cache_dir <- Sys.getenv('PERCEPTIONX_DEPMAP_CACHE_DIR', DepMap <- readRDS(file.path(cache_dir, 'DepMap.RDS')) cat('DepMap loaded:', length(DepMap), 'components\n') -fails <- 0L -skips <- 0L +counters <- new.env(parent = emptyenv()) +counters$fails <- 0L +counters$skips <- 0L t <- function(name, expr, skip_if = FALSE) { - if (skip_if) { cat('[SKIP]', name, '\n'); skips <<- skips + 1L; return(invisible(NULL)) } + if (skip_if) { cat('[SKIP]', name, '\n'); counters$skips <- counters$skips + 1L; return(invisible(NULL)) } ok <- tryCatch({ r <- force(expr); isTRUE(r) }, error = function(e) { cat(' error:', conditionMessage(e), '\n'); FALSE }) - if (ok) { cat('[PASS]', name, '\n') } else { cat('[FAIL]', name, '\n'); fails <<- fails + 1L } + if (ok) { cat('[PASS]', name, '\n') } else { cat('[FAIL]', name, '\n'); counters$fails <- counters$fails + 1L } invisible(NULL) } @@ -196,5 +197,5 @@ pp2 <- tryCatch( t('predict_patients legacy mode', !is.null(pp2)) cat('\n==== UNIT TEST SUMMARY ====\n') -cat('PASS:', 'see above | FAIL:', fails, '| SKIP:', skips, '\n') -quit(status = if (fails == 0L) 0L else 1L) +cat('PASS:', 'see above | FAIL:', counters$fails, '| SKIP:', counters$skips, '\n') +quit(status = if (counters$fails == 0L) 0L else 1L) diff --git a/dev/verify_fixes.R b/dev/verify_fixes.R index 5cf8745..f263e32 100644 --- a/dev/verify_fixes.R +++ b/dev/verify_fixes.R @@ -8,11 +8,12 @@ for (f in list.files("R", pattern = "\\.R$", full.names = TRUE)) { suppressMessages(source(f)) } -fails <- 0L +counters <- new.env(parent = emptyenv()) +counters$fails <- 0L chk <- function(name, ok, detail = "") { cat(sprintf("[%s] %s%s\n", if (ok) "PASS" else "FAIL", name, if (nzchar(detail)) paste0(" -> ", detail) else "")) - if (!ok) fails <<- fails + 1L + if (!ok) counters$fails <- counters$fails + 1L } # 1. range01 constant vector -> 0 ("no signal", not the old 0.5 midpoint) @@ -66,6 +67,6 @@ out <- tryCatch(each_patient_pseudo_bulk(x = 2, comb_viability_df = NULL, chk("each_patient_pseudo_bulk empty-clone guard", !inherits(out, "error") && all(is.na(out))) -cat(if (fails == 0L) "\nALL CHECKS PASSED\n" - else sprintf("\n%d CHECK(S) FAILED\n", fails)) -quit(save = "no", status = if (fails == 0L) 0L else 1L) +cat(if (counters$fails == 0L) "\nALL CHECKS PASSED\n" + else sprintf("\n%d CHECK(S) FAILED\n", counters$fails)) +quit(save = "no", status = if (counters$fails == 0L) 0L else 1L) diff --git a/dev/verify_install.R b/dev/verify_install.R index 5e301e3..73065a9 100644 --- a/dev/verify_install.R +++ b/dev/verify_install.R @@ -1,11 +1,12 @@ # Verify the INSTALLED package (E:/rlibtest): S3 hijack removed, exports OK. .libPaths(c('E:/rlibtest', .libPaths())) suppressMessages(library(PERCEPTIONx)) -fails <- 0L +counters <- new.env(parent = emptyenv()) +counters$fails <- 0L chk <- function(name, ok, detail = "") { cat(sprintf("[%s] %s%s\n", if (ok) "PASS" else "FAIL", name, if (nzchar(detail)) paste0(" -> ", detail) else "")) - if (!ok) fails <<- fails + 1L + if (!ok) counters$fails <- counters$fails + 1L } set.seed(1); d <- data.frame(x = 1:10, y = 1:10 + rnorm(10)) @@ -37,6 +38,6 @@ chk("installed: exports ok", dsc <- packageDescription("PERCEPTIONx") chk("installed: callr in Imports", grepl("callr", dsc$Imports, fixed = TRUE)) -cat(if (fails == 0L) "\nINSTALL VERIFY ALL PASSED\n" - else sprintf("\n%d CHECK(S) FAILED\n", fails)) -quit(save = "no", status = if (fails == 0L) 0L else 1L) +cat(if (counters$fails == 0L) "\nINSTALL VERIFY ALL PASSED\n" + else sprintf("\n%d CHECK(S) FAILED\n", counters$fails)) +quit(save = "no", status = if (counters$fails == 0L) 0L else 1L) diff --git a/inst/shiny/app/R/async_jobs.R b/inst/shiny/app/R/async_jobs.R index fa24cac..bb41d80 100644 --- a/inst/shiny/app/R/async_jobs.R +++ b/inst/shiny/app/R/async_jobs.R @@ -86,23 +86,24 @@ spawn_r_bg_retry <- function( config_err <- character(0) for (cfg in configs) { for (attempt in seq_len(retries + 1L)) { - tryCatch( - return(callr::r_bg( + job <- tryCatch( + callr::r_bg( func = func, args = args, supervise = cfg$supervise, poll_connection = FALSE, stdout = cfg$stdout, stderr = cfg$stderr - )), - error = function(e) { - last_err <<- e - if (attempt <= retries) { - Sys.sleep(delay_ms / 1000) - } - NULL - } + ), + error = function(e) e ) + if (!inherits(job, "error")) { + return(job) + } + last_err <- job + if (attempt <= retries) { + Sys.sleep(delay_ms / 1000) + } } config_err <- c(config_err, conditionMessage(last_err)) gc() # release any half-open connections before the next config diff --git a/inst/shiny/app/R/mod_data.R b/inst/shiny/app/R/mod_data.R index e39c084..43d1293 100644 --- a/inst/shiny/app/R/mod_data.R +++ b/inst/shiny/app/R/mod_data.R @@ -1560,7 +1560,7 @@ mod_data_server <- function(id, shared) { loaded_count <- 0 failed_drugs <- c() for (drug in drug_list) { - tryCatch( + load_error <- tryCatch( { new_model <- PERCEPTIONx::load_model( drug, @@ -1574,14 +1574,15 @@ mod_data_server <- function(id, shared) { shared$model_cache[[drug]] <- new_model[[drug]] shared$model_active[[drug]] <- TRUE loaded_count <- loaded_count + 1 + NULL }, error = function(e) { - failed_drugs <<- c( - failed_drugs, - paste0(drug, " (", conditionMessage(e), ")") - ) + paste0(drug, " (", conditionMessage(e), ")") } ) + if (!is.null(load_error)) { + failed_drugs <- c(failed_drugs, load_error) + } } w$hide() if (loaded_count > 0) { @@ -1634,7 +1635,7 @@ mod_data_server <- function(id, shared) { ok_names <- character(0) errs <- character(0) for (k in seq_len(nrow(files))) { - tryCatch( + read_error <- tryCatch( { model_obj <- readRDS(files$datapath[k]) drug_name <- tools::file_path_sans_ext(basename(files$name[k])) @@ -1652,14 +1653,15 @@ mod_data_server <- function(id, shared) { shared$model_cache[[drug_name]] <- model_obj shared$model_active[[drug_name]] <- TRUE ok_names <- c(ok_names, drug_name) + NULL }, error = function(e) { - errs <<- c( - errs, - paste0(basename(files$name[k]), ": ", conditionMessage(e)) - ) + paste0(basename(files$name[k]), ": ", conditionMessage(e)) } ) + if (!is.null(read_error)) { + errs <- c(errs, read_error) + } } w$hide() if (length(ok_names) > 0) { diff --git a/man/feature_ranking_bulk.Rd b/man/feature_ranking_bulk.Rd index d055ef4..5e02fb9 100644 --- a/man/feature_ranking_bulk.Rd +++ b/man/feature_ranking_bulk.Rd @@ -8,7 +8,8 @@ feature_ranking_bulk( infunc_drugName, infunc_cancerType = "PanCan", exclude_cancer = "PanCan", - infunc_GOI + infunc_GOI, + ncores = 4L ) } \arguments{ @@ -19,6 +20,8 @@ feature_ranking_bulk( \item{exclude_cancer}{Character. Cancer type to exclude. Default = "PanCan".} \item{infunc_GOI}{Character vector. Genes of Interest to rank.} + +\item{ncores}{Number of cores to use for parallelization. Default = 4.} } \value{ Matrix of ranked features with columns: p.value, estimate.cor (sorted by abs(cor) descending) diff --git a/man/perception_all_drugs.Rd b/man/perception_all_drugs.Rd new file mode 100644 index 0000000..d2831dc --- /dev/null +++ b/man/perception_all_drugs.Rd @@ -0,0 +1,17 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/load.R +\name{perception_all_drugs} +\alias{perception_all_drugs} +\title{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.} +\usage{ +perception_all_drugs +} +\description{ +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. +} diff --git a/tools/test_parse_patient.R b/tools/test_parse_patient.R index c1d6699..7562564 100644 --- a/tools/test_parse_patient.R +++ b/tools/test_parse_patient.R @@ -15,8 +15,12 @@ print(metadata_standard) # Example 2: Parse patient ID from cell names message("\n=== Example 2: Parse patient ID from cell names ===") metadata_parse <- data.frame( - Cell = c("P11_M_AAACGAACACAAGTGG", "P11_M_AAACGCTGTTAAGAAC", - "P12_M_AAAGTGAAGAGGACTC", "P12_M_AAATGGAGTGTTAACC"), + Cell = c( + "P11_M_AAACGAACACAAGTGG", + "P11_M_AAACGCTGTTAAGAAC", + "P12_M_AAAGTGAAGAGGACTC", + "P12_M_AAATGGAGTGTTAACC" + ), Cell_Type = c("Cancer cells", "Cancer cells", "Cancer cells", "Cancer cells") ) print(metadata_parse) @@ -39,27 +43,35 @@ print(metadata_parsed) # Example 3: Different separator and position message("\n=== Example 3: Different separator and position ===") metadata_dash <- data.frame( - Cell = c("AAACGAACACAAGTGG-P11", "AAACGCTGTTAAGAAC-P11", - "AAAGTGAAGAGGACTC-P12", "AAATGGAGTGTTAACC-P12") + Cell = c( + "AAACGAACACAAGTGG-P11", + "AAACGCTGTTAAGAAC-P11", + "AAAGTGAAGAGGACTC-P12", + "AAATGGAGTGTTAACC-P12" + ) ) print(metadata_dash) parsed_dash <- strsplit(metadata_dash$Cell, "-", fixed = TRUE) -patient_ids_dash <- sapply(parsed_dash, `[`, 2) # Take 2nd element +patient_ids_dash <- sapply(parsed_dash, `[`, 2) # Take 2nd element message("Parsed patient IDs (position 2):") print(patient_ids_dash) # Example 4: Complex format with multiple separators message("\n=== Example 4: Complex format ===") metadata_complex <- data.frame( - Cell = c("Patient11_Time1_Barcode001", "Patient11_Time2_Barcode002", - "Patient12_Time1_Barcode003", "Patient12_Time2_Barcode004") + Cell = c( + "Patient11_Time1_Barcode001", + "Patient11_Time2_Barcode002", + "Patient12_Time1_Barcode003", + "Patient12_Time2_Barcode004" + ) ) print(metadata_complex) parsed_complex <- strsplit(metadata_complex$Cell, "_", fixed = TRUE) -patient_ids_complex <- sapply(parsed_complex, `[`, 1) # Take 1st element -time_ids <- sapply(parsed_complex, `[`, 2) # Take 2nd element +patient_ids_complex <- sapply(parsed_complex, `[`, 1) # Take 1st element +time_ids <- sapply(parsed_complex, `[`, 2) # Take 2nd element message("Parsed patient IDs:") print(patient_ids_complex) @@ -76,4 +88,4 @@ message(" patient_pos = 1)") message("\nSupported formats:") message(" - 'P11_M_Barcode' -> sep='_', pos=1 -> 'P11'") message(" - 'Barcode-P11' -> sep='-', pos=2 -> 'P11'") -message(" - 'Patient11_Time_Barcode' -> sep='_', pos=1 -> 'Patient11'") \ No newline at end of file +message(" - 'Patient11_Time_Barcode' -> sep='_', pos=1 -> 'Patient11'") diff --git a/tools/test_pipeline.R b/tools/test_pipeline.R index 4034b66..f12e455 100644 --- a/tools/test_pipeline.R +++ b/tools/test_pipeline.R @@ -20,16 +20,16 @@ drug_list <- c("erlotinib", "gefitinib") # Cancer type -cancer_type <- "PanCan" +cancer_type <- "PanCan" exclude_cancer <- "PanCan" # Feature genes (NULL = use all DepMap genes; or provide a custom gene list) GOI <- NULL # Model hyperparameters -model_type <- "glmnet" -k_features_values <- NULL # NULL = auto-compute -ncores <- 1 +model_type <- "glmnet" +k_features_values <- NULL # NULL = auto-compute +ncores <- 1 # Output directory output_dir <- "./test_pipeline_output" @@ -51,14 +51,14 @@ message("Step 1: Training PERCEPTIONx models") message(strrep("=", 60)) models <- train_models( - drug_list = drug_list, - cancer_type = cancer_type, - exclude_cancer = exclude_cancer, - GOI = GOI, + drug_list = drug_list, + cancer_type = cancer_type, + exclude_cancer = exclude_cancer, + GOI = GOI, k_features_values = k_features_values, - model_type = model_type, - ncores = ncores, - output_dir = output_dir + model_type = model_type, + ncores = ncores, + output_dir = output_dir ) # -- Step 2: Evaluate Model Performance --------------------------------------- @@ -77,7 +77,11 @@ dev.off() message("Saved: 01_model_performance.pdf") # Filter significant models -sig_models <- get_significant_models(models, min_correlation = 0.3, max_pvalue = 0.05) +sig_models <- get_significant_models( + models, + min_correlation = 0.3, + max_pvalue = 0.05 +) # -- Step 3: Cell-Level Prediction -------------------------------------------- @@ -88,19 +92,26 @@ message(strrep("=", 60)) # Use excluded cell lines from DepMap (single-cell data) for prediction cellLines_test <- get_cellLine_list( infunc_cancerType = cancer_type, - infunc_drugName = drug_list[1], - exclude_cancer = exclude_cancer, - infunc_response = get_response_matrix(drug_list[1]) + infunc_drugName = drug_list[1], + exclude_cancer = exclude_cancer, + infunc_response = get_response_matrix(drug_list[1]) )[[2]] # Get expression matrix for test cell lines test_cells <- DepMap$metadata_CPM_scRNA$NAME[ - DepMap$metadata_CPM_scRNA$DepMap_ID %in% cellLines_test] + DepMap$metadata_CPM_scRNA$DepMap_ID %in% cellLines_test +] expr_test <- DepMap$CPM_scRNA_CCLE_rnorm[, test_cells, drop = FALSE] # Predict cell_pred <- predict_drugs(models, expr_test) -message("Cell-level predictions: ", nrow(cell_pred), " cells x ", ncol(cell_pred), " drugs") +message( + "Cell-level predictions: ", + nrow(cell_pred), + " cells x ", + ncol(cell_pred), + " drugs" +) print(head(cell_pred)) # -- Step 4: Patient-Level Prediction (Simulated) ----------------------------- @@ -126,7 +137,7 @@ for (pid in patient_ids) { row_vals <- as.list(as.vector(cell_pred[cell_idx[j], ])) names(row_vals) <- colnames(cell_pred) clone_viability_list[[length(clone_viability_list) + 1]] <- data.frame( - patient = pid, + patient = pid, clone_id = clone_ids[j], row_vals, check.names = FALSE @@ -138,7 +149,11 @@ clone_viability_df <- do.call(rbind, clone_viability_list) # Build clone_counts_df: unified columns for all clone IDs, fill 0 for missing all_clone_ids <- unique(clone_viability_df$clone_id) -clone_counts_df <- as.data.frame(matrix(0L, nrow = length(patient_ids), ncol = length(all_clone_ids))) +clone_counts_df <- as.data.frame(matrix( + 0L, + nrow = length(patient_ids), + ncol = length(all_clone_ids) +)) colnames(clone_counts_df) <- all_clone_ids rownames(clone_counts_df) <- patient_ids for (i in seq_along(patient_ids)) { @@ -149,7 +164,11 @@ for (i in seq_along(patient_ids)) { clone_counts_df$patients <- patient_ids # Patient-level prediction -patient_pred <- predict_patients(clone_viability_df, clone_counts_df, mode = "weighted_average") +patient_pred <- predict_patients( + clone_viability_df, + clone_counts_df, + mode = "weighted_average" +) message("Patient-level predictions:") print(patient_pred) @@ -164,11 +183,14 @@ counts_mat <- as.matrix(clone_counts_df[, all_clone_ids, drop = FALSE]) row_sums <- rowSums(counts_mat) clone_dist_df <- data.frame( patients = clone_viability_df$patient, - clones = clone_viability_df$clone_id, - weights = counts_mat[ - cbind(match(clone_viability_df$patient, patient_ids), - match(clone_viability_df$clone_id, all_clone_ids)) - ] / row_sums[match(clone_viability_df$patient, patient_ids)] + clones = clone_viability_df$clone_id, + weights = counts_mat[ + cbind( + match(clone_viability_df$patient, patient_ids), + match(clone_viability_df$clone_id, all_clone_ids) + ) + ] / + row_sums[match(clone_viability_df$patient, patient_ids)] ) pdf(file.path(output_dir, "02_clone_distribution.pdf"), width = 8, height = 5) @@ -179,13 +201,17 @@ message("Saved: 02_clone_distribution.pdf") # -- 5b. Clone viability (lollipop) -- # Rename prediction column to comb_viability (use first drug) -drug_col <- colnames(clone_viability_df)[3] # first drug column +drug_col <- colnames(clone_viability_df)[3] # first drug column clone_kill_plot_df <- clone_viability_df clone_kill_plot_df$comb_viability <- clone_kill_plot_df[[drug_col]] clone_kill_plot_df$weights <- clone_dist_df$weights pdf(file.path(output_dir, "03_clone_viability.pdf"), width = 20, height = 6) -p3 <- plot_clone_viability(clone_kill_plot_df, viability_var = "comb_viability", weights_var = "weights") +p3 <- plot_clone_viability( + clone_kill_plot_df, + viability_var = "comb_viability", + weights_var = "weights" +) print(p3) dev.off() message("Saved: 03_clone_viability.pdf") @@ -193,42 +219,63 @@ message("Saved: 03_clone_viability.pdf") # -- 5c. Response boxplot + ROC curve (using model's built-in pred vs ground truth) -- for (drug_name in names(models)) { model_obj <- models[[drug_name]] - if (is.null(model_obj) || (length(model_obj) == 1 && is.na(model_obj))) next + if (is.null(model_obj) || (length(model_obj) == 1 && is.na(model_obj))) { + next + } pred_gt <- model_obj$predVSgroundTruth$pred_gt_scRNA - if (is.null(pred_gt) || nrow(pred_gt) == 0) next + if (is.null(pred_gt) || nrow(pred_gt) == 0) { + next + } # Response boxplot: split by median observed value median_pred <- median(pred_gt$Test_pred_sc, na.rm = TRUE) exp_vs_pred <- data.frame( - response = ifelse(pred_gt$Observed > median(pred_gt$Observed, na.rm = TRUE), "R", "NR"), + response = ifelse( + pred_gt$Observed > median(pred_gt$Observed, na.rm = TRUE), + "R", + "NR" + ), predicted_viability = pred_gt$Test_pred_sc ) exp_vs_pred$response <- factor(exp_vs_pred$response, levels = c("R", "NR")) - pdf(file.path(output_dir, paste0("04_response_boxplot_", drug_name, ".pdf")), - width = 5, height = 5) + pdf( + file.path(output_dir, paste0("04_response_boxplot_", drug_name, ".pdf")), + width = 5, + height = 5 + ) p4 <- plot_response_boxplot(exp_vs_pred) print(p4) dev.off() message("Saved: 04_response_boxplot_", drug_name, ".pdf") # ROC curve - pdf(file.path(output_dir, paste0("05_roc_curve_", drug_name, ".pdf")), - width = 5, height = 5) - p5 <- plot_roc_curve(response = exp_vs_pred$response, predictor = exp_vs_pred$predicted_viability) + pdf( + file.path(output_dir, paste0("05_roc_curve_", drug_name, ".pdf")), + width = 5, + height = 5 + ) + p5 <- plot_roc_curve( + response = exp_vs_pred$response, + predictor = exp_vs_pred$predicted_viability + ) print(p5) dev.off() message("Saved: 05_roc_curve_", drug_name, ".pdf") } # -- 5d. Patient response panel (composite) -- -pdf(file.path(output_dir, "06_patient_response_panel.pdf"), width = 10, height = 15) +pdf( + file.path(output_dir, "06_patient_response_panel.pdf"), + width = 10, + height = 15 +) p6 <- plot_patient_response_panel( clone_distribution = clone_dist_df, - clone_viability = clone_kill_plot_df, - exp_vs_pred = exp_vs_pred, - viability_col = "comb_viability" + clone_viability = clone_kill_plot_df, + exp_vs_pred = exp_vs_pred, + viability_col = "comb_viability" ) print(p6) dev.off() @@ -241,14 +288,20 @@ n_cells_use <- min(100, ncol(expr_test)) expr_subset <- expr_test[, 1:n_cells_use] pdf(file.path(output_dir, "07_seurat_clustering.pdf"), width = 6, height = 5) -seurat_result <- plot_seurat_clustering(method = "umap", expression_matrix = expr_subset) +seurat_result <- plot_seurat_clustering( + method = "umap", + expression_matrix = expr_subset +) print(seurat_result$embedding_plot) dev.off() message("Saved: 07_seurat_clustering.pdf") # t-SNE response overlay if (!is.null(seurat_result$seurat_object)) { - umap_coords <- as.data.frame(Seurat::Embeddings(seurat_result$seurat_object, "umap")) + umap_coords <- as.data.frame(Seurat::Embeddings( + seurat_result$seurat_object, + "umap" + )) colnames(umap_coords) <- c("X", "Y") # Map predictions to t-SNE @@ -260,8 +313,11 @@ if (!is.null(seurat_result$seurat_object)) { ) pdf(file.path(output_dir, "08_tsne_response.pdf"), width = 6, height = 5) - p8 <- plot_tsne_response(tsne_data, color_var = "viability_scaled", - title = paste("Drug Viability -", drug_list[1])) + p8 <- plot_tsne_response( + tsne_data, + color_var = "viability_scaled", + title = paste("Drug Viability -", drug_list[1]) + ) print(p8) dev.off() message("Saved: 08_tsne_response.pdf") @@ -272,11 +328,17 @@ if (!is.null(seurat_result$seurat_object)) { biomarker_vals <- as.numeric(expr_subset[best_gene, ]) tsne_data$biomarker_scaled <- range01(rank(biomarker_vals)) - pdf(file.path(output_dir, "09_tsne_biomarker_viability.pdf"), width = 10, height = 5) - p9 <- plot_tsne_biomarker_viability(tsne_data, - biomarker_var = "biomarker_scaled", - viability_var = "viability_scaled", - biomarker_label = paste0("Biomarker (", best_gene, ")")) + pdf( + file.path(output_dir, "09_tsne_biomarker_viability.pdf"), + width = 10, + height = 5 + ) + p9 <- plot_tsne_biomarker_viability( + tsne_data, + biomarker_var = "biomarker_scaled", + viability_var = "viability_scaled", + biomarker_label = paste0("Biomarker (", best_gene, ")") + ) print(p9) dev.off() message("Saved: 09_tsne_biomarker_viability.pdf") diff --git a/tools/test_pipeline_v2.R b/tools/test_pipeline_v2.R index 8ca8544..6909ae3 100644 --- a/tools/test_pipeline_v2.R +++ b/tools/test_pipeline_v2.R @@ -23,16 +23,16 @@ devtools::load_all(".") drug_list <- c("erlotinib", "gefitinib") # Cancer type -cancer_type <- "PanCan" +cancer_type <- "PanCan" exclude_cancer <- "PanCan" # Feature genes (NULL = use all DepMap genes) GOI <- NULL # Model hyperparameters -model_type <- "glmnet" -k_features_values <- NULL # NULL = auto-compute -ncores <- 1 +model_type <- "glmnet" +k_features_values <- NULL # NULL = auto-compute +ncores <- 1 # Output directory output_dir <- "./test_pipeline_v2_output" @@ -55,14 +55,14 @@ message("STEP 2: Training drug response models") message(strrep("=", 60)) models <- train_models( - drug_list = drug_list, - cancer_type = cancer_type, - exclude_cancer = exclude_cancer, - GOI = GOI, + drug_list = drug_list, + cancer_type = cancer_type, + exclude_cancer = exclude_cancer, + GOI = GOI, k_features_values = k_features_values, - model_type = model_type, - ncores = ncores, - output_dir = output_dir + model_type = model_type, + ncores = ncores, + output_dir = output_dir ) message("Trained models for: ", paste(names(models), collapse = ", ")) @@ -79,14 +79,15 @@ message(strrep("=", 60)) # Get test cell lines (excluded from training) cellLines_test <- get_cellLine_list( infunc_cancerType = cancer_type, - infunc_drugName = drug_list[1], - exclude_cancer = exclude_cancer, - infunc_response = get_response_matrix(drug_list[1]) + infunc_drugName = drug_list[1], + exclude_cancer = exclude_cancer, + infunc_response = get_response_matrix(drug_list[1]) )[[2]] # Get expression for test cells test_cells <- DepMap$metadata_CPM_scRNA$NAME[ - DepMap$metadata_CPM_scRNA$DepMap_ID %in% cellLines_test] + DepMap$metadata_CPM_scRNA$DepMap_ID %in% cellLines_test +] # Use first 200 cells to simulate 3 patients (need enough cells for Seurat PCA) n_cells <- 200 @@ -122,16 +123,30 @@ metadata_df <- data.frame( message("Using metadata data frame format...") prepared <- prepare_data( expression_matrix = expr_matrix, - patient_mapping = metadata_df, # Can also use sample_cell_names_list - genes_to_use = NULL + patient_mapping = metadata_df, # Can also use sample_cell_names_list + genes_to_use = NULL ) message("\nPrepared data structure:") -message(" - clone_expression_rnorm: ", nrow(prepared$clone_expression_rnorm), " genes x ", - ncol(prepared$clone_expression_rnorm), " clones") -message(" - clone_counts: ", nrow(prepared$clone_counts), " patients x ", - ncol(prepared$clone_counts) - 1, " clones") -message(" - cell_clone_map: ", nrow(prepared$cell_clone_map), " cells annotated") +message( + " - clone_expression_rnorm: ", + nrow(prepared$clone_expression_rnorm), + " genes x ", + ncol(prepared$clone_expression_rnorm), + " clones" +) +message( + " - clone_counts: ", + nrow(prepared$clone_counts), + " patients x ", + ncol(prepared$clone_counts) - 1, + " clones" +) +message( + " - cell_clone_map: ", + nrow(prepared$cell_clone_map), + " cells annotated" +) # Show clone distribution message("\nClone counts per patient:") @@ -146,7 +161,13 @@ message(strrep("=", 60)) clone_pred <- predict_drugs(models, prepared$clone_expression_rnorm) -message("Clone-level predictions: ", nrow(clone_pred), " clones x ", ncol(clone_pred), " drugs") +message( + "Clone-level predictions: ", + nrow(clone_pred), + " clones x ", + ncol(clone_pred), + " drugs" +) message("\nClone predictions (first 5 clones):") print(head(clone_pred, 5)) @@ -164,7 +185,11 @@ message("Patient-level predictions (most resistant clone):") print(patient_pred) # Also try weighted_average mode -patient_pred_weighted <- predict_patients(clone_pred, prepared, mode = "weighted_average") +patient_pred_weighted <- predict_patients( + clone_pred, + prepared, + mode = "weighted_average" +) message("\nPatient-level predictions (weighted average):") print(patient_pred_weighted) @@ -185,8 +210,8 @@ clone_viability_df <- data.frame( # Clone distribution plot clone_dist_df <- data.frame( patients = clone_viability_df$patient, - clones = clone_viability_df$clone_id, - weights = as.numeric(prepared$clone_counts[cbind( + clones = clone_viability_df$clone_id, + weights = as.numeric(prepared$clone_counts[cbind( match(clone_viability_df$patient, prepared$clone_counts$patients), match(clone_viability_df$clone_id, colnames(prepared$clone_counts)[-1]) )]) @@ -194,7 +219,8 @@ clone_dist_df <- data.frame( # Normalize weights per patient for (pid in unique(clone_dist_df$patients)) { idx <- clone_dist_df$patients == pid - clone_dist_df$weights[idx] <- clone_dist_df$weights[idx] / sum(clone_dist_df$weights[idx]) + clone_dist_df$weights[idx] <- clone_dist_df$weights[idx] / + sum(clone_dist_df$weights[idx]) } pdf(file.path(output_dir, "clone_distribution.pdf"), width = 8, height = 5) @@ -210,7 +236,11 @@ clone_kill_plot_df$comb_viability <- clone_kill_plot_df[[drug_col]] clone_kill_plot_df$weights <- clone_dist_df$weights pdf(file.path(output_dir, "clone_viability.pdf"), width = 12, height = 5) -p2 <- plot_clone_viability(clone_kill_plot_df, viability_var = "comb_viability", weights_var = "weights") +p2 <- plot_clone_viability( + clone_kill_plot_df, + viability_var = "comb_viability", + weights_var = "weights" +) print(p2) dev.off() message("Saved: clone_viability.pdf") @@ -225,13 +255,19 @@ message(strrep("=", 60)) message("\nThe new simplified workflow:") message(" 1. load_depmap() -> DepMap reference data") message(" 2. train_models() -> Drug response models") -message(" 3. prepare_data() -> Clone expression + counts (from raw scRNA + metadata)") +message( + " 3. prepare_data() -> Clone expression + counts (from raw scRNA + metadata)" +) message(" 4. predict_drugs() -> Clone-level predictions") -message(" 5. predict_patients() -> Patient-level predictions (just pass clone_pred + prepared)") +message( + " 5. predict_patients() -> Patient-level predictions (just pass clone_pred + prepared)" +) message("\nUser inputs needed:") message(" - expression_matrix: genes x cells (raw single-cell expression)") -message(" - patient_mapping: list OR data frame with cell_id + patient_id columns") +message( + " - patient_mapping: list OR data frame with cell_id + patient_id columns" +) message("\nOutput files saved to: ", output_dir) for (f in list.files(output_dir, full.names = TRUE)) { From 0730a0c6f76fd11d2156e55edbd30e1475982020 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=81=E5=8A=A0?= Date: Thu, 5 Nov 2026 19:28:30 +0800 Subject: [PATCH 4/4] fix: keep glmnet/randomForest in Imports; copy data.table inputs - train_models() defaults to model_type = 'glmnet', and caret's glmnet model declares glmnet/Matrix at runtime. Moving them to Suggests makes the default path fail for users without those packages. - as.data.table() does not copy: the comment above the assignment promises a copy the code never made. Add an explicit copy() (also covers data.table < 1.15). --- DESCRIPTION | 4 ++-- R/annotate.R | 6 +++++- R/predict.R | 4 +++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 394b347..ff4c57d 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -21,7 +21,9 @@ VignetteBuilder: knitr Imports: ggplot2, gridExtra, + glmnet, caret, + randomForest, pROC, rlang, Seurat, @@ -49,8 +51,6 @@ Suggests: spelling, WGCNA, matrixStats, - glmnet, - randomForest, kableExtra Config/testthat/edition: 3 Language: en-US diff --git a/R/annotate.R b/R/annotate.R index 9d89a02..330e618 100644 --- a/R/annotate.R +++ b/R/annotate.R @@ -452,7 +452,11 @@ prepare_data <- function( is.data.frame(patient_mapping) || data.table::is.data.table(patient_mapping) ) { # Copy, so that set-by-reference edits below never touch the caller's object. - patient_mapping <- data.table::as.data.table(patient_mapping) + # as.data.table() returns the same object when the input is already a + # data.table, so an explicit copy() is required for that case. + patient_mapping <- data.table::copy( + data.table::as.data.table(patient_mapping) + ) # Optional per-clone abundance column (count / cells / n_cells / # n_cells_per_clone / abundance): expand each row to that many rows so that diff --git a/R/predict.R b/R/predict.R index add16d3..b3fae3c 100644 --- a/R/predict.R +++ b/R/predict.R @@ -299,7 +299,9 @@ predict_patients <- function( clone_viability_matrix[, clone_id := clone_template$clone_id] } else if (is.data.frame(prepared_data)) { # Legacy mode: prepared_data is actually clone_counts, clone_pred is clone_viability_matrix - clone_viability_matrix <- clone_pred + # copy(): the `:=` edits below would otherwise modify a data.table input in + # place, i.e. the caller's object. + clone_viability_matrix <- data.table::copy(clone_pred) clone_counts <- prepared_data } else { cli::cli_abort(