From 07011d3c26aa67a1ea8794edc6b6e68af31f78bd Mon Sep 17 00:00:00 2001 From: erliuu Date: Sun, 18 Oct 2026 21:08:28 -0700 Subject: [PATCH 01/12] feat([r] utils): Add verbose logging improvement utility --- R/utils.R | 41 ++++++++++++++----- tests/testthat/test-utils.R | 81 +++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 10 deletions(-) diff --git a/R/utils.R b/R/utils.R index c4c510f..6171c3f 100644 --- a/R/utils.R +++ b/R/utils.R @@ -89,17 +89,38 @@ selection_index <- function(selection, dim_len, dimnames) { } } -# Function which prints a message using shell echo. -# Useful for printing messages from inside mclapply when running in Rstudio. -log_progress <- function(msg, add_timestamp = TRUE) { - if (add_timestamp) { - msg <- add_timestamp(msg) - } - if (.Platform$GUI == "RStudio") { - system(sprintf('echo "%s"', paste0(msg, collapse = ""))) - } else { - message(msg) +.log_clock <- new.env(parent = emptyenv()) + +# Starts the verbose=True run clock enclosing MarchR function calls. +.start_log_clock <- function(envir = parent.frame()) { + opt <- getOption("MarchR.verbose") + if (!is.null(opt) && !rlang::is_bool(opt)) { + rlang::abort( + c("`options(MarchR.verbose)` must be TRUE, FALSE, or NULL.", x = paste("Got:", deparse1(opt))), + call = envir + ) + } + if (!is.null(.log_clock$start)) { + return(invisible()) + } + do.call(on.exit, list(quote(.log_clock$start <- NULL), add = TRUE), envir = envir) + .log_clock$start <- Sys.time() + .log_clock$new_run <- TRUE +} + +# Messages with header = TRUE is framed by hashmarks. +log_progress <- function(msg, header = FALSE) { + if (!is.null(.log_clock$start)) { + mins <- as.numeric(difftime(Sys.time(), .log_clock$start, units = "mins")) + msg <- sprintf("%s, %.3f mins elapsed.", sub("\\.+$", "", msg), mins) + header <- header || .log_clock$new_run + .log_clock$new_run <- FALSE + } + msg <- add_timestamp(msg) + if (header) { + msg <- paste("###########", msg, "###########", sep = "\n") } + message(msg) } ######################################################################## diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index fc5e1bc..964db35 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -6,3 +6,84 @@ test_that(".get_quantiles matches trunc(rank(v))/length(v) and handles ties", { expect_equal(.get_quantiles(c(1, 1, 2)), c(1 / 3, 1 / 3, 1)) expect_equal(.get_quantiles(numeric(0)), numeric(0)) }) + +test_that("log_progress prints a timestamp and no elapsed time without a run clock", { + expect_null(.log_clock$start) + msgs <- capture_messages(log_progress("Computing LSI")) + expect_match(msgs, "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Computing LSI\n$", perl = TRUE) +}) + +test_that("log_progress adds elapsed minutes, and a header on the first message of a run", { + run <- function() { + .start_log_clock() + log_progress("Calling peaks...") + log_progress("Filtering peaks") + log_progress("Running LSI (1 of 2)", header = TRUE) + } + msgs <- capture_messages(run()) + expect_match( + msgs[1], "^###########\n[^\n]+ Calling peaks, [0-9]+\\.[0-9]{3} mins elapsed\\.\n###########\n$", + perl = TRUE + ) + expect_match(msgs[2], "^[^#][^\n]+ Filtering peaks, [0-9.]+ mins elapsed\\.\n$", perl = TRUE) + expect_match( + msgs[3], "^###########\n[^\n]+ Running LSI \\(1 of 2\\), [0-9.]+ mins elapsed\\.\n###########\n$", + perl = TRUE + ) +}) + +test_that("nested calls share one run clock that is cleared on return and on error", { + inner <- function() { + .start_log_clock() + .log_clock$start + } + outer <- function() { + .start_log_clock() + list(start = .log_clock$start, inner_start = inner(), after_inner = .log_clock$start) + } + res <- outer() + expect_s3_class(res$start, "POSIXct") + expect_identical(res$inner_start, res$start) + expect_identical(res$after_inner, res$start) + expect_null(.log_clock$start) + + failing <- function() { + .start_log_clock() + stopifnot(!is.null(.log_clock$start)) + rlang::abort("boom") + } + expect_error(failing(), "boom") + expect_null(.log_clock$start) +}) + +test_that("log_progress header = TRUE frames a message without a run clock", { + msgs <- capture_messages(log_progress("Running LSI (1 of 2)", header = TRUE)) + expect_match(msgs, "^###########\n[^\n]+ Running LSI \\(1 of 2\\)\n###########\n$", perl = TRUE) +}) + +test_that("the MarchR.verbose option overrides function defaults in both directions", { + set.seed(1) + counts <- matrix(rpois(100 * 200, lambda = 2), nrow = 100, + dimnames = list(paste0("f", 1:100), paste0("c", 1:200))) + mat <- methods::as(methods::as(counts, "dgCMatrix"), "IterableMatrix") + emb <- matrix(rnorm(200 * 5), nrow = 200, dimnames = list(paste0("cell_", 1:200), NULL)) + + withr::local_options(MarchR.verbose = TRUE) + expect_match(capture_messages(LSI(mat, n_dimensions = 5)), "Starting LSI", all = FALSE) + withr::local_options(MarchR.verbose = FALSE) + expect_no_message(make_knn_pseudobulks(emb, knn_iteration = 50L, k = 20L)) + expect_match(capture_messages(LSI(mat, n_dimensions = 5, verbose = TRUE)), "Starting LSI", all = FALSE) +}) + +test_that("an invalid MarchR.verbose option is rejected when a run starts", { + starts_run <- function() .start_log_clock() + withr::local_options(MarchR.verbose = 1) + expect_error(starts_run(), "MarchR.verbose") + expect_error(make_knn_pseudobulks(matrix(0, 2, 2)), "MarchR.verbose") + expect_null(.log_clock$start) + withr::local_options(MarchR.verbose = TRUE) + expect_no_error(starts_run()) + withr::local_options(MarchR.verbose = NULL) + expect_no_error(starts_run()) + expect_null(.log_clock$start) +}) From 4c3aa8de716469544c0187627608d8c73944e19d Mon Sep 17 00:00:00 2001 From: erliuu Date: Sun, 18 Oct 2026 21:09:36 -0700 Subject: [PATCH 02/12] feat([r] logging): Add verbose logging flag to relevant functions (repo-wide), set with options(MarchR.verbose = TRUE) --- R/bulk_projection.R | 8 +- R/clustering.R | 14 ++-- R/coaccessibility.R | 7 +- R/deviations.R | 17 +++-- R/dimensionality_reduction.R | 52 +++++++------ R/doublet.R | 66 ++++++++++------- R/embeddings.R | 22 ++++-- R/enrichment.R | 30 ++++---- R/footprinting.R | 20 ++--- R/fragment_ops.R | 2 +- R/group_coverages.R | 16 ++-- R/imputation.R | 19 +++-- R/linkage.R | 9 ++- R/markers.R | 21 +++--- R/module_scores.R | 8 +- R/multi_modal.R | 5 +- R/peak2gene.R | 9 ++- R/peaks.R | 73 ++++++++++--------- R/plotting.R | 27 ++++--- R/pseudobulk.R | 37 ++++++---- R/rna_integration.R | 21 +++--- R/track_plotting.R | 5 +- R/trajectory.R | 7 +- man/IterativeLSI.Rd | 6 +- man/LSI.Rd | 6 +- man/PCA.Rd | 6 +- man/add_background_peaks.Rd | 4 +- man/add_clusters.Rd | 6 +- man/add_co_accessibility.Rd | 4 +- man/add_deviations_matrix.Rd | 4 +- man/add_doublet_scores.Rd | 8 +- man/add_gene_integration_matrix.Rd | 4 +- man/add_group_coverages.Rd | 6 +- man/add_impute_weights.Rd | 4 +- man/add_kmer_bias.Rd | 4 +- man/add_marker_features.Rd | 6 +- man/add_module_score.Rd | 6 +- man/add_motif_annotations.Rd | 4 +- man/add_peak2gene_links.Rd | 4 +- man/add_peak_annotations.Rd | 4 +- man/add_peak_gc.Rd | 10 ++- man/add_peak_matrix.Rd | 4 +- man/add_reproducible_peak_set.Rd | 4 +- man/add_tsne.Rd | 8 +- man/add_umap.Rd | 8 +- man/filter_doublets.Rd | 4 +- man/get_footprints.Rd | 4 +- man/import_feature_matrix_10x.Rd | 4 +- man/impute_matrix.Rd | 8 +- man/make_knn_pseudobulks.Rd | 4 +- man/peak_annotation_enrichment.Rd | 4 +- man/plot_browser_track.Rd | 4 +- man/plot_doublet_scores.Rd | 6 +- man/plot_embedding.Rd | 6 +- man/plot_gene_scores.Rd | 4 +- man/project_bulk_atac.Rd | 2 +- man/project_doublets.Rd | 4 +- man/pseudobulk_fragments.Rd | 4 +- man/score_doublets.Rd | 4 +- man/simulate_doublets.Rd | 4 +- man/write_pseudobulk_bigwig.Rd | 4 +- man/write_pseudobulk_coverage.Rd | 4 +- man/write_pseudobulk_fragments.Rd | 9 ++- man/write_pseudobulk_peaks.Rd | 4 +- tests/testthat/test-clustering.R | 31 ++++++++ tests/testthat/test-deviations.R | 2 +- .../testthat/test-dimensionality_reduction.R | 10 +++ tests/testthat/test-linkage.R | 10 +++ tests/testthat/test-multi_modal.R | 2 +- 69 files changed, 450 insertions(+), 307 deletions(-) diff --git a/R/bulk_projection.R b/R/bulk_projection.R index cc29903..e80dfdb 100644 --- a/R/bulk_projection.R +++ b/R/bulk_projection.R @@ -236,7 +236,7 @@ #' @param seed (numeric) Random seed. Default: 1. #' @param threads (integer) Threads for the UMAP transform in the MarchRProject method. Default #' `get_threads()`. The DimReduction method projects single-threaded (default NULL). -#' @param verbose (logical) Print progress. Default: \code{TRUE}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Passed to methods. #' #' @return A list with \code{simulated_reduced_dims}, \code{overlap_ratio} and @@ -278,9 +278,10 @@ project_bulk_atac.DimReduction <- function( force = FALSE, seed = 1L, threads = NULL, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_has_package(c("SummarizedExperiment", "GenomicRanges", "IRanges", "S4Vectors")) assert_is_wholenumber(n) assert_greater_than_zero(n) @@ -393,9 +394,10 @@ project_bulk_atac.MarchRProject <- function( force = FALSE, seed = 1L, threads = get_threads(), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(x, "MarchRProject") threads <- .resolve_threads(threads) dim_reduction_name <- select_embedding_name(x, dim_reduction_name) diff --git a/R/clustering.R b/R/clustering.R index 958aacf..b1a3920 100644 --- a/R/clustering.R +++ b/R/clustering.R @@ -53,7 +53,7 @@ add_clusters <- function(x, ...) { #' @param seed (integer) Random seed. #' @param threads (integer) Threads for the KNN search. Default runs single-threaded. #' Note that result is non-deterministic if threads > 1. -#' @param verbose (logical) Print progress messages. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @return Named character vector of cluster labels. #' @export add_clusters.default <- function( @@ -66,9 +66,10 @@ add_clusters.default <- function( prefix = "C", seed = 1L, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() if (is(x, "IterableMatrix")) x <- as.matrix(t(x)) if (is(x, "dgCMatrix")) x <- as.matrix(x) @@ -96,6 +97,7 @@ add_clusters.default <- function( knn_to_graph_method = knn_to_graph_method, cluster_graph_method = wrapped_cluster_graph, threads = threads, + verbose = verbose, .missing_args_error = FALSE )(x) names(clusters) <- rownames(x) @@ -106,7 +108,7 @@ add_clusters.default <- function( small_clusts <- names(tab[tab < n_outlier]) if (length(small_clusts) > 0) { if (verbose) { - message(sprintf( + log_progress(sprintf( "Reassigning %d outlier cluster(s) with < %d cells", length(small_clusts), n_outlier )) @@ -116,6 +118,7 @@ add_clusters.default <- function( outlier_knn_method <- partial_apply( knn_method, k = min(10L, length(non_outlier_idx)), + verbose = verbose, .overwrite = TRUE, .missing_args_error = FALSE ) @@ -151,7 +154,7 @@ add_clusters.default <- function( } if (verbose) { - message(sprintf("Found %d clusters", length(unique(clusters)))) + log_progress(sprintf("Found %d clusters", length(unique(clusters)))) } return(clusters) @@ -183,9 +186,10 @@ add_clusters.MarchRProject <- function( seed = 1L, overwrite = FALSE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() assert_for(x, "MarchRProject") assert_is_character(col_name) assert_len(col_name, 1) diff --git a/R/coaccessibility.R b/R/coaccessibility.R index 1d2cfe6..4021a06 100644 --- a/R/coaccessibility.R +++ b/R/coaccessibility.R @@ -30,7 +30,7 @@ add_co_accessibility <- function(proj, ...) { #' @param log2_norm (logical) Apply log2(x + 1) after depth normalization. Default TRUE. #' @param knn_method (function) KNN engine (BPCells partial-application). Default `knn_hnsw()`. #' @param seed (integer) Random seed for metacell sampling. Default 1L. -#' @param verbose (logical) Print progress messages. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param overwrite (logical) Replace an existing `co_accessibility` result. Default FALSE. #' #' @return `proj` with `proj$co_accessibility` populated as a data.frame with columns @@ -59,12 +59,13 @@ add_co_accessibility.MarchRProject <- function( log2_norm = TRUE, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ...) { + .start_log_clock() assert_for(proj, "MarchRProject") if (!is.null(proj$co_accessibility) && !overwrite) { - if (verbose) message("co_accessibility exists; set overwrite = TRUE to recompute.") + if (verbose) log_progress("co_accessibility exists; set overwrite = TRUE to recompute.") return(proj) } if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { diff --git a/R/deviations.R b/R/deviations.R index 68ddaa7..ffe845a 100644 --- a/R/deviations.R +++ b/R/deviations.R @@ -114,7 +114,7 @@ #' reference population configured by `add_background_peaks()`. #' @param chunk_size (integer) Cells per chunk; bounds dense per-chunk memory. Default 20000. #' @param overwrite (logical) Replace existing matrices. Default FALSE. -#' @param verbose (logical) Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Unused. #' #' @return Modified MarchRProject. @@ -169,9 +169,10 @@ add_deviations_matrix.MarchRProject <- function( dataset_names = character(0), chunk_size = 20000L, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") if (!is.numeric(chunk_size) || length(chunk_size) != 1L || !is.finite(chunk_size) || chunk_size < 1 || chunk_size != round(chunk_size)) { @@ -210,7 +211,7 @@ add_deviations_matrix.MarchRProject <- function( scratch <- NULL on.exit(unlink(scratch, recursive = TRUE, expand = FALSE), add = TRUE) for (ds in dataset_names) { - if (verbose) message(sprintf("Computing deviations for dataset '%s'...", ds)) + if (verbose) log_progress(sprintf("Computing deviations for dataset '%s'...", ds)) peak_mat <- proj$datasets[[ds]]$matrices[["PeakMatrix"]] if ((dev_name %in% names(proj$datasets[[ds]]$matrices) || @@ -249,7 +250,7 @@ add_deviations_matrix.MarchRProject <- function( dir.create(scratch, recursive = TRUE) # Column-major lets the multiplies stream cells instead of seeking each match. if (BPCells::storage_order(peak_mat) == "row") { - if (verbose) message(" Transposing PeakMatrix to column-major...") + if (verbose) log_progress(" Transposing PeakMatrix to column-major...") peak_mat <- BPCells::transpose_storage_order( peak_mat, outdir = file.path(scratch, "PeakMatrix"), tmpdir = scratch ) @@ -257,7 +258,7 @@ add_deviations_matrix.MarchRProject <- function( if (verbose) { bg <- if (analytic) sprintf("Analytic background over %d bias bins", length(bgd$bin_density)) else sprintf("Sampled background over %d iterations", ncol(bgd)) - message(sprintf(" %s (%d motifs x %d cells)...", bg, ncol(matches), ncol(peak_mat))) + log_progress(sprintf(" %s (%d motifs x %d cells)...", bg, ncol(matches), ncol(peak_mat))) } chunks <- split(seq_len(ncol(peak_mat)), ceiling(seq_len(ncol(peak_mat)) / chunk_size)) @@ -266,7 +267,7 @@ add_deviations_matrix.MarchRProject <- function( for (i in seq_along(chunks)) { cols <- chunks[[i]] if (verbose && length(chunks) > 1L) { - message(sprintf(" Cells %d-%d of %d...", cols[1], cols[length(cols)], ncol(peak_mat))) + log_progress(sprintf(" Cells %d-%d of %d...", cols[1], cols[length(cols)], ncol(peak_mat))) } out <- if (analytic) { .deviations_analytic(bgd, matches_aligned, peak_mat[, cols], row_map, @@ -292,8 +293,8 @@ add_deviations_matrix.MarchRProject <- function( proj$datasets[[ds]]$matrices[[z_name]] <- .build_integration_matrix(z_parts, z_path) if (verbose) { - message(sprintf(" Stored '%s' and '%s' on dataset '%s'", - dev_name, z_name, ds)) + log_progress(sprintf(" Stored '%s' and '%s' on dataset '%s'", + dev_name, z_name, ds)) } unlink(scratch, recursive = TRUE, expand = FALSE) } diff --git a/R/dimensionality_reduction.R b/R/dimensionality_reduction.R index 9ab0538..05331c6 100644 --- a/R/dimensionality_reduction.R +++ b/R/dimensionality_reduction.R @@ -709,6 +709,7 @@ extract_metadata_column <- function(x, column) { #' before LSI; FALSE retains them with depth floored to 1. Default TRUE. #' @param threads (integer) Threads for the SVD in `LSI()`. Default is `get_threads()`. #' Other passes and `project()` run single-threaded by default (optimal) +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @returns #' A list with the following items: #' - `cell_embeddings`: The projected data as a matrix of shape `(cells, n_dimensions)` @@ -758,7 +759,7 @@ LSI <- function( outlier_quantiles = c(0.02, 0.98), drop_zero_cells = TRUE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { if (rlang::is_missing(x)) { @@ -780,8 +781,9 @@ LSI.default <- function( outlier_quantiles = c(0.02, 0.98), drop_zero_cells = TRUE, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_mat(x) assert_is_wholenumber(n_dimensions) assert_len(n_dimensions, 1) @@ -863,7 +865,7 @@ LSI.default <- function( temp_mat_dir, compress = TRUE ) - on.exit(unlink(temp_mat_dir, recursive = TRUE, expand = FALSE)) + on.exit(unlink(temp_mat_dir, recursive = TRUE, expand = FALSE), add = TRUE) # Run pca if (verbose) { log_progress("Calculating SVD") @@ -956,8 +958,9 @@ LSI.MarchRProject <- function( drop_zero_cells = TRUE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_character(dataset_names) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) @@ -1152,7 +1155,7 @@ project_test <- function(mat, ...) { #' @param threads (integer) Per-call override of `set_threads()`. Default NULL threads each SVD with #' `get_threads()` and clusters single-threaded. Note that an explicit value also threads the clustering #' KNN, which makes results non-deterministic. -#' @param verbose (logical) Print progress messages. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments passed to methods. #' @return #' For a matrix input, `IterativeLSI()` returns a named list with two elements: @@ -1291,7 +1294,7 @@ IterativeLSI <- function( seed = 1, drop_zero_cells = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { UseMethod("IterativeLSI") @@ -1327,8 +1330,9 @@ IterativeLSI.default <- function( seed = 1, drop_zero_cells = TRUE, threads = NULL, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_has_package("RcppHNSW") assert_is_mat(x) assert_greater_than_zero(n_iterations) @@ -1521,6 +1525,7 @@ IterativeLSI.default <- function( partial_apply( cluster_method, threads = knn_threads, + verbose = verbose, .missing_args_error = FALSE )() clustering_res <- .merge_clusters( @@ -1744,8 +1749,9 @@ IterativeLSI.MarchRProject <- function( drop_zero_cells = TRUE, overwrite = FALSE, threads = NULL, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_character(dataset_names) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) @@ -1855,7 +1861,7 @@ IterativeLSI.MarchRProject <- function( #' @param overwrite (logical) Whether to overwrite existing results. Default is FALSE. #' @param threads (integer) Threads for normalization, feature selection, and the SVD. Default #' `get_threads()`. `project()` runs single-threaded by default. -#' @param verbose (logical) Whether to print progress messages. Default is FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param mat (IterableMatrix) For \code{project.PCA}: New matrix to project into PCA space. #' @param ... Additional arguments passed to methods. #' @@ -1912,7 +1918,7 @@ PCA <- function( n_features = 1000L, n_dimensions = 50L, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { if (rlang::is_missing(x)) { @@ -1930,8 +1936,9 @@ PCA.default <- function( n_features = 1000L, n_dimensions = 50L, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_mat(x) assert_is_wholenumber(n_features) assert_is_wholenumber(n_dimensions) @@ -1951,19 +1958,19 @@ PCA.default <- function( } if (verbose) { - cat("Starting PCA workflow...\n") + log_progress("Starting PCA workflow...") } if (verbose) { - cat( + log_progress(paste( "Using", n_features, - "variable features (limited by matrix dimensions)\n" - ) + "variable features (limited by matrix dimensions)" + )) } # Log normalization if (verbose) { - cat("Performing log normalization...\n") + log_progress("Performing log normalization...") } # Use MarchR's normalize_log function which implements Seurat-style normalization @@ -1972,7 +1979,7 @@ PCA.default <- function( # Variable gene selection if (verbose) { - cat("Selecting variable features...\n") + log_progress("Selecting variable features...") } # Calculate statistics for normalization @@ -2005,7 +2012,7 @@ PCA.default <- function( feature_vars <- var_stats[variable_features] if (verbose) { - cat("Caching normalized matrix...\n") + log_progress("Caching normalized matrix...") } cache_dir <- tempfile("marchr_pca_") on.exit(unlink(cache_dir, recursive = TRUE), add = TRUE) @@ -2015,7 +2022,7 @@ PCA.default <- function( # Z-score normalization if (verbose) { - cat("Applying z-score normalization...\n") + log_progress("Applying z-score normalization...") } feature_sds <- sqrt(feature_vars) feature_sds[feature_sds == 0] <- 1 @@ -2041,7 +2048,7 @@ PCA.default <- function( } if (verbose) { - cat("Computing SVD with", n_dimensions, "dimensions...\n") + log_progress(paste("Computing SVD with", n_dimensions, "dimensions...")) } svd_result <- BPCells::svds(x_norm, k = n_dimensions, threads = threads) @@ -2051,7 +2058,7 @@ PCA.default <- function( colnames(pc_embeddings) <- paste0("PC_", 1:n_dimensions) if (verbose) { - cat("PCA complete!\n") + log_progress("PCA complete") } # Get the actual variable feature names after selection @@ -2108,8 +2115,9 @@ PCA.MarchRProject <- function( n_dimensions = 50L, overwrite = FALSE, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_character(dataset_names) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) diff --git a/R/doublet.R b/R/doublet.R index 4dc0aa5..787722f 100644 --- a/R/doublet.R +++ b/R/doublet.R @@ -53,7 +53,7 @@ #' @param threads (integer) Per-call override of `set_threads()`. Default NULL uses [get_threads()] #' for the LSI SVD and UMAP, and single-threads IterativeLSI clustering KNN. #' Note that an explicit value also threads clustering, which makes doublet scores non-deterministic. -#' @param verbose (logical) Print progress messages. Default is FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments passed to methods. #' #' @return The modified MarchRDataset or MarchRProject with a @@ -101,7 +101,7 @@ add_doublet_scores <- function( seed = 1, batch = TRUE, threads = NULL, - verbose=FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { UseMethod("add_doublet_scores") @@ -129,9 +129,10 @@ add_doublet_scores.MarchRDataset <- function( seed = 1, batch = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() assert_is_character(assay_name) assert_that(is.list(lsi_params)) assay_name <- select_assay_name(x, assay_name) @@ -218,9 +219,10 @@ add_doublet_scores.MarchRProject <- function( seed = 1, batch = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() assert_is_character(assay_name) assert_is_character(dataset_names) dataset_names <- select_dataset_names(x, dataset_names) @@ -231,10 +233,12 @@ add_doublet_scores.MarchRProject <- function( # Replicates must be merged before doublet scoring so cross-sample doublets are detectable if (combine && length(dataset_names) > 1) { - log_progress(sprintf( - "Processing dataset(s): %s as replicates", - paste(dataset_names, collapse = ", ") - )) + if (verbose) { + log_progress(sprintf( + "Processing dataset(s): %s as replicates", + paste(dataset_names, collapse = ", ") + )) + } input_mats <- lapply(seq_along(dataset_names), function(i) { ds <- dataset_names[i] @@ -282,10 +286,12 @@ add_doublet_scores.MarchRProject <- function( # TODO parallelize this (based on threads) for (i in seq_along(dataset_names)) { ds <- dataset_names[i] - log_progress(sprintf( - "Processing dataset %d of %d: %s", - i, n_datasets, ds - )) + if (verbose) { + log_progress(sprintf( + "Processing dataset %d of %d: %s", + i, n_datasets, ds + )) + } x$datasets[[ds]] <- add_doublet_scores( x$datasets[[ds]], @@ -336,7 +342,7 @@ add_doublet_scores.MarchRProject <- function( #' independently to each side of the pair before summing. Default 0.5. #' @param seed (integer) Reproducibility seed for both the cell-pair draws #' and the Bernoulli downsampling. Default 1L. -#' @param verbose (logical) Print progress messages. Default is FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @returns A lazy IterableMatrix chain (bernoulli + bernoulli + add) with #' dimensions `(features x (n_doublets x n_trials))`. Downstream callers #' materialize it via \code{write_matrix_dir()} (e.g. inside @@ -348,7 +354,7 @@ simulate_doublets <- function( n_trials = NULL, sample_ratio = 0.5, seed = 1L, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { if (rlang::is_missing(mat)) { @@ -364,8 +370,9 @@ simulate_doublets.default <- function( n_trials = NULL, sample_ratio = 0.5, seed = 1L, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_greater_than_zero(n_doublets) assert_true( is.numeric(sample_ratio) && length(sample_ratio) == 1 && @@ -498,7 +505,7 @@ simulate_doublets.default <- function( } } - log_progress(sprintf("UMAP Re-projection Correlation: R^2 = %.3f", R_squared)) + if (verbose) log_progress(sprintf("UMAP Re-projection Correlation: R^2 = %.3f", R_squared)) return(umap_model) } @@ -535,7 +542,7 @@ simulate_doublets.default <- function( #' @param seed (integer) UMAP RNG seed #' @param batch (logical) Use uwot's batch UMAP optimizations. Default TRUE. #' @param threads (integer) Per-call override of `set_threads()`, as in [add_doublet_scores()]. Default NULL. -#' @param verbose (logical) Print progress messages. Default FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return A Named list with following elements: #' \describe{ @@ -560,7 +567,7 @@ project_doublets <- function( seed = 1, batch = TRUE, threads = NULL, - verbose= FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { if (rlang::is_missing(sim_doublets)) { @@ -585,8 +592,9 @@ project_doublets.default <- function( seed = 1, batch = TRUE, threads = NULL, - verbose= FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_mat(mat) assert_is_mat(sim_doublets) assert_that(is.list(lsi_params)) @@ -680,7 +688,7 @@ project_doublets.default <- function( #' @param knn_method (function) KNN method. Default #' \code{knn_hnsw(k = 10L, metric = "euclidean", ef = 200L)}. Put KNN-specific #' arguments such as \code{k} or \code{metric} inside the partial function. -#' @param verbose (logical) Default FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return A list with one row per real cell: #' \describe{ @@ -692,7 +700,7 @@ score_doublets <- function( project_res, scoring_method = c("UMAP", "LSI"), knn_method = knn_hnsw(k = 10L, metric = "euclidean", ef = 200L), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { UseMethod("score_doublets") @@ -703,8 +711,9 @@ score_doublets.default <- function( project_res, scoring_method = c("UMAP", "LSI"), knn_method = knn_hnsw(k = 10L, metric = "euclidean", ef = 200L), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() .run_knn <- function(cells_embed, doublets_embed, knn_method) { @@ -748,6 +757,7 @@ score_doublets.default <- function( scoring_method <- match.arg(scoring_method) assert_that(is.function(knn_method)) + knn_method <- partial_apply(knn_method, verbose = verbose, .missing_args_error = FALSE) lsi_cells <- as.matrix(project_res$lsi_cells) lsi_doublets <- as.matrix(project_res$lsi_doublets) @@ -803,7 +813,7 @@ score_doublets.default <- function( #' percentages of doublets because they were run with different cell loading concentrations. #' The higher the `filter_ratio`, the greater the number of cells potentially removed as doublets. #' @param clear_doublet_data (logical) Remove all stale doublet data from project (UMAPs, doublet scores & enrichments). Default is TRUE. -#' @param verbose (logical) Print progress messages. Default is FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments passed to methods. #' #' @return MarchRProject or MarchRDataset modified to have doublets removed from matrices/fragments/cell_metadata @@ -815,7 +825,7 @@ filter_doublets <- function( score_cutoff = -Inf, filter_ratio = 1, clear_doublet_data = TRUE, - verbose=FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { UseMethod("filter_doublets") @@ -828,8 +838,9 @@ filter_doublets.MarchRDataset <- function( score_cutoff = -Inf, filter_ratio = 1, clear_doublet_data = TRUE, - verbose=FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() if (!is.null(proj$filtered_doublets) && proj$filtered_doublets == TRUE) { warning("filter_doublets() has already been run on this dataset. Skipping...") return(proj) @@ -904,12 +915,13 @@ filter_doublets.MarchRProject <- function( score_cutoff = -Inf, filter_ratio = 1, clear_doublet_data = TRUE, - verbose=FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_is_character(dataset_names) dataset_names <- select_dataset_names(proj, dataset_names) - if (verbose) message(sprintf( + if (verbose) log_progress(sprintf( "Filtering doublets in %d dataset(s): %s", length(dataset_names), paste(dataset_names, collapse = ", ") diff --git a/R/embeddings.R b/R/embeddings.R index a7cd209..2c5d0c1 100644 --- a/R/embeddings.R +++ b/R/embeddings.R @@ -71,7 +71,7 @@ add_umap <- function(x, ...) { #' @param seed (integer) Random seed for reproducibility. #' @param batch (logical) Use uwot's deterministic batch optimization. Default \code{TRUE}. #' @param threads (integer) Number of threads. -#' @param verbose (logical) Whether to print progress messages. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param umap_params (list) Additional parameters passed to \code{uwot::umap2()}. #' These override any other arguments when there is a conflict. #' @param return_model (logical) For matrix inputs, return the fitted uwot @@ -90,11 +90,12 @@ add_umap.default <- function( seed = 1L, batch = TRUE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), umap_params = list(), return_model = FALSE, ... ) { + .start_log_clock() assert_has_package("uwot") threads <- .resolve_threads(threads) assert_for(batch, "logical") @@ -202,10 +203,11 @@ add_umap.MarchRDataset <- function( store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), umap_params = list(), ... ) { + .start_log_clock() assert_for(x, "MarchRDataset") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -329,11 +331,12 @@ add_umap.MarchRProject <- function( store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), umap_params = list(), return_model = TRUE, ... ) { + .start_log_clock() assert_for(x, "MarchRProject") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -589,7 +592,7 @@ add_tsne <- function(x, ...) { #' @param n_components (integer) Number of t-SNE dimensions. Default is 2. #' @param seed (integer) Random seed for reproducibility. #' @param threads (integer) Number of threads. -#' @param verbose (logical) Whether to print progress messages. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param tsne_params (list) Additional parameters passed to #' \code{Rtsne::Rtsne()}. These override any other arguments when there is #' a conflict. @@ -603,10 +606,11 @@ add_tsne.default <- function( n_components = 2L, seed = 1L, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), tsne_params = list(), ... ) { + .start_log_clock() assert_has_package("Rtsne") # BPCells stores as features x cells; uwot/Rtsne expect cells x dims @@ -691,10 +695,11 @@ add_tsne.MarchRDataset <- function( store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), tsne_params = list(), ... ) { + .start_log_clock() assert_for(x, "MarchRDataset") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -811,10 +816,11 @@ add_tsne.MarchRProject <- function( store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), tsne_params = list(), ... ) { + .start_log_clock() assert_for(x, "MarchRProject") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) diff --git a/R/enrichment.R b/R/enrichment.R index bc739d2..87dc1d6 100644 --- a/R/enrichment.R +++ b/R/enrichment.R @@ -30,7 +30,7 @@ #' used when `method = "bpcells"`). #' @param overwrite (logical) Replace existing background_peaks. Default FALSE #' keeps the stored background, warning if it was built with another `method`. -#' @param verbose (logical) Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param dataset_names (character or NULL) Reference datasets whose PeakMatrix #' counts are pooled for background matching and deviation expectations. #' NULL (default) uses all datasets with a PeakMatrix. An explicit selection @@ -90,10 +90,11 @@ add_background_peaks.MarchRProject <- function( seed = 1L, knn_ef = 200L, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), dataset_names = NULL, ... ) { + .start_log_clock() method <- match.arg(method) assert_for(proj, "MarchRProject") if (method == "betterChromVAR" && bin_size^2 > 1e5) { @@ -120,7 +121,7 @@ add_background_peaks.MarchRProject <- function( stored_method, method )) } else if (verbose) { - message("background_peaks already populated. Use overwrite = TRUE to recompute.") + log_progress("background_peaks already populated. Use overwrite = TRUE to recompute.") } return(proj) } @@ -135,7 +136,7 @@ add_background_peaks.MarchRProject <- function( chromVAR = .background_peaks_chromvar(row_sums, gc, proj$peak_set, n_iterations, w, bin_size, seed), bpcells = .background_peaks_bpcells(row_sums, gc, len, n_iterations, - seed, knn_ef), + seed, knn_ef, verbose), betterChromVAR = structure( .background_bins(row_sums, gc, bs = c(bin_size, bin_size), w = w), class = "MarchRBinBackground" @@ -159,11 +160,11 @@ add_background_peaks.MarchRProject <- function( if (verbose) { if (inherits(bgd, "MarchRBinBackground")) { - message(sprintf(" Stored background_peaks: %d peaks in %d bias bins (method = %s)", - length(bgd$peak2bin), length(bgd$bin_density), method)) + log_progress(sprintf(" Stored background_peaks: %d peaks in %d bias bins (method = %s)", + length(bgd$peak2bin), length(bgd$bin_density), method)) } else { - message(sprintf(" Stored background_peaks: %d peaks x %d iterations (method = %s)", - nrow(bgd), ncol(bgd), method)) + log_progress(sprintf(" Stored background_peaks: %d peaks x %d iterations (method = %s)", + nrow(bgd), ncol(bgd), method)) } } proj @@ -198,7 +199,7 @@ add_background_peaks.MarchRProject <- function( } # Path B: BPCells knn_hnsw on quantile-normalized (log10(rowSums+1), gc, length). -.background_peaks_bpcells <- function(row_sums, gc, len, n_iter, seed, knn_ef = 200L) { +.background_peaks_bpcells <- function(row_sums, gc, len, n_iter, seed, knn_ef = 200L, verbose) { bias_mat <- cbind( qnorm(rank(log10(row_sums + 1)) / (length(row_sums) + 1)), qnorm(rank(gc) / (length(gc) + 1)), @@ -206,7 +207,7 @@ add_background_peaks.MarchRProject <- function( ) set.seed(seed) knn <- suppressWarnings(BPCells::knn_hnsw( - bias_mat, k = n_iter + 1L, ef = knn_ef + bias_mat, k = n_iter + 1L, ef = knn_ef, verbose = verbose )$idx) t(vapply(seq_len(nrow(knn)), function(i) { neighbors <- knn[i, ] @@ -443,7 +444,7 @@ get_background_peaks.MarchRProject <- function(proj, ...) { #' @param background (character) `"all"` (whole peak set) or #' `"background_peaks"` (GC/accessibility-matched peers via #' `add_background_peaks()`). -#' @param verbose (logical) Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Unused. #' #' @return Long `tibble` with one row per (group x annotation) pair. @@ -472,9 +473,10 @@ peak_annotation_enrichment.MarchRProject <- function( matches = NULL, cutoff = "p_val_adj <= 0.1 & log2_fc >= 0.5", background = c("all", "background_peaks"), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") background <- match.arg(background) @@ -489,8 +491,8 @@ peak_annotation_enrichment.MarchRProject <- function( fg_groups <- split(results_df, results_df$foreground) if (verbose) { - message(sprintf("Running enrichment: %d groups x %d annotations", - length(fg_groups), ncol(matches))) + log_progress(sprintf("Running enrichment: %d groups x %d annotations", + length(fg_groups), ncol(matches))) } if (background == "background_peaks") { diff --git a/R/footprinting.R b/R/footprinting.R index fd1f48d..f312d57 100644 --- a/R/footprinting.R +++ b/R/footprinting.R @@ -84,7 +84,7 @@ #' @param threads (integer) Parallelism over replicates. Default 1L. #' @param seed (integer) Random seed. Default 1L. #' @param overwrite (logical) Replace existing entry. Default FALSE. -#' @param verbose (logical) Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Unused. #' #' @return Modified MarchRProject with `proj$kmer_bias[[group_by]]` populated. @@ -114,9 +114,10 @@ add_kmer_bias.MarchRProject <- function( threads = 1L, seed = 1L, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") reps <- proj$group_coverages[[group_by]] if (is.null(reps) || length(reps) == 0L) { @@ -126,7 +127,7 @@ add_kmer_bias.MarchRProject <- function( )) } if (!is.null(proj$kmer_bias[[group_by]]) && !overwrite) { - if (verbose) message(sprintf( + if (verbose) log_progress(sprintf( "kmer_bias[['%s']] already populated. Use overwrite = TRUE to recompute.", group_by )) return(proj) @@ -145,7 +146,7 @@ add_kmer_bias.MarchRProject <- function( } } - if (verbose) message("Computing expected k-mer frequencies (genome-wide)...") + if (verbose) log_progress("Computing expected k-mer frequencies (genome-wide)...") chrs <- if (methods::is(bsgenome, "BSgenome")) { GenomicRanges::seqnames(bsgenome) } else { @@ -159,7 +160,7 @@ add_kmer_bias.MarchRProject <- function( # Lock name order to .kmers(k) so downstream sweep() against observed aligns by index. expected <- expected[.kmers(k)] - if (verbose) message(sprintf( + if (verbose) log_progress(sprintf( "Computing observed k-mers for %d replicates...", length(rep_cells) )) set.seed(seed) @@ -196,7 +197,7 @@ add_kmer_bias.MarchRProject <- function( date = Sys.Date() ) - if (verbose) message(sprintf( + if (verbose) log_progress(sprintf( "Stored kmer_bias[['%s']]: %d k-mers x %d replicates", group_by, nrow(observed), ncol(observed) )) @@ -286,7 +287,7 @@ get_kmer_bias.MarchRProject <- function(proj, group_by = character(0), ...) { #' proj$genome$sequence. Ignored when norm_method = "none". #' @param min_chrom_distance (integer) bp from chrom edge required beyond flank. #' Default 50L. -#' @param verbose (logical) Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Unused. #' #' @return SummarizedExperiment with one assay per motif, two stacked channels @@ -320,9 +321,10 @@ get_footprints.MarchRProject <- function( dataset_name = NULL, bsgenome = NULL, min_chrom_distance = 50L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") norm_method <- match.arg(norm_method) @@ -416,7 +418,7 @@ get_footprints.MarchRProject <- function( assays <- list() for (motif_name in names(positions)) { gr <- positions[[motif_name]] - if (verbose) message(sprintf( + if (verbose) log_progress(sprintf( "Footprint for motif '%s' (%d positions)...", motif_name, length(gr) )) # Pass a tibble instead of GRanges so BPCells does not require GenomeInfoDb diff --git a/R/fragment_ops.R b/R/fragment_ops.R index d410587..425207d 100644 --- a/R/fragment_ops.R +++ b/R/fragment_ops.R @@ -83,7 +83,7 @@ resolve_blacklist <- function(source, blacklist, keep_chr = NULL) { if (!is.null(bl)) { merged_frags <- select_regions(merged_frags, bl, invert_selection = TRUE) } else if (isTRUE(blacklist) && verbose) { - message("No blacklist found in project genome. Skipping blacklist filtering.") + log_progress("No blacklist found in project genome. Skipping blacklist filtering.") } if (length(exclude_chr) > 0) { diff --git a/R/group_coverages.R b/R/group_coverages.R index d36b712..4d83a98 100644 --- a/R/group_coverages.R +++ b/R/group_coverages.R @@ -37,7 +37,7 @@ #' labels. NULL on the project method uses dataset membership; NULL on the #' default method disables label-aware assignment. Default NULL. #' @param seed (integer) Random seed for reproducibility. Default is 1. -#' @param verbose (logical) Print progress. Default is \code{TRUE}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return #' \itemize{ @@ -103,9 +103,10 @@ add_group_coverages.default <- function( max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assertthat::assert_that( !is.null(names(proj)), msg = "Input must be a named vector (names = cell names, values = group labels)." @@ -153,9 +154,10 @@ add_group_coverages.MarchRProject <- function( max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") assert_is_character(dataset_names) dataset_names <- select_dataset_names(proj, dataset_names) @@ -216,7 +218,7 @@ add_group_coverages.MarchRProject <- function( )) } if (length(extra_cells) > 0 && verbose) { - message(sprintf( + log_progress(sprintf( "Ignoring %d cells in group_by that are not in the project.", length(extra_cells) )) @@ -228,7 +230,7 @@ add_group_coverages.MarchRProject <- function( na_idx <- is.na(groups) if (any(na_idx)) { if (verbose) { - message(sprintf("Removing %d cells with NA group assignments.", sum(na_idx))) + log_progress(sprintf("Removing %d cells with NA group assignments.", sum(na_idx))) } groups <- groups[!na_idx] } @@ -359,7 +361,7 @@ get_group_coverages <- function(proj, group_by = character(0)) { set.seed(seed) if (verbose) { - message(sprintf( + log_progress(sprintf( "Creating pseudobulk replicates for %d groups", length(unique_groups) )) @@ -384,7 +386,7 @@ get_group_coverages <- function(proj, group_by = character(0)) { ) if (verbose) { - message(sprintf( + log_progress(sprintf( " Group '%s': %d cells -> %d replicates (%s cells each)", grp, n_cells, length(reps), paste(vapply(reps, length, integer(1)), collapse = ", ") diff --git a/R/imputation.R b/R/imputation.R index da9cb50..72f8b61 100644 --- a/R/imputation.R +++ b/R/imputation.R @@ -49,7 +49,7 @@ #' @param n_rep (integer) Number of imputation replicates to average. #' Default is 2. #' @param seed (integer) Random seed. Default is 1. -#' @param verbose (logical) Whether to print progress. Default is TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return The MarchRProject with imputation weights stored in #' `proj$impute_weights`. @@ -75,8 +75,9 @@ add_impute_weights <- function( sample_cells = 5000L, n_rep = 2L, seed = 1L, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) { + .start_log_clock() assert_that(inherits(proj, "MarchRProject")) td <- as.integer(td) ka <- as.integer(ka) @@ -86,6 +87,7 @@ add_impute_weights <- function( assert_that(is.numeric(epsilon), epsilon >= 0) assert_that(is.integer(n_rep), n_rep >= 1L) assert_that(is.function(knn_method)) + knn_method <- partial_apply(knn_method, verbose = verbose, .missing_args_error = FALSE) # Resolve which dimensionality reduction to use for building the KNN graph embedding_name <- select_embedding_name(proj, embedding_name) @@ -121,14 +123,14 @@ add_impute_weights <- function( dir.create(weight_dir, recursive = TRUE) if (verbose) { - message(sprintf( + log_progress(sprintf( "Computing MAGIC imputation weights (td=%d, ka=%d, blocks~%d cells, %d reps)", td, ka, bin_size, n_rep )) } weight_list <- lapply(seq_len(n_rep), function(rep_i) { - if (verbose) message(sprintf(" Replicate %d of %d", rep_i, n_rep)) + if (verbose) log_progress(sprintf(" Replicate %d of %d", rep_i, n_rep)) idx <- sample(seq_len(n_cells), n_cells) blocks <- split(cell_names[idx], ceiling(seq_along(idx) / bin_size)) @@ -173,7 +175,7 @@ add_impute_weights <- function( ) ) - if (verbose) message("Completed MAGIC imputation weights.") + if (verbose) log_progress("Completed MAGIC imputation weights.") return(proj) } @@ -206,7 +208,7 @@ get_impute_weights <- function(proj) { #' #' @param mat (matrix, dgCMatrix, or IterableMatrix) Feature-by-cell matrix to impute. #' @param impute_weights Impute weights object from `get_impute_weights()`. -#' @param verbose (logical) Whether to print progress. Default is FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return A dense matrix (features x cells) with imputed values. #' @@ -227,8 +229,9 @@ get_impute_weights <- function(proj) { impute_matrix <- function( mat, impute_weights, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_that(!is.null(impute_weights)) assert_that("weights" %in% names(impute_weights)) @@ -243,7 +246,7 @@ impute_matrix <- function( ) impute_mat <- lapply(seq_along(weight_list), function(rep_i) { - if (verbose) message(sprintf("Imputing replicate %d of %d", rep_i, length(weight_list))) + if (verbose) log_progress(sprintf("Imputing replicate %d of %d", rep_i, length(weight_list))) blocks <- weight_list[[rep_i]] assert_that(is.list(blocks), length(blocks) > 0L, diff --git a/R/linkage.R b/R/linkage.R index 84661fc..88cf3e8 100644 --- a/R/linkage.R +++ b/R/linkage.R @@ -15,7 +15,7 @@ #' \code{floor(overlap_cutoff * k)} cells with any accepted group. Default 0.8. #' @param knn_method (function) KNN engine (BPCells partial-app). Default \code{knn_hnsw()}. #' @param seed (integer) Random seed for anchor sampling. Default 1L. -#' @param verbose (logical) Print progress. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @details Mirrors ArchR's random-KNN aggregation (\code{.computeKNN} + #' \code{determineOverlapCpp}); uses BPCells \code{knn_hnsw} (approximate NN) @@ -25,7 +25,8 @@ #' @export make_knn_pseudobulks <- function(embedding, knn_iteration = 500L, k = 100L, overlap_cutoff = 0.8, knn_method = knn_hnsw(), - seed = 1L, verbose = TRUE) { + seed = 1L, verbose = getOption("MarchR.verbose", TRUE)) { + .start_log_clock() assert_for(embedding, "matrix") if (is.null(rownames(embedding))) { rlang::abort("`embedding` must have cell names as rownames.") @@ -45,8 +46,8 @@ make_knn_pseudobulks <- function(embedding, knn_iteration = 500L, k = 100L, keep <- .overlap_dedup(idx, floor(overlap_cutoff * k)) if (verbose) { - message(sprintf("Kept %d of %d KNN groups after overlap pruning.", - length(keep), nrow(idx))) + log_progress(sprintf("Kept %d of %d KNN groups after overlap pruning.", + length(keep), nrow(idx))) } cell_names <- rownames(embedding) lapply(keep, function(i) cell_names[idx[i, ]]) diff --git a/R/markers.R b/R/markers.R index bfa780f..d24af9c 100644 --- a/R/markers.R +++ b/R/markers.R @@ -79,7 +79,7 @@ as.data.frame.MarkerResult <- function(x, ...) { #' @param scale_to (numeric) Column-sum normalization target. Default 1e4. #' @param knn_method (function) BPCells KNN method. Default \code{knn_hnsw()}. #' @param seed (integer) Random seed. Default 1L. -#' @param verbose (logical) Print progress. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param overwrite (logical) If TRUE, overwrite existing marker result for #' this assay. Default FALSE. (MarchRProject method only.) #' @param dataset_names (character) Datasets to include. Default all. @@ -120,7 +120,7 @@ add_marker_features <- function( scale_to = 1e4, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { UseMethod("add_marker_features") @@ -144,9 +144,10 @@ add_marker_features.default <- function( scale_to = 1e4, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() mat <- proj groups <- group_by @@ -166,7 +167,7 @@ add_marker_features.default <- function( assertthat::assert_that(is.function(knn_method), msg = "knn_method must be a function (e.g., knn_hnsw()).") - if (verbose) message("Matching bias cell groups...") + if (verbose) log_progress("Matching bias cell groups...") cells_with_groups <- intersect(names(groups), rownames(cell_metadata)) cell_metadata <- cell_metadata[cells_with_groups, , drop = FALSE] @@ -179,7 +180,7 @@ add_marker_features.default <- function( k = as.integer(k), max_cells = as.integer(max_cells), buffer_ratio = buffer_ratio, - knn_method = knn_method, + knn_method = partial_apply(knn_method, verbose = verbose, .missing_args_error = FALSE), seed = as.integer(seed) ) @@ -200,19 +201,20 @@ add_marker_features.default <- function( } use_groups <- names(match_obj) - if (verbose) message(sprintf("Testing %d groups with bias-matched backgrounds...", length(use_groups))) + if (verbose) log_progress(sprintf("Testing %d groups with bias-matched backgrounds...", + length(use_groups))) results <- lapply(use_groups, function(grp) { fg_cells <- match_obj[[grp]]$fg_cells bg_cells <- match_obj[[grp]]$bg_cells if (length(fg_cells) == 0 || length(bg_cells) == 0) { - if (verbose) message(sprintf(" Skipping group '%s': insufficient matched cells", grp)) + if (verbose) log_progress(sprintf(" Skipping group '%s': insufficient matched cells", grp)) return(NULL) } if (verbose) { - message(sprintf(" Group '%s': %d fg, %d bg cells", grp, length(fg_cells), length(bg_cells))) + log_progress(sprintf(" Group '%s': %d fg, %d bg cells", grp, length(fg_cells), length(bg_cells))) } all_cells <- c(fg_cells, bg_cells) @@ -260,10 +262,11 @@ add_marker_features.MarchRProject <- function( scale_to = 1e4, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ... ) { + .start_log_clock() assay_name <- select_assay_name(proj, assay_name) dataset_names <- select_dataset_names(proj, dataset_names = dataset_names) diff --git a/R/module_scores.R b/R/module_scores.R index 710acf4..aafc6a6 100644 --- a/R/module_scores.R +++ b/R/module_scores.R @@ -69,7 +69,7 @@ add_module_score <- function(proj, ...) { #' columns with the same name. Default is \code{FALSE}. #' @param threads (integer) Threads for the `matrix_stats()` pass. Default `1L`; not read from #' `set_threads()`. -#' @param verbose (logical) Print progress messages. Default is \code{FALSE}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return The modified MarchRDataset with module score columns added to cell #' metadata. @@ -84,9 +84,10 @@ add_module_score.MarchRDataset <- function( seed = 1L, overwrite = FALSE, threads = 1L, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() assert_for(proj, "MarchRDataset") assertthat::assert_that( is.list(features), @@ -242,9 +243,10 @@ add_module_score.MarchRProject <- function( seed = 1L, overwrite = FALSE, threads = 1L, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") assert_is_character(dataset_names) dataset_names <- select_dataset_names(proj, dataset_names) diff --git a/R/multi_modal.R b/R/multi_modal.R index c0e9325..036dd03 100644 --- a/R/multi_modal.R +++ b/R/multi_modal.R @@ -113,7 +113,7 @@ add_combined_dims.MarchRProject <- function( #' @param feature_type (character) 10x feature type to keep. Default `"Gene Expression"`. #' @param genes_to_exclude (character; optional) Features to drop after import, matched by ID or symbol. #' @param overwrite (logical) Overwrite an existing assay named `matrix_name`. Default FALSE. -#' @param verbose (logical) Print progress. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Passed to methods. #' #' @return The MarchRProject with the RNA assay added to `dataset_name`, both @@ -149,9 +149,10 @@ import_feature_matrix_10x.MarchRProject <- function( feature_type = "Gene Expression", genes_to_exclude = NULL, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(x, "MarchRProject") assert_is_character(input) assert_len(input, 1) diff --git a/R/peak2gene.R b/R/peak2gene.R index 119c301..889755b 100644 --- a/R/peak2gene.R +++ b/R/peak2gene.R @@ -91,7 +91,7 @@ add_peak2gene_links <- function(proj, ...) { #' @param n_perm (integer) Permutations for `add_permuted_pval`. Default 100L. #' @param knn_method (function) KNN engine (BPCells partial-application). Default `knn_hnsw()`. #' @param seed (integer) Random seed for metacell sampling and p-value resampling. Default 1L. -#' @param verbose (logical) Print progress messages. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param overwrite (logical) Replace an existing `peak2gene_links` result. Default FALSE. #' #' @return `proj` with `proj$peak2gene_links` populated as a data.frame with columns @@ -148,12 +148,13 @@ add_peak2gene_links.MarchRProject <- function( n_perm = 100L, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ...) { + .start_log_clock() assert_for(proj, "MarchRProject") if (!is.null(proj$peak2gene_links) && !overwrite) { - if (verbose) message("peak2gene_links exists; set overwrite = TRUE to recompute.") + if (verbose) log_progress("peak2gene_links exists; set overwrite = TRUE to recompute.") return(proj) } if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { @@ -197,7 +198,7 @@ add_peak2gene_links.MarchRProject <- function( ] cell_sets <- c(cell_sets, list(score_cells)) } else if (verbose) { - message("No 'predictedScore' column found; skipping prediction_cutoff filtering.") + log_progress("No 'predictedScore' column found; skipping prediction_cutoff filtering.") } keep_cells <- Reduce(intersect, cell_sets) diff --git a/R/peaks.R b/R/peaks.R index acef2db..b102e50 100644 --- a/R/peaks.R +++ b/R/peaks.R @@ -53,7 +53,7 @@ #' or Python venv), pass the full path explicitly: #' \code{macs_executable = "/path/to/bin/macs3"}. #' @param threads (integer) Threads for parallel MACS execution. Default 1. -#' @param verbose (logical) Print progress. Default \code{TRUE}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Additional arguments. #' #' @return The modified MarchRProject with the peak set stored in @@ -132,9 +132,10 @@ add_reproducible_peak_set.MarchRProject <- function( dataset_names = character(0), macs_executable = NULL, threads = get_threads(), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() peak_method <- match.arg(peak_method) assert_for(proj, "MarchRProject") dataset_names <- select_dataset_names(proj, dataset_names) @@ -188,7 +189,7 @@ add_reproducible_peak_set.MarchRProject <- function( on.exit(unlink(peak_dir, recursive = TRUE), add = TRUE) # Call peaks per replicate - if (verbose) message("Calling peaks per replicate...") + if (verbose) log_progress("Calling peaks per replicate...") all_peaks <- .call_peaks_per_replicate( merged_frags = merged_frags, @@ -213,7 +214,7 @@ add_reproducible_peak_set.MarchRProject <- function( all_peaks$end <- all_peaks$summit_pos + extend_summits + 1L # Build reproducible peak set - if (verbose) message("Filtering for reproducible peaks...") + if (verbose) log_progress("Filtering for reproducible peaks...") reproducible <- .build_reproducible_peak_set( all_peaks = all_peaks, @@ -236,11 +237,11 @@ add_reproducible_peak_set.MarchRProject <- function( peak_set <- .annotate_peaks(proj, peak_set, promoter_region) if (verbose) { - message(sprintf("Final peak set: %d peaks", nrow(peak_set))) + log_progress(sprintf("Final peak set: %d peaks", nrow(peak_set))) if ("peakType" %in% names(peak_set)) { type_counts <- table(peak_set$peakType) for (tp in names(type_counts)) { - message(sprintf(" %s: %d", tp, type_counts[[tp]])) + log_progress(sprintf(" %s: %d", tp, type_counts[[tp]])) } } } @@ -306,7 +307,7 @@ get_peak_set <- function(proj) { #' @param blacklist (logical or data.frame) Blacklist filtering for fragments. #' @param exclude_chr (character) Chromosomes to exclude from fragments. #' @param overwrite (logical) Overwrite existing assay. Default \code{FALSE}. -#' @param verbose (logical) Print progress. Default \code{TRUE}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Additional arguments. #' #' @return The modified MarchRProject with a \code{PeakMatrix} assay added to @@ -349,9 +350,10 @@ add_peak_matrix.MarchRProject <- function( blacklist = TRUE, exclude_chr = c("chrM", "chrY"), overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() mode <- match.arg(mode) assert_for(proj, "MarchRProject") dataset_names <- select_dataset_names(proj, dataset_names) @@ -378,7 +380,7 @@ add_peak_matrix.MarchRProject <- function( # Resolve blacklist once bl <- resolve_blacklist(proj, blacklist) - if (verbose) message("Creating peak matrix...") + if (verbose) log_progress("Creating peak matrix...") for (dataset_name in dataset_names) { if (!frags_name %in% get_fragment_names(proj, dataset_name)) next @@ -419,7 +421,7 @@ add_peak_matrix.MarchRProject <- function( } if (verbose) { - message(sprintf( + log_progress(sprintf( " %s: %d peaks x %d cells", dataset_name, nrow(mat), ncol(mat) )) @@ -440,7 +442,7 @@ add_peak_matrix.MarchRProject <- function( rownames(peak_metadata) <- peak_names proj$feature_metadata[[output_assay_name]] <- peak_metadata - if (verbose) message("Done.") + if (verbose) log_progress("Done.") return(proj) } @@ -473,7 +475,7 @@ add_peak_matrix.MarchRProject <- function( rep_label <- paste0(group_name, "_", rep_name) if (verbose) { - message(sprintf(" %s: %d cells", rep_label, length(cells))) + log_progress(sprintf(" %s: %d cells", rep_label, length(cells))) } # Subset fragments to this replicate's cells (lazy) @@ -492,8 +494,8 @@ add_peak_matrix.MarchRProject <- function( ) }, error = function(e) { if (verbose) { - message(sprintf(" Warning: peak calling failed for %s: %s", - rep_label, conditionMessage(e))) + log_progress(sprintf(" Warning: peak calling failed for %s: %s", + rep_label, conditionMessage(e))) } tibble::tibble() }) @@ -550,7 +552,7 @@ add_peak_matrix.MarchRProject <- function( if (n_cells < min_cells) { if (verbose) { - message(sprintf( + log_progress(sprintf( " Skipping group '%s': %d cells < min_cells (%d)", group_name, n_cells, min_cells )) @@ -620,7 +622,7 @@ add_peak_matrix.MarchRProject <- function( group_peaks_list <- c(group_peaks_list, list(candidates)) if (verbose) { - message(sprintf( + log_progress(sprintf( " Group '%s': %d reproducible peaks (from %d replicates)", group_name, nrow(candidates), n_replicates )) @@ -1002,7 +1004,7 @@ add_peak_matrix.MarchRProject <- function( #' (set via `set_genome_sequence()`). #' @param overwrite (logical) Whether to recompute when `gc` already exists. #' Default `FALSE`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Currently unused. #' #' @return The modified MarchRProject with `peak_set$gc` and `peak_set$idx` @@ -1032,16 +1034,17 @@ add_peak_gc.MarchRProject <- function( proj, bsgenome = NULL, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { rlang::abort("Project has no peak set. Run add_reproducible_peak_set() first.") } if (!is.null(proj$peak_set$gc) && !overwrite) { - if (verbose) message("peak_set$gc already populated. Use overwrite = TRUE to replace.") + if (verbose) log_progress("peak_set$gc already populated. Use overwrite = TRUE to replace.") if (is.null(proj$peak_set$idx)) { proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) } @@ -1072,7 +1075,7 @@ add_peak_gc.MarchRProject <- function( )) } - if (verbose) message("Computing peak GC content...") + if (verbose) log_progress("Computing peak GC content...") chr_groups <- split(seq_len(nrow(proj$peak_set)), proj$peak_set$chr) gc <- numeric(nrow(proj$peak_set)) for (chr in names(chr_groups)) { @@ -1095,8 +1098,8 @@ add_peak_gc.MarchRProject <- function( proj$peak_set$gc <- gc proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) if (verbose) { - message(sprintf(" GC mean: %.3f, range: [%.3f, %.3f]", - mean(gc), min(gc), max(gc))) + log_progress(sprintf(" GC mean: %.3f, range: [%.3f, %.3f]", + mean(gc), min(gc), max(gc))) } proj } @@ -1118,7 +1121,7 @@ add_peak_gc.MarchRProject <- function( #' @param name (character) Name of the annotation. Default `"Region"`. #' @param overwrite (logical) Overwrite existing annotation with the same #' name. Default `FALSE`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Currently unused. #' #' @return The modified MarchRProject with the annotation stored at @@ -1151,9 +1154,10 @@ add_peak_annotations.MarchRProject <- function( regions, name = "Region", overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") assert_for(name, "character") assertthat::assert_that(length(name) == 1, msg = "`name` must be a single character string.") @@ -1171,7 +1175,7 @@ add_peak_annotations.MarchRProject <- function( peak_gr <- .peak_set_to_granges(proj$peak_set) if (verbose) { - message(sprintf( + log_progress(sprintf( "Computing overlaps: %d peaks x %d annotation regions", length(peak_gr), length(region_grl) )) @@ -1194,7 +1198,7 @@ add_peak_annotations.MarchRProject <- function( keep <- Matrix::colSums(m) > 0 if (verbose && sum(keep) < length(region_grl)) { - message(sprintf( + log_progress(sprintf( " Dropping %d annotation%s with zero peak overlaps", length(region_grl) - sum(keep), ifelse(length(region_grl) - sum(keep) == 1, "", "s") @@ -1211,7 +1215,7 @@ add_peak_annotations.MarchRProject <- function( ) if (verbose) { - message(sprintf( + log_progress(sprintf( " Stored '%s' (%d annotations, %d non-zero entries)", name, ncol(m), Matrix::nnzero(m) )) @@ -1253,7 +1257,7 @@ add_peak_annotations.MarchRProject <- function( #' (set via `set_genome_sequence()`). #' @param overwrite (logical) Overwrite existing annotation with the same #' name. Default `FALSE`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Currently unused. #' #' @return The modified `MarchRProject` with the motif annotation stored at @@ -1304,9 +1308,10 @@ add_motif_annotations.MarchRProject <- function( pwm_version = 2L, bsgenome = NULL, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() motif_set <- match.arg(motif_set) assert_for(proj, "MarchRProject") assert_for(anno_name, "character") @@ -1341,7 +1346,7 @@ add_motif_annotations.MarchRProject <- function( # - motif_pwms non-NULL: pass user-supplied PWMatrixList through. # - motif_set == "JASPAR2020": load via TFBSTools::getMatrixSet. # - motif_set in {"cisbp","encode","homer"}: load chromVARmotifs data file. - if (verbose) message("Resolving PWMs...") + if (verbose) log_progress("Resolving PWMs...") if (!is.null(motif_pwms)) { raw_pwms <- motif_pwms } else if (identical(motif_set, "JASPAR2020")) { @@ -1405,11 +1410,11 @@ add_motif_annotations.MarchRProject <- function( raw_pwms <- e[[data_name]] } pwms <- .summarize_chromvar_motifs(raw_pwms) - if (verbose) message(sprintf(" %d motifs to scan", length(pwms))) + if (verbose) log_progress(sprintf(" %d motifs to scan", length(pwms))) # Run motifmatchr to get positions. peak_gr <- .peak_set_to_granges(proj$peak_set) - if (verbose) message("Scanning motifs against peaks...") + if (verbose) log_progress("Scanning motifs against peaks...") motif_positions <- motifmatchr::matchMotifs( pwms = pwms, subject = peak_gr, @@ -1426,7 +1431,7 @@ add_motif_annotations.MarchRProject <- function( rlang::abort("No motif hits found in any peak. Lower `cutoff` or check inputs.") } if (verbose && sum(hit_counts == 0) > 0) { - message(sprintf( + log_progress(sprintf( " Dropping %d motifs with zero peak hits", sum(hit_counts == 0) )) } @@ -1478,7 +1483,7 @@ add_motif_annotations.MarchRProject <- function( ) if (verbose) { - message(sprintf( + log_progress(sprintf( " Stored '%s' (%d motifs, %d non-zero entries)", anno_name, ncol(m), Matrix::nnzero(m) )) diff --git a/R/plotting.R b/R/plotting.R index 71dc927..d4cb5a1 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -393,7 +393,7 @@ palette_continuous <- function(set = "solarExtra", n = 256L) { #' @param legend_position (character) Legend position. Default \code{"bottom"}. #' @param legend_text_size (numeric) Legend text size. Default 5. #' @param legend_title (character) Legend title. NULL for auto. -#' @param verbose (logical) Print progress. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Additional arguments (unused). #' @return A ggplot object, or named list of ggplot objects for multiple features. #' @@ -445,9 +445,10 @@ plot_embedding.default <- function( legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_that(is.matrix(embedding), ncol(embedding) == 2) # Auto-derive axis labels from embedding column names @@ -691,9 +692,10 @@ plot_embedding.MarchRProject <- function( legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_that(inherits(x, "MarchRProject")) cell_meta <- get_cell_metadata(x) @@ -764,7 +766,7 @@ plot_embedding.MarchRProject <- function( #' @param log_transform (logical) Apply \code{log2(x + 1)}. Default TRUE. #' @param limits Absolute value clipping: \code{c(min, max)} or \code{"range"}. #' @param patchwork (logical) Returns multi-gene output as patchwork object if TRUE. Default FALSE. -#' @param verbose (logical) Print progress. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param ... Passed to \code{\link{plot_embedding}} (e.g. \code{plot_as}, #' \code{colors_continuous}, \code{size}, \code{rastr}, \code{quant_cut}). #' @return A named list of ggplot objects, keyed by gene name. @@ -794,9 +796,10 @@ plot_gene_scores.MarchRProject <- function( log_transform = TRUE, limits = NULL, patchwork = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_that(inherits(x, "MarchRProject")) assert_that(is.character(genes), length(genes) >= 1) assert_that(is.logical(patchwork), length(patchwork) == 1, !is.na(patchwork)) @@ -817,8 +820,10 @@ plot_gene_scores.MarchRProject <- function( if (length(available_genes) == 0) rlang::abort("None of the requested genes were found.") if (impute && !is.null(x$impute_weights)) { - if (verbose) message("Imputing gene scores with MAGIC weights") - mat <- impute_matrix(gene_score_mat[available_genes, , drop = FALSE], x$impute_weights) + if (verbose) log_progress("Imputing gene scores with MAGIC weights") + mat <- impute_matrix( + gene_score_mat[available_genes, , drop = FALSE], x$impute_weights, verbose = FALSE + ) } else { if (impute && is.null(x$impute_weights)) { rlang::warn("Impute weights not found, plotting raw scores. Run add_impute_weights() first.") @@ -1279,7 +1284,7 @@ plot_enrichment_heatmap <- function(enrichment, n = 10L, cutoff = 20, ...) { #' @param dataset_name (character) For MarchRProject only. #' @param plot (character) One or more of \code{"enrichment"}, \code{"score"}, #' \code{"density"}. Default plots all. -#' @param verbose (logical) Print progress. Default FALSE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Passed to \code{\link{plot_embedding}} for enrichment/score panels. #' @return ggplot object or patchwork composition. #' @export @@ -1292,9 +1297,10 @@ plot_doublet_scores <- function(x, ...) { plot_doublet_scores.MarchRDataset <- function( x, plot = c("enrichment", "score", "density"), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() plot <- match.arg(plot, several.ok = TRUE) if (is.null(x$doublet_data) || is.null(x$doublet_data$scores)) { @@ -1397,9 +1403,10 @@ plot_doublet_scores.MarchRProject <- function( x, dataset_name = character(0), plot = c("enrichment", "score", "density"), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) { + .start_log_clock() dataset_name <- select_dataset_name(x, dataset_name) plot_doublet_scores( x$datasets[[dataset_name]], diff --git a/R/pseudobulk.R b/R/pseudobulk.R index 57f95ae..e161b37 100644 --- a/R/pseudobulk.R +++ b/R/pseudobulk.R @@ -130,7 +130,7 @@ pseudobulk_fragments <- function(proj, ...) { #' gating. Default `NULL`. #' @param on_low_depth (character) Response when a group falls below `min_fragments`. #' One of `"warn"`, `"abort"`, `"drop"`. Default `"warn"`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @export pseudobulk_fragments.MarchRProject <- function( proj, @@ -141,9 +141,10 @@ pseudobulk_fragments.MarchRProject <- function( exclude_chr = c("chrM"), min_fragments = NULL, on_low_depth = c("warn", "abort", "drop"), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") on_low_depth <- match.arg(on_low_depth) dataset_names <- select_dataset_names(proj, dataset_names) @@ -193,7 +194,7 @@ pseudobulk_fragments.MarchRProject <- function( abort = rlang::abort(msg), warn = rlang::warn(msg), drop = { - if (verbose) message(msg) + if (verbose) log_progress(msg) fragments <- fragments[setdiff(names(fragments), failing)] } ) @@ -317,7 +318,7 @@ print.MarchRPseudobulk <- function(x, ...) { #' @param dir (character) Output directory. Files land in `/fragments/`. #' @param append_5th_column (logical) Write a 5th column. BPCells fills it with a #' literal `0`, not a duplicate count. Default `FALSE`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return `pb` with a `fragments_path` column added to its manifest. #' @@ -332,14 +333,15 @@ write_pseudobulk_fragments <- function( pb, dir, append_5th_column = FALSE, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) { + .start_log_clock() assert_for(pb, "MarchRPseudobulk") out_dir <- .pseudobulk_subdir(dir, "fragments") paths <- vapply(names(pb$fragments), function(grp) { path <- file.path(out_dir, paste0(.sanitize_group_name(grp), ".tsv.gz")) - if (verbose) message(sprintf(" Writing fragments for group '%s'", grp)) + if (verbose) log_progress(sprintf(" Writing fragments for group '%s'", grp)) write_fragments_10x( pb$fragments[[grp]], path, @@ -373,7 +375,7 @@ write_pseudobulk_fragments <- function( #' @param shift_end (integer) Basepairs to shift fragment ends. Default `0L`. #' @param chrom_sizes (data.frame or NULL) Chromosome sizes for clipping tiles. #' Default `NULL`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return `pb` with a `coverage_path` column added to its manifest. #' @@ -396,8 +398,9 @@ write_pseudobulk_coverage <- function( shift_start = 0L, shift_end = 0L, chrom_sizes = NULL, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) { + .start_log_clock() assert_for(pb, "MarchRPseudobulk") insertion_mode <- match.arg(insertion_mode) normalization <- match.arg(normalization) @@ -415,7 +418,7 @@ write_pseudobulk_coverage <- function( ) if (verbose) { - message(sprintf( + log_progress(sprintf( "Writing insertion coverage for %d groups in one pass", nlevels(cell_groups) )) } @@ -494,7 +497,7 @@ write_pseudobulk_chrom_sizes <- function(pb, dir, chrom_sizes) { #' @param executable (character) Path or name of the converter. Default #' `"bedGraphToBigWig"`. #' @param keep_bedgraph (logical) Retain the source bedGraphs. Default `TRUE`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return `pb` with a `bigwig_path` column added to its manifest, `NA` for any group #' whose conversion was skipped or failed. @@ -512,8 +515,9 @@ write_pseudobulk_bigwig <- function( chrom_sizes, executable = "bedGraphToBigWig", keep_bedgraph = TRUE, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) { + .start_log_clock() assert_for(pb, "MarchRPseudobulk") if (!"coverage_path" %in% names(pb$manifest)) { rlang::abort( @@ -543,7 +547,7 @@ write_pseudobulk_bigwig <- function( if (is.na(bedgraph)) return(NA_character_) bigwig <- sub("\\.bedGraph$", ".bw", bedgraph) if (verbose) { - message(sprintf(" Converting '%s' to bigWig", pb$manifest$group[[i]])) + log_progress(sprintf(" Converting '%s' to bigWig", pb$manifest$group[[i]])) } status <- system2(executable, c(bedgraph, sizes_path, bigwig)) if (!identical(as.integer(status), 0L)) { @@ -573,7 +577,7 @@ write_pseudobulk_bigwig <- function( #' @param dir (character) Output directory. Files land in `/peaks/`. #' @param scope (character) Which peak sets to write. One of `"both"`, `"group"`, #' `"union"`. Default `"both"`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return `pb` with a `peaks_path` column added to its manifest. #' @@ -587,8 +591,9 @@ write_pseudobulk_peaks <- function( pb, dir, scope = c("both", "group", "union"), - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) { + .start_log_clock() assert_for(pb, "MarchRPseudobulk") scope <- match.arg(scope) out_dir <- .pseudobulk_subdir(dir, "peaks") @@ -617,7 +622,7 @@ write_pseudobulk_peaks <- function( peaks <- pb$group_peak_sets[[grp]] if (is.null(peaks) || nrow(peaks) == 0) return(NA_character_) path <- file.path(out_dir, paste0(.sanitize_group_name(grp), ".narrowPeak")) - if (verbose) message(sprintf(" Writing peaks for group '%s'", grp)) + if (verbose) log_progress(sprintf(" Writing peaks for group '%s'", grp)) .write_narrowpeak(peaks, path, grp) path }, character(1)) @@ -954,7 +959,7 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, verbose = TRUE na_idx <- is.na(groups) if (any(na_idx)) { if (verbose) { - message(sprintf("Removing %d cells with NA group assignments.", sum(na_idx))) + log_progress(sprintf("Removing %d cells with NA group assignments.", sum(na_idx))) } groups <- groups[!na_idx] } diff --git a/R/rna_integration.R b/R/rna_integration.R index fcebacf..56a903a 100644 --- a/R/rna_integration.R +++ b/R/rna_integration.R @@ -53,7 +53,7 @@ #' @param threads (integer) Threads for the normalization and `matrix_stats()` passes. Default `1L`; #' not read from `set_threads()`. #' @param seed (integer) Random seed. Default 1. -#' @param verbose (logical) Print progress. Default TRUE. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' @param overwrite (logical) Overwrite existing columns / assay. Default FALSE. #' @param ... Passed to methods. #' @@ -115,10 +115,11 @@ add_gene_integration_matrix.MarchRProject <- function( genes_use = NULL, threads = 1L, seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ... ) { + .start_log_clock() assert_for(proj, "MarchRProject") assert_for(reference_dataset_name, "character") assert_for(group_rna, "character") @@ -146,8 +147,8 @@ add_gene_integration_matrix.MarchRProject <- function( } if (identical(method, "marchr") && verbose && (!is.null(embedding_atac) || !identical(as.integer(sample_cells_atac), 10000L))) { - message("method = 'marchr' integrates all cells at once; ", - "sample_cells_atac and embedding_atac are ignored.") + log_progress(paste0("method = 'marchr' integrates all cells at once; ", + "sample_cells_atac and embedding_atac are ignored.")) } if (length(atac_dataset_names) == 0L) { @@ -173,8 +174,8 @@ add_gene_integration_matrix.MarchRProject <- function( feature_set <- if (is.null(genes_use)) shared_genes else genes_use if (verbose) { - message(sprintf("Integrating %d ATAC dataset(s) against '%s' (%d shared genes)...", - length(atac_dataset_names), reference_dataset_name, length(shared_genes))) + log_progress(sprintf("Integrating %d ATAC dataset(s) against '%s' (%d shared genes)...", + length(atac_dataset_names), reference_dataset_name, length(shared_genes))) } # A dense cast would allocate ~5 GB on a large reference; keep counts sparse. @@ -270,7 +271,7 @@ add_gene_integration_matrix.MarchRProject <- function( spec <- block_specs[[i]] block_cells <- spec$atac if (verbose) { - message(sprintf(" Block %d of %d (%d ATAC cells)", i, n_blocks, length(block_cells))) + log_progress(sprintf(" Block %d of %d (%d ATAC cells)", i, n_blocks, length(block_cells))) } ref <- Seurat::FindVariableFeatures(seurat_rna[, spec$rna], nfeatures = n_genes, @@ -348,7 +349,7 @@ add_gene_integration_matrix.MarchRProject <- function( overwrite = overwrite) } } - if (verbose) message("Done.") + if (verbose) log_progress("Done.") proj } @@ -873,8 +874,8 @@ add_gene_integration_matrix.MarchRProject <- function( rna_cells <- .sample_rna_cells(groups[[gname]]$RNA, sample_cells_rna, embedding_rna, seed) if (verbose) { - message(sprintf(" Group '%s': %d ATAC cells vs %d RNA cells", - gname, length(atac_cells), length(rna_cells))) + log_progress(sprintf(" Group '%s': %d ATAC cells vs %d RNA cells", + gname, length(atac_cells), length(rna_cells))) } ref_block <- rna_mat[feature_set, rna_cells] diff --git a/R/track_plotting.R b/R/track_plotting.R index f394905..9f40300 100644 --- a/R/track_plotting.R +++ b/R/track_plotting.R @@ -157,7 +157,7 @@ gene_region <- function(transcripts, gene_symbol, #' @param colors (character or NULL) Color vector for groups. \code{NULL} #' uses BPCells' default palette. #' @param title (character or NULL) Plot title. -#' @param verbose (logical) Print progress messages. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return A \code{patchwork} ggplot object with stacked tracks. #' @@ -227,8 +227,9 @@ plot_browser_track <- function( combine = c("patchwork", "bpcells", "none"), colors = NULL, title = NULL, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) { + .start_log_clock() assert_for(proj, "MarchRProject") assert_is_character(group_by) assert_len(group_by, 1) diff --git a/R/trajectory.R b/R/trajectory.R index c1503c8..7173b0d 100644 --- a/R/trajectory.R +++ b/R/trajectory.R @@ -144,11 +144,16 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", use_all = FALSE, dof = 250L, spar = 1, knn_method = knn_hnsw(k = 3L), force = FALSE, seed = 1L) { + .start_log_clock() assert_for(proj, "MarchRProject") assert_for(trajectory, "character") assert_for(name, "character") assert_for(group_by, "character") assertthat::assert_that(is.function(knn_method)) + verbose_opt <- getOption("MarchR.verbose") + if (!is.null(verbose_opt)) { + knn_method <- partial_apply(knn_method, verbose = verbose_opt, .missing_args_error = FALSE) + } assertthat::assert_that( is.numeric(pre_filter_quantile), length(pre_filter_quantile) == 1, pre_filter_quantile >= 0, pre_filter_quantile <= 1, @@ -608,7 +613,7 @@ plot_trajectory_heatmap <- function(se_trajectory, var_cutoff = 0.9, max_feature # Impute over the full cell set the weights were built on, then select `cells`; # subsetting before imputation would drop cells the weights reference. if (!is.null(impute_weights)) { - dense <- impute_matrix(fmat[col_name, , drop = FALSE], impute_weights) + dense <- impute_matrix(fmat[col_name, , drop = FALSE], impute_weights, verbose = FALSE) vals <- as.numeric(dense[1, cells]) } else { vals <- as.numeric(as.matrix(fmat[col_name, cells, drop = FALSE])) diff --git a/man/IterativeLSI.Rd b/man/IterativeLSI.Rd index 5ff63c0..fedb00d 100644 --- a/man/IterativeLSI.Rd +++ b/man/IterativeLSI.Rd @@ -33,7 +33,7 @@ seed = 1, drop_zero_cells = TRUE, threads = NULL, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) \method{project}{IterativeLSI}(x, mat, iteration = x$fitted_params$iterations, threads = NULL, ...) @@ -69,7 +69,7 @@ drop_zero_cells = TRUE, overwrite = FALSE, threads = NULL, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -175,7 +175,7 @@ uses uniform sampling. Default NULL.} \code{get_threads()} and clusters single-threaded. Note that an explicit value also threads the clustering KNN, which makes results non-deterministic.} -\item{verbose}{(logical) Print progress messages.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{mat}{(IterableMatrix) Counts matrix of shape \verb{(features x cells)}.} diff --git a/man/LSI.Rd b/man/LSI.Rd index f527c32..9c22663 100644 --- a/man/LSI.Rd +++ b/man/LSI.Rd @@ -18,7 +18,7 @@ outlier_quantiles = c(0.02, 0.98), drop_zero_cells = TRUE, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) \method{LSI}{MarchRProject}( @@ -36,7 +36,7 @@ drop_zero_cells = TRUE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) \method{project}{LSI}(x, mat, threads = NULL, drop_zero_cells = TRUE, ...) @@ -77,6 +77,8 @@ before LSI; FALSE retains them with depth floored to 1. Default TRUE.} \item{threads}{(integer) Threads for the SVD in \code{LSI()}. Default is \code{get_threads()}. Other passes and \code{project()} run single-threaded by default (optimal)} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} + \item{assay_name}{(character) Name of the assay to apply the function to. If not provided, defaults to the first assay in the dataset.} \item{dataset_names}{(character) Names of the datasets to apply the function to. If not provided, defaults to all datasets in the project.} diff --git a/man/PCA.Rd b/man/PCA.Rd index 58f337b..739f716 100644 --- a/man/PCA.Rd +++ b/man/PCA.Rd @@ -14,7 +14,7 @@ n_features = 1000L, n_dimensions = 50L, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) \method{PCA}{MarchRProject}( @@ -29,7 +29,7 @@ n_dimensions = 50L, overwrite = FALSE, threads = get_threads(), - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) \method{project}{PCA}(x, mat, threads = NULL, ...) @@ -52,7 +52,7 @@ Will be automatically limited based on matrix dimensions after feature selection \item{threads}{(integer) Threads for normalization, feature selection, and the SVD. Default \code{get_threads()}. \code{project()} runs single-threaded by default.} -\item{verbose}{(logical) Whether to print progress messages. Default is FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{assay_name}{(character) For MarchRProject/MarchRDataset: name of the matrix to use.} diff --git a/man/add_background_peaks.Rd b/man/add_background_peaks.Rd index 9a70c7b..5ac1617 100644 --- a/man/add_background_peaks.Rd +++ b/man/add_background_peaks.Rd @@ -14,7 +14,7 @@ seed = 1L, knn_ef = 200L, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), dataset_names = NULL, ... ) @@ -47,7 +47,7 @@ used when \code{method = "bpcells"}).} \item{overwrite}{(logical) Replace existing background_peaks. Default FALSE keeps the stored background, warning if it was built with another \code{method}.} -\item{verbose}{(logical) Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{dataset_names}{(character or NULL) Reference datasets whose PeakMatrix counts are pooled for background matching and deviation expectations. diff --git a/man/add_clusters.Rd b/man/add_clusters.Rd index 8d18d27..908798f 100644 --- a/man/add_clusters.Rd +++ b/man/add_clusters.Rd @@ -16,7 +16,7 @@ prefix = "C", seed = 1L, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -34,7 +34,7 @@ seed = 1L, overwrite = FALSE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -64,7 +64,7 @@ hierarchical clustering on centroids. Default 25. \code{NULL} to disable.} \item{threads}{(integer) Threads for the KNN search. Default runs single-threaded. Note that result is non-deterministic if threads > 1.} -\item{verbose}{(logical) Print progress messages.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments passed to specific methods.} diff --git a/man/add_co_accessibility.Rd b/man/add_co_accessibility.Rd index 3705c4a..b5007be 100644 --- a/man/add_co_accessibility.Rd +++ b/man/add_co_accessibility.Rd @@ -23,7 +23,7 @@ add_co_accessibility(proj, ...) log2_norm = TRUE, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ... ) @@ -61,7 +61,7 @@ add_co_accessibility(proj, ...) \item{seed}{(integer) Random seed for metacell sampling. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{overwrite}{(logical) Replace an existing \code{co_accessibility} result. Default FALSE.} } diff --git a/man/add_deviations_matrix.Rd b/man/add_deviations_matrix.Rd index 8724dab..1f9c1f6 100644 --- a/man/add_deviations_matrix.Rd +++ b/man/add_deviations_matrix.Rd @@ -12,7 +12,7 @@ dataset_names = character(0), chunk_size = 20000L, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -33,7 +33,7 @@ reference population configured by \code{add_background_peaks()}.} \item{overwrite}{(logical) Replace existing matrices. Default FALSE.} -\item{verbose}{(logical) Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Unused.} } diff --git a/man/add_doublet_scores.Rd b/man/add_doublet_scores.Rd index 3c29eea..492b86a 100644 --- a/man/add_doublet_scores.Rd +++ b/man/add_doublet_scores.Rd @@ -25,7 +25,7 @@ add_doublet_scores( seed = 1, batch = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -49,7 +49,7 @@ add_doublet_scores( seed = 1, batch = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -75,7 +75,7 @@ add_doublet_scores( seed = 1, batch = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -131,7 +131,7 @@ This typically indicates a very homogenous population of cells, and is not recom for the LSI SVD and UMAP, and single-threads IterativeLSI clustering KNN. Note that an explicit value also threads clustering, which makes doublet scores non-deterministic.} -\item{verbose}{(logical) Print progress messages. Default is FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments passed to methods.} diff --git a/man/add_gene_integration_matrix.Rd b/man/add_gene_integration_matrix.Rd index 6d77077..afc6140 100644 --- a/man/add_gene_integration_matrix.Rd +++ b/man/add_gene_integration_matrix.Rd @@ -40,7 +40,7 @@ add_gene_integration_matrix(proj, ...) genes_use = NULL, threads = 1L, seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ... ) @@ -120,7 +120,7 @@ not read from \code{set_threads()}.} \item{seed}{(integer) Random seed. Default 1.} -\item{verbose}{(logical) Print progress. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{overwrite}{(logical) Overwrite existing columns / assay. Default FALSE.} } diff --git a/man/add_group_coverages.Rd b/man/add_group_coverages.Rd index 937609f..052973b 100644 --- a/man/add_group_coverages.Rd +++ b/man/add_group_coverages.Rd @@ -15,7 +15,7 @@ max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) @@ -30,7 +30,7 @@ max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -62,7 +62,7 @@ has fewer than \code{min_cells * min_replicates} cells. Default is 0.8 \item{seed}{(integer) Random seed for reproducibility. Default is 1.} -\item{verbose}{(logical) Print progress. Default is \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{group_by}{(character or named character vector) Either a metadata column name (e.g., \code{"clusters"}) or a named character vector of diff --git a/man/add_impute_weights.Rd b/man/add_impute_weights.Rd index 1d4d292..962b9a0 100644 --- a/man/add_impute_weights.Rd +++ b/man/add_impute_weights.Rd @@ -15,7 +15,7 @@ add_impute_weights( sample_cells = 5000L, n_rep = 2L, seed = 1L, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) } \arguments{ @@ -52,7 +52,7 @@ Default is 2.} \item{seed}{(integer) Random seed. Default is 1.} -\item{verbose}{(logical) Whether to print progress. Default is TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ The MarchRProject with imputation weights stored in diff --git a/man/add_kmer_bias.Rd b/man/add_kmer_bias.Rd index e6d958c..687feb0 100644 --- a/man/add_kmer_bias.Rd +++ b/man/add_kmer_bias.Rd @@ -15,7 +15,7 @@ threads = 1L, seed = 1L, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -41,7 +41,7 @@ NULL resolves from proj$genome$sequence.} \item{overwrite}{(logical) Replace existing entry. Default FALSE.} -\item{verbose}{(logical) Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Unused.} } diff --git a/man/add_marker_features.Rd b/man/add_marker_features.Rd index 20d7580..ed5d914 100644 --- a/man/add_marker_features.Rd +++ b/man/add_marker_features.Rd @@ -20,7 +20,7 @@ scale_to = 10000, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) @@ -39,7 +39,7 @@ scale_to = 10000, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ... ) @@ -81,7 +81,7 @@ backgrounds. Default 0.8.} \item{seed}{(integer) Random seed. Default 1L.} -\item{verbose}{(logical) Print progress. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Additional arguments passed to methods.} diff --git a/man/add_module_score.Rd b/man/add_module_score.Rd index 4a06d52..42ecd7b 100644 --- a/man/add_module_score.Rd +++ b/man/add_module_score.Rd @@ -16,7 +16,7 @@ seed = 1L, overwrite = FALSE, threads = 1L, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -31,7 +31,7 @@ seed = 1L, overwrite = FALSE, threads = 1L, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -64,7 +64,7 @@ columns with the same name. Default is \code{FALSE}.} \item{threads}{(integer) Threads for the \code{matrix_stats()} pass. Default \code{1L}; not read from \code{set_threads()}.} -\item{verbose}{(logical) Print progress messages. Default is \code{FALSE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments passed to methods.} diff --git a/man/add_motif_annotations.Rd b/man/add_motif_annotations.Rd index 3fd799e..3be13e3 100644 --- a/man/add_motif_annotations.Rd +++ b/man/add_motif_annotations.Rd @@ -17,7 +17,7 @@ pwm_version = 2L, bsgenome = NULL, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -57,7 +57,7 @@ extraction. When \code{NULL} (default), resolved from \code{proj$genome$sequence \item{overwrite}{(logical) Overwrite existing annotation with the same name. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Currently unused.} } diff --git a/man/add_peak2gene_links.Rd b/man/add_peak2gene_links.Rd index 3fade1a..0f66077 100644 --- a/man/add_peak2gene_links.Rd +++ b/man/add_peak2gene_links.Rd @@ -28,7 +28,7 @@ add_peak2gene_links(proj, ...) n_perm = 100L, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), overwrite = FALSE, ... ) @@ -77,7 +77,7 @@ dim reduction.} \item{seed}{(integer) Random seed for metacell sampling and p-value resampling. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{overwrite}{(logical) Replace an existing \code{peak2gene_links} result. Default FALSE.} } diff --git a/man/add_peak_annotations.Rd b/man/add_peak_annotations.Rd index 3359f7b..d628701 100644 --- a/man/add_peak_annotations.Rd +++ b/man/add_peak_annotations.Rd @@ -10,7 +10,7 @@ regions, name = "Region", overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -25,7 +25,7 @@ Input regions. See details for accepted forms.} \item{overwrite}{(logical) Overwrite existing annotation with the same name. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Currently unused.} } diff --git a/man/add_peak_gc.Rd b/man/add_peak_gc.Rd index 2a182b7..85a0bd5 100644 --- a/man/add_peak_gc.Rd +++ b/man/add_peak_gc.Rd @@ -5,7 +5,13 @@ \alias{add_peak_gc.MarchRProject} \title{Add GC content to the peak set} \usage{ -\method{add_peak_gc}{MarchRProject}(proj, bsgenome = NULL, overwrite = FALSE, verbose = TRUE, ...) +\method{add_peak_gc}{MarchRProject}( + proj, + bsgenome = NULL, + overwrite = FALSE, + verbose = getOption("MarchR.verbose", TRUE), + ... +) } \arguments{ \item{proj}{(MarchRProject) Project with a populated peak set.} @@ -17,7 +23,7 @@ sequences. When \code{NULL} (default), resolved from \code{proj$genome$sequence} \item{overwrite}{(logical) Whether to recompute when \code{gc} already exists. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Currently unused.} } diff --git a/man/add_peak_matrix.Rd b/man/add_peak_matrix.Rd index 47bd801..e08f841 100644 --- a/man/add_peak_matrix.Rd +++ b/man/add_peak_matrix.Rd @@ -17,7 +17,7 @@ blacklist = TRUE, exclude_chr = c("chrM", "chrY"), overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -52,7 +52,7 @@ each fragment end separately (0, 1, or 2 per fragment; matching ArchR), \item{overwrite}{(logical) Overwrite existing assay. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Additional arguments.} } diff --git a/man/add_reproducible_peak_set.Rd b/man/add_reproducible_peak_set.Rd index 8dc3ae1..4d4d97e 100644 --- a/man/add_reproducible_peak_set.Rd +++ b/man/add_reproducible_peak_set.Rd @@ -24,7 +24,7 @@ dataset_names = character(0), macs_executable = NULL, threads = get_threads(), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -91,7 +91,7 @@ or Python venv), pass the full path explicitly: \item{threads}{(integer) Threads for parallel MACS execution. Default 1.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Additional arguments.} } diff --git a/man/add_tsne.Rd b/man/add_tsne.Rd index 97a6f87..ad1e4e1 100644 --- a/man/add_tsne.Rd +++ b/man/add_tsne.Rd @@ -14,7 +14,7 @@ n_components = 2L, seed = 1L, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), tsne_params = list(), ... ) @@ -30,7 +30,7 @@ store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), tsne_params = list(), ... ) @@ -47,7 +47,7 @@ store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), tsne_params = list(), ... ) @@ -67,7 +67,7 @@ \item{threads}{(integer) Number of threads.} -\item{verbose}{(logical) Whether to print progress messages.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{tsne_params}{(list) Additional parameters passed to \code{Rtsne::Rtsne()}. These override any other arguments when there is diff --git a/man/add_umap.Rd b/man/add_umap.Rd index 5808494..73e4dfd 100644 --- a/man/add_umap.Rd +++ b/man/add_umap.Rd @@ -16,7 +16,7 @@ seed = 1L, batch = TRUE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), umap_params = list(), return_model = FALSE, ... @@ -35,7 +35,7 @@ store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), umap_params = list(), ... ) @@ -54,7 +54,7 @@ store_as_matrix = FALSE, overwrite = FALSE, threads = get_threads(), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), umap_params = list(), return_model = TRUE, ... @@ -80,7 +80,7 @@ Default is 0.4 (matching ArchR).} \item{threads}{(integer) Number of threads.} -\item{verbose}{(logical) Whether to print progress messages.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{umap_params}{(list) Additional parameters passed to \code{uwot::umap2()}. These override any other arguments when there is a conflict.} diff --git a/man/filter_doublets.Rd b/man/filter_doublets.Rd index 84b1952..d99ed9e 100644 --- a/man/filter_doublets.Rd +++ b/man/filter_doublets.Rd @@ -10,7 +10,7 @@ filter_doublets( score_cutoff = -Inf, filter_ratio = 1, clear_doublet_data = TRUE, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -30,7 +30,7 @@ The higher the \code{filter_ratio}, the greater the number of cells potentially \item{clear_doublet_data}{(logical) Remove all stale doublet data from project (UMAPs, doublet scores & enrichments). Default is TRUE.} -\item{verbose}{(logical) Print progress messages. Default is FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments passed to methods.} diff --git a/man/get_footprints.Rd b/man/get_footprints.Rd index 686ba52..9ca61e8 100644 --- a/man/get_footprints.Rd +++ b/man/get_footprints.Rd @@ -18,7 +18,7 @@ dataset_name = NULL, bsgenome = NULL, min_chrom_distance = 50L, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -51,7 +51,7 @@ proj$genome$sequence. Ignored when norm_method = "none".} \item{min_chrom_distance}{(integer) bp from chrom edge required beyond flank. Default 50L.} -\item{verbose}{(logical) Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Unused.} } diff --git a/man/import_feature_matrix_10x.Rd b/man/import_feature_matrix_10x.Rd index 6c2c54a..5c7690c 100644 --- a/man/import_feature_matrix_10x.Rd +++ b/man/import_feature_matrix_10x.Rd @@ -15,7 +15,7 @@ import_feature_matrix_10x(x, ...) feature_type = "Gene Expression", genes_to_exclude = NULL, overwrite = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -36,7 +36,7 @@ import_feature_matrix_10x(x, ...) \item{overwrite}{(logical) Overwrite an existing assay named \code{matrix_name}. Default FALSE.} -\item{verbose}{(logical) Print progress. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ The MarchRProject with the RNA assay added to \code{dataset_name}, both diff --git a/man/impute_matrix.Rd b/man/impute_matrix.Rd index c4e9dd7..d0f0268 100644 --- a/man/impute_matrix.Rd +++ b/man/impute_matrix.Rd @@ -4,14 +4,18 @@ \alias{impute_matrix} \title{Impute a matrix using MAGIC weights} \usage{ -impute_matrix(mat, impute_weights, verbose = FALSE) +impute_matrix( + mat, + impute_weights, + verbose = getOption("MarchR.verbose", FALSE) +) } \arguments{ \item{mat}{(matrix, dgCMatrix, or IterableMatrix) Feature-by-cell matrix to impute.} \item{impute_weights}{Impute weights object from \code{get_impute_weights()}.} -\item{verbose}{(logical) Whether to print progress. Default is FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A dense matrix (features x cells) with imputed values. diff --git a/man/make_knn_pseudobulks.Rd b/man/make_knn_pseudobulks.Rd index 31d4914..c616a2b 100644 --- a/man/make_knn_pseudobulks.Rd +++ b/man/make_knn_pseudobulks.Rd @@ -11,7 +11,7 @@ make_knn_pseudobulks( overlap_cutoff = 0.8, knn_method = knn_hnsw(), seed = 1L, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) } \arguments{ @@ -28,7 +28,7 @@ make_knn_pseudobulks( \item{seed}{(integer) Random seed for anchor sampling. Default 1L.} -\item{verbose}{(logical) Print progress. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ A list of character vectors (cell names per accepted group). diff --git a/man/peak_annotation_enrichment.Rd b/man/peak_annotation_enrichment.Rd index db05e99..3efd876 100644 --- a/man/peak_annotation_enrichment.Rd +++ b/man/peak_annotation_enrichment.Rd @@ -12,7 +12,7 @@ matches = NULL, cutoff = "p_val_adj <= 0.1 & log2_fc >= 0.5", background = c("all", "background_peaks"), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -34,7 +34,7 @@ to filter foreground peaks per group. Default \code{"background_peaks"} (GC/accessibility-matched peers via \code{add_background_peaks()}).} -\item{verbose}{(logical) Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Unused.} } diff --git a/man/plot_browser_track.Rd b/man/plot_browser_track.Rd index 3eb2645..23465c5 100644 --- a/man/plot_browser_track.Rd +++ b/man/plot_browser_track.Rd @@ -33,7 +33,7 @@ plot_browser_track( combine = c("patchwork", "bpcells", "none"), colors = NULL, title = NULL, - verbose = FALSE + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -141,7 +141,7 @@ uses BPCells' default palette.} \item{title}{(character or NULL) Plot title.} -\item{verbose}{(logical) Print progress messages.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A \code{patchwork} ggplot object with stacked tracks. diff --git a/man/plot_doublet_scores.Rd b/man/plot_doublet_scores.Rd index 301f9de..7dbd4e4 100644 --- a/man/plot_doublet_scores.Rd +++ b/man/plot_doublet_scores.Rd @@ -11,7 +11,7 @@ plot_doublet_scores(x, ...) \method{plot_doublet_scores}{MarchRDataset}( x, plot = c("enrichment", "score", "density"), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -19,7 +19,7 @@ plot_doublet_scores(x, ...) x, dataset_name = character(0), plot = c("enrichment", "score", "density"), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -31,7 +31,7 @@ plot_doublet_scores(x, ...) \item{plot}{(character) One or more of \code{"enrichment"}, \code{"score"}, \code{"density"}. Default plots all.} -\item{verbose}{(logical) Print progress. Default FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{dataset_name}{(character) For MarchRProject only.} } diff --git a/man/plot_embedding.Rd b/man/plot_embedding.Rd index f4137cc..5480e15 100644 --- a/man/plot_embedding.Rd +++ b/man/plot_embedding.Rd @@ -41,7 +41,7 @@ plot_embedding(x, ...) legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) @@ -79,7 +79,7 @@ plot_embedding(x, ...) legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -157,7 +157,7 @@ plotting. NULL plots all cells. Default NULL.} \item{legend_title}{(character) Legend title. NULL for auto.} -\item{verbose}{(logical) Print progress. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{color_by}{(character) \code{"cell_metadata"} or matrix assay name.} diff --git a/man/plot_gene_scores.Rd b/man/plot_gene_scores.Rd index f82b706..5a5c525 100644 --- a/man/plot_gene_scores.Rd +++ b/man/plot_gene_scores.Rd @@ -16,7 +16,7 @@ plot_gene_scores(x, ...) log_transform = TRUE, limits = NULL, patchwork = FALSE, - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -40,7 +40,7 @@ plot_gene_scores(x, ...) \item{patchwork}{(logical) Returns multi-gene output as patchwork object if TRUE. Default FALSE.} -\item{verbose}{(logical) Print progress. Default TRUE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ A named list of ggplot objects, keyed by gene name. diff --git a/man/project_bulk_atac.Rd b/man/project_bulk_atac.Rd index 199b869..a0391ac 100644 --- a/man/project_bulk_atac.Rd +++ b/man/project_bulk_atac.Rd @@ -50,7 +50,7 @@ Default: \code{FALSE}.} \item{threads}{(integer) Threads for the UMAP transform in the MarchRProject method. Default \code{get_threads()}. The DimReduction method projects single-threaded (default NULL).} -\item{verbose}{(logical) Print progress. Default: \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ A list with \code{simulated_reduced_dims}, \code{overlap_ratio} and diff --git a/man/project_doublets.Rd b/man/project_doublets.Rd index 47469c4..96a6a27 100644 --- a/man/project_doublets.Rd +++ b/man/project_doublets.Rd @@ -19,7 +19,7 @@ project_doublets( seed = 1, batch = TRUE, threads = NULL, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -54,7 +54,7 @@ See the function \code{umap} in the \code{uwot} package.} \item{threads}{(integer) Per-call override of \code{set_threads()}, as in \code{\link[=add_doublet_scores]{add_doublet_scores()}}. Default NULL.} -\item{verbose}{(logical) Print progress messages. Default FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A Named list with following elements: diff --git a/man/pseudobulk_fragments.Rd b/man/pseudobulk_fragments.Rd index 52f9422..95f0679 100644 --- a/man/pseudobulk_fragments.Rd +++ b/man/pseudobulk_fragments.Rd @@ -14,7 +14,7 @@ exclude_chr = c("chrM"), min_fragments = NULL, on_low_depth = c("warn", "abort", "drop"), - verbose = TRUE, + verbose = getOption("MarchR.verbose", TRUE), ... ) } @@ -41,7 +41,7 @@ gating. Default \code{NULL}.} \item{on_low_depth}{(character) Response when a group falls below \code{min_fragments}. One of \code{"warn"}, \code{"abort"}, \code{"drop"}. Default \code{"warn"}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} \item{...}{Passed to methods.} } diff --git a/man/score_doublets.Rd b/man/score_doublets.Rd index ea24066..07719bc 100644 --- a/man/score_doublets.Rd +++ b/man/score_doublets.Rd @@ -8,7 +8,7 @@ score_doublets( project_res, scoring_method = c("UMAP", "LSI"), knn_method = knn_hnsw(k = 10L, metric = "euclidean", ef = 200L), - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -22,7 +22,7 @@ Possible values are "UMAP" or "LSI". Default and recommended is "UMAP".} \code{knn_hnsw(k = 10L, metric = "euclidean", ef = 200L)}. Put KNN-specific arguments such as \code{k} or \code{metric} inside the partial function.} -\item{verbose}{(logical) Default FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A list with one row per real cell: diff --git a/man/simulate_doublets.Rd b/man/simulate_doublets.Rd index 791a55b..2e7ba7c 100644 --- a/man/simulate_doublets.Rd +++ b/man/simulate_doublets.Rd @@ -10,7 +10,7 @@ simulate_doublets( n_trials = NULL, sample_ratio = 0.5, seed = 1L, - verbose = FALSE, + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -28,7 +28,7 @@ independently to each side of the pair before summing. Default 0.5.} \item{seed}{(integer) Reproducibility seed for both the cell-pair draws and the Bernoulli downsampling. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default is FALSE.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A lazy IterableMatrix chain (bernoulli + bernoulli + add) with diff --git a/man/write_pseudobulk_bigwig.Rd b/man/write_pseudobulk_bigwig.Rd index cc2ba1e..1dfee6c 100644 --- a/man/write_pseudobulk_bigwig.Rd +++ b/man/write_pseudobulk_bigwig.Rd @@ -10,7 +10,7 @@ write_pseudobulk_bigwig( chrom_sizes, executable = "bedGraphToBigWig", keep_bedgraph = TRUE, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) } \arguments{ @@ -25,7 +25,7 @@ write_pseudobulk_bigwig( \item{keep_bedgraph}{(logical) Retain the source bedGraphs. Default \code{TRUE}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ \code{pb} with a \code{bigwig_path} column added to its manifest, \code{NA} for any group diff --git a/man/write_pseudobulk_coverage.Rd b/man/write_pseudobulk_coverage.Rd index 23067b2..1fbd6f7 100644 --- a/man/write_pseudobulk_coverage.Rd +++ b/man/write_pseudobulk_coverage.Rd @@ -13,7 +13,7 @@ write_pseudobulk_coverage( shift_start = 0L, shift_end = 0L, chrom_sizes = NULL, - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) } \arguments{ @@ -37,7 +37,7 @@ write_pseudobulk_coverage( \item{chrom_sizes}{(data.frame or NULL) Chromosome sizes for clipping tiles. Default \code{NULL}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ \code{pb} with a \code{coverage_path} column added to its manifest. diff --git a/man/write_pseudobulk_fragments.Rd b/man/write_pseudobulk_fragments.Rd index d147d2c..07afacf 100644 --- a/man/write_pseudobulk_fragments.Rd +++ b/man/write_pseudobulk_fragments.Rd @@ -4,7 +4,12 @@ \alias{write_pseudobulk_fragments} \title{Write one fragment file per pseudobulk group} \usage{ -write_pseudobulk_fragments(pb, dir, append_5th_column = FALSE, verbose = TRUE) +write_pseudobulk_fragments( + pb, + dir, + append_5th_column = FALSE, + verbose = getOption("MarchR.verbose", TRUE) +) } \arguments{ \item{pb}{(MarchRPseudobulk) Output of \code{pseudobulk_fragments()}.} @@ -14,7 +19,7 @@ write_pseudobulk_fragments(pb, dir, append_5th_column = FALSE, verbose = TRUE) \item{append_5th_column}{(logical) Write a 5th column. BPCells fills it with a literal \code{0}, not a duplicate count. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ \code{pb} with a \code{fragments_path} column added to its manifest. diff --git a/man/write_pseudobulk_peaks.Rd b/man/write_pseudobulk_peaks.Rd index 49f8ca5..8b659be 100644 --- a/man/write_pseudobulk_peaks.Rd +++ b/man/write_pseudobulk_peaks.Rd @@ -8,7 +8,7 @@ write_pseudobulk_peaks( pb, dir, scope = c("both", "group", "union"), - verbose = TRUE + verbose = getOption("MarchR.verbose", TRUE) ) } \arguments{ @@ -19,7 +19,7 @@ write_pseudobulk_peaks( \item{scope}{(character) Which peak sets to write. One of \code{"both"}, \code{"group"}, \code{"union"}. Default \code{"both"}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ \code{pb} with a \code{peaks_path} column added to its manifest. diff --git a/tests/testthat/test-clustering.R b/tests/testthat/test-clustering.R index a0e19d7..b0feab7 100644 --- a/tests/testthat/test-clustering.R +++ b/tests/testthat/test-clustering.R @@ -404,3 +404,34 @@ test_that("add_clusters.MarchRProject with Seurat clustering", { expect_true("seurat_clusters" %in% colnames(meta)) expect_true(all(!is.na(meta$seurat_clusters))) }) + +test_that("add_clusters forwards verbose to knn_method and accepts methods without verbose", { + skip_if_not_installed("RcppHNSW") + set.seed(42) + embedding <- matrix(rnorm(200), nrow = 40, ncol = 5) + rownames(embedding) <- paste0("cell_", seq_len(40)) + seen <- logical(0) + spy_knn <- function(data, query = NULL, threads = 1L, verbose = TRUE) { + seen <<- c(seen, verbose) + knn_hnsw(data, query, k = 10L, threads = threads, verbose = FALSE) + } + + suppressMessages( + add_clusters(embedding, knn_method = spy_knn, n_outlier = 0L, seed = 1L, verbose = TRUE) + ) + expect_identical(seen, TRUE) + + two_groups <- function(mat, ...) factor(rep(c("A", "B"), c(nrow(mat) - 2L, 2L))) + seen <- logical(0) + suppressMessages(add_clusters(embedding, knn_method = spy_knn, cluster_graph_method = two_groups, + n_outlier = 5L, seed = 1L, verbose = TRUE)) + expect_identical(seen, c(TRUE, TRUE)) + seen <- logical(0) + add_clusters(embedding, knn_method = spy_knn, cluster_graph_method = two_groups, + n_outlier = 5L, seed = 1L, verbose = FALSE) + expect_identical(seen, c(FALSE, FALSE)) + + expect_no_error( + add_clusters(embedding, knn_method = knn_annoy(k = 10L), n_outlier = 0L, seed = 1L, verbose = FALSE) + ) +}) diff --git a/tests/testthat/test-deviations.R b/tests/testthat/test-deviations.R index 812f06f..6163735 100644 --- a/tests/testthat/test-deviations.R +++ b/tests/testthat/test-deviations.R @@ -713,7 +713,7 @@ test_that("add_deviations_matrix gives the same result in chunks of cells", { overwrite = TRUE, verbose = FALSE) expect_message( add_deviations_matrix(p, "TestMotif", matrix_name = "Progress", chunk_size = 3L, - overwrite = TRUE), + overwrite = TRUE, verbose = TRUE), "Cells 1-3 of 8" ) for (size in c(3L, 7L)) { diff --git a/tests/testthat/test-dimensionality_reduction.R b/tests/testthat/test-dimensionality_reduction.R index a87f46e..9641967 100644 --- a/tests/testthat/test-dimensionality_reduction.R +++ b/tests/testthat/test-dimensionality_reduction.R @@ -1078,3 +1078,13 @@ test_that("PCA removes its on-disk normalization cache", { expect_identical(after, before) expect_equal(ncol(pca_res$cell_embeddings), 5) }) + +test_that("LSI logs elapsed time and leaves no run clock behind", { + set.seed(1) + counts <- matrix(rpois(100 * 200, lambda = 2), nrow = 100, + dimnames = list(paste0("f", 1:100), paste0("c", 1:200))) + mat <- methods::as(methods::as(counts, "dgCMatrix"), "IterableMatrix") + msgs <- capture_messages(LSI(mat, n_dimensions = 5, verbose = TRUE)) + expect_match(msgs, "Starting LSI, [0-9.]+ mins elapsed", all = FALSE) + expect_null(.log_clock$start) +}) diff --git a/tests/testthat/test-linkage.R b/tests/testthat/test-linkage.R index f873085..a76cd91 100644 --- a/tests/testthat/test-linkage.R +++ b/tests/testthat/test-linkage.R @@ -220,3 +220,13 @@ test_that(".make_linkage_loops returns an empty GRanges for zero-row links", { expect_s4_class(gr, "GRanges") expect_equal(length(gr), 0L) }) + +test_that("make_knn_pseudobulks reports overlap pruning through log_progress", { + set.seed(1) + emb <- matrix(rnorm(200 * 5), nrow = 200, ncol = 5) + rownames(emb) <- paste0("cell_", seq_len(200)) + expect_message( + make_knn_pseudobulks(emb, knn_iteration = 50L, k = 20L, seed = 1L, verbose = TRUE), + "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Kept [0-9]+ of 50 KNN groups" + ) +}) diff --git a/tests/testthat/test-multi_modal.R b/tests/testthat/test-multi_modal.R index c851825..35e13aa 100644 --- a/tests/testthat/test-multi_modal.R +++ b/tests/testthat/test-multi_modal.R @@ -137,7 +137,7 @@ test_that("import_feature_matrix_10x intersects barcodes and stays aligned", { proj <- make_atac_proj(atac_bc) expect_message( - proj <- import_feature_matrix_10x(proj, h5, dataset_name = "sampleA"), + proj <- import_feature_matrix_10x(proj, h5, dataset_name = "sampleA", verbose = TRUE), "Barcode intersection" ) From 8145612f4e234ebf5443bac3c8dfcee905eddb13 Mon Sep 17 00:00:00 2001 From: erliuu Date: Mon, 19 Oct 2026 16:16:59 -0700 Subject: [PATCH 03/12] feat([html] tutorials): Update tutorial HTMLs and regenerate with new logging format --- R/pseudobulk.R | 10 +- man/write_sce2g_inputs.Rd | 10 +- vignettes/marchr_chrombpnet.html | 156 ++++---- vignettes/marchr_hematopoiesis.html | 584 +++++++++++++++------------- vignettes/marchr_multiome.html | 384 ++++++++++-------- 5 files changed, 620 insertions(+), 524 deletions(-) diff --git a/R/pseudobulk.R b/R/pseudobulk.R index e161b37..8e80a32 100644 --- a/R/pseudobulk.R +++ b/R/pseudobulk.R @@ -731,7 +731,7 @@ write_pseudobulk_manifest <- function(pb, dir) { #' \code{proj[["RNA", by_dataset = FALSE]]}. `NULL` for ATAC-only. Default `NULL`. #' @param model (character) scE2G model folder names under its `models/` directory. Default #' `"multiome_powerlaw_v3"` when `rna` is given, else `"scATAC_powerlaw_v3"`. -#' @param verbose (logical) Print progress. Default `TRUE`. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. #' #' @return `pb` with `fragments_path` (and `rna_path` when `rna` is given) added to its #' manifest, and `params$sce2g_config_path` set to the cluster table. @@ -762,7 +762,9 @@ write_pseudobulk_manifest <- function(pb, dir) { #' } #' #' @export -write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, verbose = TRUE) { +write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, + verbose = getOption("MarchR.verbose", TRUE)) { + .start_log_clock() assert_for(pb, "MarchRPseudobulk") if (!requireNamespace("Rsamtools", quietly = TRUE)) { rlang::abort( @@ -831,7 +833,7 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, verbose = TRUE file.path(rna_dir, paste0(.sanitize_group_name(groups), ".h5ad")), groups ) purrr::iwalk(rna_paths, function(path, grp) { - if (verbose) message(sprintf(" Writing RNA counts for group '%s'", grp)) + if (verbose) log_progress(sprintf(" Writing RNA counts for group '%s'", grp)) unlink(path) write_matrix_anndata_hdf5(rna[, names(pb$cell_groups)[pb$cell_groups == grp]], path) }) @@ -854,7 +856,7 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, verbose = TRUE utils::write.table(config, config_path, sep = "\t", quote = FALSE, row.names = FALSE) config_path <- normalizePath(config_path) - if (verbose) message("Run scE2G with --config cell_clusters=", config_path) + if (verbose) log_progress(paste0("Run scE2G with --config cell_clusters=", config_path)) pb$params$sce2g_config_path <- config_path pb } diff --git a/man/write_sce2g_inputs.Rd b/man/write_sce2g_inputs.Rd index b029c81..01c29de 100644 --- a/man/write_sce2g_inputs.Rd +++ b/man/write_sce2g_inputs.Rd @@ -4,7 +4,13 @@ \alias{write_sce2g_inputs} \title{Write pseudobulk inputs for the scE2G enhancer-gene pipeline} \usage{ -write_sce2g_inputs(pb, dir, rna = NULL, model = NULL, verbose = TRUE) +write_sce2g_inputs( + pb, + dir, + rna = NULL, + model = NULL, + verbose = getOption("MarchR.verbose", TRUE) +) } \arguments{ \item{pb}{(MarchRPseudobulk) Output of \code{pseudobulk_fragments()}, built with @@ -19,7 +25,7 @@ and \verb{/config_cell_clusters.tsv}.} \item{model}{(character) scE2G model folder names under its \verb{models/} directory. Default \code{"multiome_powerlaw_v3"} when \code{rna} is given, else \code{"scATAC_powerlaw_v3"}.} -\item{verbose}{(logical) Print progress. Default \code{TRUE}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} } \value{ \code{pb} with \code{fragments_path} (and \code{rna_path} when \code{rna} is given) added to its diff --git a/vignettes/marchr_chrombpnet.html b/vignettes/marchr_chrombpnet.html index 80fd080..2733947 100644 --- a/vignettes/marchr_chrombpnet.html +++ b/vignettes/marchr_chrombpnet.html @@ -1496,7 +1496,7 @@ -

Exporting Pseudobulks for ChromBPNet with MarchR

+

Exporting Pseudobulks for ChromBPNet with MarchR (WIP)

Eric Liu

@@ -1647,57 +1647,61 @@

Calling Peaks per Cluster

"-p 0.01" ) ) -
Output
## Creating pseudobulk replicates for 11 groups
-##   Group 'C8': 2546 cells -> 2 replicates (500, 500 cells each)
-##   Group 'C4': 434 cells -> 2 replicates (255, 173 cells each)
-##   Group 'C2': 1352 cells -> 2 replicates (500, 67 cells each)
-##   Group 'C6': 378 cells -> 2 replicates (189, 189 cells each)
-##   Group 'C5': 322 cells -> 2 replicates (168, 145 cells each)
-##   Group 'C10': 1188 cells -> 2 replicates (500, 343 cells each)
-##   Group 'C1': 862 cells -> 2 replicates (500, 279 cells each)
-##   Group 'C9': 876 cells -> 2 replicates (500, 201 cells each)
-##   Group 'C3': 574 cells -> 2 replicates (500, 48 cells each)
-##   Group 'C7': 446 cells -> 2 replicates (358, 88 cells each)
-##   Group 'C11': 1293 cells -> 2 replicates (500, 143 cells each)
-## Calling peaks per replicate...
-##   C8_Rep1: 500 cells
-##   C8_Rep2: 500 cells
-##   C4_Rep1: 255 cells
-##   C4_Rep2: 173 cells
-##   C2_Rep1: 500 cells
-##   C2_Rep2: 67 cells
-##   C6_Rep1: 189 cells
-##   C6_Rep2: 189 cells
-##   C5_Rep1: 168 cells
-##   C5_Rep2: 145 cells
-##   C10_Rep1: 500 cells
-##   C10_Rep2: 343 cells
-##   C1_Rep1: 500 cells
-##   C1_Rep2: 279 cells
-##   C9_Rep1: 500 cells
-##   C9_Rep2: 201 cells
-##   C3_Rep1: 500 cells
-##   C3_Rep2: 48 cells
-##   C7_Rep1: 358 cells
-##   C7_Rep2: 88 cells
-##   C11_Rep1: 500 cells
-##   C11_Rep2: 143 cells
-## Filtering for reproducible peaks...
-##   Group 'C8': 72869 reproducible peaks (from 2 replicates)
-##   Group 'C4': 86125 reproducible peaks (from 2 replicates)
-##   Group 'C2': 57013 reproducible peaks (from 2 replicates)
-##   Group 'C6': 95956 reproducible peaks (from 2 replicates)
-##   Group 'C5': 95402 reproducible peaks (from 2 replicates)
-##   Group 'C10': 99365 reproducible peaks (from 2 replicates)
-##   Group 'C1': 77834 reproducible peaks (from 2 replicates)
-##   Group 'C9': 91391 reproducible peaks (from 2 replicates)
-##   Group 'C3': 38690 reproducible peaks (from 2 replicates)
-##   Group 'C7': 70884 reproducible peaks (from 2 replicates)
-##   Group 'C11': 70714 reproducible peaks (from 2 replicates)
-## Final peak set: 306316 peaks
-##   Distal: 114959
-##   Intronic: 164432
-##   Promoter: 26925
+
Output
## ###########
+## 2026-10-18 21:19:42 Creating pseudobulk replicates for 11 groups, 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:19:42   Group 'C8': 2546 cells -> 2 replicates (500, 500 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C4': 434 cells -> 2 replicates (255, 173 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C2': 1352 cells -> 2 replicates (500, 67 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C6': 378 cells -> 2 replicates (189, 189 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C5': 322 cells -> 2 replicates (168, 145 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C10': 1188 cells -> 2 replicates (500, 343 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C1': 862 cells -> 2 replicates (500, 279 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C9': 876 cells -> 2 replicates (500, 201 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C3': 574 cells -> 2 replicates (500, 48 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C7': 446 cells -> 2 replicates (358, 88 cells each), 0.000 mins elapsed.
+## 2026-10-18 21:19:42   Group 'C11': 1293 cells -> 2 replicates (500, 143 cells each), 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:19:42 Calling peaks per replicate, 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:19:42   C8_Rep1: 500 cells, 0.000 mins elapsed.
+## 2026-10-18 21:20:06   C8_Rep2: 500 cells, 0.408 mins elapsed.
+## 2026-10-18 21:20:27   C4_Rep1: 255 cells, 0.758 mins elapsed.
+## 2026-10-18 21:21:17   C4_Rep2: 173 cells, 1.598 mins elapsed.
+## 2026-10-18 21:22:08   C2_Rep1: 500 cells, 2.436 mins elapsed.
+## 2026-10-18 21:23:24   C2_Rep2: 67 cells, 3.714 mins elapsed.
+## 2026-10-18 21:23:47   C6_Rep1: 189 cells, 4.083 mins elapsed.
+## 2026-10-18 21:24:37   C6_Rep2: 189 cells, 4.918 mins elapsed.
+## 2026-10-18 21:25:28   C5_Rep1: 168 cells, 5.772 mins elapsed.
+## 2026-10-18 21:26:23   C5_Rep2: 145 cells, 6.696 mins elapsed.
+## 2026-10-18 21:26:56   C10_Rep1: 500 cells, 7.235 mins elapsed.
+## 2026-10-18 21:27:23   C10_Rep2: 343 cells, 7.695 mins elapsed.
+## 2026-10-18 21:27:56   C1_Rep1: 500 cells, 8.237 mins elapsed.
+## 2026-10-18 21:28:26   C1_Rep2: 279 cells, 8.744 mins elapsed.
+## 2026-10-18 21:29:17   C9_Rep1: 500 cells, 9.595 mins elapsed.
+## 2026-10-18 21:29:43   C9_Rep2: 201 cells, 10.017 mins elapsed.
+## 2026-10-18 21:30:39   C3_Rep1: 500 cells, 10.954 mins elapsed.
+## 2026-10-18 21:31:02   C3_Rep2: 48 cells, 11.342 mins elapsed.
+## 2026-10-18 21:31:17   C7_Rep1: 358 cells, 11.594 mins elapsed.
+## 2026-10-18 21:32:32   C7_Rep2: 88 cells, 12.847 mins elapsed.
+## 2026-10-18 21:32:53   C11_Rep1: 500 cells, 13.198 mins elapsed.
+## 2026-10-18 21:33:17   C11_Rep2: 143 cells, 13.589 mins elapsed.
+## 2026-10-18 21:34:00 Filtering for reproducible peaks, 14.302 mins elapsed.
+## 2026-10-18 21:34:12   Group 'C8': 72869 reproducible peaks (from 2 replicates), 14.506 mins elapsed.
+## 2026-10-18 21:35:35   Group 'C4': 86125 reproducible peaks (from 2 replicates), 15.885 mins elapsed.
+## 2026-10-18 21:36:58   Group 'C2': 57013 reproducible peaks (from 2 replicates), 17.277 mins elapsed.
+## 2026-10-18 21:38:29   Group 'C6': 95956 reproducible peaks (from 2 replicates), 18.789 mins elapsed.
+## 2026-10-18 21:39:41   Group 'C5': 95402 reproducible peaks (from 2 replicates), 19.990 mins elapsed.
+## 2026-10-18 21:40:06   Group 'C10': 99365 reproducible peaks (from 2 replicates), 20.405 mins elapsed.
+## 2026-10-18 21:41:03   Group 'C1': 77834 reproducible peaks (from 2 replicates), 21.358 mins elapsed.
+## 2026-10-18 21:42:10   Group 'C9': 91391 reproducible peaks (from 2 replicates), 22.477 mins elapsed.
+## 2026-10-18 21:42:22   Group 'C3': 38690 reproducible peaks (from 2 replicates), 22.668 mins elapsed.
+## 2026-10-18 21:44:02   Group 'C7': 70884 reproducible peaks (from 2 replicates), 24.342 mins elapsed.
+## 2026-10-18 21:44:30   Group 'C11': 70714 reproducible peaks (from 2 replicates), 24.803 mins elapsed.
+## 2026-10-18 21:44:38 Final peak set: 306316 peaks, 24.934 mins elapsed.
+## 2026-10-18 21:44:38   Distal: 114959, 24.934 mins elapsed.
+## 2026-10-18 21:44:38   Intronic: 164432, 24.934 mins elapsed.
+## 2026-10-18 21:44:38   Promoter: 26925, 24.934 mins elapsed.
 
@@ -1730,17 +1734,19 @@

Grouping Fragments by Cluster

Writing Fragment Files

write_pseudobulk_fragments() writes one gzipped, 10x-style fragment file per cluster to export_dir/fragments/. These are the -ifrag inputs.

pb <- write_pseudobulk_fragments(pb, export_dir)
-
Output
##   Writing fragments for group 'C8'
-##   Writing fragments for group 'C4'
-##   Writing fragments for group 'C2'
-##   Writing fragments for group 'C6'
-##   Writing fragments for group 'C5'
-##   Writing fragments for group 'C10'
-##   Writing fragments for group 'C1'
-##   Writing fragments for group 'C9'
-##   Writing fragments for group 'C3'
-##   Writing fragments for group 'C7'
-##   Writing fragments for group 'C11'
+
Output
## ###########
+## 2026-10-18 21:44:39   Writing fragments for group 'C8', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:44:43   Writing fragments for group 'C4', 0.072 mins elapsed.
+## 2026-10-18 21:44:44   Writing fragments for group 'C2', 0.092 mins elapsed.
+## 2026-10-18 21:44:46   Writing fragments for group 'C6', 0.127 mins elapsed.
+## 2026-10-18 21:44:47   Writing fragments for group 'C5', 0.146 mins elapsed.
+## 2026-10-18 21:44:48   Writing fragments for group 'C10', 0.165 mins elapsed.
+## 2026-10-18 21:44:52   Writing fragments for group 'C1', 0.218 mins elapsed.
+## 2026-10-18 21:44:54   Writing fragments for group 'C9', 0.263 mins elapsed.
+## 2026-10-18 21:44:56   Writing fragments for group 'C3', 0.298 mins elapsed.
+## 2026-10-18 21:44:58   Writing fragments for group 'C7', 0.329 mins elapsed.
+## 2026-10-18 21:45:00   Writing fragments for group 'C11', 0.350 mins elapsed.
 
read.delim(pb$manifest$fragments_path[[1]], header = FALSE, nrows = 5)
Output
##     V1     V2     V3                                V4
@@ -1758,17 +1764,19 @@ 

Writing Peaks

write_pseudobulk_peaks() writes each cluster’s peaks to export_dir/peaks/. scope = "group" skips the merged peak set; the default, "both", also writes it as union.narrowPeak.

pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group")
read.delim(pb$manifest$peaks_path[[1]], header = FALSE, nrows = 5)
-
Output
##   Writing peaks for group 'C8'
-##   Writing peaks for group 'C4'
-##   Writing peaks for group 'C2'
-##   Writing peaks for group 'C6'
-##   Writing peaks for group 'C5'
-##   Writing peaks for group 'C10'
-##   Writing peaks for group 'C1'
-##   Writing peaks for group 'C9'
-##   Writing peaks for group 'C3'
-##   Writing peaks for group 'C7'
-##   Writing peaks for group 'C11'
+
Output
## ###########
+## 2026-10-18 21:45:02   Writing peaks for group 'C8', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:45:03   Writing peaks for group 'C4', 0.003 mins elapsed.
+## 2026-10-18 21:45:03   Writing peaks for group 'C2', 0.007 mins elapsed.
+## 2026-10-18 21:45:03   Writing peaks for group 'C6', 0.010 mins elapsed.
+## 2026-10-18 21:45:03   Writing peaks for group 'C5', 0.014 mins elapsed.
+## 2026-10-18 21:45:03   Writing peaks for group 'C10', 0.018 mins elapsed.
+## 2026-10-18 21:45:04   Writing peaks for group 'C1', 0.023 mins elapsed.
+## 2026-10-18 21:45:04   Writing peaks for group 'C9', 0.027 mins elapsed.
+## 2026-10-18 21:45:04   Writing peaks for group 'C3', 0.031 mins elapsed.
+## 2026-10-18 21:45:04   Writing peaks for group 'C7', 0.033 mins elapsed.
+## 2026-10-18 21:45:05   Writing peaks for group 'C11', 0.036 mins elapsed.
 ##      V1        V2        V3   V4   V5 V6      V7      V8 V9 V10
 ## 1 chr14  77234591  77235092 C8_1 1000  . 314.012 314.012 -1 250
 ## 2  chr2  64977998  64978499 C8_2 1000  . 211.867 211.867 -1 250
diff --git a/vignettes/marchr_hematopoiesis.html b/vignettes/marchr_hematopoiesis.html
index b540420..76a7daa 100644
--- a/vignettes/marchr_hematopoiesis.html
+++ b/vignettes/marchr_hematopoiesis.html
@@ -1577,7 +1577,7 @@ 

Initialize a MarchRProject

} proj
Output
## MarchRProject Object
-## Directory: /tmp/Rtmpim34J4/marchr_project
+## Directory: /tmp/RtmplouxB8/marchr_project
 ## 3 Datasets:
 ##   scATAC_BMMC_R1:
 ##     5000 cells: scATAC_BMMC_R1#TAGGAGGGTTAACCGT-1, scATAC_BMMC_R1#CCTTGGTAGTTCTCCC-1, scATAC_BMMC_R1#GCCAGCAGTTCTGAGT-1, scATAC_BMMC_R1#TAGCATGGTGACCAGA-1 ... scATAC_BMMC_R1#CTGCTCAAGTGTCGGA-1
@@ -1594,7 +1594,7 @@ 

Initialize a MarchRProject

Genome Annotations

-

The ArchR tutorial fragments are aligned to hg19. Note that the built-in GENCODE hg19 annotation set differs from the one used in ArchR. Transcripts are used for TSS enrichment QC, genes for gene scores, and exons for the gene track in genome browser plots.

+

The ArchR tutorial fragments are aligned to hg19. Transcripts are used for TSS enrichment QC, genes for gene scores, and exons for the gene track in genome browser plots.

proj <- set_gene_annotations(
   proj,
   annotation_type = "transcripts",
@@ -1669,203 +1669,221 @@ 

Doublet Scoring and Filtering

assay_name = "TileMatrix", verbose = TRUE )
-
Output
## 2026-10-01 15:18:58 Processing dataset 1 of 3: scATAC_BMMC_R1
-## 2026-10-01 15:19:03 Simulating 20000 synthetic doublets (1000 doublets x 20 trials)
-## 2026-10-01 15:19:03 Running Iterative LSI on input matrix
-## 2026-10-01 15:19:05 Starting Iterative LSI
-## 2026-10-01 15:19:05 Starting Iterative LSI iteration 1 of 2
-## 2026-10-01 15:19:05 Selecting features
-## 2026-10-01 15:19:06 Running LSI
-## 2026-10-01 15:19:06 Starting LSI
-## 2026-10-01 15:19:07 Normalizing matrix
+
Output
## ###########
+## 2026-10-18 21:15:59 Processing dataset 1 of 3: scATAC_BMMC_R1, 0.006 mins elapsed.
+## ###########
+## 2026-10-18 21:16:04 Simulating 20000 synthetic doublets (1000 doublets x 20 trials), 0.095 mins elapsed.
+## 2026-10-18 21:16:04 Running Iterative LSI on input matrix, 0.095 mins elapsed.
+## 2026-10-18 21:16:06 Starting Iterative LSI, 0.115 mins elapsed.
+## 2026-10-18 21:16:06 Starting Iterative LSI iteration 1 of 2, 0.115 mins elapsed.
+## 2026-10-18 21:16:06 Selecting features, 0.115 mins elapsed.
+## 2026-10-18 21:16:09 Running LSI, 0.166 mins elapsed.
+## 2026-10-18 21:16:09 Starting LSI, 0.167 mins elapsed.
+## 2026-10-18 21:16:09 Normalizing matrix, 0.171 mins elapsed.
 ## Warning: Matrix compression performs poorly with non-integers.
 ## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
-## 2026-10-01 15:19:07 Calculating SVD
+## 2026-10-18 21:16:09 Calculating SVD, 0.178 mins elapsed.
 ## 
-## 2026-10-01 15:19:08 Clustering LSI results
+## 2026-10-18 21:16:10 Clustering LSI results, 0.192 mins elapsed.
+## 
+## 21:16:10 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 
+## 21:16:10 Finished building index
+## 
+## 21:16:10 Searching HNSW index with ef = 100 and 1 threads
+## 
+## 21:16:11 Finished searching
 ## 
 ## This message is displayed once every 8 hours.
-## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
+## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-## 2026-10-01 15:19:08 Merging 15 clusters down to 6 via hierarchical clustering
-## 2026-10-01 15:19:08 Pseudobulking matrix
-## 2026-10-01 15:19:09 Starting Iterative LSI iteration 2 of 2
-## 2026-10-01 15:19:09 Selecting features
-## 2026-10-01 15:19:09 Running LSI
-## 2026-10-01 15:19:09 Starting LSI
-## 2026-10-01 15:19:09 Normalizing matrix
-## 2026-10-01 15:19:10 Calculating SVD
-## 2026-10-01 15:19:09 Finished running Iterative LSI
-## 2026-10-01 15:19:09 Projecting simulated doublets on LSI space
-## 2026-10-01 15:19:16 Running UMAP fitting on LSI matrix
-## 15:19:16 Using HNSW for nearest neighbor search
-## 15:19:16 UMAP embedding parameters a = 0.7669 b = 1.223
-## 15:19:16 Setting random seed 1
-## 15:19:16 Read 4939 rows and found 30 numeric columns
-## 15:19:16 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 15:19:17 Finished building index
-## 15:19:17 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:17 Finished searching
-## 15:19:18 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:19:19 Initializing from normalized Laplacian + noise (using RSpectra)
-## 15:19:19 Range-scaling initial input columns to 0-10
-## 15:19:19 Commencing optimization for 500 epochs, with 342252 positive edges using 4 threads
-## 15:19:19 Using rng type: pcg
-## 15:19:21 Optimization finished
-## 2026-10-01 15:19:21 Validating re-projection Pearson correlation
-## 15:19:21 Setting model random seed 1
-## 15:19:21 Read 4939 rows and found 30 numeric columns
-## 15:19:21 Processing block 1 of 1
-## 15:19:21 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:21 Finished searching
-## 15:19:21 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:19:21 Initializing by weighted average of neighbor coordinates using 4 threads
-## 15:19:21 Commencing optimization for 167 epochs, with 197560 positive edges using 4 threads
-## 15:19:21 Finished
-## 2026-10-01 15:19:21 UMAP Re-projection Correlation: R^2 = 0.984
-## 2026-10-01 15:19:21 Projecting simulated doublets on UMAP space
-## 15:19:21 Setting model random seed 1
-## 15:19:21 Read 20000 rows and found 30 numeric columns
-## 15:19:21 Processing block 1 of 1
-## 15:19:21 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:21 Finished searching
-## 15:19:21 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:19:22 Initializing by weighted average of neighbor coordinates using 4 threads
-## 15:19:22 Commencing optimization for 167 epochs, with 800000 positive edges using 4 threads
-## 15:19:23 Finished
-## 2026-10-01 15:19:23 Compute doublet scores and enrichments from UMAP
-## 15:19:23 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:19:23 Finished building index
-## 15:19:23 Searching HNSW index with ef = 200 and 1 threads
-## 15:19:23 Finished searching
-## 2026-10-01 15:19:23 Processing dataset 2 of 3: scATAC_CD34_BMMC_R1
-## 2026-10-01 15:19:28 Simulating 15000 synthetic doublets (1000 doublets x 15 trials)
-## 2026-10-01 15:19:28 Running Iterative LSI on input matrix
-## 2026-10-01 15:19:29 Starting Iterative LSI
-## 2026-10-01 15:19:29 Starting Iterative LSI iteration 1 of 2
-## 2026-10-01 15:19:29 Selecting features
-## 2026-10-01 15:19:30 Running LSI
-## 2026-10-01 15:19:30 Starting LSI
-## 2026-10-01 15:19:31 Normalizing matrix
-## 2026-10-01 15:19:31 Calculating SVD
-## 2026-10-01 15:19:31 Clustering LSI results
-## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
+## 2026-10-18 21:16:11 Merging 15 clusters down to 6 via hierarchical clustering, 0.203 mins elapsed.
+## 2026-10-18 21:16:11 Pseudobulking matrix, 0.203 mins elapsed.
+## 2026-10-18 21:16:12 Starting Iterative LSI iteration 2 of 2, 0.215 mins elapsed.
+## 2026-10-18 21:16:12 Selecting features, 0.215 mins elapsed.
+## 2026-10-18 21:16:12 Running LSI, 0.218 mins elapsed.
+## 2026-10-18 21:16:12 Starting LSI, 0.218 mins elapsed.
+## 2026-10-18 21:16:12 Normalizing matrix, 0.222 mins elapsed.
+## 2026-10-18 21:16:12 Calculating SVD, 0.227 mins elapsed.
+## 2026-10-18 21:16:13 Finished running Iterative LSI, 0.234 mins elapsed.
+## 2026-10-18 21:16:13 Projecting simulated doublets on LSI space, 0.234 mins elapsed.
+## 2026-10-18 21:16:20 Running UMAP fitting on LSI matrix, 0.350 mins elapsed.
+## 21:16:20 Using HNSW for nearest neighbor search
+## 21:16:20 UMAP embedding parameters a = 0.7669 b = 1.223
+## 21:16:20 Setting random seed 1
+## 21:16:20 Read 4939 rows and found 30 numeric columns
+## 21:16:20 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 21:16:20 Finished building index
+## 21:16:20 Searching HNSW index with ef = 40 and 4 threads
+## 21:16:20 Finished searching
+## 21:16:21 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:16:22 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:16:22 Range-scaling initial input columns to 0-10
+## 21:16:22 Commencing optimization for 500 epochs, with 342252 positive edges using 4 threads
+## 21:16:22 Using rng type: pcg
+## 21:16:24 Optimization finished
+## 2026-10-18 21:16:24 Validating re-projection Pearson correlation, 0.429 mins elapsed.
+## 21:16:24 Setting model random seed 1
+## 21:16:24 Read 4939 rows and found 30 numeric columns
+## 21:16:24 Processing block 1 of 1
+## 21:16:24 Searching HNSW index with ef = 40 and 4 threads
+## 21:16:24 Finished searching
+## 21:16:24 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:16:24 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:16:24 Commencing optimization for 167 epochs, with 197560 positive edges using 4 threads
+## 21:16:25 Finished
+## 2026-10-18 21:16:25 UMAP Re-projection Correlation: R^2 = 0.984, 0.434 mins elapsed.
+## 2026-10-18 21:16:25 Projecting simulated doublets on UMAP space, 0.434 mins elapsed.
+## 21:16:25 Setting model random seed 1
+## 21:16:25 Read 20000 rows and found 30 numeric columns
+## 21:16:25 Processing block 1 of 1
+## 21:16:25 Searching HNSW index with ef = 40 and 4 threads
+## 21:16:25 Finished searching
+## 21:16:25 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:16:25 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:16:25 Commencing optimization for 167 epochs, with 800000 positive edges using 4 threads
+## 21:16:26 Finished
+## 2026-10-18 21:16:26 Compute doublet scores and enrichments from UMAP, 0.455 mins elapsed.
+## 21:16:26 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:16:26 Finished building index
+## 21:16:26 Searching HNSW index with ef = 200 and 1 threads
+## 21:16:27 Finished searching
+## 2026-10-18 21:16:27 Processing dataset 2 of 3: scATAC_CD34_BMMC_R1, 0.467 mins elapsed.
+## 2026-10-18 21:16:31 Simulating 15000 synthetic doublets (1000 doublets x 15 trials), 0.543 mins elapsed.
+## 2026-10-18 21:16:31 Running Iterative LSI on input matrix, 0.543 mins elapsed.
+## 2026-10-18 21:16:32 Starting Iterative LSI, 0.560 mins elapsed.
+## 2026-10-18 21:16:32 Starting Iterative LSI iteration 1 of 2, 0.560 mins elapsed.
+## 2026-10-18 21:16:32 Selecting features, 0.560 mins elapsed.
+## 2026-10-18 21:16:33 Running LSI, 0.580 mins elapsed.
+## 2026-10-18 21:16:33 Starting LSI, 0.581 mins elapsed.
+## 2026-10-18 21:16:34 Normalizing matrix, 0.583 mins elapsed.
+## 2026-10-18 21:16:34 Calculating SVD, 0.587 mins elapsed.
+## 2026-10-18 21:16:35 Clustering LSI results, 0.599 mins elapsed.
+## 21:16:35 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:16:35 Finished building index
+## 21:16:35 Searching HNSW index with ef = 100 and 1 threads
+## 21:16:35 Finished searching
+## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 16 datapoints. Try higher ef value
-## 2026-10-01 15:19:32 Merging 13 clusters down to 6 via hierarchical clustering
-## 2026-10-01 15:19:32 Pseudobulking matrix
-## 2026-10-01 15:19:33 Starting Iterative LSI iteration 2 of 2
-## 2026-10-01 15:19:33 Selecting features
-## 2026-10-01 15:19:33 Running LSI
-## 2026-10-01 15:19:33 Starting LSI
-## 2026-10-01 15:19:33 Normalizing matrix
-## 2026-10-01 15:19:33 Calculating SVD
-## 2026-10-01 15:19:34 Finished running Iterative LSI
-## 2026-10-01 15:19:34 Projecting simulated doublets on LSI space
-## 2026-10-01 15:19:39 Running UMAP fitting on LSI matrix
-## 15:19:39 Using HNSW for nearest neighbor search
-## 15:19:39 UMAP embedding parameters a = 0.7669 b = 1.223
-## 15:19:39 Setting random seed 1
-## 15:19:39 Read 3280 rows and found 30 numeric columns
-## 15:19:39 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 15:19:39 Finished building index
-## 15:19:39 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:39 Finished searching
-## 15:19:41 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:19:41 Initializing from normalized Laplacian + noise (using RSpectra)
-## 15:19:41 Range-scaling initial input columns to 0-10
-## 15:19:41 Commencing optimization for 500 epochs, with 208246 positive edges using 4 threads
-## 15:19:41 Using rng type: pcg
-## 15:19:42 Optimization finished
-## 2026-10-01 15:19:42 Validating re-projection Pearson correlation
-## 15:19:42 Setting model random seed 1
-## 15:19:42 Read 3280 rows and found 30 numeric columns
-## 15:19:42 Processing block 1 of 1
-## 15:19:42 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:42 Finished searching
-## 15:19:42 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:19:42 Initializing by weighted average of neighbor coordinates using 4 threads
-## 15:19:42 Commencing optimization for 167 epochs, with 131200 positive edges using 4 threads
-## 15:19:42 Finished
-## 2026-10-01 15:19:42 UMAP Re-projection Correlation: R^2 = 0.994
-## 2026-10-01 15:19:42 Projecting simulated doublets on UMAP space
-## 15:19:42 Setting model random seed 1
-## 15:19:42 Read 15000 rows and found 30 numeric columns
-## 15:19:42 Processing block 1 of 1
-## 15:19:42 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:43 Finished searching
-## 15:19:43 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:19:43 Initializing by weighted average of neighbor coordinates using 4 threads
-## 15:19:43 Commencing optimization for 167 epochs, with 600000 positive edges using 4 threads
-## 15:19:43 Finished
-## 2026-10-01 15:19:43 Compute doublet scores and enrichments from UMAP
-## 15:19:43 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:19:43 Finished building index
-## 15:19:43 Searching HNSW index with ef = 200 and 1 threads
-## 15:19:44 Finished searching
-## 2026-10-01 15:19:44 Processing dataset 3 of 3: scATAC_PBMC_R1
-## 2026-10-01 15:19:49 Simulating 10000 synthetic doublets (1000 doublets x 10 trials)
-## 2026-10-01 15:19:49 Running Iterative LSI on input matrix
-## 2026-10-01 15:19:50 Starting Iterative LSI
-## 2026-10-01 15:19:50 Starting Iterative LSI iteration 1 of 2
-## 2026-10-01 15:19:50 Selecting features
-## 2026-10-01 15:19:51 Running LSI
-## 2026-10-01 15:19:51 Starting LSI
-## 2026-10-01 15:19:51 Normalizing matrix
-## 2026-10-01 15:19:51 Calculating SVD
-## 2026-10-01 15:19:52 Clustering LSI results
-## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
+## 2026-10-18 21:16:35 Merging 13 clusters down to 6 via hierarchical clustering, 0.605 mins elapsed.
+## 2026-10-18 21:16:35 Pseudobulking matrix, 0.605 mins elapsed.
+## 2026-10-18 21:16:36 Starting Iterative LSI iteration 2 of 2, 0.616 mins elapsed.
+## 2026-10-18 21:16:36 Selecting features, 0.616 mins elapsed.
+## 2026-10-18 21:16:36 Running LSI, 0.620 mins elapsed.
+## 2026-10-18 21:16:36 Starting LSI, 0.620 mins elapsed.
+## 2026-10-18 21:16:36 Normalizing matrix, 0.623 mins elapsed.
+## 2026-10-18 21:16:36 Calculating SVD, 0.627 mins elapsed.
+## 2026-10-18 21:16:37 Finished running Iterative LSI, 0.636 mins elapsed.
+## 2026-10-18 21:16:37 Projecting simulated doublets on LSI space, 0.636 mins elapsed.
+## 2026-10-18 21:16:43 Running UMAP fitting on LSI matrix, 0.732 mins elapsed.
+## 21:16:43 Using HNSW for nearest neighbor search
+## 21:16:43 UMAP embedding parameters a = 0.7669 b = 1.223
+## 21:16:43 Setting random seed 1
+## 21:16:43 Read 3280 rows and found 30 numeric columns
+## 21:16:43 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 21:16:43 Finished building index
+## 21:16:43 Searching HNSW index with ef = 40 and 4 threads
+## 21:16:43 Finished searching
+## 21:16:44 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:16:44 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:16:45 Range-scaling initial input columns to 0-10
+## 21:16:45 Commencing optimization for 500 epochs, with 208246 positive edges using 4 threads
+## 21:16:45 Using rng type: pcg
+## 21:16:46 Optimization finished
+## 2026-10-18 21:16:46 Validating re-projection Pearson correlation, 0.794 mins elapsed.
+## 21:16:46 Setting model random seed 1
+## 21:16:46 Read 3280 rows and found 30 numeric columns
+## 21:16:46 Processing block 1 of 1
+## 21:16:46 Searching HNSW index with ef = 40 and 4 threads
+## 21:16:46 Finished searching
+## 21:16:46 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:16:46 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:16:46 Commencing optimization for 167 epochs, with 131200 positive edges using 4 threads
+## 21:16:46 Finished
+## 2026-10-18 21:16:46 UMAP Re-projection Correlation: R^2 = 0.994, 0.797 mins elapsed.
+## 2026-10-18 21:16:46 Projecting simulated doublets on UMAP space, 0.797 mins elapsed.
+## 21:16:46 Setting model random seed 1
+## 21:16:46 Read 15000 rows and found 30 numeric columns
+## 21:16:46 Processing block 1 of 1
+## 21:16:46 Searching HNSW index with ef = 40 and 4 threads
+## 21:16:47 Finished searching
+## 21:16:47 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:16:47 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:16:47 Commencing optimization for 167 epochs, with 600000 positive edges using 4 threads
+## 21:16:47 Finished
+## 2026-10-18 21:16:47 Compute doublet scores and enrichments from UMAP, 0.811 mins elapsed.
+## 21:16:47 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:16:47 Finished building index
+## 21:16:47 Searching HNSW index with ef = 200 and 1 threads
+## 21:16:48 Finished searching
+## 2026-10-18 21:16:48 Processing dataset 3 of 3: scATAC_PBMC_R1, 0.819 mins elapsed.
+## 2026-10-18 21:16:53 Simulating 10000 synthetic doublets (1000 doublets x 10 trials), 0.903 mins elapsed.
+## 2026-10-18 21:16:53 Running Iterative LSI on input matrix, 0.903 mins elapsed.
+## 2026-10-18 21:16:54 Starting Iterative LSI, 0.921 mins elapsed.
+## 2026-10-18 21:16:54 Starting Iterative LSI iteration 1 of 2, 0.921 mins elapsed.
+## 2026-10-18 21:16:54 Selecting features, 0.921 mins elapsed.
+## 2026-10-18 21:16:55 Running LSI, 0.941 mins elapsed.
+## 2026-10-18 21:16:55 Starting LSI, 0.941 mins elapsed.
+## 2026-10-18 21:16:55 Normalizing matrix, 0.943 mins elapsed.
+## 2026-10-18 21:16:56 Calculating SVD, 0.948 mins elapsed.
+## 2026-10-18 21:16:56 Clustering LSI results, 0.959 mins elapsed.
+## 21:16:56 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:16:56 Finished building index
+## 21:16:56 Searching HNSW index with ef = 100 and 1 threads
+## 21:16:56 Finished searching
+## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-## 2026-10-01 15:19:52 Merging 12 clusters down to 6 via hierarchical clustering
-## 2026-10-01 15:19:52 Pseudobulking matrix
-## 2026-10-01 15:19:53 Starting Iterative LSI iteration 2 of 2
-## 2026-10-01 15:19:53 Selecting features
-## 2026-10-01 15:19:53 Running LSI
-## 2026-10-01 15:19:53 Starting LSI
-## 2026-10-01 15:19:53 Normalizing matrix
-## 2026-10-01 15:19:54 Calculating SVD
-## 2026-10-01 15:19:54 Finished running Iterative LSI
-## 2026-10-01 15:19:54 Projecting simulated doublets on LSI space
-## 2026-10-01 15:19:59 Running UMAP fitting on LSI matrix
-## 15:19:59 Using HNSW for nearest neighbor search
-## 15:19:59 UMAP embedding parameters a = 0.7669 b = 1.223
-## 15:19:59 Setting random seed 1
-## 15:19:59 Read 2462 rows and found 30 numeric columns
-## 15:19:59 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 15:19:59 Finished building index
-## 15:19:59 Searching HNSW index with ef = 40 and 4 threads
-## 15:19:59 Finished searching
-## 15:20:00 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:20:01 Initializing from normalized Laplacian + noise (using RSpectra)
-## 15:20:01 Range-scaling initial input columns to 0-10
-## 15:20:01 Commencing optimization for 500 epochs, with 170712 positive edges using 4 threads
-## 15:20:01 Using rng type: pcg
-## 15:20:03 Optimization finished
-## 2026-10-01 15:20:03 Validating re-projection Pearson correlation
-## 15:20:03 Setting model random seed 1
-## 15:20:03 Read 2462 rows and found 30 numeric columns
-## 15:20:03 Processing block 1 of 1
-## 15:20:03 Searching HNSW index with ef = 40 and 4 threads
-## 15:20:03 Finished searching
-## 15:20:03 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:20:03 Initializing by weighted average of neighbor coordinates using 4 threads
-## 15:20:03 Commencing optimization for 167 epochs, with 98480 positive edges using 4 threads
-## 15:20:03 Finished
-## 2026-10-01 15:20:03 UMAP Re-projection Correlation: R^2 = 0.951
-## 2026-10-01 15:20:03 Projecting simulated doublets on UMAP space
-## 15:20:03 Setting model random seed 1
-## 15:20:03 Read 10000 rows and found 30 numeric columns
-## 15:20:03 Processing block 1 of 1
-## 15:20:03 Searching HNSW index with ef = 40 and 4 threads
-## 15:20:03 Finished searching
-## 15:20:03 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 15:20:03 Initializing by weighted average of neighbor coordinates using 4 threads
-## 15:20:03 Commencing optimization for 167 epochs, with 400000 positive edges using 4 threads
-## 15:20:04 Finished
-## 2026-10-01 15:20:04 Compute doublet scores and enrichments from UMAP
-## 15:20:04 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:20:04 Finished building index
-## 15:20:04 Searching HNSW index with ef = 200 and 1 threads
-## 15:20:04 Finished searching
+## 2026-10-18 21:16:56 Merging 12 clusters down to 6 via hierarchical clustering, 0.964 mins elapsed.
+## 2026-10-18 21:16:57 Pseudobulking matrix, 0.964 mins elapsed.
+## 2026-10-18 21:16:57 Starting Iterative LSI iteration 2 of 2, 0.969 mins elapsed.
+## 2026-10-18 21:16:57 Selecting features, 0.969 mins elapsed.
+## 2026-10-18 21:16:57 Running LSI, 0.978 mins elapsed.
+## 2026-10-18 21:16:57 Starting LSI, 0.978 mins elapsed.
+## 2026-10-18 21:16:57 Normalizing matrix, 0.980 mins elapsed.
+## 2026-10-18 21:16:58 Calculating SVD, 0.984 mins elapsed.
+## 2026-10-18 21:16:59 Finished running Iterative LSI, 0.998 mins elapsed.
+## 2026-10-18 21:16:59 Projecting simulated doublets on LSI space, 0.998 mins elapsed.
+## 2026-10-18 21:17:03 Running UMAP fitting on LSI matrix, 1.073 mins elapsed.
+## 21:17:03 Using HNSW for nearest neighbor search
+## 21:17:03 UMAP embedding parameters a = 0.7669 b = 1.223
+## 21:17:03 Setting random seed 1
+## 21:17:03 Read 2462 rows and found 30 numeric columns
+## 21:17:03 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 21:17:03 Finished building index
+## 21:17:03 Searching HNSW index with ef = 40 and 4 threads
+## 21:17:03 Finished searching
+## 21:17:04 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:17:06 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:17:06 Range-scaling initial input columns to 0-10
+## 21:17:06 Commencing optimization for 500 epochs, with 170712 positive edges using 4 threads
+## 21:17:06 Using rng type: pcg
+## 21:17:07 Optimization finished
+## 2026-10-18 21:17:07 Validating re-projection Pearson correlation, 1.147 mins elapsed.
+## 21:17:07 Setting model random seed 1
+## 21:17:07 Read 2462 rows and found 30 numeric columns
+## 21:17:07 Processing block 1 of 1
+## 21:17:07 Searching HNSW index with ef = 40 and 4 threads
+## 21:17:07 Finished searching
+## 21:17:07 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:17:07 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:17:07 Commencing optimization for 167 epochs, with 98480 positive edges using 4 threads
+## 21:17:08 Finished
+## 2026-10-18 21:17:08 UMAP Re-projection Correlation: R^2 = 0.951, 1.150 mins elapsed.
+## 2026-10-18 21:17:08 Projecting simulated doublets on UMAP space, 1.150 mins elapsed.
+## 21:17:08 Setting model random seed 1
+## 21:17:08 Read 10000 rows and found 30 numeric columns
+## 21:17:08 Processing block 1 of 1
+## 21:17:08 Searching HNSW index with ef = 40 and 4 threads
+## 21:17:08 Finished searching
+## 21:17:08 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:17:08 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:17:08 Commencing optimization for 167 epochs, with 400000 positive edges using 4 threads
+## 21:17:08 Finished
+## 2026-10-18 21:17:08 Compute doublet scores and enrichments from UMAP, 1.160 mins elapsed.
+## 21:17:08 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:17:08 Finished building index
+## 21:17:08 Searching HNSW index with ef = 200 and 1 threads
+## 21:17:09 Finished searching
 
for (sample_name in names(input_files)) {
   print(plot_doublet_scores(proj, dataset_name = sample_name))
@@ -1873,22 +1891,24 @@ 

Doublet Scoring and Filtering

filter_doublets() removes the highest-enrichment predicted doublets from every dataset in the project.

proj <- filter_doublets(proj, verbose = TRUE)
-
Output
## Filtering doublets in 3 dataset(s): scATAC_BMMC_R1, scATAC_CD34_BMMC_R1, scATAC_PBMC_R1
-## 2026-10-01 15:20:07 filtering dataset: scATAC_BMMC_R1.
-## 2026-10-01 15:20:07 Filtering 243 doublets from 4939 cells (4.9%)
-## 2026-10-01 15:20:07 Dataset successfully filtered.
-## 2026-10-01 15:20:07 Removing stale doublet data
-## 2026-10-01 15:20:07 doublet filtering complete.
-## 2026-10-01 15:20:07 filtering dataset: scATAC_CD34_BMMC_R1.
-## 2026-10-01 15:20:07 Filtering 107 doublets from 3280 cells (3.3%)
-## 2026-10-01 15:20:08 Dataset successfully filtered.
-## 2026-10-01 15:20:08 Removing stale doublet data
-## 2026-10-01 15:20:08 doublet filtering complete.
-## 2026-10-01 15:20:08 filtering dataset: scATAC_PBMC_R1.
-## 2026-10-01 15:20:08 Filtering 60 doublets from 2462 cells (2.4%)
-## 2026-10-01 15:20:08 Dataset successfully filtered.
-## 2026-10-01 15:20:08 Removing stale doublet data
-## 2026-10-01 15:20:08 doublet filtering complete.
+
Output
## ###########
+## 2026-10-18 21:17:12 Filtering doublets in 3 dataset(s): scATAC_BMMC_R1, scATAC_CD34_BMMC_R1, scATAC_PBMC_R1, 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:17:12 filtering dataset: scATAC_BMMC_R1, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Filtering 243 doublets from 4939 cells (4.9%), 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Dataset successfully filtered, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Removing stale doublet data, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 doublet filtering complete, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 filtering dataset: scATAC_CD34_BMMC_R1, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Filtering 107 doublets from 3280 cells (3.3%), 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Dataset successfully filtered, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Removing stale doublet data, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 doublet filtering complete, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 filtering dataset: scATAC_PBMC_R1, 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Filtering 60 doublets from 2462 cells (2.4%), 0.000 mins elapsed.
+## 2026-10-18 21:17:12 Dataset successfully filtered, 0.001 mins elapsed.
+## 2026-10-18 21:17:12 Removing stale doublet data, 0.001 mins elapsed.
+## 2026-10-18 21:17:12 doublet filtering complete, 0.001 mins elapsed.
 
@@ -1904,28 +1924,34 @@

Iterative LSI

max_clusters = 25, verbose = TRUE )
-
Output
## 2026-10-01 15:20:16 Starting Iterative LSI
-## 2026-10-01 15:20:16 Starting Iterative LSI iteration 1 of 2
-## 2026-10-01 15:20:16 Selecting features
-## 2026-10-01 15:20:17 Running LSI
-## 2026-10-01 15:20:18 Starting LSI
-## 2026-10-01 15:20:18 Filtering 404 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-01 15:20:19 Normalizing matrix
-## 2026-10-01 15:20:21 Calculating SVD
-## 2026-10-01 15:20:25 Dropping PCs 1 due to high correlation with sequencing depth
-## 2026-10-01 15:20:25 Re-projecting outlier cells into LSI space
-## 2026-10-01 15:20:27 Clustering LSI results
-## 2026-10-01 15:20:29 Pseudobulking matrix
-## 2026-10-01 15:20:34 Starting Iterative LSI iteration 2 of 2
-## 2026-10-01 15:20:34 Selecting features
-## 2026-10-01 15:20:34 Running LSI
-## 2026-10-01 15:20:34 Starting LSI
-## 2026-10-01 15:20:35 Filtering 412 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-01 15:20:36 Normalizing matrix
-## 2026-10-01 15:20:37 Calculating SVD
-## 2026-10-01 15:20:41 Dropping PCs 1 due to high correlation with sequencing depth
-## 2026-10-01 15:20:41 Re-projecting outlier cells into LSI space
-## 2026-10-01 15:20:43 Finished running Iterative LSI
+
Output
## ###########
+## 2026-10-18 21:17:20 Starting Iterative LSI, 0.138 mins elapsed.
+## ###########
+## 2026-10-18 21:17:20 Starting Iterative LSI iteration 1 of 2, 0.138 mins elapsed.
+## 2026-10-18 21:17:20 Selecting features, 0.139 mins elapsed.
+## 2026-10-18 21:17:22 Running LSI, 0.165 mins elapsed.
+## 2026-10-18 21:17:22 Starting LSI, 0.168 mins elapsed.
+## 2026-10-18 21:17:23 Filtering 404 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.188 mins elapsed.
+## 2026-10-18 21:17:24 Normalizing matrix, 0.201 mins elapsed.
+## 2026-10-18 21:17:26 Calculating SVD, 0.228 mins elapsed.
+## 2026-10-18 21:17:30 Dropping PCs 1 due to high correlation with sequencing depth, 0.301 mins elapsed.
+## 2026-10-18 21:17:30 Re-projecting outlier cells into LSI space, 0.301 mins elapsed.
+## 2026-10-18 21:17:32 Clustering LSI results, 0.335 mins elapsed.
+## 21:17:32 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:17:33 Finished building index
+## 21:17:33 Searching HNSW index with ef = 100 and 1 threads
+## 21:17:33 Finished searching
+## 2026-10-18 21:17:34 Pseudobulking matrix, 0.358 mins elapsed.
+## 2026-10-18 21:17:37 Starting Iterative LSI iteration 2 of 2, 0.418 mins elapsed.
+## 2026-10-18 21:17:37 Selecting features, 0.418 mins elapsed.
+## 2026-10-18 21:17:37 Running LSI, 0.422 mins elapsed.
+## 2026-10-18 21:17:38 Starting LSI, 0.424 mins elapsed.
+## 2026-10-18 21:17:38 Filtering 412 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.436 mins elapsed.
+## 2026-10-18 21:17:39 Normalizing matrix, 0.448 mins elapsed.
+## 2026-10-18 21:17:40 Calculating SVD, 0.473 mins elapsed.
+## 2026-10-18 21:17:45 Dropping PCs 1 due to high correlation with sequencing depth, 0.540 mins elapsed.
+## 2026-10-18 21:17:45 Re-projecting outlier cells into LSI space, 0.540 mins elapsed.
+## 2026-10-18 21:17:46 Finished running Iterative LSI, 0.569 mins elapsed.
 
@@ -1939,13 +1965,23 @@

Clustering

cluster_graph_method = cluster_graph_leiden(resolution = 0.8), knn_method = knn_hnsw(k = 20L) )
-
Output
## 2026-10-01 15:20:43 Extracting embedding 'IterativeLSI'
+
Output
## ###########
+## 2026-10-18 21:17:46 Extracting embedding 'IterativeLSI', 0.000 mins elapsed.
+## ###########
 ## Warning: Converting to a dense matrix may use excessive memory
-## 2026-10-01 15:20:44 Clustering 10271 cells with 29 dimensions
+## 2026-10-18 21:17:49 Clustering 10271 cells with 29 dimensions, 0.040 mins elapsed.
+## 
+## 21:17:49 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 
+## 21:17:49 Finished building index
+## 
+## 21:17:50 Searching HNSW index with ef = 100 and 1 threads
+## 
+## 21:17:50 Finished searching
 ## 
-## Found 11 clusters
+## 2026-10-18 21:17:51 Found 11 clusters, 0.071 mins elapsed.
 ## 
-## 2026-10-01 15:20:46 Added 11 clusters as 'atac_clusters' in cell metadata
+## 2026-10-18 21:17:51 Added 11 clusters as 'atac_clusters' in cell metadata, 0.072 mins elapsed.
 ## 
 ## This message is displayed once every 8 hours.
 
@@ -1960,23 +1996,25 @@

UMAP Embedding

min_dist = 0.5, verbose = TRUE )
-
Output
## 2026-10-01 15:20:46 Extracting embedding 'IterativeLSI'
-## 2026-10-01 15:20:46 Computing UMAP on 10271 cells with 29 dimensions
-## 15:20:46 Using HNSW for nearest neighbor search
-## 15:20:46 UMAP embedding parameters a = 0.583 b = 1.334
-## 15:20:46 Setting random seed 1
-## 15:20:46 Read 10271 rows and found 29 numeric columns
-## 15:20:46 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 15:20:47 Finished building index
-## 15:20:47 Searching HNSW index with ef = 30 and 4 threads
-## 15:20:47 Finished searching
-## 15:20:48 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 30
-## 15:20:49 Initializing from normalized Laplacian + noise (using RSpectra)
-## 15:20:50 Range-scaling initial input columns to 0-10
-## 15:20:50 Commencing optimization for 500 epochs, with 464838 positive edges using 4 threads
-## 15:20:50 Using rng type: pcg
-## 15:20:52 Optimization finished
-## 2026-10-01 15:20:52 Added UMAP embedding as 'UMAP' (2 components)
+
Output
## ###########
+## 2026-10-18 21:17:51 Extracting embedding 'IterativeLSI', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:17:51 Computing UMAP on 10271 cells with 29 dimensions, 0.000 mins elapsed.
+## 21:17:51 Using HNSW for nearest neighbor search
+## 21:17:51 UMAP embedding parameters a = 0.583 b = 1.334
+## 21:17:51 Setting random seed 1
+## 21:17:51 Read 10271 rows and found 29 numeric columns
+## 21:17:51 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
+## 21:17:51 Finished building index
+## 21:17:51 Searching HNSW index with ef = 30 and 4 threads
+## 21:17:51 Finished searching
+## 21:17:53 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 30
+## 21:17:54 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:17:54 Range-scaling initial input columns to 0-10
+## 21:17:54 Commencing optimization for 500 epochs, with 464838 positive edges using 4 threads
+## 21:17:54 Using rng type: pcg
+## 21:17:57 Optimization finished
+## 2026-10-18 21:17:57 Added UMAP embedding as 'UMAP' (2 components), 0.112 mins elapsed.
 

We can visualize the attributes of our cells, using the plot_embedding() function, specifying the coloration via the col_name parameter.

plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters") +
@@ -2004,26 +2042,28 @@ 

Assigning Clusters with Gene Scores

Raw gene scores can be noisy at the single-cell level. add_impute_weights() computes MAGIC diffusion weights from the LSI embedding.

proj <- add_impute_weights(proj, embedding_name = "IterativeLSI")
-
Output
## Computing MAGIC imputation weights (td=3, ka=4, blocks~5136 cells, 2 reps)
-##   Replicate 1 of 2
-## 15:21:02 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:21:02 Finished building index
-## 15:21:02 Searching HNSW index with ef = 100 and 1 threads
-## 15:21:03 Finished searching
-## 15:21:04 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:21:04 Finished building index
-## 15:21:04 Searching HNSW index with ef = 100 and 1 threads
-## 15:21:04 Finished searching
-##   Replicate 2 of 2
-## 15:21:05 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:21:05 Finished building index
-## 15:21:05 Searching HNSW index with ef = 100 and 1 threads
-## 15:21:05 Finished searching
-## 15:21:06 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 15:21:07 Finished building index
-## 15:21:07 Searching HNSW index with ef = 100 and 1 threads
-## 15:21:07 Finished searching
-## Completed MAGIC imputation weights.
+
Output
## ###########
+## 2026-10-18 21:18:07 Computing MAGIC imputation weights (td=3, ka=4, blocks~5136 cells, 2 reps), 0.040 mins elapsed.
+## ###########
+## 2026-10-18 21:18:07   Replicate 1 of 2, 0.040 mins elapsed.
+## 21:18:07 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:18:07 Finished building index
+## 21:18:07 Searching HNSW index with ef = 100 and 1 threads
+## 21:18:07 Finished searching
+## 21:18:08 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:18:09 Finished building index
+## 21:18:09 Searching HNSW index with ef = 100 and 1 threads
+## 21:18:09 Finished searching
+## 2026-10-18 21:18:10   Replicate 2 of 2, 0.086 mins elapsed.
+## 21:18:10 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:18:10 Finished building index
+## 21:18:10 Searching HNSW index with ef = 100 and 1 threads
+## 21:18:10 Finished searching
+## 21:18:11 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:18:11 Finished building index
+## 21:18:11 Searching HNSW index with ef = 100 and 1 threads
+## 21:18:11 Finished searching
+## 2026-10-18 21:18:12 Completed MAGIC imputation weights, 0.129 mins elapsed.
 
plot_gene_scores(
   proj,
@@ -2034,7 +2074,9 @@ 

Assigning Clusters with Gene Scores

patchwork = TRUE )

-
Output
## Imputing gene scores with MAGIC weights
+
Output
## ###########
+## 2026-10-18 21:18:15 Imputing gene scores with MAGIC weights, 0.044 mins elapsed.
+## ###########
 
diff --git a/vignettes/marchr_multiome.html b/vignettes/marchr_multiome.html index fc1a115..3906a41 100644 --- a/vignettes/marchr_multiome.html +++ b/vignettes/marchr_multiome.html @@ -1496,7 +1496,7 @@ -

MarchR Multiome (ATAC + RNA) tutorial

+

MarchR Multiome (ATAC + RNA) Tutorial (WIP)

Eric Liu

@@ -1574,7 +1574,7 @@

Initialize a MarchRProject

proj <- add_fragments(proj, frags, frags_name = "ATAC", dataset_name = sample_name) proj
Output
## MarchRProject Object
-## Directory: /tmp/RtmpwPUqnD/marchr_project
+## Directory: /tmp/RtmpKpXPaN/marchr_project
 ## 1 Dataset:
 ##   PBMC_10k:
 ##     671397 cells: PBMC_10k#GTAGGTGCATAACGGG-1, PBMC_10k#CCAACCCGTGGAAGGC-1, PBMC_10k#ACGGGAAGTTTACGTC-1, PBMC_10k#TAGGTTGGTTTGTGGA-1 ... PBMC_10k#GTTTCCTCACCTACGG-1
@@ -1614,81 +1614,93 @@ 

Doublet Scoring and Filtering

add_doublet_scores() simulates synthetic doublets and scores each real cell by its local doublet enrichment; filter_doublets() removes the highest-enrichment predicted doublets.

proj <- add_doublet_scores(proj, assay_name = "TileMatrix", verbose = TRUE)
proj <- filter_doublets(proj, verbose = TRUE)
-
Output
## 2026-10-16 14:21:25 Processing dataset 1 of 1: PBMC_10k
-## 2026-10-16 14:21:39 Simulating 65000 synthetic doublets (1000 doublets x 65 trials)
-## 2026-10-16 14:21:39 Running Iterative LSI on input matrix
-## 2026-10-16 14:21:42 Starting Iterative LSI
-## 2026-10-16 14:21:42 Starting Iterative LSI iteration 1 of 2
-## 2026-10-16 14:21:42 Selecting features
-## 2026-10-16 14:21:46 Running LSI
-## 2026-10-16 14:21:46 Starting LSI
-## 2026-10-16 14:21:48 Normalizing matrix
+
Output
## ###########
+## 2026-10-18 21:47:18 Processing dataset 1 of 1: PBMC_10k, 0.003 mins elapsed.
+## ###########
+## 2026-10-18 21:47:33 Simulating 65000 synthetic doublets (1000 doublets x 65 trials), 0.254 mins elapsed.
+## 2026-10-18 21:47:33 Running Iterative LSI on input matrix, 0.254 mins elapsed.
+## 2026-10-18 21:47:35 Starting Iterative LSI, 0.295 mins elapsed.
+## 2026-10-18 21:47:35 Starting Iterative LSI iteration 1 of 2, 0.295 mins elapsed.
+## 2026-10-18 21:47:35 Selecting features, 0.295 mins elapsed.
+## 2026-10-18 21:47:38 Running LSI, 0.334 mins elapsed.
+## 2026-10-18 21:47:38 Starting LSI, 0.336 mins elapsed.
+## 2026-10-18 21:47:39 Normalizing matrix, 0.360 mins elapsed.
 ## Warning: Matrix compression performs poorly with non-integers.
 ## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
-## 2026-10-16 14:21:50 Calculating SVD
+## 2026-10-18 21:47:42 Calculating SVD, 0.397 mins elapsed.
 ## 
-## 2026-10-16 14:21:57 Clustering LSI results
+## 2026-10-18 21:47:48 Clustering LSI results, 0.512 mins elapsed.
+## 
+## 21:47:48 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 
+## 21:47:49 Finished building index
+## 
+## 21:47:49 Searching HNSW index with ef = 100 and 1 threads
+## 
+## 21:47:50 Finished searching
 ## 
 ## This message is displayed once every 8 hours.
-## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
+## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 371 datapoints. Try higher ef value
-## 2026-10-16 14:21:59 Merging 29 clusters down to 6 via hierarchical clustering
-## 2026-10-16 14:21:59 Pseudobulking matrix
-## 2026-10-16 14:22:00 Starting Iterative LSI iteration 2 of 2
-## 2026-10-16 14:22:00 Selecting features
-## 2026-10-16 14:22:01 Running LSI
-## 2026-10-16 14:22:01 Starting LSI
-## 2026-10-16 14:22:02 Normalizing matrix
-## 2026-10-16 14:22:05 Calculating SVD
-## 2026-10-16 14:22:10 Finished running Iterative LSI
-## 2026-10-16 14:22:10 Projecting simulated doublets on LSI space
-## 2026-10-16 14:23:03 Running UMAP fitting on LSI matrix
-## 14:23:03 Using HNSW for nearest neighbor search
-## 14:23:03 UMAP embedding parameters a = 0.7669 b = 1.223
-## 14:23:03 Setting random seed 1
-## 14:23:03 Read 13164 rows and found 30 numeric columns
-## 14:23:03 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 14:23:04 Finished building index
-## 14:23:04 Searching HNSW index with ef = 40 and 4 threads
-## 14:23:05 Finished searching
-## 14:23:06 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 14:23:07 Initializing from normalized Laplacian + noise (using RSpectra)
-## 14:23:07 Range-scaling initial input columns to 0-10
-## 14:23:07 Commencing optimization for 500 epochs, with 946616 positive edges using 4 threads
-## 14:23:07 Using rng type: pcg
-## 14:23:10 Optimization finished
-## 2026-10-16 14:23:10 Validating re-projection Pearson correlation
-## 14:23:10 Setting model random seed 1
-## 14:23:10 Read 13164 rows and found 30 numeric columns
-## 14:23:10 Processing block 1 of 1
-## 14:23:10 Searching HNSW index with ef = 40 and 4 threads
-## 14:23:10 Finished searching
-## 14:23:10 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 14:23:10 Initializing by weighted average of neighbor coordinates using 4 threads
-## 14:23:10 Commencing optimization for 167 epochs, with 526560 positive edges using 4 threads
-## 14:23:11 Finished
-## 2026-10-16 14:23:11 UMAP Re-projection Correlation: R^2 = 0.902
-## 2026-10-16 14:23:11 Projecting simulated doublets on UMAP space
-## 14:23:11 Setting model random seed 1
-## 14:23:11 Read 65000 rows and found 30 numeric columns
-## 14:23:11 Processing block 1 of 1
-## 14:23:11 Searching HNSW index with ef = 40 and 4 threads
-## 14:23:11 Finished searching
-## 14:23:11 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 14:23:11 Initializing by weighted average of neighbor coordinates using 4 threads
-## 14:23:12 Commencing optimization for 167 epochs, with 2600000 positive edges using 4 threads
-## 14:23:13 Finished
-## 2026-10-16 14:23:13 Compute doublet scores and enrichments from UMAP
-## 14:23:13 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 14:23:14 Finished building index
-## 14:23:14 Searching HNSW index with ef = 200 and 1 threads
-## 14:23:15 Finished searching
-## Filtering doublets in 1 dataset(s): PBMC_10k
-## 2026-10-16 14:23:16 filtering dataset: PBMC_10k.
-## 2026-10-16 14:23:16 Filtering 1732 doublets from 13164 cells (13.2%)
-## 2026-10-16 14:23:16 Dataset successfully filtered.
-## 2026-10-16 14:23:16 Removing stale doublet data
-## 2026-10-16 14:23:16 doublet filtering complete.
+## 2026-10-18 21:47:50 Merging 29 clusters down to 6 via hierarchical clustering, 0.539 mins elapsed.
+## 2026-10-18 21:47:50 Pseudobulking matrix, 0.539 mins elapsed.
+## 2026-10-18 21:47:52 Starting Iterative LSI iteration 2 of 2, 0.565 mins elapsed.
+## 2026-10-18 21:47:52 Selecting features, 0.565 mins elapsed.
+## 2026-10-18 21:47:53 Running LSI, 0.586 mins elapsed.
+## 2026-10-18 21:47:53 Starting LSI, 0.586 mins elapsed.
+## 2026-10-18 21:47:54 Normalizing matrix, 0.607 mins elapsed.
+## 2026-10-18 21:47:57 Calculating SVD, 0.647 mins elapsed.
+## 2026-10-18 21:48:04 Finished running Iterative LSI, 0.766 mins elapsed.
+## 2026-10-18 21:48:04 Projecting simulated doublets on LSI space, 0.766 mins elapsed.
+## 2026-10-18 21:48:54 Running UMAP fitting on LSI matrix, 1.602 mins elapsed.
+## 21:48:54 Using HNSW for nearest neighbor search
+## 21:48:54 UMAP embedding parameters a = 0.7669 b = 1.223
+## 21:48:54 Setting random seed 1
+## 21:48:54 Read 13164 rows and found 30 numeric columns
+## 21:48:54 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 21:48:54 Finished building index
+## 21:48:54 Searching HNSW index with ef = 40 and 4 threads
+## 21:48:55 Finished searching
+## 21:48:56 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:48:57 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:48:57 Range-scaling initial input columns to 0-10
+## 21:48:57 Commencing optimization for 500 epochs, with 946616 positive edges using 4 threads
+## 21:48:57 Using rng type: pcg
+## 21:49:00 Optimization finished
+## 2026-10-18 21:49:00 Validating re-projection Pearson correlation, 1.705 mins elapsed.
+## 21:49:00 Setting model random seed 1
+## 21:49:00 Read 13164 rows and found 30 numeric columns
+## 21:49:00 Processing block 1 of 1
+## 21:49:00 Searching HNSW index with ef = 40 and 4 threads
+## 21:49:00 Finished searching
+## 21:49:00 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:49:00 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:49:00 Commencing optimization for 167 epochs, with 526560 positive edges using 4 threads
+## 21:49:01 Finished
+## 2026-10-18 21:49:01 UMAP Re-projection Correlation: R^2 = 0.902, 1.716 mins elapsed.
+## 2026-10-18 21:49:01 Projecting simulated doublets on UMAP space, 1.716 mins elapsed.
+## 21:49:01 Setting model random seed 1
+## 21:49:01 Read 65000 rows and found 30 numeric columns
+## 21:49:01 Processing block 1 of 1
+## 21:49:01 Searching HNSW index with ef = 40 and 4 threads
+## 21:49:01 Finished searching
+## 21:49:01 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:49:01 Initializing by weighted average of neighbor coordinates using 4 threads
+## 21:49:02 Commencing optimization for 167 epochs, with 2600000 positive edges using 4 threads
+## 21:49:04 Finished
+## 2026-10-18 21:49:04 Compute doublet scores and enrichments from UMAP, 1.771 mins elapsed.
+## 21:49:04 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:49:04 Finished building index
+## 21:49:04 Searching HNSW index with ef = 200 and 1 threads
+## 21:49:06 Finished searching
+## ###########
+## 2026-10-18 21:49:07 Filtering doublets in 1 dataset(s): PBMC_10k, 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:49:07 filtering dataset: PBMC_10k, 0.000 mins elapsed.
+## 2026-10-18 21:49:07 Filtering 1732 doublets from 13164 cells (13.2%), 0.000 mins elapsed.
+## 2026-10-18 21:49:07 Dataset successfully filtered, 0.000 mins elapsed.
+## 2026-10-18 21:49:07 Removing stale doublet data, 0.000 mins elapsed.
+## 2026-10-18 21:49:07 doublet filtering complete, 0.000 mins elapsed.
 
@@ -1697,7 +1709,9 @@

Import RNA

proj <- import_feature_matrix_10x(proj, input = rna_h5)
proj <- align_cells(proj)
 head(get_feature_metadata(proj, assay_names = "GeneExpressionMatrix"))
-
Output
## 2026-10-16 14:23:16 Barcode intersection: 10010 shared, 1422 ATAC-only dropped, 2002 RNA-only dropped.
+
Output
## ###########
+## 2026-10-18 21:49:07 Barcode intersection: 10010 shared, 1422 ATAC-only dropped, 2002 RNA-only dropped, 0.005 mins elapsed.
+## ###########
 ##                 gene_symbol           assay_name
 ## ENSG00000243485 MIR1302-2HG GeneExpressionMatrix
 ## ENSG00000237613     FAM138A GeneExpressionMatrix
@@ -1727,52 +1741,64 @@ 

Iterative LSI

feature_selection_method = select_features_variance(num_feats = 2500L), verbose = TRUE )
-
Output
## 2026-10-16 14:23:25 Starting Iterative LSI
-## 2026-10-16 14:23:25 Starting Iterative LSI iteration 1 of 2
-## 2026-10-16 14:23:25 Selecting features
-## 2026-10-16 14:23:27 Running LSI
-## 2026-10-16 14:23:27 Starting LSI
-## 2026-10-16 14:23:31 Filtering 401 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-16 14:23:35 Normalizing matrix
-## 2026-10-16 14:23:43 Calculating SVD
-## 2026-10-16 14:23:55 Dropping PCs 1 due to high correlation with sequencing depth
-## 2026-10-16 14:23:55 Re-projecting outlier cells into LSI space
-## 2026-10-16 14:24:05 Clustering LSI results
-## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
+
Output
## ###########
+## 2026-10-18 21:49:16 Starting Iterative LSI, 0.149 mins elapsed.
+## ###########
+## 2026-10-18 21:49:16 Starting Iterative LSI iteration 1 of 2, 0.149 mins elapsed.
+## 2026-10-18 21:49:16 Selecting features, 0.149 mins elapsed.
+## 2026-10-18 21:49:19 Running LSI, 0.196 mins elapsed.
+## 2026-10-18 21:49:19 Starting LSI, 0.204 mins elapsed.
+## 2026-10-18 21:49:24 Filtering 401 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.278 mins elapsed.
+## 2026-10-18 21:49:27 Normalizing matrix, 0.340 mins elapsed.
+## 2026-10-18 21:49:36 Calculating SVD, 0.483 mins elapsed.
+## 2026-10-18 21:49:48 Dropping PCs 1 due to high correlation with sequencing depth, 0.685 mins elapsed.
+## 2026-10-18 21:49:48 Re-projecting outlier cells into LSI space, 0.685 mins elapsed.
+## 2026-10-18 21:49:57 Clustering LSI results, 0.837 mins elapsed.
+## 21:49:57 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:49:58 Finished building index
+## 21:49:58 Searching HNSW index with ef = 100 and 1 threads
+## 21:49:58 Finished searching
+## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 1 datapoints. Try higher ef value
-## 2026-10-16 14:24:07 Merging 22 clusters down to 6 via hierarchical clustering
-## 2026-10-16 14:24:07 Pseudobulking matrix
-## 2026-10-16 14:24:13 Starting Iterative LSI iteration 2 of 2
-## 2026-10-16 14:24:13 Selecting features
-## 2026-10-16 14:24:13 Running LSI
-## 2026-10-16 14:24:14 Starting LSI
-## 2026-10-16 14:24:16 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-16 14:24:20 Normalizing matrix
-## 2026-10-16 14:24:28 Calculating SVD
-## 2026-10-16 14:24:35 Dropping PCs 1 due to high correlation with sequencing depth
-## 2026-10-16 14:24:35 Re-projecting outlier cells into LSI space
-## 2026-10-16 14:24:44 Finished running Iterative LSI
-## 2026-10-16 14:25:07 Starting Iterative LSI
-## 2026-10-16 14:25:07 Starting Iterative LSI iteration 1 of 2
-## 2026-10-16 14:25:07 Selecting features
-## 2026-10-16 14:25:30 Running LSI
-## 2026-10-16 14:25:30 Starting LSI
-## 2026-10-16 14:25:33 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-16 14:25:36 Normalizing matrix
-## 2026-10-16 14:25:42 Calculating SVD
-## 2026-10-16 14:25:44 Re-projecting outlier cells into LSI space
-## 2026-10-16 14:25:46 Clustering LSI results
-## 2026-10-16 14:25:48 Merging 27 clusters down to 6 via hierarchical clustering
-## 2026-10-16 14:25:48 Pseudobulking matrix
-## 2026-10-16 14:25:50 Starting Iterative LSI iteration 2 of 2
-## 2026-10-16 14:25:50 Selecting features
-## 2026-10-16 14:25:50 Running LSI
-## 2026-10-16 14:25:50 Starting LSI
-## 2026-10-16 14:26:13 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-16 14:26:35 Normalizing matrix
-## 2026-10-16 14:27:19 Calculating SVD
-## 2026-10-16 14:27:20 Re-projecting outlier cells into LSI space
-## 2026-10-16 14:27:22 Finished running Iterative LSI
+## 2026-10-18 21:49:58 Merging 22 clusters down to 6 via hierarchical clustering, 0.859 mins elapsed.
+## 2026-10-18 21:49:58 Pseudobulking matrix, 0.859 mins elapsed.
+## 2026-10-18 21:50:05 Starting Iterative LSI iteration 2 of 2, 0.967 mins elapsed.
+## 2026-10-18 21:50:05 Selecting features, 0.967 mins elapsed.
+## 2026-10-18 21:50:06 Running LSI, 0.977 mins elapsed.
+## 2026-10-18 21:50:06 Starting LSI, 0.977 mins elapsed.
+## 2026-10-18 21:50:09 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD, 1.039 mins elapsed.
+## 2026-10-18 21:50:13 Normalizing matrix, 1.106 mins elapsed.
+## 2026-10-18 21:50:21 Calculating SVD, 1.235 mins elapsed.
+## 2026-10-18 21:50:28 Dropping PCs 1 due to high correlation with sequencing depth, 1.358 mins elapsed.
+## 2026-10-18 21:50:28 Re-projecting outlier cells into LSI space, 1.358 mins elapsed.
+## 2026-10-18 21:50:37 Finished running Iterative LSI, 1.495 mins elapsed.
+## ###########
+## 2026-10-18 21:51:01 Starting Iterative LSI, 0.405 mins elapsed.
+## ###########
+## 2026-10-18 21:51:01 Starting Iterative LSI iteration 1 of 2, 0.405 mins elapsed.
+## 2026-10-18 21:51:01 Selecting features, 0.405 mins elapsed.
+## 2026-10-18 21:51:24 Running LSI, 0.796 mins elapsed.
+## 2026-10-18 21:51:24 Starting LSI, 0.796 mins elapsed.
+## 2026-10-18 21:51:28 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.848 mins elapsed.
+## 2026-10-18 21:51:31 Normalizing matrix, 0.899 mins elapsed.
+## 2026-10-18 21:51:36 Calculating SVD, 0.990 mins elapsed.
+## 2026-10-18 21:51:37 Re-projecting outlier cells into LSI space, 1.008 mins elapsed.
+## 2026-10-18 21:51:40 Clustering LSI results, 1.048 mins elapsed.
+## 21:51:40 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:51:40 Finished building index
+## 21:51:40 Searching HNSW index with ef = 100 and 1 threads
+## 21:51:41 Finished searching
+## 2026-10-18 21:51:41 Merging 27 clusters down to 6 via hierarchical clustering, 1.068 mins elapsed.
+## 2026-10-18 21:51:41 Pseudobulking matrix, 1.068 mins elapsed.
+## 2026-10-18 21:51:44 Starting Iterative LSI iteration 2 of 2, 1.119 mins elapsed.
+## 2026-10-18 21:51:44 Selecting features, 1.119 mins elapsed.
+## 2026-10-18 21:51:44 Running LSI, 1.119 mins elapsed.
+## 2026-10-18 21:51:44 Starting LSI, 1.119 mins elapsed.
+## 2026-10-18 21:52:06 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD, 1.496 mins elapsed.
+## 2026-10-18 21:52:29 Normalizing matrix, 1.868 mins elapsed.
+## 2026-10-18 21:53:13 Calculating SVD, 2.598 mins elapsed.
+## 2026-10-18 21:53:14 Re-projecting outlier cells into LSI space, 2.614 mins elapsed.
+## 2026-10-18 21:53:16 Finished running Iterative LSI, 2.663 mins elapsed.
 
@@ -1797,12 +1823,18 @@

Clustering

verbose = TRUE )
table(get_cell_metadata(proj)$clusters)
-
Output
## 2026-10-16 14:27:23 Extracting embedding 'LSI_Combined'
-## 2026-10-16 14:27:23 Clustering 10010 cells with 59 dimensions
-## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
+
Output
## ###########
+## 2026-10-18 21:53:17 Extracting embedding 'LSI_Combined', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:53:17 Clustering 10010 cells with 59 dimensions, 0.000 mins elapsed.
+## 21:53:17 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 21:53:17 Finished building index
+## 21:53:17 Searching HNSW index with ef = 100 and 1 threads
+## 21:53:18 Finished searching
+## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 2 datapoints. Try higher ef value
-## Found 16 clusters
-## 2026-10-16 14:27:24 Added 16 clusters as 'clusters' in cell metadata
+## 2026-10-18 21:53:18 Found 16 clusters, 0.028 mins elapsed.
+## 2026-10-18 21:53:18 Added 16 clusters as 'clusters' in cell metadata, 0.029 mins elapsed.
 ## 
 ##   C1  C10  C11  C12  C13  C14  C15  C16   C2   C3   C4   C5   C6   C7   C8   C9 
 ##  228 2852  477   98   34  338  364  401 1092 1143 1128  343  657  124  567  164
@@ -1820,57 +1852,63 @@ 

UMAP Embedding

verbose = TRUE ) }
-
Output
## 2026-10-16 14:27:24 Extracting embedding 'LSI_ATAC'
-## 2026-10-16 14:27:24 Computing UMAP on 10010 cells with 29 dimensions
-## 14:27:24 Using HNSW for nearest neighbor search
-## 14:27:24 UMAP embedding parameters a = 0.2321 b = 1.681
-## 14:27:24 Setting random seed 1
-## 14:27:24 Read 10010 rows and found 29 numeric columns
-## 14:27:24 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 14:27:25 Finished building index
-## 14:27:25 Searching HNSW index with ef = 40 and 4 threads
-## 14:27:25 Finished searching
-## 14:27:26 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 14:27:27 Initializing from normalized Laplacian + noise (using RSpectra)
-## 14:27:27 Range-scaling initial input columns to 0-10
-## 14:27:27 Commencing optimization for 500 epochs, with 586026 positive edges using 4 threads
-## 14:27:27 Using rng type: pcg
-## 14:27:30 Optimization finished
-## 2026-10-16 14:27:30 Added UMAP embedding as 'UMAP_ATAC' (2 components)
-## 2026-10-16 14:27:30 Extracting embedding 'LSI_RNA'
-## 2026-10-16 14:27:30 Computing UMAP on 10010 cells with 30 dimensions
-## 14:27:30 Using HNSW for nearest neighbor search
-## 14:27:30 UMAP embedding parameters a = 0.2321 b = 1.681
-## 14:27:30 Setting random seed 1
-## 14:27:30 Read 10010 rows and found 30 numeric columns
-## 14:27:30 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 14:27:31 Finished building index
-## 14:27:31 Searching HNSW index with ef = 40 and 4 threads
-## 14:27:31 Finished searching
-## 14:27:32 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 14:27:33 Initializing from normalized Laplacian + noise (using RSpectra)
-## 14:27:33 Range-scaling initial input columns to 0-10
-## 14:27:33 Commencing optimization for 500 epochs, with 573228 positive edges using 4 threads
-## 14:27:33 Using rng type: pcg
-## 14:27:36 Optimization finished
-## 2026-10-16 14:27:36 Added UMAP embedding as 'UMAP_RNA' (2 components)
-## 2026-10-16 14:27:36 Extracting embedding 'LSI_Combined'
-## 2026-10-16 14:27:36 Computing UMAP on 10010 cells with 59 dimensions
-## 14:27:36 Using HNSW for nearest neighbor search
-## 14:27:36 UMAP embedding parameters a = 0.2321 b = 1.681
-## 14:27:36 Setting random seed 1
-## 14:27:36 Read 10010 rows and found 59 numeric columns
-## 14:27:36 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 14:27:37 Finished building index
-## 14:27:37 Searching HNSW index with ef = 40 and 4 threads
-## 14:27:37 Finished searching
-## 14:27:38 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 14:27:39 Initializing from normalized Laplacian + noise (using RSpectra)
-## 14:27:39 Range-scaling initial input columns to 0-10
-## 14:27:39 Commencing optimization for 500 epochs, with 587204 positive edges using 4 threads
-## 14:27:39 Using rng type: pcg
-## 14:27:42 Optimization finished
-## 2026-10-16 14:27:42 Added UMAP embedding as 'UMAP_Combined' (2 components)
+
Output
## ###########
+## 2026-10-18 21:53:18 Extracting embedding 'LSI_ATAC', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:53:18 Computing UMAP on 10010 cells with 29 dimensions, 0.000 mins elapsed.
+## 21:53:18 Using HNSW for nearest neighbor search
+## 21:53:18 UMAP embedding parameters a = 0.2321 b = 1.681
+## 21:53:18 Setting random seed 1
+## 21:53:18 Read 10010 rows and found 29 numeric columns
+## 21:53:18 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
+## 21:53:19 Finished building index
+## 21:53:19 Searching HNSW index with ef = 40 and 4 threads
+## 21:53:19 Finished searching
+## 21:53:20 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:53:21 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:53:21 Range-scaling initial input columns to 0-10
+## 21:53:21 Commencing optimization for 500 epochs, with 586026 positive edges using 4 threads
+## 21:53:21 Using rng type: pcg
+## 21:53:24 Optimization finished
+## 2026-10-18 21:53:24 Added UMAP embedding as 'UMAP_ATAC' (2 components), 0.096 mins elapsed.
+## ###########
+## 2026-10-18 21:53:24 Extracting embedding 'LSI_RNA', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:53:24 Computing UMAP on 10010 cells with 30 dimensions, 0.000 mins elapsed.
+## 21:53:24 Using HNSW for nearest neighbor search
+## 21:53:24 UMAP embedding parameters a = 0.2321 b = 1.681
+## 21:53:24 Setting random seed 1
+## 21:53:24 Read 10010 rows and found 30 numeric columns
+## 21:53:24 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
+## 21:53:25 Finished building index
+## 21:53:25 Searching HNSW index with ef = 40 and 4 threads
+## 21:53:25 Finished searching
+## 21:53:26 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:53:27 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:53:27 Range-scaling initial input columns to 0-10
+## 21:53:27 Commencing optimization for 500 epochs, with 573228 positive edges using 4 threads
+## 21:53:27 Using rng type: pcg
+## 21:53:30 Optimization finished
+## 2026-10-18 21:53:30 Added UMAP embedding as 'UMAP_RNA' (2 components), 0.095 mins elapsed.
+## ###########
+## 2026-10-18 21:53:30 Extracting embedding 'LSI_Combined', 0.000 mins elapsed.
+## ###########
+## 2026-10-18 21:53:30 Computing UMAP on 10010 cells with 59 dimensions, 0.000 mins elapsed.
+## 21:53:30 Using HNSW for nearest neighbor search
+## 21:53:30 UMAP embedding parameters a = 0.2321 b = 1.681
+## 21:53:30 Setting random seed 1
+## 21:53:30 Read 10010 rows and found 59 numeric columns
+## 21:53:30 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
+## 21:53:31 Finished building index
+## 21:53:31 Searching HNSW index with ef = 40 and 4 threads
+## 21:53:31 Finished searching
+## 21:53:32 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 21:53:33 Initializing from normalized Laplacian + noise (using RSpectra)
+## 21:53:33 Range-scaling initial input columns to 0-10
+## 21:53:33 Commencing optimization for 500 epochs, with 587204 positive edges using 4 threads
+## 21:53:33 Using rng type: pcg
+## 21:53:35 Optimization finished
+## 2026-10-18 21:53:36 Added UMAP embedding as 'UMAP_Combined' (2 components), 0.097 mins elapsed.
 

All three embeddings, colored by the joint clusters:

plot_embedding(proj, embedding = "UMAP_ATAC", title = "ATAC") +

From d32b8dec82f38047dc21f458505153f99c48cec8 Mon Sep 17 00:00:00 2001
From: erliuu 
Date: Mon, 19 Oct 2026 21:35:02 -0700
Subject: [PATCH 04/12] feat([r] logging): Add run total logging addition and
 tests

---
 R/dimensionality_reduction.R                  |   7 -
 R/doublet.R                                   |   2 -
 R/imputation.R                                |   2 -
 R/peaks.R                                     |   1 -
 R/rna_integration.R                           |   1 -
 R/utils.R                                     |  22 +-
 .../testthat/test-dimensionality_reduction.R  |   4 +-
 tests/testthat/test-utils.R                   |  39 +-
 vignettes/marchr_hematopoiesis.html           | 588 +++++++++---------
 9 files changed, 330 insertions(+), 336 deletions(-)

diff --git a/R/dimensionality_reduction.R b/R/dimensionality_reduction.R
index 05331c6..4b58255 100644
--- a/R/dimensionality_reduction.R
+++ b/R/dimensionality_reduction.R
@@ -1545,9 +1545,6 @@ IterativeLSI.default <- function(
       threads = 1L
     )
   }
-  if (verbose) {
-    log_progress("Finished running Iterative LSI")
-  }
 
   # Apply scale_dims to final embeddings so the stored result is ready for
   # direct use by downstream functions (clustering, UMAP, imputation)
@@ -2057,10 +2054,6 @@ PCA.default <- function(
   rownames(pc_embeddings) <- colnames(x)
   colnames(pc_embeddings) <- paste0("PC_", 1:n_dimensions)
 
-  if (verbose) {
-    log_progress("PCA complete")
-  }
-
   # Get the actual variable feature names after selection
   variable_feature_names <- if (!is.null(rownames(x))) {
     rownames(x)[variable_features]
diff --git a/R/doublet.R b/R/doublet.R
index 787722f..3c18ee5 100644
--- a/R/doublet.R
+++ b/R/doublet.R
@@ -941,8 +941,6 @@ filter_doublets.MarchRProject <- function(
       clear_doublet_data = clear_doublet_data,
       verbose = verbose
     )
-
-    if (verbose) log_progress("doublet filtering complete.")
   }
   return(proj)
 }
diff --git a/R/imputation.R b/R/imputation.R
index 72f8b61..6759e7b 100644
--- a/R/imputation.R
+++ b/R/imputation.R
@@ -175,8 +175,6 @@ add_impute_weights <- function(
     )
   )
 
-  if (verbose) log_progress("Completed MAGIC imputation weights.")
-
   return(proj)
 }
 
diff --git a/R/peaks.R b/R/peaks.R
index b102e50..c1ec56c 100644
--- a/R/peaks.R
+++ b/R/peaks.R
@@ -442,7 +442,6 @@ add_peak_matrix.MarchRProject <- function(
   rownames(peak_metadata) <- peak_names
   proj$feature_metadata[[output_assay_name]] <- peak_metadata
 
-  if (verbose) log_progress("Done.")
   return(proj)
 }
 
diff --git a/R/rna_integration.R b/R/rna_integration.R
index 56a903a..0aa2c41 100644
--- a/R/rna_integration.R
+++ b/R/rna_integration.R
@@ -349,7 +349,6 @@ add_gene_integration_matrix.MarchRProject <- function(
                             overwrite = overwrite)
     }
   }
-  if (verbose) log_progress("Done.")
   proj
 }
 
diff --git a/R/utils.R b/R/utils.R
index 6171c3f..4e660d7 100644
--- a/R/utils.R
+++ b/R/utils.R
@@ -103,19 +103,25 @@ selection_index <- function(selection, dim_len, dimnames) {
   if (!is.null(.log_clock$start)) {
     return(invisible())
   }
-  do.call(on.exit, list(quote(.log_clock$start <- NULL), add = TRUE), envir = envir)
+  exit_expr <- quote(.end_log_run(returnValue(.log_clock), environment()))
+  do.call(on.exit, list(exit_expr, add = TRUE), envir = envir)
   .log_clock$start <- Sys.time()
-  .log_clock$new_run <- TRUE
+  .log_clock$printed <- FALSE
+}
+
+# Clears the run clock. returnValue() gives back .log_clock itself when the run ended in an error.
+.end_log_run <- function(returned, envir) {
+  start <- .log_clock$start
+  .log_clock$start <- NULL
+  if (!identical(returned, .log_clock) && isTRUE(.log_clock$printed) &&
+      isTRUE(get0("verbose", envir = envir, inherits = FALSE))) {
+    log_progress(sprintf("Finished (%.1fs)", as.numeric(difftime(Sys.time(), start, units = "secs"))))
+  }
 }
 
 # Messages with header = TRUE is framed by hashmarks.
 log_progress <- function(msg, header = FALSE) {
-  if (!is.null(.log_clock$start)) {
-    mins <- as.numeric(difftime(Sys.time(), .log_clock$start, units = "mins"))
-    msg <- sprintf("%s, %.3f mins elapsed.", sub("\\.+$", "", msg), mins)
-    header <- header || .log_clock$new_run
-    .log_clock$new_run <- FALSE
-  }
+  .log_clock$printed <- TRUE
   msg <- add_timestamp(msg)
   if (header) {
     msg <- paste("###########", msg, "###########", sep = "\n")
diff --git a/tests/testthat/test-dimensionality_reduction.R b/tests/testthat/test-dimensionality_reduction.R
index 9641967..792689d 100644
--- a/tests/testthat/test-dimensionality_reduction.R
+++ b/tests/testthat/test-dimensionality_reduction.R
@@ -1079,12 +1079,12 @@ test_that("PCA removes its on-disk normalization cache", {
   expect_equal(ncol(pca_res$cell_embeddings), 5)
 })
 
-test_that("LSI logs elapsed time and leaves no run clock behind", {
+test_that("LSI reports its total time and leaves no run clock behind", {
   set.seed(1)
   counts <- matrix(rpois(100 * 200, lambda = 2), nrow = 100,
                    dimnames = list(paste0("f", 1:100), paste0("c", 1:200)))
   mat <- methods::as(methods::as(counts, "dgCMatrix"), "IterableMatrix")
   msgs <- capture_messages(LSI(mat, n_dimensions = 5, verbose = TRUE))
-  expect_match(msgs, "Starting LSI, [0-9.]+ mins elapsed", all = FALSE)
+  expect_equal(sum(grepl("Finished \\([0-9]+\\.[0-9]s\\)", msgs)), 1L)
   expect_null(.log_clock$start)
 })
diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R
index 964db35..cedde41 100644
--- a/tests/testthat/test-utils.R
+++ b/tests/testthat/test-utils.R
@@ -7,29 +7,44 @@ test_that(".get_quantiles matches trunc(rank(v))/length(v) and handles ties", {
   expect_equal(.get_quantiles(numeric(0)), numeric(0))
 })
 
-test_that("log_progress prints a timestamp and no elapsed time without a run clock", {
+test_that("log_progress prints a timestamp and the message", {
   expect_null(.log_clock$start)
   msgs <- capture_messages(log_progress("Computing LSI"))
   expect_match(msgs, "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Computing LSI\n$", perl = TRUE)
 })
 
-test_that("log_progress adds elapsed minutes, and a header on the first message of a run", {
+test_that("messages inside a run carry only a timestamp", {
   run <- function() {
     .start_log_clock()
     log_progress("Calling peaks...")
-    log_progress("Filtering peaks")
-    log_progress("Running LSI (1 of 2)", header = TRUE)
   }
   msgs <- capture_messages(run())
+  expect_match(msgs, "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Calling peaks\\.\\.\\.\n$", perl = TRUE)
+})
+
+test_that("a verbose run that printed something reports its total time on a normal return", {
+  run <- function(verbose, say = TRUE, fail = FALSE) {
+    .start_log_clock()
+    if (say) log_progress("Working")
+    if (fail) rlang::abort("boom")
+    invisible(NULL)
+  }
+  outer <- function(verbose) {
+    .start_log_clock()
+    run(verbose = TRUE)
+  }
+
+  msgs <- capture_messages(run(verbose = TRUE))
+  expect_length(msgs, 2)
   expect_match(
-    msgs[1], "^###########\n[^\n]+ Calling peaks, [0-9]+\\.[0-9]{3} mins elapsed\\.\n###########\n$",
-    perl = TRUE
-  )
-  expect_match(msgs[2], "^[^#][^\n]+ Filtering peaks, [0-9.]+ mins elapsed\\.\n$", perl = TRUE)
-  expect_match(
-    msgs[3], "^###########\n[^\n]+ Running LSI \\(1 of 2\\), [0-9.]+ mins elapsed\\.\n###########\n$",
-    perl = TRUE
+    msgs[2], "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Finished \\([0-9]+\\.[0-9]s\\)\n$", perl = TRUE
   )
+  expect_length(capture_messages(run(verbose = FALSE)), 1)
+  expect_length(capture_messages(run(verbose = TRUE, say = FALSE)), 0)
+  expect_length(capture_messages(try(run(verbose = TRUE, fail = TRUE), silent = TRUE)), 1)
+  expect_length(capture_messages(outer(verbose = TRUE)), 2)
+  expect_length(capture_messages(outer(verbose = FALSE)), 1)
+  expect_null(.log_clock$start)
 })
 
 test_that("nested calls share one run clock that is cleared on return and on error", {
@@ -56,7 +71,7 @@ test_that("nested calls share one run clock that is cleared on return and on err
   expect_null(.log_clock$start)
 })
 
-test_that("log_progress header = TRUE frames a message without a run clock", {
+test_that("log_progress header = TRUE frames a message", {
   msgs <- capture_messages(log_progress("Running LSI (1 of 2)", header = TRUE))
   expect_match(msgs, "^###########\n[^\n]+ Running LSI \\(1 of 2\\)\n###########\n$", perl = TRUE)
 })
diff --git a/vignettes/marchr_hematopoiesis.html b/vignettes/marchr_hematopoiesis.html
index 76a7daa..e8066f2 100644
--- a/vignettes/marchr_hematopoiesis.html
+++ b/vignettes/marchr_hematopoiesis.html
@@ -1577,7 +1577,7 @@ 

Initialize a MarchRProject

} proj
Output
## MarchRProject Object
-## Directory: /tmp/RtmplouxB8/marchr_project
+## Directory: /tmp/RtmpVp380g/marchr_project
 ## 3 Datasets:
 ##   scATAC_BMMC_R1:
 ##     5000 cells: scATAC_BMMC_R1#TAGGAGGGTTAACCGT-1, scATAC_BMMC_R1#CCTTGGTAGTTCTCCC-1, scATAC_BMMC_R1#GCCAGCAGTTCTGAGT-1, scATAC_BMMC_R1#TAGCATGGTGACCAGA-1 ... scATAC_BMMC_R1#CTGCTCAAGTGTCGGA-1
@@ -1669,221 +1669,217 @@ 

Doublet Scoring and Filtering

assay_name = "TileMatrix", verbose = TRUE )
-
Output
## ###########
-## 2026-10-18 21:15:59 Processing dataset 1 of 3: scATAC_BMMC_R1, 0.006 mins elapsed.
-## ###########
-## 2026-10-18 21:16:04 Simulating 20000 synthetic doublets (1000 doublets x 20 trials), 0.095 mins elapsed.
-## 2026-10-18 21:16:04 Running Iterative LSI on input matrix, 0.095 mins elapsed.
-## 2026-10-18 21:16:06 Starting Iterative LSI, 0.115 mins elapsed.
-## 2026-10-18 21:16:06 Starting Iterative LSI iteration 1 of 2, 0.115 mins elapsed.
-## 2026-10-18 21:16:06 Selecting features, 0.115 mins elapsed.
-## 2026-10-18 21:16:09 Running LSI, 0.166 mins elapsed.
-## 2026-10-18 21:16:09 Starting LSI, 0.167 mins elapsed.
-## 2026-10-18 21:16:09 Normalizing matrix, 0.171 mins elapsed.
+
Output
## 2026-10-19 19:07:35 Processing dataset 1 of 3: scATAC_BMMC_R1
+## 2026-10-19 19:07:38 Simulating 20000 synthetic doublets (1000 doublets x 20 trials)
+## 2026-10-19 19:07:38 Running Iterative LSI on input matrix
+## 2026-10-19 19:07:39 Starting Iterative LSI
+## 2026-10-19 19:07:39 Starting Iterative LSI iteration 1 of 2
+## 2026-10-19 19:07:39 Selecting features
+## 2026-10-19 19:07:42 Running LSI
+## 2026-10-19 19:07:42 Starting LSI
+## 2026-10-19 19:07:42 Normalizing matrix
 ## Warning: Matrix compression performs poorly with non-integers.
 ## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
-## 2026-10-18 21:16:09 Calculating SVD, 0.178 mins elapsed.
+## 2026-10-19 19:07:42 Calculating SVD
 ## 
-## 2026-10-18 21:16:10 Clustering LSI results, 0.192 mins elapsed.
+## 2026-10-19 19:07:43 Clustering LSI results
 ## 
-## 21:16:10 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:07:43 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
 ## 
-## 21:16:10 Finished building index
+## 19:07:43 Finished building index
 ## 
-## 21:16:10 Searching HNSW index with ef = 100 and 1 threads
+## 19:07:43 Searching HNSW index with ef = 100 and 1 threads
 ## 
-## 21:16:11 Finished searching
+## 19:07:43 Finished searching
 ## 
 ## This message is displayed once every 8 hours.
 ## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-## 2026-10-18 21:16:11 Merging 15 clusters down to 6 via hierarchical clustering, 0.203 mins elapsed.
-## 2026-10-18 21:16:11 Pseudobulking matrix, 0.203 mins elapsed.
-## 2026-10-18 21:16:12 Starting Iterative LSI iteration 2 of 2, 0.215 mins elapsed.
-## 2026-10-18 21:16:12 Selecting features, 0.215 mins elapsed.
-## 2026-10-18 21:16:12 Running LSI, 0.218 mins elapsed.
-## 2026-10-18 21:16:12 Starting LSI, 0.218 mins elapsed.
-## 2026-10-18 21:16:12 Normalizing matrix, 0.222 mins elapsed.
-## 2026-10-18 21:16:12 Calculating SVD, 0.227 mins elapsed.
-## 2026-10-18 21:16:13 Finished running Iterative LSI, 0.234 mins elapsed.
-## 2026-10-18 21:16:13 Projecting simulated doublets on LSI space, 0.234 mins elapsed.
-## 2026-10-18 21:16:20 Running UMAP fitting on LSI matrix, 0.350 mins elapsed.
-## 21:16:20 Using HNSW for nearest neighbor search
-## 21:16:20 UMAP embedding parameters a = 0.7669 b = 1.223
-## 21:16:20 Setting random seed 1
-## 21:16:20 Read 4939 rows and found 30 numeric columns
-## 21:16:20 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 21:16:20 Finished building index
-## 21:16:20 Searching HNSW index with ef = 40 and 4 threads
-## 21:16:20 Finished searching
-## 21:16:21 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:16:22 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:16:22 Range-scaling initial input columns to 0-10
-## 21:16:22 Commencing optimization for 500 epochs, with 342252 positive edges using 4 threads
-## 21:16:22 Using rng type: pcg
-## 21:16:24 Optimization finished
-## 2026-10-18 21:16:24 Validating re-projection Pearson correlation, 0.429 mins elapsed.
-## 21:16:24 Setting model random seed 1
-## 21:16:24 Read 4939 rows and found 30 numeric columns
-## 21:16:24 Processing block 1 of 1
-## 21:16:24 Searching HNSW index with ef = 40 and 4 threads
-## 21:16:24 Finished searching
-## 21:16:24 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:16:24 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:16:24 Commencing optimization for 167 epochs, with 197560 positive edges using 4 threads
-## 21:16:25 Finished
-## 2026-10-18 21:16:25 UMAP Re-projection Correlation: R^2 = 0.984, 0.434 mins elapsed.
-## 2026-10-18 21:16:25 Projecting simulated doublets on UMAP space, 0.434 mins elapsed.
-## 21:16:25 Setting model random seed 1
-## 21:16:25 Read 20000 rows and found 30 numeric columns
-## 21:16:25 Processing block 1 of 1
-## 21:16:25 Searching HNSW index with ef = 40 and 4 threads
-## 21:16:25 Finished searching
-## 21:16:25 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:16:25 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:16:25 Commencing optimization for 167 epochs, with 800000 positive edges using 4 threads
-## 21:16:26 Finished
-## 2026-10-18 21:16:26 Compute doublet scores and enrichments from UMAP, 0.455 mins elapsed.
-## 21:16:26 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:16:26 Finished building index
-## 21:16:26 Searching HNSW index with ef = 200 and 1 threads
-## 21:16:27 Finished searching
-## 2026-10-18 21:16:27 Processing dataset 2 of 3: scATAC_CD34_BMMC_R1, 0.467 mins elapsed.
-## 2026-10-18 21:16:31 Simulating 15000 synthetic doublets (1000 doublets x 15 trials), 0.543 mins elapsed.
-## 2026-10-18 21:16:31 Running Iterative LSI on input matrix, 0.543 mins elapsed.
-## 2026-10-18 21:16:32 Starting Iterative LSI, 0.560 mins elapsed.
-## 2026-10-18 21:16:32 Starting Iterative LSI iteration 1 of 2, 0.560 mins elapsed.
-## 2026-10-18 21:16:32 Selecting features, 0.560 mins elapsed.
-## 2026-10-18 21:16:33 Running LSI, 0.580 mins elapsed.
-## 2026-10-18 21:16:33 Starting LSI, 0.581 mins elapsed.
-## 2026-10-18 21:16:34 Normalizing matrix, 0.583 mins elapsed.
-## 2026-10-18 21:16:34 Calculating SVD, 0.587 mins elapsed.
-## 2026-10-18 21:16:35 Clustering LSI results, 0.599 mins elapsed.
-## 21:16:35 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:16:35 Finished building index
-## 21:16:35 Searching HNSW index with ef = 100 and 1 threads
-## 21:16:35 Finished searching
+## 2026-10-19 19:07:44 Merging 15 clusters down to 6 via hierarchical clustering
+## 2026-10-19 19:07:44 Pseudobulking matrix
+## 2026-10-19 19:07:44 Starting Iterative LSI iteration 2 of 2
+## 2026-10-19 19:07:44 Selecting features
+## 2026-10-19 19:07:45 Running LSI
+## 2026-10-19 19:07:45 Starting LSI
+## 2026-10-19 19:07:45 Normalizing matrix
+## 2026-10-19 19:07:45 Calculating SVD
+## 2026-10-19 19:07:46 Projecting simulated doublets on LSI space
+## 2026-10-19 19:07:53 Running UMAP fitting on LSI matrix
+## 19:07:53 Using HNSW for nearest neighbor search
+## 19:07:53 UMAP embedding parameters a = 0.7669 b = 1.223
+## 19:07:53 Setting random seed 1
+## 19:07:53 Read 4939 rows and found 30 numeric columns
+## 19:07:53 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 19:07:53 Finished building index
+## 19:07:53 Searching HNSW index with ef = 40 and 4 threads
+## 19:07:54 Finished searching
+## 19:07:55 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:07:56 Initializing from normalized Laplacian + noise (using RSpectra)
+## 19:07:56 Range-scaling initial input columns to 0-10
+## 19:07:56 Commencing optimization for 500 epochs, with 342252 positive edges using 4 threads
+## 19:07:56 Using rng type: pcg
+## 19:07:58 Optimization finished
+## 2026-10-19 19:07:58 Validating re-projection Pearson correlation
+## 19:07:58 Setting model random seed 1
+## 19:07:58 Read 4939 rows and found 30 numeric columns
+## 19:07:58 Processing block 1 of 1
+## 19:07:58 Searching HNSW index with ef = 40 and 4 threads
+## 19:07:58 Finished searching
+## 19:07:58 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:07:58 Initializing by weighted average of neighbor coordinates using 4 threads
+## 19:07:58 Commencing optimization for 167 epochs, with 197560 positive edges using 4 threads
+## 19:07:58 Finished
+## 2026-10-19 19:07:58 UMAP Re-projection Correlation: R^2 = 0.984
+## 2026-10-19 19:07:58 Projecting simulated doublets on UMAP space
+## 19:07:58 Setting model random seed 1
+## 19:07:58 Read 20000 rows and found 30 numeric columns
+## 19:07:58 Processing block 1 of 1
+## 19:07:58 Searching HNSW index with ef = 40 and 4 threads
+## 19:07:58 Finished searching
+## 19:07:58 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:07:59 Initializing by weighted average of neighbor coordinates using 4 threads
+## 19:07:59 Commencing optimization for 167 epochs, with 800000 positive edges using 4 threads
+## 19:08:00 Finished
+## 2026-10-19 19:08:00 Compute doublet scores and enrichments from UMAP
+## 19:08:00 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:08:00 Finished building index
+## 19:08:00 Searching HNSW index with ef = 200 and 1 threads
+## 19:08:00 Finished searching
+## 2026-10-19 19:08:00 Processing dataset 2 of 3: scATAC_CD34_BMMC_R1
+## 2026-10-19 19:08:06 Simulating 15000 synthetic doublets (1000 doublets x 15 trials)
+## 2026-10-19 19:08:06 Running Iterative LSI on input matrix
+## 2026-10-19 19:08:05 Starting Iterative LSI
+## 2026-10-19 19:08:05 Starting Iterative LSI iteration 1 of 2
+## 2026-10-19 19:08:05 Selecting features
+## 2026-10-19 19:08:06 Running LSI
+## 2026-10-19 19:08:06 Starting LSI
+## 2026-10-19 19:08:06 Normalizing matrix
+## 2026-10-19 19:08:07 Calculating SVD
+## 2026-10-19 19:08:07 Clustering LSI results
+## 19:08:07 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:08:08 Finished building index
+## 19:08:08 Searching HNSW index with ef = 100 and 1 threads
+## 19:08:08 Finished searching
 ## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 16 datapoints. Try higher ef value
-## 2026-10-18 21:16:35 Merging 13 clusters down to 6 via hierarchical clustering, 0.605 mins elapsed.
-## 2026-10-18 21:16:35 Pseudobulking matrix, 0.605 mins elapsed.
-## 2026-10-18 21:16:36 Starting Iterative LSI iteration 2 of 2, 0.616 mins elapsed.
-## 2026-10-18 21:16:36 Selecting features, 0.616 mins elapsed.
-## 2026-10-18 21:16:36 Running LSI, 0.620 mins elapsed.
-## 2026-10-18 21:16:36 Starting LSI, 0.620 mins elapsed.
-## 2026-10-18 21:16:36 Normalizing matrix, 0.623 mins elapsed.
-## 2026-10-18 21:16:36 Calculating SVD, 0.627 mins elapsed.
-## 2026-10-18 21:16:37 Finished running Iterative LSI, 0.636 mins elapsed.
-## 2026-10-18 21:16:37 Projecting simulated doublets on LSI space, 0.636 mins elapsed.
-## 2026-10-18 21:16:43 Running UMAP fitting on LSI matrix, 0.732 mins elapsed.
-## 21:16:43 Using HNSW for nearest neighbor search
-## 21:16:43 UMAP embedding parameters a = 0.7669 b = 1.223
-## 21:16:43 Setting random seed 1
-## 21:16:43 Read 3280 rows and found 30 numeric columns
-## 21:16:43 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 21:16:43 Finished building index
-## 21:16:43 Searching HNSW index with ef = 40 and 4 threads
-## 21:16:43 Finished searching
-## 21:16:44 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:16:44 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:16:45 Range-scaling initial input columns to 0-10
-## 21:16:45 Commencing optimization for 500 epochs, with 208246 positive edges using 4 threads
-## 21:16:45 Using rng type: pcg
-## 21:16:46 Optimization finished
-## 2026-10-18 21:16:46 Validating re-projection Pearson correlation, 0.794 mins elapsed.
-## 21:16:46 Setting model random seed 1
-## 21:16:46 Read 3280 rows and found 30 numeric columns
-## 21:16:46 Processing block 1 of 1
-## 21:16:46 Searching HNSW index with ef = 40 and 4 threads
-## 21:16:46 Finished searching
-## 21:16:46 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:16:46 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:16:46 Commencing optimization for 167 epochs, with 131200 positive edges using 4 threads
-## 21:16:46 Finished
-## 2026-10-18 21:16:46 UMAP Re-projection Correlation: R^2 = 0.994, 0.797 mins elapsed.
-## 2026-10-18 21:16:46 Projecting simulated doublets on UMAP space, 0.797 mins elapsed.
-## 21:16:46 Setting model random seed 1
-## 21:16:46 Read 15000 rows and found 30 numeric columns
-## 21:16:46 Processing block 1 of 1
-## 21:16:46 Searching HNSW index with ef = 40 and 4 threads
-## 21:16:47 Finished searching
-## 21:16:47 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:16:47 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:16:47 Commencing optimization for 167 epochs, with 600000 positive edges using 4 threads
-## 21:16:47 Finished
-## 2026-10-18 21:16:47 Compute doublet scores and enrichments from UMAP, 0.811 mins elapsed.
-## 21:16:47 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:16:47 Finished building index
-## 21:16:47 Searching HNSW index with ef = 200 and 1 threads
-## 21:16:48 Finished searching
-## 2026-10-18 21:16:48 Processing dataset 3 of 3: scATAC_PBMC_R1, 0.819 mins elapsed.
-## 2026-10-18 21:16:53 Simulating 10000 synthetic doublets (1000 doublets x 10 trials), 0.903 mins elapsed.
-## 2026-10-18 21:16:53 Running Iterative LSI on input matrix, 0.903 mins elapsed.
-## 2026-10-18 21:16:54 Starting Iterative LSI, 0.921 mins elapsed.
-## 2026-10-18 21:16:54 Starting Iterative LSI iteration 1 of 2, 0.921 mins elapsed.
-## 2026-10-18 21:16:54 Selecting features, 0.921 mins elapsed.
-## 2026-10-18 21:16:55 Running LSI, 0.941 mins elapsed.
-## 2026-10-18 21:16:55 Starting LSI, 0.941 mins elapsed.
-## 2026-10-18 21:16:55 Normalizing matrix, 0.943 mins elapsed.
-## 2026-10-18 21:16:56 Calculating SVD, 0.948 mins elapsed.
-## 2026-10-18 21:16:56 Clustering LSI results, 0.959 mins elapsed.
-## 21:16:56 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:16:56 Finished building index
-## 21:16:56 Searching HNSW index with ef = 100 and 1 threads
-## 21:16:56 Finished searching
+## 2026-10-19 19:08:08 Merging 13 clusters down to 6 via hierarchical clustering
+## 2026-10-19 19:08:08 Pseudobulking matrix
+## 2026-10-19 19:08:08 Starting Iterative LSI iteration 2 of 2
+## 2026-10-19 19:08:08 Selecting features
+## 2026-10-19 19:08:09 Running LSI
+## 2026-10-19 19:08:09 Starting LSI
+## 2026-10-19 19:08:09 Normalizing matrix
+## 2026-10-19 19:08:09 Calculating SVD
+## 2026-10-19 19:08:10 Projecting simulated doublets on LSI space
+## 2026-10-19 19:08:15 Running UMAP fitting on LSI matrix
+## 19:08:15 Using HNSW for nearest neighbor search
+## 19:08:15 UMAP embedding parameters a = 0.7669 b = 1.223
+## 19:08:15 Setting random seed 1
+## 19:08:15 Read 3280 rows and found 30 numeric columns
+## 19:08:15 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 19:08:15 Finished building index
+## 19:08:15 Searching HNSW index with ef = 40 and 4 threads
+## 19:08:15 Finished searching
+## 19:08:16 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:08:17 Initializing from normalized Laplacian + noise (using RSpectra)
+## 19:08:17 Range-scaling initial input columns to 0-10
+## 19:08:17 Commencing optimization for 500 epochs, with 208246 positive edges using 4 threads
+## 19:08:17 Using rng type: pcg
+## 19:08:19 Optimization finished
+## 2026-10-19 19:08:19 Validating re-projection Pearson correlation
+## 19:08:19 Setting model random seed 1
+## 19:08:19 Read 3280 rows and found 30 numeric columns
+## 19:08:19 Processing block 1 of 1
+## 19:08:19 Searching HNSW index with ef = 40 and 4 threads
+## 19:08:19 Finished searching
+## 19:08:19 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:08:19 Initializing by weighted average of neighbor coordinates using 4 threads
+## 19:08:19 Commencing optimization for 167 epochs, with 131200 positive edges using 4 threads
+## 19:08:19 Finished
+## 2026-10-19 19:08:19 UMAP Re-projection Correlation: R^2 = 0.994
+## 2026-10-19 19:08:19 Projecting simulated doublets on UMAP space
+## 19:08:19 Setting model random seed 1
+## 19:08:19 Read 15000 rows and found 30 numeric columns
+## 19:08:19 Processing block 1 of 1
+## 19:08:19 Searching HNSW index with ef = 40 and 4 threads
+## 19:08:19 Finished searching
+## 19:08:19 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:08:19 Initializing by weighted average of neighbor coordinates using 4 threads
+## 19:08:19 Commencing optimization for 167 epochs, with 600000 positive edges using 4 threads
+## 19:08:20 Finished
+## 2026-10-19 19:08:20 Compute doublet scores and enrichments from UMAP
+## 19:08:20 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:08:20 Finished building index
+## 19:08:20 Searching HNSW index with ef = 200 and 1 threads
+## 19:08:21 Finished searching
+## 2026-10-19 19:08:21 Processing dataset 3 of 3: scATAC_PBMC_R1
+## 2026-10-19 19:08:26 Simulating 10000 synthetic doublets (1000 doublets x 10 trials)
+## 2026-10-19 19:08:26 Running Iterative LSI on input matrix
+## 2026-10-19 19:08:27 Starting Iterative LSI
+## 2026-10-19 19:08:27 Starting Iterative LSI iteration 1 of 2
+## 2026-10-19 19:08:27 Selecting features
+## 2026-10-19 19:08:29 Running LSI
+## 2026-10-19 19:08:29 Starting LSI
+## 2026-10-19 19:08:29 Normalizing matrix
+## 2026-10-19 19:08:29 Calculating SVD
+## 2026-10-19 19:08:30 Clustering LSI results
+## 19:08:30 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:08:30 Finished building index
+## 19:08:30 Searching HNSW index with ef = 100 and 1 threads
+## 19:08:30 Finished searching
 ## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-## 2026-10-18 21:16:56 Merging 12 clusters down to 6 via hierarchical clustering, 0.964 mins elapsed.
-## 2026-10-18 21:16:57 Pseudobulking matrix, 0.964 mins elapsed.
-## 2026-10-18 21:16:57 Starting Iterative LSI iteration 2 of 2, 0.969 mins elapsed.
-## 2026-10-18 21:16:57 Selecting features, 0.969 mins elapsed.
-## 2026-10-18 21:16:57 Running LSI, 0.978 mins elapsed.
-## 2026-10-18 21:16:57 Starting LSI, 0.978 mins elapsed.
-## 2026-10-18 21:16:57 Normalizing matrix, 0.980 mins elapsed.
-## 2026-10-18 21:16:58 Calculating SVD, 0.984 mins elapsed.
-## 2026-10-18 21:16:59 Finished running Iterative LSI, 0.998 mins elapsed.
-## 2026-10-18 21:16:59 Projecting simulated doublets on LSI space, 0.998 mins elapsed.
-## 2026-10-18 21:17:03 Running UMAP fitting on LSI matrix, 1.073 mins elapsed.
-## 21:17:03 Using HNSW for nearest neighbor search
-## 21:17:03 UMAP embedding parameters a = 0.7669 b = 1.223
-## 21:17:03 Setting random seed 1
-## 21:17:03 Read 2462 rows and found 30 numeric columns
-## 21:17:03 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 21:17:03 Finished building index
-## 21:17:03 Searching HNSW index with ef = 40 and 4 threads
-## 21:17:03 Finished searching
-## 21:17:04 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:17:06 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:17:06 Range-scaling initial input columns to 0-10
-## 21:17:06 Commencing optimization for 500 epochs, with 170712 positive edges using 4 threads
-## 21:17:06 Using rng type: pcg
-## 21:17:07 Optimization finished
-## 2026-10-18 21:17:07 Validating re-projection Pearson correlation, 1.147 mins elapsed.
-## 21:17:07 Setting model random seed 1
-## 21:17:07 Read 2462 rows and found 30 numeric columns
-## 21:17:07 Processing block 1 of 1
-## 21:17:07 Searching HNSW index with ef = 40 and 4 threads
-## 21:17:07 Finished searching
-## 21:17:07 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:17:07 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:17:07 Commencing optimization for 167 epochs, with 98480 positive edges using 4 threads
-## 21:17:08 Finished
-## 2026-10-18 21:17:08 UMAP Re-projection Correlation: R^2 = 0.951, 1.150 mins elapsed.
-## 2026-10-18 21:17:08 Projecting simulated doublets on UMAP space, 1.150 mins elapsed.
-## 21:17:08 Setting model random seed 1
-## 21:17:08 Read 10000 rows and found 30 numeric columns
-## 21:17:08 Processing block 1 of 1
-## 21:17:08 Searching HNSW index with ef = 40 and 4 threads
-## 21:17:08 Finished searching
-## 21:17:08 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:17:08 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:17:08 Commencing optimization for 167 epochs, with 400000 positive edges using 4 threads
-## 21:17:08 Finished
-## 2026-10-18 21:17:08 Compute doublet scores and enrichments from UMAP, 1.160 mins elapsed.
-## 21:17:08 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:17:08 Finished building index
-## 21:17:08 Searching HNSW index with ef = 200 and 1 threads
-## 21:17:09 Finished searching
+## 2026-10-19 19:08:30 Merging 12 clusters down to 6 via hierarchical clustering
+## 2026-10-19 19:08:30 Pseudobulking matrix
+## 2026-10-19 19:08:30 Starting Iterative LSI iteration 2 of 2
+## 2026-10-19 19:08:30 Selecting features
+## 2026-10-19 19:08:31 Running LSI
+## 2026-10-19 19:08:31 Starting LSI
+## 2026-10-19 19:08:31 Normalizing matrix
+## 2026-10-19 19:08:31 Calculating SVD
+## 2026-10-19 19:08:32 Projecting simulated doublets on LSI space
+## 2026-10-19 19:08:36 Running UMAP fitting on LSI matrix
+## 19:08:36 Using HNSW for nearest neighbor search
+## 19:08:36 UMAP embedding parameters a = 0.7669 b = 1.223
+## 19:08:36 Setting random seed 1
+## 19:08:36 Read 2462 rows and found 30 numeric columns
+## 19:08:36 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
+## 19:08:36 Finished building index
+## 19:08:36 Searching HNSW index with ef = 40 and 4 threads
+## 19:08:36 Finished searching
+## 19:08:35 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:08:36 Initializing from normalized Laplacian + noise (using RSpectra)
+## 19:08:36 Range-scaling initial input columns to 0-10
+## 19:08:36 Commencing optimization for 500 epochs, with 170712 positive edges using 4 threads
+## 19:08:36 Using rng type: pcg
+## 19:08:38 Optimization finished
+## 2026-10-19 19:08:38 Validating re-projection Pearson correlation
+## 19:08:38 Setting model random seed 1
+## 19:08:38 Read 2462 rows and found 30 numeric columns
+## 19:08:38 Processing block 1 of 1
+## 19:08:38 Searching HNSW index with ef = 40 and 4 threads
+## 19:08:38 Finished searching
+## 19:08:38 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:08:38 Initializing by weighted average of neighbor coordinates using 4 threads
+## 19:08:38 Commencing optimization for 167 epochs, with 98480 positive edges using 4 threads
+## 19:08:38 Finished
+## 2026-10-19 19:08:38 UMAP Re-projection Correlation: R^2 = 0.951
+## 2026-10-19 19:08:38 Projecting simulated doublets on UMAP space
+## 19:08:38 Setting model random seed 1
+## 19:08:38 Read 10000 rows and found 30 numeric columns
+## 19:08:38 Processing block 1 of 1
+## 19:08:38 Searching HNSW index with ef = 40 and 4 threads
+## 19:08:38 Finished searching
+## 19:08:38 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
+## 19:08:38 Initializing by weighted average of neighbor coordinates using 4 threads
+## 19:08:38 Commencing optimization for 167 epochs, with 400000 positive edges using 4 threads
+## 19:08:39 Finished
+## 2026-10-19 19:08:39 Compute doublet scores and enrichments from UMAP
+## 19:08:39 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:08:39 Finished building index
+## 19:08:39 Searching HNSW index with ef = 200 and 1 threads
+## 19:08:39 Finished searching
+## 2026-10-19 19:08:39 Finished (64.0s)
 
for (sample_name in names(input_files)) {
   print(plot_doublet_scores(proj, dataset_name = sample_name))
@@ -1891,24 +1887,20 @@ 

Doublet Scoring and Filtering

filter_doublets() removes the highest-enrichment predicted doublets from every dataset in the project.

proj <- filter_doublets(proj, verbose = TRUE)
-
Output
## ###########
-## 2026-10-18 21:17:12 Filtering doublets in 3 dataset(s): scATAC_BMMC_R1, scATAC_CD34_BMMC_R1, scATAC_PBMC_R1, 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:17:12 filtering dataset: scATAC_BMMC_R1, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Filtering 243 doublets from 4939 cells (4.9%), 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Dataset successfully filtered, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Removing stale doublet data, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 doublet filtering complete, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 filtering dataset: scATAC_CD34_BMMC_R1, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Filtering 107 doublets from 3280 cells (3.3%), 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Dataset successfully filtered, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Removing stale doublet data, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 doublet filtering complete, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 filtering dataset: scATAC_PBMC_R1, 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Filtering 60 doublets from 2462 cells (2.4%), 0.000 mins elapsed.
-## 2026-10-18 21:17:12 Dataset successfully filtered, 0.001 mins elapsed.
-## 2026-10-18 21:17:12 Removing stale doublet data, 0.001 mins elapsed.
-## 2026-10-18 21:17:12 doublet filtering complete, 0.001 mins elapsed.
+
Output
## 2026-10-19 19:08:43 Filtering doublets in 3 dataset(s): scATAC_BMMC_R1, scATAC_CD34_BMMC_R1, scATAC_PBMC_R1
+## 2026-10-19 19:08:43 filtering dataset: scATAC_BMMC_R1.
+## 2026-10-19 19:08:43 Filtering 243 doublets from 4939 cells (4.9%)
+## 2026-10-19 19:08:43 Dataset successfully filtered.
+## 2026-10-19 19:08:43 Removing stale doublet data
+## 2026-10-19 19:08:43 filtering dataset: scATAC_CD34_BMMC_R1.
+## 2026-10-19 19:08:43 Filtering 107 doublets from 3280 cells (3.3%)
+## 2026-10-19 19:08:43 Dataset successfully filtered.
+## 2026-10-19 19:08:43 Removing stale doublet data
+## 2026-10-19 19:08:43 filtering dataset: scATAC_PBMC_R1.
+## 2026-10-19 19:08:43 Filtering 60 doublets from 2462 cells (2.4%)
+## 2026-10-19 19:08:43 Dataset successfully filtered.
+## 2026-10-19 19:08:43 Removing stale doublet data
+## 2026-10-19 19:08:43 Finished (0.0s)
 
@@ -1924,34 +1916,32 @@

Iterative LSI

max_clusters = 25, verbose = TRUE )
-
Output
## ###########
-## 2026-10-18 21:17:20 Starting Iterative LSI, 0.138 mins elapsed.
-## ###########
-## 2026-10-18 21:17:20 Starting Iterative LSI iteration 1 of 2, 0.138 mins elapsed.
-## 2026-10-18 21:17:20 Selecting features, 0.139 mins elapsed.
-## 2026-10-18 21:17:22 Running LSI, 0.165 mins elapsed.
-## 2026-10-18 21:17:22 Starting LSI, 0.168 mins elapsed.
-## 2026-10-18 21:17:23 Filtering 404 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.188 mins elapsed.
-## 2026-10-18 21:17:24 Normalizing matrix, 0.201 mins elapsed.
-## 2026-10-18 21:17:26 Calculating SVD, 0.228 mins elapsed.
-## 2026-10-18 21:17:30 Dropping PCs 1 due to high correlation with sequencing depth, 0.301 mins elapsed.
-## 2026-10-18 21:17:30 Re-projecting outlier cells into LSI space, 0.301 mins elapsed.
-## 2026-10-18 21:17:32 Clustering LSI results, 0.335 mins elapsed.
-## 21:17:32 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:17:33 Finished building index
-## 21:17:33 Searching HNSW index with ef = 100 and 1 threads
-## 21:17:33 Finished searching
-## 2026-10-18 21:17:34 Pseudobulking matrix, 0.358 mins elapsed.
-## 2026-10-18 21:17:37 Starting Iterative LSI iteration 2 of 2, 0.418 mins elapsed.
-## 2026-10-18 21:17:37 Selecting features, 0.418 mins elapsed.
-## 2026-10-18 21:17:37 Running LSI, 0.422 mins elapsed.
-## 2026-10-18 21:17:38 Starting LSI, 0.424 mins elapsed.
-## 2026-10-18 21:17:38 Filtering 412 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.436 mins elapsed.
-## 2026-10-18 21:17:39 Normalizing matrix, 0.448 mins elapsed.
-## 2026-10-18 21:17:40 Calculating SVD, 0.473 mins elapsed.
-## 2026-10-18 21:17:45 Dropping PCs 1 due to high correlation with sequencing depth, 0.540 mins elapsed.
-## 2026-10-18 21:17:45 Re-projecting outlier cells into LSI space, 0.540 mins elapsed.
-## 2026-10-18 21:17:46 Finished running Iterative LSI, 0.569 mins elapsed.
+
Output
## 2026-10-19 19:08:52 Starting Iterative LSI
+## 2026-10-19 19:08:52 Starting Iterative LSI iteration 1 of 2
+## 2026-10-19 19:08:52 Selecting features
+## 2026-10-19 19:08:53 Running LSI
+## 2026-10-19 19:08:54 Starting LSI
+## 2026-10-19 19:08:55 Filtering 404 outlier cells (colSum quantiles 0.02-0.98) before SVD
+## 2026-10-19 19:08:56 Normalizing matrix
+## 2026-10-19 19:08:58 Calculating SVD
+## 2026-10-19 19:09:02 Dropping PCs 1 due to high correlation with sequencing depth
+## 2026-10-19 19:09:02 Re-projecting outlier cells into LSI space
+## 2026-10-19 19:09:04 Clustering LSI results
+## 19:09:04 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:09:05 Finished building index
+## 19:09:05 Searching HNSW index with ef = 100 and 1 threads
+## 19:09:05 Finished searching
+## 2026-10-19 19:09:05 Pseudobulking matrix
+## 2026-10-19 19:09:06 Starting Iterative LSI iteration 2 of 2
+## 2026-10-19 19:09:06 Selecting features
+## 2026-10-19 19:09:07 Running LSI
+## 2026-10-19 19:09:07 Starting LSI
+## 2026-10-19 19:09:08 Filtering 412 outlier cells (colSum quantiles 0.02-0.98) before SVD
+## 2026-10-19 19:09:08 Normalizing matrix
+## 2026-10-19 19:09:10 Calculating SVD
+## 2026-10-19 19:09:14 Dropping PCs 1 due to high correlation with sequencing depth
+## 2026-10-19 19:09:14 Re-projecting outlier cells into LSI space
+## 2026-10-19 19:09:16 Finished (32.8s)
 
@@ -1965,23 +1955,23 @@

Clustering

cluster_graph_method = cluster_graph_leiden(resolution = 0.8), knn_method = knn_hnsw(k = 20L) )
-
Output
## ###########
-## 2026-10-18 21:17:46 Extracting embedding 'IterativeLSI', 0.000 mins elapsed.
-## ###########
+
Output
## 2026-10-19 19:09:16 Extracting embedding 'IterativeLSI'
 ## Warning: Converting to a dense matrix may use excessive memory
-## 2026-10-18 21:17:49 Clustering 10271 cells with 29 dimensions, 0.040 mins elapsed.
+## 2026-10-19 19:09:18 Clustering 10271 cells with 29 dimensions
 ## 
-## 21:17:49 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:09:18 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
 ## 
-## 21:17:49 Finished building index
+## 19:09:19 Finished building index
 ## 
-## 21:17:50 Searching HNSW index with ef = 100 and 1 threads
+## 19:09:19 Searching HNSW index with ef = 100 and 1 threads
 ## 
-## 21:17:50 Finished searching
+## 19:09:20 Finished searching
 ## 
-## 2026-10-18 21:17:51 Found 11 clusters, 0.071 mins elapsed.
+## 2026-10-19 19:09:20 Found 11 clusters
 ## 
-## 2026-10-18 21:17:51 Added 11 clusters as 'atac_clusters' in cell metadata, 0.072 mins elapsed.
+## 2026-10-19 19:09:20 Added 11 clusters as 'atac_clusters' in cell metadata
+## 
+## 2026-10-19 19:09:20 Finished (4.7s)
 ## 
 ## This message is displayed once every 8 hours.
 
@@ -1996,25 +1986,24 @@

UMAP Embedding

min_dist = 0.5, verbose = TRUE )
-
Output
## ###########
-## 2026-10-18 21:17:51 Extracting embedding 'IterativeLSI', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:17:51 Computing UMAP on 10271 cells with 29 dimensions, 0.000 mins elapsed.
-## 21:17:51 Using HNSW for nearest neighbor search
-## 21:17:51 UMAP embedding parameters a = 0.583 b = 1.334
-## 21:17:51 Setting random seed 1
-## 21:17:51 Read 10271 rows and found 29 numeric columns
-## 21:17:51 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 21:17:51 Finished building index
-## 21:17:51 Searching HNSW index with ef = 30 and 4 threads
-## 21:17:51 Finished searching
-## 21:17:53 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 30
-## 21:17:54 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:17:54 Range-scaling initial input columns to 0-10
-## 21:17:54 Commencing optimization for 500 epochs, with 464838 positive edges using 4 threads
-## 21:17:54 Using rng type: pcg
-## 21:17:57 Optimization finished
-## 2026-10-18 21:17:57 Added UMAP embedding as 'UMAP' (2 components), 0.112 mins elapsed.
+
Output
## 2026-10-19 19:09:20 Extracting embedding 'IterativeLSI'
+## 2026-10-19 19:09:20 Computing UMAP on 10271 cells with 29 dimensions
+## 19:09:20 Using HNSW for nearest neighbor search
+## 19:09:20 UMAP embedding parameters a = 0.583 b = 1.334
+## 19:09:20 Setting random seed 1
+## 19:09:20 Read 10271 rows and found 29 numeric columns
+## 19:09:20 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
+## 19:09:21 Finished building index
+## 19:09:21 Searching HNSW index with ef = 30 and 4 threads
+## 19:09:21 Finished searching
+## 19:09:23 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 30
+## 19:09:24 Initializing from normalized Laplacian + noise (using RSpectra)
+## 19:09:24 Range-scaling initial input columns to 0-10
+## 19:09:24 Commencing optimization for 500 epochs, with 464838 positive edges using 4 threads
+## 19:09:24 Using rng type: pcg
+## 19:09:27 Optimization finished
+## 2026-10-19 19:09:27 Added UMAP embedding as 'UMAP' (2 components)
+## 2026-10-19 19:09:27 Finished (7.0s)
 

We can visualize the attributes of our cells, using the plot_embedding() function, specifying the coloration via the col_name parameter.

plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters") +
@@ -2042,28 +2031,26 @@ 

Assigning Clusters with Gene Scores

Raw gene scores can be noisy at the single-cell level. add_impute_weights() computes MAGIC diffusion weights from the LSI embedding.

proj <- add_impute_weights(proj, embedding_name = "IterativeLSI")
-
Output
## ###########
-## 2026-10-18 21:18:07 Computing MAGIC imputation weights (td=3, ka=4, blocks~5136 cells, 2 reps), 0.040 mins elapsed.
-## ###########
-## 2026-10-18 21:18:07   Replicate 1 of 2, 0.040 mins elapsed.
-## 21:18:07 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:18:07 Finished building index
-## 21:18:07 Searching HNSW index with ef = 100 and 1 threads
-## 21:18:07 Finished searching
-## 21:18:08 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:18:09 Finished building index
-## 21:18:09 Searching HNSW index with ef = 100 and 1 threads
-## 21:18:09 Finished searching
-## 2026-10-18 21:18:10   Replicate 2 of 2, 0.086 mins elapsed.
-## 21:18:10 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:18:10 Finished building index
-## 21:18:10 Searching HNSW index with ef = 100 and 1 threads
-## 21:18:10 Finished searching
-## 21:18:11 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:18:11 Finished building index
-## 21:18:11 Searching HNSW index with ef = 100 and 1 threads
-## 21:18:11 Finished searching
-## 2026-10-18 21:18:12 Completed MAGIC imputation weights, 0.129 mins elapsed.
+
Output
## 2026-10-19 19:09:34 Computing MAGIC imputation weights (td=3, ka=4, blocks~5136 cells, 2 reps)
+## 2026-10-19 19:09:34   Replicate 1 of 2
+## 19:09:34 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:09:34 Finished building index
+## 19:09:34 Searching HNSW index with ef = 100 and 1 threads
+## 19:09:35 Finished searching
+## 19:09:36 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:09:36 Finished building index
+## 19:09:36 Searching HNSW index with ef = 100 and 1 threads
+## 19:09:36 Finished searching
+## 2026-10-19 19:09:37   Replicate 2 of 2
+## 19:09:37 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:09:37 Finished building index
+## 19:09:37 Searching HNSW index with ef = 100 and 1 threads
+## 19:09:37 Finished searching
+## 19:09:38 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
+## 19:09:39 Finished building index
+## 19:09:39 Searching HNSW index with ef = 100 and 1 threads
+## 19:09:39 Finished searching
+## 2026-10-19 19:09:40 Finished (5.7s)
 
plot_gene_scores(
   proj,
@@ -2074,9 +2061,8 @@ 

Assigning Clusters with Gene Scores

patchwork = TRUE )

-
Output
## ###########
-## 2026-10-18 21:18:15 Imputing gene scores with MAGIC weights, 0.044 mins elapsed.
-## ###########
+
Output
## 2026-10-19 19:09:42 Imputing gene scores with MAGIC weights
+## 2026-10-19 19:09:43 Finished (3.4s)
 
From d49bfcb2b564883ba8acb563af532c1685dcd0a9 Mon Sep 17 00:00:00 2001 From: erliuu Date: Tue, 20 Oct 2026 12:17:29 -0700 Subject: [PATCH 05/12] feat([r] logging): Restructure IterativeLSI logging output, logs total elapsed for each subprocess --- R/RcppExports.R | 4 + R/clustering.R | 77 +++++---- R/dimensionality_reduction.R | 153 ++++++++++++------ R/utils.R | 81 +++++++++- man/add_clusters.Rd | 2 +- src/RcppExports.cpp | 11 ++ src/selections.cpp | 8 + tests/testthat/setup-matrices.R | 6 + tests/testthat/test-clustering.R | 76 +++++++-- .../testthat/test-dimensionality_reduction.R | 105 +++++++++++- .../test-iterative-lsi-embedding-copies.R | 10 +- tests/testthat/test-utils.R | 107 +++++++++++- 12 files changed, 530 insertions(+), 110 deletions(-) diff --git a/R/RcppExports.R b/R/RcppExports.R index f46dfd9..633c512 100644 --- a/R/RcppExports.R +++ b/R/RcppExports.R @@ -5,6 +5,10 @@ rcpp_hello_world <- function() { .Call(`_MarchR_rcpp_hello_world`) } +steady_clock_seconds_rcpp <- function() { + .Call(`_MarchR_steady_clock_seconds_rcpp`) +} + get_subset_from_logical_selection_rcpp <- function(selection, dimension_sums) { .Call(`_MarchR_get_subset_from_logical_selection_rcpp`, selection, dimension_sums) } diff --git a/R/clustering.R b/R/clustering.R index b1a3920..06933c5 100644 --- a/R/clustering.R +++ b/R/clustering.R @@ -46,7 +46,7 @@ add_clusters <- function(x, ...) { #' \code{cluster_graph_seurat(resolution = 0.8)} to use Seurat instead, which #' requires the optional Seurat package. #' @param n_outlier (integer) Minimum cluster size; smaller clusters are -#' reassigned via KNN. Default 5. +#' reassigned via KNN; errors if every cluster is smaller. Default 5. #' @param max_clusters (integer) Maximum clusters; excess merged via #' hierarchical clustering on centroids. Default 25. \code{NULL} to disable. #' @param prefix (character) Label prefix. Default \code{"C"}. @@ -70,7 +70,11 @@ add_clusters.default <- function( ... ) { .start_log_clock() - if (is(x, "IterableMatrix")) x <- as.matrix(t(x)) + assert_for(verbose, "logical") + # Muffles BPCells' periodic note about dense conversion without using up its display slot. + if (is(x, "IterableMatrix")) { + x <- rlang::with_options(as.matrix(t(x)), rlib_message_verbosity = "quiet") + } if (is(x, "dgCMatrix")) x <- as.matrix(x) assert_for(x, "matrix") @@ -78,6 +82,11 @@ add_clusters.default <- function( msg = "Input matrix must have rownames (cell names).") assertthat::assert_that(nrow(x) >= 2, msg = "Input matrix must have at least 2 cells.") + if (verbose) { + run <- .log_start("Clustering", sprintf( + "%s, %s", .log_plural(nrow(x), "cell"), .log_plural(ncol(x), "dim") + )) + } set.seed(seed) # Threaded knn_hnsw() is non-deterministic, so it needs an explicit request @@ -97,28 +106,36 @@ add_clusters.default <- function( knn_to_graph_method = knn_to_graph_method, cluster_graph_method = wrapped_cluster_graph, threads = threads, - verbose = verbose, + verbose = FALSE, .missing_args_error = FALSE )(x) names(clusters) <- rownames(x) + n_found <- length(unique(clusters)) + n_small <- 0L + n_moved <- 0L # Reassign outlier cells (small clusters) to nearest large cluster if (n_outlier > 0) { tab <- table(clusters) small_clusts <- names(tab[tab < n_outlier]) if (length(small_clusts) > 0) { - if (verbose) { - log_progress(sprintf( - "Reassigning %d outlier cluster(s) with < %d cells", - length(small_clusts), n_outlier - )) - } all_outlier_idx <- which(clusters %in% small_clusts) non_outlier_idx <- which(!clusters %in% small_clusts) + if (length(non_outlier_idx) == 0) { + rlang::abort(c( + sprintf( + "All %d clusters have fewer than `n_outlier` = %d cells (largest has %d).", + length(tab), n_outlier, max(tab) + ), + i = "Lower `n_outlier`, or set it to 0 to skip reassigning small clusters." + )) + } + n_small <- length(small_clusts) + n_moved <- length(all_outlier_idx) outlier_knn_method <- partial_apply( knn_method, k = min(10L, length(non_outlier_idx)), - verbose = verbose, + verbose = FALSE, .overwrite = TRUE, .missing_args_error = FALSE ) @@ -136,7 +153,8 @@ add_clusters.default <- function( } } - clusters <- .merge_clusters(x, clusters, max_clusters, verbose = verbose) + n_unmerged <- length(unique(clusters)) + clusters <- .merge_clusters(x, clusters, max_clusters) # Relabel so similar clusters get adjacent numbers (C1, C2, ...) unique_clusts <- unique(clusters) @@ -154,7 +172,15 @@ add_clusters.default <- function( } if (verbose) { - log_progress(sprintf("Found %d clusters", length(unique(clusters)))) + n_final <- length(unique(clusters)) + found <- paste("Found", .log_plural(n_found, "cluster")) + if (n_small > 0) { + found <- sprintf("%s, reassigned %s (%s)", found, .log_plural(n_small, "small cluster"), + .log_plural(n_moved, "cell")) + } + if (n_final < n_unmerged) found <- paste0(found, ", merged to ", .log_count(n_final)) + .log_step(found, since = run$start) + .log_finish(run, .log_plural(n_final, "cluster")) } return(clusters) @@ -190,6 +216,7 @@ add_clusters.MarchRProject <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRProject") assert_is_character(col_name) assert_len(col_name, 1) @@ -226,13 +253,14 @@ add_clusters.MarchRProject <- function( } } - if (verbose) log_progress(sprintf("Extracting embedding '%s'", embedding_name)) - embedding <- as.matrix(t(x[[embedding_name, dataset_names]])) - + embedding <- rlang::with_options( + as.matrix(t(x[[embedding_name, dataset_names]])), + rlib_message_verbosity = "quiet" + ) if (verbose) { - log_progress(sprintf( - "Clustering %d cells with %d dimensions", - nrow(embedding), ncol(embedding) + run <- .log_start("Clustering", sprintf( + "%s on '%s' (%s)", .log_plural(nrow(embedding), "cell"), embedding_name, + .log_plural(ncol(embedding), "dim") )) } clusters <- add_clusters.default( @@ -260,9 +288,8 @@ add_clusters.MarchRProject <- function( } if (verbose) { - log_progress(sprintf( - "Added %d clusters as '%s' in cell metadata", - length(unique(clusters)), col_name + .log_finish(run, sprintf( + "added cell metadata column '%s' (%s)", col_name, .log_plural(length(unique(clusters)), "cluster") )) } @@ -331,16 +358,10 @@ select_embedding_name <- function(proj, embedding_name) { #' Merge clusters via hierarchical clustering on centroids #' @keywords internal #' @noRd -.merge_clusters <- function(mat, clusters, max_clusters, verbose = FALSE) { +.merge_clusters <- function(mat, clusters, max_clusters) { if (is.null(max_clusters) || length(unique(clusters)) <= max_clusters) { return(droplevels(as.factor(clusters))) } - if (verbose) { - log_progress(sprintf( - "Merging %d clusters down to %d via hierarchical clustering", - length(unique(clusters)), max_clusters - )) - } cluster_means <- .compute_cluster_means(mat, clusters) hc <- stats::hclust(stats::dist(cluster_means)) ct <- stats::cutree(hc, k = max_clusters) diff --git a/R/dimensionality_reduction.R b/R/dimensionality_reduction.R index 4b58255..1316051 100644 --- a/R/dimensionality_reduction.R +++ b/R/dimensionality_reduction.R @@ -784,6 +784,7 @@ LSI.default <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_mat(x) assert_is_wholenumber(n_dimensions) assert_len(n_dimensions, 1) @@ -792,13 +793,17 @@ LSI.default <- function( assert_true(n_dimensions < min(ncol(x), nrow(x))) assert_true((corr_cutoff >= 0) && (corr_cutoff <= 1)) assert_is_wholenumber(threads) + assert_len(threads, 1) if (binarize) { x <- binarize(x) } if (verbose) { - log_progress("Starting LSI") + run <- .log_start("LSI", sprintf( + "%s, %s, %s, %s", .log_plural(ncol(x), "cell"), .log_plural(nrow(x), "feature"), + .log_plural(n_dimensions, "dim"), .log_plural(threads, "thread") + ), compact = TRUE) } original_x <- if (!is.null(outlier_quantiles)) x else NULL @@ -828,12 +833,6 @@ LSI.default <- function( q_bounds <- quantile(read_depth, probs = outlier_quantiles) outlier_idx <- which(read_depth <= q_bounds[1] | read_depth >= q_bounds[2]) if (length(outlier_idx) > 0) { - if (verbose) { - log_progress(sprintf( - "Filtering %d outlier cells (colSum quantiles %.2f-%.2f) before SVD", - length(outlier_idx), outlier_quantiles[1], outlier_quantiles[2] - )) - } outlier_cells <- colnames(x)[outlier_idx] x <- x[, -outlier_idx] mat_stats <- matrix_stats(x, row_stats = "mean", col_stats = "mean") @@ -848,9 +847,6 @@ LSI.default <- function( } # Normalization - if (verbose) { - log_progress("Normalizing matrix") - } mat <- normalize_tfidf( x = x, feature_means = mat_stats$row_stats["mean", ], @@ -860,16 +856,14 @@ LSI.default <- function( # Save to prevent repeating queued calculations during SVD temp_mat_dir <- tempfile("mat") - mat <- write_matrix_dir( + # Muffles BPCells' periodic note about compressing non-integer matrices without using up its slot. + mat <- rlang::with_options(write_matrix_dir( convert_matrix_type(mat, type = "float"), temp_mat_dir, compress = TRUE - ) + ), rlib_message_verbosity = "quiet") on.exit(unlink(temp_mat_dir, recursive = TRUE, expand = FALSE), add = TRUE) # Run pca - if (verbose) { - log_progress("Calculating SVD") - } svd_attr <- svds(mat, k = n_dimensions, threads = threads) singular_values <- svd_attr$d pca_res <- svd_attr$v @@ -881,19 +875,15 @@ LSI.default <- function( # Filter out PCs that are highly correlated with sequencing depth if (!is.null(depth)) { + depth_label <- sprintf("log10(%s)", attr(depth, "label") %||% "depth") depth_signal <- log10(depth[colnames(mat)] + 1) } else { + depth_label <- "total counts" depth_signal <- read_depth } pca_corrs <- abs(cor(depth_signal, pca_res)) pca_feats_to_keep <- which(pca_corrs < corr_cutoff) if (length(pca_feats_to_keep) != n_dimensions) { - if (verbose) { - log_progress(sprintf( - "Dropping PCs %s due to high correlation with sequencing depth", - paste(setdiff(1:n_dimensions, pca_feats_to_keep), collapse = ", ") - )) - } pca_res <- pca_res[, pca_feats_to_keep, drop = FALSE] } fitted_params <- list( @@ -913,7 +903,6 @@ LSI.default <- function( # Re-project outlier cells that were excluded from SVD if (length(outlier_cells) > 0) { - if (verbose) log_progress("Re-projecting outlier cells into LSI space") outlier_proj <- project.LSI(dim_reduction, original_x[, outlier_cells], drop_zero_cells = drop_zero_cells) all_cells <- colnames(original_x) @@ -931,6 +920,25 @@ LSI.default <- function( pca_res <- ordered_res } + if (verbose) { + fit <- paste("Fit LSI on", .log_plural(ncol(mat), "cell")) + if (length(outlier_cells) > 0) { + fit <- paste0(fit, ", projected ", .log_plural(length(outlier_cells), "depth outlier")) + } + .log_step(fit, since = run$start) + dropped <- setdiff(seq_len(n_dimensions), pca_feats_to_keep) + if (length(dropped) > 0) { + .log_step(sprintf( + "Dropped LSI component%s %s (r = %s with %s)", + if (length(dropped) > 1) "s" else "", + paste(dropped, collapse = ", "), + paste(sprintf("%.2f", as.numeric(pca_corrs)[dropped]), collapse = ", "), + depth_label + )) + } + .log_finish(run, sprintf("%s x %d embedding", .log_count(nrow(pca_res)), ncol(pca_res))) + } + return(list( cell_embeddings = pca_res, dim_reduction = dim_reduction @@ -962,6 +970,9 @@ LSI.MarchRProject <- function( ) { .start_log_clock() assert_is_character(dataset_names) + assert_for(verbose, "logical") + assert_is_wholenumber(threads) + assert_len(threads, 1) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) @@ -978,11 +989,19 @@ LSI.MarchRProject <- function( if (length(qc_list) > 0) { qc_all <- do.call(rbind, qc_list) depth <- stats::setNames(qc_all$nFrags, qc_all$cellName) + attr(depth, "label") <- "nFrags" } } # Get matrices from all specified datasets input_mat <- x[[assay_name, dataset_names]] + if (verbose) { + run <- .log_start("LSI", sprintf( + "%s, %s, %s, %s", .log_plural(ncol(input_mat), "cell"), + .log_plural(nrow(input_mat), "feature"), .log_plural(n_dimensions, "dim"), + .log_plural(threads, "thread") + )) + } lsi_results <- LSI.default( input_mat, n_dimensions = n_dimensions, @@ -1013,6 +1032,12 @@ LSI.MarchRProject <- function( output_assay_name, overwrite = overwrite ) + if (verbose) { + .log_finish(run, sprintf( + "added dim reduction '%s' (%s x %d)", dim_reduction_name, + .log_count(nrow(lsi_results$cell_embeddings)), ncol(lsi_results$cell_embeddings) + )) + } return(x) } @@ -1062,11 +1087,12 @@ project.LSI <- function(x, mat, threads = NULL, drop_zero_cells = TRUE, ...) { # Flush to disk to avoid re-evaluating the lazy TF-IDF chain per column during %*% temp_mat_dir <- tempfile("mat") - mat <- write_matrix_dir( + # Hides BPCells' periodic note about compressing non-integer matrices + mat <- rlang::with_options(write_matrix_dir( convert_matrix_type(mat, type = "float"), temp_mat_dir, compress = TRUE - ) + ), rlib_message_verbosity = "quiet") on.exit(unlink(temp_mat_dir, recursive = TRUE, expand = FALSE), add = TRUE) feature_loadings <- fitted_params$feature_loadings @@ -1363,6 +1389,12 @@ IterativeLSI.default <- function( )) } assert_greater_than_zero(total_features) + if (verbose) { + run <- .log_start("Iterative LSI", sprintf( + "%s, %s, %s, %s", .log_plural(ncol(x), "cell"), .log_plural(n_iterations, "iteration"), + .log_plural(n_dimensions, "dim"), .log_plural(threads, "thread") + )) + } # Binarize for both LSI and feature selection if (binarize) { @@ -1412,21 +1444,9 @@ IterativeLSI.default <- function( order(fitted_params$feature_means, decreasing = TRUE)[seq_len(total_features)] ) } - if (verbose) { - log_progress("Starting Iterative LSI") - } for (i in seq_len(n_iterations)) { - if (verbose) { - log_progress(sprintf( - "Starting Iterative LSI iteration %s of %s", - i, - n_iterations - )) - } + if (verbose) pass <- .log_pass(sprintf("Iteration %d/%d", i, n_iterations), "Iteration") # run variable feature selection - if (verbose) { - log_progress("Selecting features") - } if (i == 1 && first_selection == "top") { var_feature_table <- select_features_top( x, @@ -1465,11 +1485,13 @@ IterativeLSI.default <- function( ) ) } - # run LSI if (verbose) { - log_progress("Running LSI") + .log_step(sprintf( + "Selected %s %s", .log_count(length(mat_indices)), + if (i == 1 && first_selection == "top") "features (top accessible)" else "variable features" + ), since = pass$start) } - + # run LSI iter_cells <- if (i < n_iterations) { .draw_lsi_subsample(colnames(x), sample_cells_pre, sample_group, seed + i) } else { @@ -1509,13 +1531,12 @@ IterativeLSI.default <- function( ) # only cluster + pseudobulk if this isn't the last iteration if (i == n_iterations) { + if (verbose) .log_pass_end(pass) break } # cluster the LSI results - if (verbose) { - log_progress("Clustering LSI results") - } + step_start <- steady_clock_seconds_rcpp() # Scale dimensions before clustering to equalize PC contributions cluster_input <- if (scale_dims) .scale_dims(lsi_embeddings) else lsi_embeddings if (scale_dims) { @@ -1525,18 +1546,21 @@ IterativeLSI.default <- function( partial_apply( cluster_method, threads = knn_threads, - verbose = verbose, + verbose = FALSE, .missing_args_error = FALSE )() - clustering_res <- .merge_clusters( - cluster_input, clustering_res, max_clusters, verbose = verbose - ) + n_found <- length(unique(clustering_res)) + clustering_res <- .merge_clusters(cluster_input, clustering_res, max_clusters) + n_kept <- length(unique(clustering_res)) + if (verbose) { + found <- paste("Found", .log_plural(n_found, "cluster")) + if (n_kept < n_found) found <- paste0(found, ", merged to ", .log_count(n_kept)) + .log_step(found, since = step_start) + step_start <- steady_clock_seconds_rcpp() + } cluster_input <- NULL fitted_params$iter_info$clusters[[i]] <- clustering_res # Pseudobulk and pass onto the next iteration. - if (verbose) { - log_progress("Pseudobulking matrix") - } pseudobulk_input <- if (cap_pool) iter_x[feature_pool, ] else iter_x pseudobulk_res <- .materialize_lsi_pseudobulk( pseudobulk_input, @@ -1544,6 +1568,10 @@ IterativeLSI.default <- function( format = pseudobulk_format, threads = 1L ) + if (verbose) { + .log_step(paste("Pseudobulked", .log_plural(n_kept, "cluster")), since = step_start) + .log_pass_end(pass) + } } # Apply scale_dims to final embeddings so the stored result is ready for @@ -1561,6 +1589,11 @@ IterativeLSI.default <- function( feature_names = rownames(x) ) class(dim_reduction) <- c("IterativeLSI", class(dim_reduction)) + if (verbose) { + .log_finish(run, sprintf( + "%s x %d embedding", .log_count(nrow(lsi_embeddings)), ncol(lsi_embeddings) + )) + } return(list( cell_embeddings = lsi_embeddings, dim_reduction = dim_reduction @@ -1687,11 +1720,12 @@ project.IterativeLSI <- function( # Flush to disk to avoid re-evaluating the lazy TF-IDF chain per column during %*% temp_mat_dir <- tempfile("mat") - mat <- write_matrix_dir( + # Hides BPCells' periodic note about compressing non-integer matrices + mat <- rlang::with_options(write_matrix_dir( convert_matrix_type(mat, type = "float"), temp_mat_dir, compress = TRUE - ) + ), rlib_message_verbosity = "quiet") on.exit(unlink(temp_mat_dir, recursive = TRUE, expand = FALSE), add = TRUE) res <- t(mat) %*% feature_loadings @@ -1750,6 +1784,7 @@ IterativeLSI.MarchRProject <- function( ) { .start_log_clock() assert_is_character(dataset_names) + assert_for(verbose, "logical") dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) @@ -1766,11 +1801,19 @@ IterativeLSI.MarchRProject <- function( if (length(qc_list) > 0) { qc_all <- do.call(rbind, qc_list) depth <- stats::setNames(qc_all$nFrags, qc_all$cellName) + attr(depth, "label") <- "nFrags" } } # Get matrices from all specified datasets input_mat <- x[[assay_name, dataset_names]] + if (verbose) { + run <- .log_start("Iterative LSI", sprintf( + "%s, %s, %s, %s", .log_plural(ncol(input_mat), "cell"), + .log_plural(n_iterations, "iteration"), .log_plural(n_dimensions, "dim"), + .log_plural(.resolve_threads(threads), "thread") + )) + } # Stratify pre-iteration subsampling by dataset of origin when not supplied if (is.null(sample_group)) { @@ -1828,6 +1871,12 @@ IterativeLSI.MarchRProject <- function( output_assay_name, overwrite = overwrite ) + if (verbose) { + .log_finish(run, sprintf( + "added dim reduction '%s' (%s x %d)", dim_reduction_name, + .log_count(nrow(iterative_results$cell_embeddings)), ncol(iterative_results$cell_embeddings) + )) + } return(x) } diff --git a/R/utils.R b/R/utils.R index 4e660d7..d0d8fab 100644 --- a/R/utils.R +++ b/R/utils.R @@ -89,7 +89,7 @@ selection_index <- function(selection, dim_len, dimnames) { } } -.log_clock <- new.env(parent = emptyenv()) +.log_clock <- list2env(list(depth = 0L, open = character(0)), parent = emptyenv()) # Starts the verbose=True run clock enclosing MarchR function calls. .start_log_clock <- function(envir = parent.frame()) { @@ -105,20 +105,93 @@ selection_index <- function(selection, dim_len, dimnames) { } exit_expr <- quote(.end_log_run(returnValue(.log_clock), environment())) do.call(on.exit, list(exit_expr, add = TRUE), envir = envir) - .log_clock$start <- Sys.time() + .log_clock$start <- steady_clock_seconds_rcpp() .log_clock$printed <- FALSE + .log_clock$owner <- envir + .log_clock$depth <- 0L + .log_clock$open <- character(0) + .log_clock$reported <- FALSE } # Clears the run clock. returnValue() gives back .log_clock itself when the run ended in an error. .end_log_run <- function(returned, envir) { start <- .log_clock$start .log_clock$start <- NULL + .log_clock$owner <- NULL + .log_clock$depth <- 0L + .log_clock$open <- character(0) if (!identical(returned, .log_clock) && isTRUE(.log_clock$printed) && - isTRUE(get0("verbose", envir = envir, inherits = FALSE))) { - log_progress(sprintf("Finished (%.1fs)", as.numeric(difftime(Sys.time(), start, units = "secs")))) + !isTRUE(.log_clock$reported) && isTRUE(get0("verbose", envir = envir, inherits = FALSE))) { + log_progress(paste("Finished", .log_secs(start))) } } +.log_secs <- function(since) { + sprintf("[%.1fs]", steady_clock_seconds_rcpp() - since) +} + +.log_count <- function(n) formatC(n, format = "f", digits = 0, big.mark = ",") + +.log_plural <- function(n, word) paste(.log_count(n), if (isTRUE(n == 1)) word else paste0(word, "s")) + +# Only the setup and finished lines of the outermost call carry a timestamp. +.log_line <- function(msg, timestamp = FALSE) { + if (timestamp) return(log_progress(msg)) + .log_clock$printed <- TRUE + message(paste0(strrep(" ", .log_clock$depth), msg)) +} + +# Opens a run's block. A nested run prints untimestamped and indents its contents; a compact run, or +# one nested directly in an open run with the same title, prints nothing and logs only its steps. +.log_start <- function(title, details, compact = FALSE, envir = parent.frame()) { + owner <- identical(envir, .log_clock$owner) && !length(.log_clock$open) + merged <- identical(.log_clock$open[length(.log_clock$open)], title) + shown <- owner || !(compact || merged) + run <- list( + title = title, start = steady_clock_seconds_rcpp(), owner = owner, shown = shown, + depth = .log_clock$depth, open = .log_clock$open + ) + if (shown) { + .log_line(paste0(title, ": ", details), timestamp = owner) + .log_clock$open <- c(.log_clock$open, title) + if (!owner) .log_clock$depth <- .log_clock$depth + 1L + } + restore <- bquote({ + .log_clock$depth <- .(run$depth) + .log_clock$open <- .(run$open) + }) + do.call(on.exit, list(restore, add = TRUE, after = FALSE), envir = envir) + invisible(run) +} + +.log_step <- function(msg, since = NULL) { + .log_line(if (is.null(since)) msg else paste(msg, .log_secs(since))) +} + +.log_pass <- function(label, kind) { + .log_line(paste0("[", label, "]")) + pass <- list(kind = kind, start = steady_clock_seconds_rcpp(), depth = .log_clock$depth) + .log_clock$depth <- .log_clock$depth + 1L + invisible(pass) +} + +.log_pass_end <- function(pass) { + .log_line(paste(pass$kind, "finished", .log_secs(pass$start))) + .log_clock$depth <- pass$depth +} + +.log_finish <- function(run, summary = NULL) { + if (!run$shown) { + return(invisible()) + } + .log_clock$depth <- run$depth + .log_clock$open <- run$open + msg <- paste(run$title, "finished", .log_secs(run$start)) + if (!is.null(summary)) msg <- paste0(msg, ": ", summary) + .log_line(msg, timestamp = run$owner) + if (run$owner) .log_clock$reported <- TRUE +} + # Messages with header = TRUE is framed by hashmarks. log_progress <- function(msg, header = FALSE) { .log_clock$printed <- TRUE diff --git a/man/add_clusters.Rd b/man/add_clusters.Rd index 908798f..cae0112 100644 --- a/man/add_clusters.Rd +++ b/man/add_clusters.Rd @@ -52,7 +52,7 @@ requires the optional Seurat package.} \item{n_outlier}{(integer) Minimum cluster size; smaller clusters are -reassigned via KNN. Default 5.} +reassigned via KNN; errors if every cluster is smaller. Default 5.} \item{max_clusters}{(integer) Maximum clusters; excess merged via hierarchical clustering on centroids. Default 25. \code{NULL} to disable.} diff --git a/src/RcppExports.cpp b/src/RcppExports.cpp index fa45346..a3b5de7 100644 --- a/src/RcppExports.cpp +++ b/src/RcppExports.cpp @@ -20,6 +20,16 @@ BEGIN_RCPP return rcpp_result_gen; END_RCPP } +// steady_clock_seconds_rcpp +double steady_clock_seconds_rcpp(); +RcppExport SEXP _MarchR_steady_clock_seconds_rcpp() { +BEGIN_RCPP + Rcpp::RObject rcpp_result_gen; + Rcpp::RNGScope rcpp_rngScope_gen; + rcpp_result_gen = Rcpp::wrap(steady_clock_seconds_rcpp()); + return rcpp_result_gen; +END_RCPP +} // get_subset_from_logical_selection_rcpp List get_subset_from_logical_selection_rcpp(const LogicalVector& selection, const IntegerVector& dimension_sums); RcppExport SEXP _MarchR_get_subset_from_logical_selection_rcpp(SEXP selectionSEXP, SEXP dimension_sumsSEXP) { @@ -59,6 +69,7 @@ END_RCPP static const R_CallMethodDef CallEntries[] = { {"_MarchR_rcpp_hello_world", (DL_FUNC) &_MarchR_rcpp_hello_world, 0}, + {"_MarchR_steady_clock_seconds_rcpp", (DL_FUNC) &_MarchR_steady_clock_seconds_rcpp, 0}, {"_MarchR_get_subset_from_logical_selection_rcpp", (DL_FUNC) &_MarchR_get_subset_from_logical_selection_rcpp, 2}, {"_MarchR_get_subset_from_integer_selection_rcpp", (DL_FUNC) &_MarchR_get_subset_from_integer_selection_rcpp, 2}, {"_MarchR_get_subset_from_character_selection_rcpp", (DL_FUNC) &_MarchR_get_subset_from_character_selection_rcpp, 2}, diff --git a/src/selections.cpp b/src/selections.cpp index c94727e..4ca55c6 100644 --- a/src/selections.cpp +++ b/src/selections.cpp @@ -1,4 +1,5 @@ #include +#include #include #include "cpp/selections/selection_masks.cpp" using namespace Rcpp; @@ -22,6 +23,13 @@ List rcpp_hello_world() { return z; } +// Seconds on a monotonic clock, so log durations never go negative when the wall clock is stepped. +// [[Rcpp::export]] +double steady_clock_seconds_rcpp() { + auto now = std::chrono::steady_clock::now().time_since_epoch(); + return std::chrono::duration(now).count(); +} + // Get the selections for each matrix // @param selection Logical selection indicating for each row/feature, which // columns to take. TRUE if taking, False, if not. diff --git a/tests/testthat/setup-matrices.R b/tests/testthat/setup-matrices.R index 8028927..321c0d5 100644 --- a/tests/testthat/setup-matrices.R +++ b/tests/testthat/setup-matrices.R @@ -20,3 +20,9 @@ create_small_matrix <- function( colnames(mat) <- paste0(col_name_prefix, '_', 1:ncol) return(mat %>% as("IterableMatrix")) } + +# Drops timestamps and trailing newlines from captured log lines and masks durations as [Xs]. +.strip_log <- function(msgs) { + msgs <- sub("^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} ", "", sub("\n$", "", msgs)) + gsub("\\[[0-9]+\\.[0-9]s\\]", "[Xs]", msgs) +} diff --git a/tests/testthat/test-clustering.R b/tests/testthat/test-clustering.R index b0feab7..45c5375 100644 --- a/tests/testthat/test-clustering.R +++ b/tests/testthat/test-clustering.R @@ -405,7 +405,19 @@ test_that("add_clusters.MarchRProject with Seurat clustering", { expect_true(all(!is.na(meta$seurat_clusters))) }) -test_that("add_clusters forwards verbose to knn_method and accepts methods without verbose", { +test_that("add_clusters aborts when every cluster is smaller than n_outlier", { + set.seed(42) + embedding <- matrix(rnorm(200), nrow = 40, ncol = 5) + rownames(embedding) <- paste0("cell_", seq_len(40)) + singletons <- function(mat, ...) factor(seq_len(nrow(mat))) + + expect_error( + add_clusters(embedding, cluster_graph_method = singletons, n_outlier = 5L, seed = 1L), + "All 40 clusters have fewer than `n_outlier` = 5 cells" + ) +}) + +test_that("add_clusters silences knn_method output and accepts methods without verbose", { skip_if_not_installed("RcppHNSW") set.seed(42) embedding <- matrix(rnorm(200), nrow = 40, ncol = 5) @@ -415,23 +427,61 @@ test_that("add_clusters forwards verbose to knn_method and accepts methods witho seen <<- c(seen, verbose) knn_hnsw(data, query, k = 10L, threads = threads, verbose = FALSE) } - - suppressMessages( - add_clusters(embedding, knn_method = spy_knn, n_outlier = 0L, seed = 1L, verbose = TRUE) - ) - expect_identical(seen, TRUE) - two_groups <- function(mat, ...) factor(rep(c("A", "B"), c(nrow(mat) - 2L, 2L))) - seen <- logical(0) + suppressMessages(add_clusters(embedding, knn_method = spy_knn, cluster_graph_method = two_groups, n_outlier = 5L, seed = 1L, verbose = TRUE)) - expect_identical(seen, c(TRUE, TRUE)) - seen <- logical(0) - add_clusters(embedding, knn_method = spy_knn, cluster_graph_method = two_groups, - n_outlier = 5L, seed = 1L, verbose = FALSE) expect_identical(seen, c(FALSE, FALSE)) - expect_no_error( add_clusters(embedding, knn_method = knn_annoy(k = 10L), n_outlier = 0L, seed = 1L, verbose = FALSE) ) }) + +test_that("add_clusters reports what it found and what it added", { + skip_if_not_installed("RcppHNSW") + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(42) + embedding <- matrix(rnorm(200), nrow = 40, ncol = 5) + rownames(embedding) <- paste0("cell_", seq_len(40)) + two_groups <- function(mat, ...) factor(rep(c("A", "B"), c(nrow(mat) - 2L, 2L))) + + msgs <- capture_messages(add_clusters(embedding, cluster_graph_method = two_groups, + n_outlier = 5L, seed = 1L, verbose = TRUE)) + expect_identical(.strip_log(msgs), c( + "Clustering: 40 cells, 5 dims", + "Found 2 clusters, reassigned 1 small cluster (2 cells) [Xs]", + "Clustering finished [Xs]: 1 cluster" + )) + expect_no_message( + add_clusters(embedding, cluster_graph_method = two_groups, n_outlier = 5L, seed = 1L, + verbose = FALSE) + ) + + three_groups <- function(mat, ...) factor(rep(c("A", "B", "C"), c(15L, 15L, 10L))) + lines <- .strip_log(capture_messages(add_clusters(embedding, cluster_graph_method = three_groups, + n_outlier = 0L, max_clusters = 2L, seed = 1L, + verbose = TRUE))) + expect_identical(lines[2:3], c( + "Found 3 clusters, merged to 2 [Xs]", + "Clustering finished [Xs]: 2 clusters" + )) + + proj <- create_cluster_test_project() + proj <- PCA(proj, assay_name = "RNA", output_assay_name = "test_pca", dim_reduction_name = "test_pca", + n_dimensions = 5, n_features = 8) + lines <- .strip_log(capture_messages( + add_clusters(proj, embedding_name = "test_pca", col_name = "clusters", seed = 1L, verbose = TRUE) + )) + expect_length(lines, 3) + expect_identical(lines[1], "Clustering: 48 cells on 'test_pca' (5 dims)") + found_pattern <- paste0( + "^Found [0-9]+ clusters?(, reassigned [0-9]+ small clusters? \\([0-9]+ cells?\\))?", + "(, merged to [0-9]+)? \\[Xs\\]$" + ) + expect_match(lines[2], found_pattern, perl = TRUE) + finished_pattern <- paste0( + "^Clustering finished \\[Xs\\]: added cell metadata column 'clusters' ", + "\\([0-9]+ clusters?\\)$" + ) + expect_match(lines[3], finished_pattern, perl = TRUE) +}) diff --git a/tests/testthat/test-dimensionality_reduction.R b/tests/testthat/test-dimensionality_reduction.R index 792689d..fcfebd0 100644 --- a/tests/testthat/test-dimensionality_reduction.R +++ b/tests/testthat/test-dimensionality_reduction.R @@ -1079,12 +1079,109 @@ test_that("PCA removes its on-disk normalization cache", { expect_equal(ncol(pca_res$cell_embeddings), 5) }) -test_that("LSI reports its total time and leaves no run clock behind", { +test_that("LSI reports its fit and dropped components, then its result", { + withr::local_options(rlib_message_verbosity = "verbose") set.seed(1) - counts <- matrix(rpois(100 * 200, lambda = 2), nrow = 100, + scale <- seq(0.2, 3, length.out = 200) + counts <- matrix(rpois(100 * 200, lambda = rep(2 * scale, each = 100)), nrow = 100, dimnames = list(paste0("f", 1:100), paste0("c", 1:200))) mat <- methods::as(methods::as(counts, "dgCMatrix"), "IterableMatrix") - msgs <- capture_messages(LSI(mat, n_dimensions = 5, verbose = TRUE)) - expect_equal(sum(grepl("Finished \\([0-9]+\\.[0-9]s\\)", msgs)), 1L) + + msgs <- capture_messages(LSI(mat, n_dimensions = 5, corr_cutoff = 0.5, threads = 1L, verbose = TRUE)) + expect_match(msgs[c(1, length(msgs))], "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} ", perl = TRUE) + lines <- .strip_log(msgs) + expect_length(lines, 4) + expect_identical(lines[1], "LSI: 200 cells, 100 features, 5 dims, 1 thread") + expect_identical(lines[2], "Fit LSI on 191 cells, projected 9 depth outliers [Xs]") + expect_match(lines[3], "^Dropped LSI component 1 \\(r = [0-9.]+ with total counts\\)$", perl = TRUE) + expect_identical(lines[4], "LSI finished [Xs]: 200 x 4 embedding") expect_null(.log_clock$start) + + depth <- structure(stats::setNames(colSums(counts), colnames(counts)), label = "nFrags") + lines <- .strip_log(capture_messages( + LSI(mat, n_dimensions = 5, corr_cutoff = 0.5, depth = depth, threads = 1L, verbose = TRUE) + )) + expect_match(lines[3], " with log10\\(nFrags\\)\\)$", perl = TRUE) + expect_no_message(LSI(mat, n_dimensions = 5, corr_cutoff = 0.5, threads = 1L, verbose = FALSE)) + + lines <- .strip_log(capture_messages( + LSI(mat, n_dimensions = 5, corr_cutoff = 0.05, threads = 1L, verbose = TRUE) + )) + expect_match( + lines[3], "^Dropped LSI components [0-9, ]+ \\(r = [0-9., ]+ with total counts\\)$", perl = TRUE + ) +}) + +test_that("LSI on a project prints one setup and one finished line naming the dim reduction", { + proj <- create_test_project() + lines <- .strip_log(capture_messages( + proj <- LSI(proj, dim_reduction_name = "test_lsi", n_dimensions = 5, threads = 1L, verbose = TRUE) + )) + expect_match(lines[1], "^LSI: [0-9,]+ cells, [0-9,]+ features, 5 dims, 1 thread$", perl = TRUE) + expect_match( + lines[length(lines)], + "^LSI finished \\[Xs\\]: added dim reduction 'test_lsi' \\([0-9,]+ x [0-9]+\\)$", + perl = TRUE + ) + expect_equal(sum(grepl("^LSI: ", lines)), 1L) + expect_equal(sum(grepl("^LSI finished", lines)), 1L) + expect_false(any(grepl("Finished \\[", lines))) +}) + +test_that("IterativeLSI reports each iteration's steps and silences the KNN search", { + skip_if_not_installed("RcppHNSW") + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(1) + mat <- matrix(runif(50000), nrow = 500, ncol = 100) %>% + as("dgCMatrix") %>% + as("IterableMatrix") + rownames(mat) <- paste0("feat", seq_len(500)) + colnames(mat) <- paste0("cell", seq_len(100)) + + msgs <- capture_messages(IterativeLSI( + mat, n_iterations = 2, n_dimensions = 10L, first_selection = "var", + feature_selection_method = select_features_variance(num_feats = 250L), + binarize = FALSE, outlier_quantiles = NULL, threads = 1L, verbose = TRUE + )) + expect_false(any(grepl("HNSW", msgs))) + lines <- .strip_log(msgs) + dropped <- grepl("Dropped LSI component", lines) + expect_true(all(grepl("^ Dropped LSI components? [0-9, ]+ \\(r = [0-9., ]+ with total counts\\)$", + lines[dropped]))) + patterns <- c( + "^Iterative LSI: 100 cells, 2 iterations, 10 dims, 1 thread$", + "^\\[Iteration 1/2\\]$", + "^ Selected 250 variable features \\[Xs\\]$", + "^ Fit LSI on 100 cells \\[Xs\\]$", + "^ Found [0-9]+ clusters?(, merged to [0-9]+)? \\[Xs\\]$", + "^ Pseudobulked [0-9]+ clusters? \\[Xs\\]$", + "^ Iteration finished \\[Xs\\]$", + "^\\[Iteration 2/2\\]$", + "^ Selected 250 variable features \\[Xs\\]$", + "^ Fit LSI on 100 cells \\[Xs\\]$", + "^ Iteration finished \\[Xs\\]$", + "^Iterative LSI finished \\[Xs\\]: 100 x 10 embedding$" + ) + core <- lines[!dropped] + expect_length(core, length(patterns)) + for (k in seq_along(patterns)) expect_match(core[k], patterns[k], perl = TRUE) + expect_no_message(IterativeLSI( + mat, n_iterations = 2, n_dimensions = 10L, first_selection = "var", + feature_selection_method = select_features_variance(num_feats = 250L), + binarize = FALSE, outlier_quantiles = NULL, threads = 1L, verbose = FALSE + )) +}) + +test_that("IterativeLSI on a project prints one setup and one finished line", { + proj <- create_test_project(nrow = 50, ncol1 = 100, ncol2 = 0) + lines <- .strip_log(capture_messages(proj <- IterativeLSI( + proj, n_iterations = 1, n_dimensions = 5L, binarize = FALSE, threads = 1L, verbose = TRUE + ))) + expect_match(lines[1], "^Iterative LSI: [0-9,]+ cells, 1 iteration, 5 dims, 1 thread$", perl = TRUE) + expect_match(lines[3], "^ Selected [0-9,]+ features \\(top accessible\\) \\[Xs\\]$", perl = TRUE) + expect_match(lines[length(lines)], + "^Iterative LSI finished \\[Xs\\]: added dim reduction 'IterativeLSI' \\([0-9,]+ x [0-9]+\\)$", + perl = TRUE) + expect_equal(sum(grepl("^Iterative LSI", lines)), 2L) + expect_false(any(grepl("Finished \\[", lines))) }) diff --git a/tests/testthat/test-iterative-lsi-embedding-copies.R b/tests/testthat/test-iterative-lsi-embedding-copies.R index 771b868..29e65fb 100644 --- a/tests/testthat/test-iterative-lsi-embedding-copies.R +++ b/tests/testthat/test-iterative-lsi-embedding-copies.R @@ -8,9 +8,11 @@ test_that("LSI holds out and re-projects depth outliers on this fixture", { mat <- .lsi_tail_fixture() - expect_message( - LSI(mat, n_dimensions = 10, outlier_quantiles = c(0.05, 0.95), - drop_zero_cells = FALSE, verbose = TRUE), - "Re-projecting outlier cells" + expect_match( + capture_messages( + LSI(mat, n_dimensions = 10, outlier_quantiles = c(0.05, 0.95), + drop_zero_cells = FALSE, verbose = TRUE) + ), + "projected [0-9]+ depth outliers?", all = FALSE ) }) diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index cedde41..3b7de66 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -37,7 +37,7 @@ test_that("a verbose run that printed something reports its total time on a norm msgs <- capture_messages(run(verbose = TRUE)) expect_length(msgs, 2) expect_match( - msgs[2], "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Finished \\([0-9]+\\.[0-9]s\\)\n$", perl = TRUE + msgs[2], "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Finished \\[[0-9]+\\.[0-9]s\\]\n$", perl = TRUE ) expect_length(capture_messages(run(verbose = FALSE)), 1) expect_length(capture_messages(run(verbose = TRUE, say = FALSE)), 0) @@ -57,7 +57,7 @@ test_that("nested calls share one run clock that is cleared on return and on err list(start = .log_clock$start, inner_start = inner(), after_inner = .log_clock$start) } res <- outer() - expect_s3_class(res$start, "POSIXct") + expect_type(res$start, "double") expect_identical(res$inner_start, res$start) expect_identical(res$after_inner, res$start) expect_null(.log_clock$start) @@ -84,10 +84,12 @@ test_that("the MarchR.verbose option overrides function defaults in both directi emb <- matrix(rnorm(200 * 5), nrow = 200, dimnames = list(paste0("cell_", 1:200), NULL)) withr::local_options(MarchR.verbose = TRUE) - expect_match(capture_messages(LSI(mat, n_dimensions = 5)), "Starting LSI", all = FALSE) + expect_match(capture_messages(LSI(mat, n_dimensions = 5)), "LSI: 200 cells", all = FALSE) withr::local_options(MarchR.verbose = FALSE) expect_no_message(make_knn_pseudobulks(emb, knn_iteration = 50L, k = 20L)) - expect_match(capture_messages(LSI(mat, n_dimensions = 5, verbose = TRUE)), "Starting LSI", all = FALSE) + expect_match( + capture_messages(LSI(mat, n_dimensions = 5, verbose = TRUE)), "LSI: 200 cells", all = FALSE + ) }) test_that("an invalid MarchR.verbose option is rejected when a run starts", { @@ -102,3 +104,100 @@ test_that("an invalid MarchR.verbose option is rejected when a run starts", { expect_no_error(starts_run()) expect_null(.log_clock$start) }) + +test_that("an owner run prints a timestamped setup line, plain steps, and a timestamped finish", { + widget <- function(verbose = TRUE) { + .start_log_clock() + run <- .log_start("Widget", "3 cells") + .log_step("Counted 3 cells", since = run$start) + .log_finish(run, "added nothing") + invisible(NULL) + } + msgs <- capture_messages(widget()) + stamp <- "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} " + expect_length(msgs, 3) + expect_match(msgs[c(1, 3)], stamp, perl = TRUE) + expect_no_match(msgs[2], stamp, perl = TRUE) + expect_identical(.strip_log(msgs), c( + "Widget: 3 cells", + "Counted 3 cells [Xs]", + "Widget finished [Xs]: added nothing" + )) +}) + +test_that("nested runs indent without timestamps; compact and same-title runs log only steps", { + child <- function(title, compact = FALSE) { + .start_log_clock() + run <- .log_start(title, "child setup", compact = compact) + .log_step("Child step") + .log_finish(run, "child done") + } + parent <- function(title, compact = FALSE, verbose = TRUE) { + .start_log_clock() + run <- .log_start("Parent", "parent setup") + pass <- .log_pass("Iteration 1/1", "Iteration") + child(title, compact) + .log_pass_end(pass) + .log_finish(run, "parent done") + invisible(NULL) + } + + msgs <- capture_messages(parent("Child")) + expect_no_match(msgs[2:6], "^[0-9]{4}-", perl = TRUE) + expect_identical(.strip_log(msgs), c( + "Parent: parent setup", + "[Iteration 1/1]", + " Child: child setup", + " Child step", + " Child finished [Xs]: child done", + " Iteration finished [Xs]", + "Parent finished [Xs]: parent done" + )) + steps_only <- c( + "Parent: parent setup", + "[Iteration 1/1]", + " Child step", + " Iteration finished [Xs]", + "Parent finished [Xs]: parent done" + ) + expect_identical(.strip_log(capture_messages(parent("Child", compact = TRUE))), steps_only) + expect_identical(.strip_log(capture_messages(parent("Parent"))), steps_only) +}) + +test_that("an error inside a nested run restores the indentation", { + failing <- function() { + .start_log_clock() + .log_start("Child", "child setup") + rlang::abort("boom") + } + parent <- function(verbose = TRUE) { + .start_log_clock() + run <- .log_start("Parent", "parent setup") + pass <- .log_pass("Iteration 1/1", "Iteration") + try(failing(), silent = TRUE) + open_after <- .log_clock$open + .log_pass_end(pass) + .log_step("After the child") + .log_finish(run, "parent done") + open_after + } + msgs <- capture_messages(open_after <- parent()) + expect_identical(open_after, "Parent") + expect_identical(.strip_log(msgs), c( + "Parent: parent setup", + "[Iteration 1/1]", + " Child: child setup", + " Iteration finished [Xs]", + "After the child", + "Parent finished [Xs]: parent done" + )) + expect_null(.log_clock$start) + expect_identical(.log_clock$depth, 0L) +}) + +test_that("log durations come from a monotonic clock in seconds", { + t0 <- steady_clock_seconds_rcpp() + expect_type(t0, "double") + expect_gte(steady_clock_seconds_rcpp(), t0) + expect_match(.log_secs(t0 - 2), "^\\[2\\.[0-9]s\\]$", perl = TRUE) +}) From e990cb41707f5accefba5fe8a5c30f1437164288 Mon Sep 17 00:00:00 2001 From: erliuu Date: Tue, 20 Oct 2026 23:56:20 -0700 Subject: [PATCH 06/12] feat([r] logging): Updating logging format for remaining hema tutorial functions as working test --- R/doublet.R | 231 +++++++++++----- R/embeddings.R | 154 ++++++++--- R/imputation.R | 75 +++-- man/add_impute_weights.Rd | 4 +- tests/testthat/test-doublet.R | 222 +++++++++++++++ tests/testthat/test-embeddings.R | 152 ++++++++++ tests/testthat/test-imputation.R | 51 ++++ vignettes/marchr_hematopoiesis.Rmd | 2 +- vignettes/marchr_hematopoiesis.html | 415 +++++++--------------------- 9 files changed, 859 insertions(+), 447 deletions(-) diff --git a/R/doublet.R b/R/doublet.R index 3c18ee5..fffff46 100644 --- a/R/doublet.R +++ b/R/doublet.R @@ -133,6 +133,7 @@ add_doublet_scores.MarchRDataset <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_character(assay_name) assert_that(is.list(lsi_params)) assay_name <- select_assay_name(x, assay_name) @@ -140,12 +141,19 @@ add_doublet_scores.MarchRDataset <- function( scoring_method <- match.arg(scoring_method) assert_that(is.function(knn_method)) + if (verbose) { + run <- .log_start("Doublet scoring", sprintf( + "%s, %s", .log_plural(ncol(input_mat), "cell"), .log_plural(.resolve_threads(threads), "thread") + )) + } # Re-orient input matrix if transposed + t0 <- steady_clock_seconds_rcpp() if (input_mat@transpose) { src_dir <- tempfile("doublet_src_") on.exit(unlink(src_dir, recursive = TRUE, expand = FALSE), add = TRUE) input_mat <- transpose_storage_order(input_mat, src_dir) + if (verbose) .log_step(sprintf("Transposed %s storage order", assay_name), since = t0) } sim_doublets <- simulate_doublets( @@ -192,6 +200,7 @@ add_doublet_scores.MarchRDataset <- function( lsi_cells = project_res$lsi_cells ) + if (verbose) .log_finish(run, sprintf("added doublet scores (%s)", .log_plural(nrow(scores), "cell"))) return(x) } @@ -223,6 +232,7 @@ add_doublet_scores.MarchRProject <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_character(assay_name) assert_is_character(dataset_names) dataset_names <- select_dataset_names(x, dataset_names) @@ -230,16 +240,20 @@ add_doublet_scores.MarchRProject <- function( scoring_method <- match.arg(scoring_method) assert_that(is.function(knn_method)) + combined <- combine && length(dataset_names) > 1 + if (verbose) { + n_cells <- sum(purrr::map_int(dataset_names, function(ds) { + ncol(get_matrix(x, assay_name = assay_name, dataset_name = ds)) + })) + run <- .log_start("Doublet scoring", sprintf( + "%s%s, %s, %s", .log_plural(length(dataset_names), "dataset"), + if (combined) " combined as replicates" else "", .log_plural(n_cells, "cell"), + .log_plural(.resolve_threads(threads), "thread") + )) + } # Replicates must be merged before doublet scoring so cross-sample doublets are detectable - if (combine && length(dataset_names) > 1) { - if (verbose) { - log_progress(sprintf( - "Processing dataset(s): %s as replicates", - paste(dataset_names, collapse = ", ") - )) - } - + if (combined) { input_mats <- lapply(seq_along(dataset_names), function(i) { ds <- dataset_names[i] mat <- get_matrix(x, assay_name = assay_name, dataset_name = ds) @@ -259,6 +273,7 @@ add_doublet_scores.MarchRProject <- function( prefix_cells = FALSE ) + if (verbose) pass <- .log_pass(new_dataset_name, "Dataset") x$datasets[[new_dataset_name]] <- add_doublet_scores( x$datasets[[new_dataset_name]], assay_name = assay_name, @@ -281,18 +296,11 @@ add_doublet_scores.MarchRProject <- function( threads = threads, verbose = verbose ) + if (verbose) .log_pass_end(pass) } else { - n_datasets <- length(dataset_names) # TODO parallelize this (based on threads) - for (i in seq_along(dataset_names)) { - ds <- dataset_names[i] - if (verbose) { - log_progress(sprintf( - "Processing dataset %d of %d: %s", - i, n_datasets, ds - )) - } - + for (ds in dataset_names) { + if (verbose) pass <- .log_pass(ds, "Dataset") x$datasets[[ds]] <- add_doublet_scores( x$datasets[[ds]], assay_name = assay_name, @@ -315,9 +323,15 @@ add_doublet_scores.MarchRProject <- function( threads = threads, verbose = verbose ) + if (verbose) .log_pass_end(pass) } } + if (verbose) { + target <- if (combined) sprintf("dataset '%s'", new_dataset_name) else + .log_plural(length(dataset_names), "dataset") + .log_finish(run, sprintf("added doublet scores to %s (%s)", target, .log_plural(n_cells, "cell"))) + } return(x) } @@ -373,6 +387,7 @@ simulate_doublets.default <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_greater_than_zero(n_doublets) assert_true( is.numeric(sample_ratio) && length(sample_ratio) == 1 && @@ -389,9 +404,10 @@ simulate_doublets.default <- function( n_total <- n_doublets * n_trials if (verbose) { - log_progress(sprintf( - "Simulating %d synthetic doublets (%d doublets x %d trials)", - n_total, n_doublets, n_trials + run <- .log_start("Doublet simulation", .log_plural(n_cells, "cell"), compact = TRUE) + .log_step(sprintf( + "Simulated %s (%s x %s)", .log_plural(n_total, "doublet"), .log_count(n_doublets), + .log_plural(n_trials, "trial") )) } @@ -404,7 +420,9 @@ simulate_doublets.default <- function( left <- sample_bernoulli(.repeating_col_select(mat_u32, idx1_all), sample_ratio, seed = seed) right <- sample_bernoulli(.repeating_col_select(mat_u32, idx2_all), sample_ratio, seed = seed + 1L) colnames(right) <- colnames(left) - left + right + doublets <- left + right + if (verbose) .log_finish(run, .log_plural(n_total, "simulated doublet")) + doublets } #' Lazy column selection that permits duplicates @@ -456,10 +474,7 @@ simulate_doublets.default <- function( threads = get_threads(), verbose = FALSE ) { - if (verbose) { - log_progress("Running UMAP fitting on LSI matrix") - } - + t0 <- steady_clock_seconds_rcpp() umap_defaults <- c( list( X = as.matrix(lsi_cells), @@ -468,7 +483,7 @@ simulate_doublets.default <- function( metric = "euclidean", ret_nn = TRUE, ret_model = TRUE, - verbose = verbose + verbose = FALSE ), .umap2_defaults(seed = seed, batch = batch, threads = threads) ) @@ -476,15 +491,12 @@ simulate_doublets.default <- function( umap_model <- do.call(uwot::umap2, umap_args) umap_cells <- umap_model$embedding - if (verbose) { - log_progress("Validating re-projection Pearson correlation") - } umap_reprojected <- uwot::umap_transform( as.matrix(lsi_cells), umap_model, n_threads = threads, n_sgd_threads = .umap_sgd_threads(umap_model), - verbose = verbose + verbose = FALSE ) corr_projection <- c( @@ -494,19 +506,31 @@ simulate_doublets.default <- function( R_squared = round(mean(corr_projection)^2, 5) projection_ok <- R_squared >= min_corr_threshold + if (verbose) { + fit <- if (projection_ok) { + sprintf("Fit UMAP, re-projection R^2 = %.3f", R_squared) + } else { + sprintf( + "Fit UMAP, re-projection R^2 = %.4f (below %.2f), %s", R_squared, min_corr_threshold, + if (force) "proceeding (force = TRUE)" else "scoring in LSI instead" + ) + } + .log_step(fit, since = t0) + } + if (!projection_ok) { - log_progress(sprintf("Projection R^2 is below minimum threshold: R^2 = %.4f, min = %.2f. Population may be too homogeneous for reliable doublet scoring.", - R_squared, min_corr_threshold)) + below <- sprintf(paste( + "Projection R^2 = %.4f is below %.2f; the population may be too homogeneous for reliable", + "doublet scoring." + ), R_squared, min_corr_threshold) if (force) { - warning(" Proceeding anyway (force = TRUE).") + warning(paste(below, "Proceeding anyway (force = TRUE)."), call. = FALSE) } else { - warning(" Returning NULL UMAP model. Use force = TRUE to override.") + warning(paste(below, "Returning NULL UMAP model; use force = TRUE to override."), call. = FALSE) return(NULL) } } - if (verbose) log_progress(sprintf("UMAP Re-projection Correlation: R^2 = %.3f", R_squared)) - return(umap_model) } @@ -595,14 +619,18 @@ project_doublets.default <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_mat(mat) assert_is_mat(sim_doublets) assert_that(is.list(lsi_params)) # `threads` stays unresolved for IterativeLSI(), which threads its clustering only when the # value was given explicitly umap_threads <- .resolve_threads(threads) - - if (verbose) log_progress("Running Iterative LSI on input matrix") + if (verbose) { + run <- .log_start("Doublet projection", sprintf( + "%s, %s", .log_plural(ncol(mat), "cell"), .log_plural(ncol(sim_doublets), "doublet") + ), compact = TRUE) + } # Compute IterativeLSI given input matrix # ArchR defaults to LSIMethod = 1 (tf-logidf) for doublet inference @@ -626,11 +654,14 @@ project_doublets.default <- function( lsi_dimred <- lsi_result$dim_reduction lsi_cells <- lsi_result$cell_embeddings - if (verbose) log_progress("Projecting simulated doublets on LSI space") + t0 <- steady_clock_seconds_rcpp() lsi_doublets <- project( lsi_dimred, sim_doublets ) + if (verbose) { + .log_step(sprintf("Projected %s into LSI", .log_plural(nrow(lsi_doublets), "doublet")), since = t0) + } # UMAP provides a 2D space where doublet proximity is more interpretable than high-dim LSI umap_model <- .run_umap_projections( @@ -648,15 +679,19 @@ project_doublets.default <- function( umap_cells <- umap_model$embedding # Project simulated doublets into the fitted UMAP space - if (verbose) log_progress("Projecting simulated doublets on UMAP space") - + t0 <- steady_clock_seconds_rcpp() umap_doublets <- uwot::umap_transform( as.matrix(lsi_doublets), umap_model, n_threads = umap_threads, n_sgd_threads = .umap_sgd_threads(umap_model), - verbose = verbose + verbose = FALSE ) + if (verbose) { + .log_step( + sprintf("Projected %s into UMAP", .log_plural(nrow(umap_doublets), "doublet")), since = t0 + ) + } colnames(umap_cells) <- c("UMAP1", "UMAP2") colnames(umap_doublets) <- c("UMAP1", "UMAP2") } else { @@ -664,6 +699,12 @@ project_doublets.default <- function( umap_doublets <- NULL } + if (verbose) { + .log_finish(run, sprintf( + "%s embeddings for %s and %s", if (is.null(umap_model)) "LSI" else "LSI and UMAP", + .log_plural(nrow(lsi_cells), "cell"), .log_plural(nrow(lsi_doublets), "doublet") + )) + } list( lsi_cells = lsi_cells, lsi_doublets = lsi_doublets, @@ -714,6 +755,7 @@ score_doublets.default <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") .run_knn <- function(cells_embed, doublets_embed, knn_method) { @@ -757,15 +799,21 @@ score_doublets.default <- function( scoring_method <- match.arg(scoring_method) assert_that(is.function(knn_method)) - knn_method <- partial_apply(knn_method, verbose = verbose, .missing_args_error = FALSE) + knn_method <- partial_apply(knn_method, verbose = FALSE, .missing_args_error = FALSE) lsi_cells <- as.matrix(project_res$lsi_cells) lsi_doublets <- as.matrix(project_res$lsi_doublets) # Fall back to LSI space when UMAP projection failed (NULL model) or user explicitly chose LSI - if (scoring_method == "LSI" || (is.null(project_res$umap_cells))) { + space <- if (scoring_method == "LSI" || is.null(project_res$umap_cells)) "LSI" else "UMAP" + if (verbose) { + run <- .log_start("Doublet neighbor scoring", sprintf( + "%s in %s", .log_plural(nrow(lsi_cells), "cell"), space + ), compact = TRUE) + } + t0 <- steady_clock_seconds_rcpp() + if (space == "LSI") { # Use higher-dimensional LSI embedding for KNN doublet scoring - if (verbose) log_progress("Compute doublet scores and enrichments from LSI") scores <- .run_knn( cells_embed = lsi_cells, doublets_embed = lsi_doublets, @@ -778,7 +826,6 @@ score_doublets.default <- function( umap_doublets <- as.matrix(project_res$umap_doublets) # UMAP preserves local structure, making KNN doublet detection more sensitive - if (verbose) log_progress("Compute doublet scores and enrichments from UMAP") scores <- .run_knn( cells_embed = umap_cells, doublets_embed = umap_doublets, @@ -791,6 +838,12 @@ score_doublets.default <- function( # BPCells knn_hnsw strips rownames from results, so restore cell IDs for downstream joins rownames(scores) <- cell_ids + if (verbose) { + .log_step(sprintf( + "Scored %s by doublet neighbors in %s", .log_plural(nrow(scores), "cell"), space + ), since = t0) + .log_finish(run, sprintf("scores for %s", .log_plural(nrow(scores), "cell"))) + } return(scores) } @@ -841,6 +894,7 @@ filter_doublets.MarchRDataset <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") if (!is.null(proj$filtered_doublets) && proj$filtered_doublets == TRUE) { warning("filter_doublets() has already been run on this dataset. Skipping...") return(proj) @@ -851,6 +905,12 @@ filter_doublets.MarchRDataset <- function( } scores <- proj$doublet_data$scores + if (verbose) { + run <- .log_start("Doublet filtering", sprintf( + "%s (%s)", .log_plural(nrow(scores), "cell"), + .doublet_cutoffs(enrich_cutoff, score_cutoff, filter_ratio) + )) + } # Rank cells by enrichment so the most doublet-like cells are removed first up to the cap n <- nrow(scores) @@ -873,16 +933,7 @@ filter_doublets.MarchRDataset <- function( } n_remove <- length(remove_cells) - if (n_remove == 0) { - if (verbose) log_progress("Doublet filtering has removed no cells.") - - } else { - if (verbose) { - log_progress(sprintf( - "Filtering %d doublets from %d cells (%.1f%%)", - n_remove, n, (100 * n_remove / n) - )) - } + if (n_remove > 0) { # Remove doublet cells from the primary assay, then propagate via align_cells to all assays/fragments assay_name <- get_assay_names(proj)[1] mat <- proj$matrices[[assay_name]] @@ -896,14 +947,17 @@ filter_doublets.MarchRDataset <- function( # Prevent accidental double-filtering by marking this dataset as already processed proj$filtered_doublets <- TRUE - if (verbose) log_progress("Dataset successfully filtered.") } if (clear_doublet_data) { - if (verbose) log_progress("Removing stale doublet data") proj$doublet_data <- NULL } + if (verbose) { + .log_finish(run, paste0( + .doublet_removed(n_remove, n), if (clear_doublet_data) ", cleared doublet data" + )) + } return(proj) } @@ -918,20 +972,30 @@ filter_doublets.MarchRProject <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_character(dataset_names) dataset_names <- select_dataset_names(proj, dataset_names) - if (verbose) log_progress(sprintf( - "Filtering doublets in %d dataset(s): %s", - length(dataset_names), - paste(dataset_names, collapse = ", ") - )) + # Counts the primary-assay matrix, which is the matrix the dataset method filters + count_cells <- function(ds) { + dataset <- proj$datasets[[ds]] + if (length(dataset$matrices) == 0) 0L else ncol(dataset$matrices[[get_assay_names(dataset)[1]]]) + } + if (verbose) { + n_cells <- sum(purrr::map_int(dataset_names, count_cells)) + n_removed <- 0L + n_processed <- 0L + run <- .log_start("Doublet filtering", sprintf( + "%s, %s (%s)", .log_plural(length(dataset_names), "dataset"), .log_plural(n_cells, "cell"), + .doublet_cutoffs(enrich_cutoff, score_cutoff, filter_ratio) + )) + } for (ds in dataset_names) { - if (verbose) log_progress(sprintf( - "filtering dataset: %s.", - ds - )) + already_filtered <- isTRUE(proj$datasets[[ds]]$filtered_doublets) + if (verbose && already_filtered) .log_step(paste0(ds, ": already filtered, skipped")) + t0 <- steady_clock_seconds_rcpp() + if (verbose) n_before <- count_cells(ds) proj$datasets[[ds]] <- filter_doublets( proj$datasets[[ds]], @@ -939,12 +1003,41 @@ filter_doublets.MarchRProject <- function( score_cutoff = score_cutoff, filter_ratio = filter_ratio, clear_doublet_data = clear_doublet_data, - verbose = verbose + verbose = FALSE ) + + if (verbose && !already_filtered) { + n_ds_removed <- n_before - count_cells(ds) + n_removed <- n_removed + n_ds_removed + n_processed <- n_processed + 1L + .log_step(paste0(ds, ": ", .doublet_removed(n_ds_removed, n_before)), since = t0) + } + } + + if (verbose) { + .log_finish(run, paste0( + .doublet_removed(n_removed, n_cells), + if (clear_doublet_data && n_processed > 0) ", cleared doublet data" + )) } return(proj) } +.doublet_cutoffs <- function(enrich_cutoff, score_cutoff, filter_ratio) { + paste(c( + if (!is.null(enrich_cutoff)) paste("enrichment >=", enrich_cutoff), + if (!is.null(score_cutoff) && is.finite(score_cutoff)) paste("score >=", score_cutoff), + paste("filter ratio", filter_ratio) + ), collapse = ", ") +} + +.doublet_removed <- function(k, n) { + sprintf( + "removed %s of %s (%s)", .log_count(k), .log_plural(n, "cell"), + if (n > 0) sprintf("%.1f%%", 100 * k / n) else "0.0%" + ) +} + ######################################################################## # add_doublet_umap() method definition ######################################################################## diff --git a/R/embeddings.R b/R/embeddings.R index 2c5d0c1..723c5e4 100644 --- a/R/embeddings.R +++ b/R/embeddings.R @@ -55,6 +55,16 @@ add_umap <- function(x, ...) { if (isTRUE(model$batch)) "auto" else 0L } +# Finished-line summary of what an embedding run added. +.embedding_added_summary <- function(coords, assay = NULL, model = NULL) { + paste0( + "added cell metadata ", if (ncol(coords) == 1) "column " else "columns ", + paste0("'", colnames(coords), "'", collapse = ", "), + if (!is.null(assay)) sprintf(", assay '%s'", assay), + if (!is.null(model)) sprintf(", embedding model '%s'", model) + ) +} + #' @describeIn add_umap Compute UMAP on a cells x dimensions matrix #' #' @param x (matrix, dgCMatrix, IterableMatrix) An embedding matrix. @@ -96,6 +106,7 @@ add_umap.default <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_has_package("uwot") threads <- .resolve_threads(threads) assert_for(batch, "logical") @@ -103,7 +114,7 @@ add_umap.default <- function( # BPCells stores as features x cells; uwot/Rtsne expect cells x dims if (is(x, "IterableMatrix")) { - x <- as.matrix(t(x)) + x <- rlang::with_options(as.matrix(t(x)), rlib_message_verbosity = "quiet") } # Sparse matrices need densification for uwot/Rtsne if (is(x, "dgCMatrix")) { @@ -119,14 +130,20 @@ add_umap.default <- function( nrow(x) >= 2, msg = "Input matrix must have at least 2 cells." ) + if (verbose) { + run <- .log_start("UMAP", sprintf( + "%s, %s, %s", .log_plural(nrow(x), "cell"), .log_plural(ncol(x), "dim"), + .log_plural(threads, "thread") + )) + } # uwot requires n_neighbors < nrow; cap to avoid errors on small datasets max_neighbors <- nrow(x) - 1 if (n_neighbors > max_neighbors) { if (verbose) { - log_progress(sprintf( - "Reducing n_neighbors from %d to %d (must be < number of cells)", - n_neighbors, max_neighbors + .log_step(sprintf( + "Reduced n_neighbors from %s to %s (%s)", n_neighbors, max_neighbors, + .log_plural(nrow(x), "cell") )) } n_neighbors <- max_neighbors @@ -139,7 +156,7 @@ add_umap.default <- function( min_dist = min_dist, metric = metric, n_components = n_components, - verbose = verbose + verbose = FALSE ), .umap2_defaults(seed = seed, batch = batch, threads = threads) ) @@ -148,7 +165,14 @@ add_umap.default <- function( umap_args$X <- x umap_args$ret_model <- TRUE } + t0 <- steady_clock_seconds_rcpp() umap_result <- do.call(uwot::umap2, umap_args) + if (verbose) { + .log_step(sprintf( + "Fit %dD UMAP (%s neighbors, min_dist %s, %s)", umap_args$n_components, umap_args$n_neighbors, + umap_args$min_dist, paste(names(umap_args$metric) %||% umap_args$metric, collapse = "+") + ), since = t0) + } # uwot returns either a bare matrix or a list with $embedding depending on ret_model if (is.list(umap_result)) { @@ -159,6 +183,9 @@ add_umap.default <- function( rownames(umap_coords) <- rownames(x) colnames(umap_coords) <- paste0("UMAP_", seq_len(ncol(umap_coords))) + if (verbose) { + .log_finish(run, sprintf("%s x %d embedding", .log_count(nrow(umap_coords)), ncol(umap_coords))) + } if (return_model) { effective_params <- umap_args[setdiff(names(umap_args), c("X", "ret_model"))] @@ -208,6 +235,7 @@ add_umap.MarchRDataset <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRDataset") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -234,12 +262,14 @@ add_umap.MarchRDataset <- function( } # BPCells stores embeddings as features x cells; transpose to cells x dims for uwot/Rtsne - embedding <- as.matrix(t(x$matrices[[embedding_name]])) - + embedding <- rlang::with_options( + as.matrix(t(x$matrices[[embedding_name]])), + rlib_message_verbosity = "quiet" + ) if (verbose) { - log_progress(sprintf( - "Computing UMAP from '%s' (%d cells, %d dimensions)", - embedding_name, nrow(embedding), ncol(embedding) + run <- .log_start("UMAP", sprintf( + "%s on '%s' (%s), %s", .log_plural(nrow(embedding), "cell"), embedding_name, + .log_plural(ncol(embedding), "dim"), .log_plural(.resolve_threads(threads), "thread") )) } @@ -284,6 +314,12 @@ add_umap.MarchRDataset <- function( ) } + if (verbose) { + .log_finish(run, .embedding_added_summary( + umap_coords, assay = if (store_as_matrix) output_assay_name + )) + } + return(x) } @@ -337,6 +373,7 @@ add_umap.MarchRProject <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRProject") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -393,12 +430,12 @@ add_umap.MarchRProject <- function( } # Pull the shared embedding across datasets in an explicit feature order. - if (verbose) { - log_progress(sprintf("Extracting embedding '%s'", embedding_name)) - } - embedding_matrices <- lapply(dataset_names, function(dset) { - as.matrix(x$datasets[[dset]]$matrices[[embedding_name]]) - }) + embedding_matrices <- rlang::with_options( + lapply(dataset_names, function(dset) { + as.matrix(x$datasets[[dset]]$matrices[[embedding_name]]) + }), + rlib_message_verbosity = "quiet" + ) canonical_features <- rownames(embedding_matrices[[1]]) if (is.null(canonical_features)) { rlang::abort("Embedding assays must have feature names before computing UMAP.") @@ -424,14 +461,14 @@ add_umap.MarchRProject <- function( "Cell names must be globally unique across selected datasets before computing UMAP." ) } - - # Compute UMAP on the concatenated embedding so coordinates are comparable across datasets if (verbose) { - log_progress(sprintf( - "Computing UMAP on %d cells with %d dimensions", - nrow(embedding), ncol(embedding) + run <- .log_start("UMAP", sprintf( + "%s on '%s' (%s), %s", .log_plural(nrow(embedding), "cell"), embedding_name, + .log_plural(ncol(embedding), "dim"), .log_plural(.resolve_threads(threads), "thread") )) } + + # Compute UMAP on the concatenated embedding so coordinates are comparable across datasets umap_result <- add_umap.default( embedding, n_neighbors = n_neighbors, @@ -482,7 +519,9 @@ add_umap.MarchRProject <- function( if (overwrite && file.exists(model_file)) { unlink(model_file) } + t0 <- steady_clock_seconds_rcpp() uwot::save_uwot(umap_result$model, model_file, unload = TRUE) + if (verbose) .log_step("Saved UMAP model", since = t0) model_file <- normalizePath(model_file, mustWork = TRUE) } @@ -530,9 +569,10 @@ add_umap.MarchRProject <- function( } if (verbose) { - log_progress(sprintf( - "Added UMAP embedding as '%s' (%d components)", - output_assay_name, n_components + .log_finish(run, .embedding_added_summary( + umap_coords, + assay = if (store_as_matrix) output_assay_name, + model = if (return_model) output_assay_name )) } @@ -611,11 +651,13 @@ add_tsne.default <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_has_package("Rtsne") + threads <- .resolve_threads(threads) # BPCells stores as features x cells; uwot/Rtsne expect cells x dims if (is(x, "IterableMatrix")) { - x <- as.matrix(t(x)) + x <- rlang::with_options(as.matrix(t(x)), rlib_message_verbosity = "quiet") } # Sparse matrices need densification for uwot/Rtsne if (is(x, "dgCMatrix")) { @@ -631,14 +673,20 @@ add_tsne.default <- function( nrow(x) >= 2, msg = "Input matrix must have at least 2 cells." ) + if (verbose) { + run <- .log_start("t-SNE", sprintf( + "%s, %s, %s", .log_plural(nrow(x), "cell"), .log_plural(ncol(x), "dim"), + .log_plural(threads, "thread") + )) + } # Rtsne requires perplexity < n/3; cap to avoid errors on small datasets max_perplexity <- floor((nrow(x) - 1) / 3) if (perplexity > max_perplexity) { if (verbose) { - log_progress(sprintf( - "Reducing perplexity from %d to %d (must be < nrow / 3)", - perplexity, max_perplexity + .log_step(sprintf( + "Reduced perplexity from %s to %s (%s)", perplexity, max_perplexity, + .log_plural(nrow(x), "cell") )) } perplexity <- max_perplexity @@ -652,16 +700,23 @@ add_tsne.default <- function( perplexity = perplexity, max_iter = max_iterations, num_threads = threads, - verbose = verbose, + verbose = FALSE, pca = FALSE, check_duplicates = FALSE ) tsne_args <- modifyList(tsne_defaults, tsne_params) + t0 <- steady_clock_seconds_rcpp() tsne_result <- do.call(Rtsne::Rtsne, tsne_args) + if (verbose) { + .log_step(sprintf("Fit %dD t-SNE (perplexity %s)", tsne_args$dims, tsne_args$perplexity), since = t0) + } tsne_coords <- tsne_result$Y rownames(tsne_coords) <- rownames(x) colnames(tsne_coords) <- paste0("TSNE_", seq_len(ncol(tsne_coords))) + if (verbose) { + .log_finish(run, sprintf("%s x %d embedding", .log_count(nrow(tsne_coords)), ncol(tsne_coords))) + } return(tsne_coords) } @@ -700,6 +755,7 @@ add_tsne.MarchRDataset <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRDataset") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -726,12 +782,14 @@ add_tsne.MarchRDataset <- function( } # BPCells stores embeddings as features x cells; transpose to cells x dims for uwot/Rtsne - embedding <- as.matrix(t(x$matrices[[embedding_name]])) - + embedding <- rlang::with_options( + as.matrix(t(x$matrices[[embedding_name]])), + rlib_message_verbosity = "quiet" + ) if (verbose) { - log_progress(sprintf( - "Computing t-SNE from '%s' (%d cells, %d dimensions)", - embedding_name, nrow(embedding), ncol(embedding) + run <- .log_start("t-SNE", sprintf( + "%s on '%s' (%s), %s", .log_plural(nrow(embedding), "cell"), embedding_name, + .log_plural(ncol(embedding), "dim"), .log_plural(.resolve_threads(threads), "thread") )) } @@ -774,6 +832,12 @@ add_tsne.MarchRDataset <- function( ) } + if (verbose) { + .log_finish(run, .embedding_added_summary( + tsne_coords, assay = if (store_as_matrix) output_assay_name + )) + } + return(x) } @@ -821,6 +885,7 @@ add_tsne.MarchRProject <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRProject") assert_is_character(output_assay_name) assert_len(output_assay_name, 1) @@ -866,18 +931,18 @@ add_tsne.MarchRProject <- function( } # Pull the shared embedding across datasets; BPCells returns features x cells + embedding <- rlang::with_options( + as.matrix(t(x[[embedding_name, dataset_names]])), + rlib_message_verbosity = "quiet" + ) if (verbose) { - log_progress(sprintf("Extracting embedding '%s'", embedding_name)) + run <- .log_start("t-SNE", sprintf( + "%s on '%s' (%s), %s", .log_plural(nrow(embedding), "cell"), embedding_name, + .log_plural(ncol(embedding), "dim"), .log_plural(.resolve_threads(threads), "thread") + )) } - embedding <- as.matrix(t(x[[embedding_name, dataset_names]])) # Compute t-SNE on the concatenated embedding so coordinates are comparable across datasets - if (verbose) { - log_progress(sprintf( - "Computing t-SNE on %d cells with %d dimensions", - nrow(embedding), ncol(embedding) - )) - } tsne_coords <- add_tsne.default( embedding, perplexity = perplexity, @@ -917,9 +982,8 @@ add_tsne.MarchRProject <- function( } if (verbose) { - log_progress(sprintf( - "Added t-SNE embedding as '%s' (%d components)", - output_assay_name, n_components + .log_finish(run, .embedding_added_summary( + tsne_coords, assay = if (store_as_matrix) output_assay_name )) } diff --git a/R/imputation.R b/R/imputation.R index 6759e7b..46f16d5 100644 --- a/R/imputation.R +++ b/R/imputation.R @@ -49,7 +49,7 @@ #' @param n_rep (integer) Number of imputation replicates to average. #' Default is 2. #' @param seed (integer) Random seed. Default is 1. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return The MarchRProject with imputation weights stored in #' `proj$impute_weights`. @@ -75,9 +75,10 @@ add_impute_weights <- function( sample_cells = 5000L, n_rep = 2L, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_that(inherits(proj, "MarchRProject")) td <- as.integer(td) ka <- as.integer(ka) @@ -87,11 +88,11 @@ add_impute_weights <- function( assert_that(is.numeric(epsilon), epsilon >= 0) assert_that(is.integer(n_rep), n_rep >= 1L) assert_that(is.function(knn_method)) - knn_method <- partial_apply(knn_method, verbose = verbose, .missing_args_error = FALSE) + knn_method <- partial_apply(knn_method, verbose = FALSE, .missing_args_error = FALSE) # Resolve which dimensionality reduction to use for building the KNN graph embedding_name <- select_embedding_name(proj, embedding_name) - mat_dr <- as.matrix(t(proj[[embedding_name]])) + mat_dr <- rlang::with_options(as.matrix(t(proj[[embedding_name]])), rlib_message_verbosity = "quiet") # Restrict dimensions if (!is.null(dims_to_use)) { @@ -114,6 +115,18 @@ add_impute_weights <- function( bin_size <- n_cells n_rep <- 1L } + n_blocks <- ceiling(n_cells / bin_size) + + if (verbose) { + block_text <- sprintf( + "%s x %s (%s%s cells)", .log_plural(n_rep, "replicate"), .log_plural(n_blocks, "block"), + if (n_blocks > 1) "~" else "", .log_count(bin_size) + ) + run <- .log_start("Impute weights", sprintf( + "%s on '%s' (%s), %s, td = %d, ka = %d", .log_plural(n_cells, "cell"), embedding_name, + .log_plural(ncol(mat_dr), "dim"), block_text, td, ka + )) + } set.seed(seed) @@ -122,15 +135,8 @@ add_impute_weights <- function( weight_dir <- tempfile("impute_weights_") dir.create(weight_dir, recursive = TRUE) - if (verbose) { - log_progress(sprintf( - "Computing MAGIC imputation weights (td=%d, ka=%d, blocks~%d cells, %d reps)", - td, ka, bin_size, n_rep - )) - } - weight_list <- lapply(seq_len(n_rep), function(rep_i) { - if (verbose) log_progress(sprintf(" Replicate %d of %d", rep_i, n_rep)) + t0 <- steady_clock_seconds_rcpp() idx <- sample(seq_len(n_cells), n_cells) blocks <- split(cell_names[idx], ceiling(seq_along(idx) / bin_size)) @@ -153,13 +159,21 @@ add_impute_weights <- function( pattern = sprintf("impute_rep%d_block%d_", rep_i, block_i), tmpdir = weight_dir ) - write_matrix_dir( - as(wt, "dgCMatrix") %>% as("IterableMatrix"), - block_dir, - compress = TRUE + rlang::with_options( + write_matrix_dir( + as(wt, "dgCMatrix") %>% as("IterableMatrix"), + block_dir, + compress = TRUE + ), + rlib_message_verbosity = "quiet" ) }) + if (verbose) { + .log_step(sprintf( + "Replicate %d/%d: built %s", rep_i, n_rep, .log_plural(length(blocks), "diffusion graph") + ), since = t0) + } block_weights }) @@ -175,6 +189,11 @@ add_impute_weights <- function( ) ) + if (verbose) { + .log_finish(run, sprintf( + "added impute weights (%s x %s)", .log_plural(n_rep, "replicate"), .log_plural(n_blocks, "block") + )) + } return(proj) } @@ -230,6 +249,7 @@ impute_matrix <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_that(!is.null(impute_weights)) assert_that("weights" %in% names(impute_weights)) @@ -243,9 +263,14 @@ impute_matrix <- function( msg = "Matrix must have unique, non-missing cell names to match impute weights." ) - impute_mat <- lapply(seq_along(weight_list), function(rep_i) { - if (verbose) log_progress(sprintf("Imputing replicate %d of %d", rep_i, length(weight_list))) + if (verbose) { + run <- .log_start("Imputation", sprintf( + "%s x %s, %s", .log_plural(nrow(mat), "feature"), .log_plural(ncol(mat), "cell"), + .log_plural(length(weight_list), "replicate") + )) + } + impute_mat <- lapply(seq_along(weight_list), function(rep_i) { blocks <- weight_list[[rep_i]] assert_that(is.list(blocks), length(blocks) > 0L, msg = "Each imputation replicate must contain at least one block.") @@ -270,7 +295,10 @@ impute_matrix <- function( } # Materialize only this block's columns - block_mat <- as.matrix(mat[, bn, drop = FALSE]) + block_mat <- rlang::with_options( + as.matrix(mat[, bn, drop = FALSE]), + rlib_message_verbosity = "quiet" + ) t(w %*% t(block_mat)) }) @@ -286,7 +314,12 @@ impute_matrix <- function( # Replicates have independent shuffled block orders: align BEFORE averaging. result <- Reduce("+", impute_mat) / length(impute_mat) - result <- result[, all_cell_names, drop = FALSE] + result <- as.matrix(result[, all_cell_names, drop = FALSE]) - as.matrix(result) + if (verbose) { + .log_finish(run, sprintf( + "%s x %s imputed matrix", .log_count(nrow(result)), .log_count(ncol(result)) + )) + } + result } diff --git a/man/add_impute_weights.Rd b/man/add_impute_weights.Rd index 962b9a0..410a143 100644 --- a/man/add_impute_weights.Rd +++ b/man/add_impute_weights.Rd @@ -15,7 +15,7 @@ add_impute_weights( sample_cells = 5000L, n_rep = 2L, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -52,7 +52,7 @@ Default is 2.} \item{seed}{(integer) Random seed. Default is 1.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ The MarchRProject with imputation weights stored in diff --git a/tests/testthat/test-doublet.R b/tests/testthat/test-doublet.R index c340aab..18f044f 100644 --- a/tests/testthat/test-doublet.R +++ b/tests/testthat/test-doublet.R @@ -239,3 +239,225 @@ test_that("simulate_doublets validates sample_ratio bounds", { sample_ratio = -0.1, seed = 1L )) }) + +.doublet_test_lsi_params <- list( + cluster_method = function(x, ...) factor(rep(c("A", "B"), length.out = nrow(x))), + feature_selection_method = select_features_variance(num_feats = 20L) +) + +.score_test_doublets <- function(x, ...) { + suppressWarnings(add_doublet_scores( + x, assay_name = "TileMatrix", n_doublets = 20L, n_trials = 1L, n_dimensions = 5L, + lsi_params = .doublet_test_lsi_params, umap_params = list(n_neighbors = 10), ... + )) +} + +test_that("add_doublet_scores reports each dataset's steps", { + withr::local_options(rlib_message_verbosity = "verbose") + one <- add_matrix(MarchRProject(), .doublet_test_mat, dataset_name = "A", mat_name = "TileMatrix") + transposed <- transpose_storage_order(.doublet_test_mat, withr::local_tempfile()) + proj <- add_matrix(one, transposed, dataset_name = "B", mat_name = "TileMatrix") + + lines <- .strip_log(capture_messages(.score_test_doublets(proj, verbose = TRUE))) + expect_match(lines[1], "^Doublet scoring: 2 datasets, 80 cells, [0-9]+ threads?$") + steps <- c( + "^ Simulated 20 doublets \\(20 x 1 trial\\)$", + "^ Iterative LSI: ", + "^ \\[Iteration 1/2\\]$", + "^ Iteration finished \\[Xs\\]$", + "^ Iterative LSI finished ", + "^ Projected [0-9,]+ doublets into LSI \\[Xs\\]$", + "^ Fit UMAP, re-projection R\\^2 = [0-9.]+", + "^ Scored 40 cells by doublet neighbors in (UMAP|LSI) \\[Xs\\]$", + "^ Dataset finished \\[Xs\\]$" + ) + for (ds in c("A", "B")) { + start <- match(paste0("[", ds, "]"), lines) + end <- start + match(" Dataset finished [Xs]", lines[-seq_len(start)]) + block <- lines[start:end] + hits <- purrr::map_int(steps, function(pattern) grep(pattern, block)[1]) + expect_false(anyNA(hits), info = ds) + expect_false(is.unsorted(hits, strictly = TRUE), info = ds) + expect_identical( + any(block == " Transposed TileMatrix storage order [Xs]"), ds == "B", info = ds + ) + } + expect_match( + lines[length(lines)], + "^Doublet scoring finished \\[Xs\\]: added doublet scores to 2 datasets \\(80 cells\\)$" + ) + expect_false(any(grepl( + "HNSW|UMAP embedding parameters|Commencing|Optimization|Running Iterative LSI|Using method", lines + ))) + expect_no_message(.score_test_doublets(one, verbose = FALSE)) +}) + +test_that("add_doublet_scores reports combined replicates as one pass", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- add_matrix(MarchRProject(), .doublet_test_mat, dataset_name = "A", mat_name = "TileMatrix") + proj <- add_matrix(proj, .doublet_test_mat, dataset_name = "B", mat_name = "TileMatrix") + + lines <- .strip_log(capture_messages( + .score_test_doublets(proj, combine = TRUE, force = TRUE, verbose = TRUE) + )) + expect_match( + lines[1], "^Doublet scoring: 2 datasets combined as replicates, 80 cells, [0-9]+ threads?$" + ) + expect_identical(grep("^\\[", lines, value = TRUE), "[A_B]") + expect_true(" Scored 80 cells by doublet neighbors in UMAP [Xs]" %in% lines) + expect_identical( + lines[length(lines)], + "Doublet scoring finished [Xs]: added doublet scores to dataset 'A_B' (80 cells)" + ) + expect_no_message(.score_test_doublets(proj, combine = TRUE, force = TRUE, verbose = FALSE)) +}) + +test_that("add_doublet_scores on a dataset reports its own run", { + withr::local_options(rlib_message_verbosity = "verbose") + ds <- add_matrix(MarchRDataset(), .doublet_test_mat, mat_name = "TileMatrix") + + lines <- .strip_log(capture_messages(.score_test_doublets(ds, verbose = TRUE))) + expect_match(lines[1], "^Doublet scoring: 40 cells, [0-9]+ threads?$") + expect_identical(lines[2], "Simulated 20 doublets (20 x 1 trial)") + expect_true("Iterative LSI finished [Xs]: 40 x 5 embedding" %in% lines) + expect_identical( + lines[length(lines)], "Doublet scoring finished [Xs]: added doublet scores (40 cells)" + ) + expect_no_message(.score_test_doublets(ds, verbose = FALSE)) +}) + +test_that("project_doublets reports its LSI and UMAP projections", { + withr::local_options(rlib_message_verbosity = "verbose") + sim <- simulate_doublets(.doublet_test_mat, n_doublets = 20L, n_trials = 1L, seed = 1L) + run <- function(...) { + project_doublets( + .doublet_test_mat, sim, n_dimensions = 5L, lsi_params = .doublet_test_lsi_params, + umap_params = list(n_neighbors = 10), ... + ) + } + + lines <- .strip_log(capture_messages(suppressWarnings(run(force = TRUE, verbose = TRUE)))) + expect_identical(lines[1], "Doublet projection: 40 cells, 20 doublets") + expect_true("Projected 20 doublets into LSI [Xs]" %in% lines) + expect_true("Projected 20 doublets into UMAP [Xs]" %in% lines) + expect_identical( + lines[length(lines)], + "Doublet projection finished [Xs]: LSI and UMAP embeddings for 40 cells and 20 doublets" + ) + expect_no_message(suppressWarnings(run(force = TRUE, verbose = FALSE))) + + expect_warning(msgs <- capture_messages(run(verbose = TRUE)), "Returning NULL UMAP model") + lines <- .strip_log(msgs) + expect_false("Projected 20 doublets into UMAP [Xs]" %in% lines) + expect_identical( + lines[length(lines)], "Doublet projection finished [Xs]: LSI embeddings for 40 cells and 20 doublets" + ) +}) + +test_that("score_doublets reports the scoring space", { + withr::local_options(rlib_message_verbosity = "verbose") + withr::local_seed(1) + cells <- matrix(rnorm(40 * 5), nrow = 40, dimnames = list(paste0("cell_", 1:40), NULL)) + doublets <- matrix(rnorm(20 * 5), nrow = 20) + project_res <- list( + lsi_cells = cells, lsi_doublets = doublets, + umap_cells = cells[, 1:2], umap_doublets = doublets[, 1:2] + ) + + expect_identical(.strip_log(capture_messages(score_doublets(project_res, verbose = TRUE))), c( + "Doublet neighbor scoring: 40 cells in UMAP", + "Scored 40 cells by doublet neighbors in UMAP [Xs]", + "Doublet neighbor scoring finished [Xs]: scores for 40 cells" + )) + lines <- .strip_log(capture_messages( + score_doublets(project_res, scoring_method = "LSI", verbose = TRUE) + )) + expect_identical(lines[1:2], c( + "Doublet neighbor scoring: 40 cells in LSI", "Scored 40 cells by doublet neighbors in LSI [Xs]" + )) + expect_no_message(score_doublets(project_res, verbose = FALSE)) +}) + +test_that("simulate_doublets reports the simulated doublets", { + withr::local_options(rlib_message_verbosity = "verbose") + n_cells <- ncol(.doublet_test_mat) + n_trials <- 5L * floor(n_cells / 10L) + lines <- .strip_log(capture_messages( + simulate_doublets(.doublet_test_mat, n_doublets = 10L, verbose = TRUE) + )) + expect_identical(lines, c( + paste("Doublet simulation:", .log_count(n_cells), "cells"), + sprintf("Simulated %s doublets (10 x %s trials)", .log_count(10L * n_trials), .log_count(n_trials)), + sprintf("Doublet simulation finished [Xs]: %s simulated doublets", .log_count(10L * n_trials)) + )) + expect_no_message(simulate_doublets(.doublet_test_mat, n_doublets = 10L, verbose = FALSE)) +}) + +test_that("filter_doublets reports removed cells per dataset", { + withr::local_options(rlib_message_verbosity = "verbose") + # 1,000 cells cap removal at 1,000^2 / 1e5 = 10 cells per dataset + scored_dataset <- function(prefix) { + mat <- create_small_matrix(nrow = 5, ncol = 1000, col_name_prefix = prefix) + ds <- add_matrix(MarchRDataset(), mat, mat_name = "TileMatrix") + ds$doublet_data <- list(scores = data.frame( + doublet_score = 1, doublet_enrichment = seq(20, 0, length.out = 1000), + row.names = colnames(mat) + )) + ds + } + proj <- insert_dataset(MarchRProject(), scored_dataset("a"), dataset_name = "A") + proj <- insert_dataset(proj, scored_dataset("b"), dataset_name = "B") + + msgs <- capture_messages(filtered <- filter_doublets(proj, verbose = TRUE)) + expect_identical(.strip_log(msgs), c( + "Doublet filtering: 2 datasets, 2,000 cells (enrichment >= 1, filter ratio 1)", + "A: removed 10 of 1,000 cells (1.0%) [Xs]", + "B: removed 10 of 1,000 cells (1.0%) [Xs]", + "Doublet filtering finished [Xs]: removed 20 of 2,000 cells (1.0%), cleared doublet data" + )) + expect_no_message(filter_doublets(proj, verbose = FALSE)) + + lines <- .strip_log(capture_messages(filter_doublets( + proj$datasets$A, score_cutoff = 0.5, clear_doublet_data = FALSE, verbose = TRUE + ))) + expect_identical(lines, c( + "Doublet filtering: 1,000 cells (enrichment >= 1, score >= 0.5, filter ratio 1)", + "Doublet filtering finished [Xs]: removed 10 of 1,000 cells (1.0%)" + )) + + lines <- .strip_log(capture_messages(suppressWarnings(filter_doublets(filtered, verbose = TRUE)))) + expect_identical(lines[2:3], c("A: already filtered, skipped", "B: already filtered, skipped")) + expect_match(lines[4], "^Doublet filtering finished \\[Xs\\]: removed 0 of 1,980 cells \\(0.0%\\)$") + expect_warning(filter_doublets(filtered, dataset_names = "A"), "already been run") + + kept <- filter_doublets(proj, clear_doublet_data = FALSE) + lines <- .strip_log(capture_messages(suppressWarnings(filter_doublets(kept, verbose = TRUE)))) + expect_identical(lines[4], "Doublet filtering finished [Xs]: removed 0 of 1,980 cells (0.0%)") +}) + +test_that(".run_umap_projections explains a failed re-projection check", { + withr::local_options(rlib_message_verbosity = "verbose") + withr::local_seed(1) + lsi <- matrix(rnorm(100 * 5), nrow = 100, dimnames = list(paste0("cell_", 1:100), NULL)) + fit <- function(...) { + .run_umap_projections(lsi, umap_params = list(n_neighbors = 10), min_corr_threshold = 1.01, ...) + } + + msgs <- capture_messages( + expect_warning(res <- fit(verbose = TRUE), "Projection R\\^2 = [0-9.]+ is below 1.01") + ) + expect_null(res) + expect_match( + .strip_log(msgs), + "^Fit UMAP, re-projection R\\^2 = [0-9.]+ \\(below 1.01\\), scoring in LSI instead \\[Xs\\]$" + ) + expect_no_message( + expect_warning(res <- fit(verbose = FALSE), "below 1.01; .*use force = TRUE to override") + ) + expect_null(res) + msgs <- capture_messages( + expect_warning(res <- fit(force = TRUE, verbose = TRUE), "Proceeding anyway \\(force = TRUE\\)") + ) + expect_false(is.null(res)) + expect_match(.strip_log(msgs), "\\(below 1.01\\), proceeding \\(force = TRUE\\) \\[Xs\\]$") +}) diff --git a/tests/testthat/test-embeddings.R b/tests/testthat/test-embeddings.R index 790fff4..d000189 100644 --- a/tests/testthat/test-embeddings.R +++ b/tests/testthat/test-embeddings.R @@ -799,3 +799,155 @@ test_that("add_tsne.MarchRProject errors on nonexistent embedding", { "not found" ) }) + +######################################################################## +# Verbose logging tests +######################################################################## + +test_that("add_umap.default reports its fit and result", { + skip_if_not_installed("uwot") + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(42) + embedding <- matrix(rnorm(200), nrow = 40, ncol = 5) + rownames(embedding) <- paste0("cell_", seq_len(40)) + + lines <- .strip_log(capture_messages( + add_umap(embedding, n_neighbors = 15L, threads = 1L, verbose = TRUE) + )) + expect_identical(lines, c( + "UMAP: 40 cells, 5 dims, 1 thread", + "Fit 2D UMAP (15 neighbors, min_dist 0.4, cosine) [Xs]", + "UMAP finished [Xs]: 40 x 2 embedding" + )) + expect_no_message(add_umap(embedding, n_neighbors = 15L, threads = 1L, verbose = FALSE)) + + res <- NULL + lines <- .strip_log(capture_messages(res <- add_umap( + embedding, n_neighbors = 10L, metric = list(euclidean = 1:2, cosine = 3:5), threads = 1L, + return_model = TRUE, verbose = TRUE + ))) + uwot::unload_uwot(res$model) + expect_length(lines, 3) + expect_identical(lines[2], "Fit 2D UMAP (10 neighbors, min_dist 0.4, euclidean+cosine) [Xs]") + expect_identical(lines[3], "UMAP finished [Xs]: 40 x 2 embedding") + + small <- embedding[1:10, ] + lines <- .strip_log(capture_messages( + add_umap(small, n_neighbors = 30L, threads = 1L, verbose = TRUE) + )) + expect_identical(lines, c( + "UMAP: 10 cells, 5 dims, 1 thread", + "Reduced n_neighbors from 30 to 9 (10 cells)", + "Fit 2D UMAP (9 neighbors, min_dist 0.4, cosine) [Xs]", + "UMAP finished [Xs]: 10 x 2 embedding" + )) +}) + +test_that("add_umap.MarchRDataset reports one block with what it added", { + skip_if_not_installed("uwot") + withr::local_options(rlib_message_verbosity = "verbose") + dataset <- create_embedding_test_project()$datasets[["dataset1"]] + + lines <- .strip_log(capture_messages(add_umap( + dataset, embedding_name = "test_pca", n_neighbors = 10L, n_components = 1L, store_as_matrix = TRUE, + threads = 1L, verbose = TRUE + ))) + expect_identical(lines, c( + "UMAP: 24 cells on 'test_pca' (5 dims), 1 thread", + "Fit 1D UMAP (10 neighbors, min_dist 0.4, cosine) [Xs]", + "UMAP finished [Xs]: added cell metadata column 'UMAP_1', assay 'UMAP'" + )) + expect_no_message(add_umap( + dataset, embedding_name = "test_pca", n_neighbors = 10L, n_components = 1L, store_as_matrix = TRUE, + threads = 1L, verbose = FALSE + )) +}) + +test_that("add_umap.MarchRProject reports one block with what it added", { + skip_if_not_installed("uwot") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_embedding_test_project() + + lines <- .strip_log(capture_messages( + add_umap(proj, embedding_name = "test_pca", return_model = FALSE, verbose = TRUE) + )) + expect_length(lines, 3) + expect_match(lines[1], "^UMAP: [0-9,]+ cells on 'test_pca' \\([0-9]+ dims?\\), [0-9]+ threads?$") + expect_identical(lines[2], "Fit 2D UMAP (40 neighbors, min_dist 0.4, cosine) [Xs]") + expect_match(lines[3], "^UMAP finished \\[Xs\\]: added cell metadata columns 'UMAP_1', 'UMAP_2'$") + + lines <- .strip_log(capture_messages(add_umap(proj, embedding_name = "test_pca", verbose = TRUE))) + expect_length(lines, 4) + expect_identical(lines[2:3], c( + "Fit 2D UMAP (40 neighbors, min_dist 0.4, cosine) [Xs]", + "Saved UMAP model [Xs]" + )) + expect_identical( + lines[4], + "UMAP finished [Xs]: added cell metadata columns 'UMAP_1', 'UMAP_2', embedding model 'UMAP'" + ) + expect_no_message(add_umap(proj, embedding_name = "test_pca", verbose = FALSE)) +}) + +test_that("add_tsne.default reports its fit and result", { + skip_if_not_installed("Rtsne") + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(42) + embedding <- matrix(rnorm(200), nrow = 40, ncol = 5) + rownames(embedding) <- paste0("cell_", seq_len(40)) + + expect_output(lines <- .strip_log(capture_messages( + add_tsne(embedding, perplexity = 10, threads = 1L, verbose = TRUE) + )), NA) + expect_identical(lines, c( + "t-SNE: 40 cells, 5 dims, 1 thread", + "Fit 2D t-SNE (perplexity 10) [Xs]", + "t-SNE finished [Xs]: 40 x 2 embedding" + )) + expect_no_message(add_tsne(embedding, perplexity = 10, threads = 1L, verbose = FALSE)) + + small <- embedding[1:10, ] + expect_output(lines <- .strip_log(capture_messages( + add_tsne(small, perplexity = 30, threads = 1L, verbose = TRUE) + )), NA) + expect_identical(lines, c( + "t-SNE: 10 cells, 5 dims, 1 thread", + "Reduced perplexity from 30 to 3 (10 cells)", + "Fit 2D t-SNE (perplexity 3) [Xs]", + "t-SNE finished [Xs]: 10 x 2 embedding" + )) + expect_no_message(add_tsne(small, perplexity = 30, threads = 1L, verbose = FALSE)) +}) + +test_that("add_tsne.MarchRDataset reports one block with what it added", { + skip_if_not_installed("Rtsne") + withr::local_options(rlib_message_verbosity = "verbose") + dataset <- create_embedding_test_project()$datasets[["dataset1"]] + + expect_output(lines <- .strip_log(capture_messages(add_tsne( + dataset, embedding_name = "test_pca", perplexity = 5, threads = 1L, verbose = TRUE + ))), NA) + expect_identical(lines, c( + "t-SNE: 24 cells on 'test_pca' (5 dims), 1 thread", + "Fit 2D t-SNE (perplexity 5) [Xs]", + "t-SNE finished [Xs]: added cell metadata columns 'TSNE_1', 'TSNE_2'" + )) + expect_no_message(add_tsne( + dataset, embedding_name = "test_pca", perplexity = 5, threads = 1L, verbose = FALSE + )) +}) + +test_that("add_tsne.MarchRProject reports one block with what it added", { + skip_if_not_installed("Rtsne") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_embedding_test_project() + + expect_output(lines <- .strip_log(capture_messages( + add_tsne(proj, embedding_name = "test_pca", perplexity = 10, verbose = TRUE) + )), NA) + expect_length(lines, 3) + expect_match(lines[1], "^t-SNE: [0-9,]+ cells on 'test_pca' \\([0-9]+ dims?\\), [0-9]+ threads?$") + expect_identical(lines[2], "Fit 2D t-SNE (perplexity 10) [Xs]") + expect_match(lines[3], "^t-SNE finished \\[Xs\\]: added cell metadata columns 'TSNE_1', 'TSNE_2'$") + expect_no_message(add_tsne(proj, embedding_name = "test_pca", perplexity = 10, verbose = FALSE)) +}) diff --git a/tests/testthat/test-imputation.R b/tests/testthat/test-imputation.R index dcfe736..50f9626 100644 --- a/tests/testthat/test-imputation.R +++ b/tests/testthat/test-imputation.R @@ -69,3 +69,54 @@ test_that("imputation rejects incomplete or ambiguous cell mappings", { colnames(mat) <- c("A", "A") expect_error(impute_matrix(mat, list(weights = list(list(w)))), "unique, non-missing") }) + +test_that("add_impute_weights reports one line per replicate", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_linkage_project(n_cells = 24L) + knn <- BPCells::knn_hnsw(k = 5L) + lines <- .strip_log(capture_messages(add_impute_weights( + proj, embedding_name = "IterativeLSI", knn_method = knn, sample_cells = 12L, n_rep = 2L, + verbose = TRUE + ))) + expect_length(lines, 4L) + expect_match(lines[1], paste0( + "^Impute weights: [0-9,]+ cells on 'IterativeLSI' \\([0-9]+ dims?\\), ", + "2 replicates x 2 blocks \\(~[0-9,]+ cells\\), td = 3, ka = 4$" + )) + expect_identical(lines[2:4], c( + "Replicate 1/2: built 2 diffusion graphs [Xs]", + "Replicate 2/2: built 2 diffusion graphs [Xs]", + "Impute weights finished [Xs]: added impute weights (2 replicates x 2 blocks)" + )) + expect_false(any(grepl("HNSW", lines))) + + lines <- .strip_log(capture_messages(add_impute_weights( + proj, embedding_name = "IterativeLSI", knn_method = knn, sample_cells = NULL, verbose = TRUE + ))) + expect_identical(lines, c( + paste0( + "Impute weights: 24 cells on 'IterativeLSI' (5 dims), 1 replicate x 1 block (24 cells), ", + "td = 3, ka = 4" + ), + "Replicate 1/1: built 1 diffusion graph [Xs]", + "Impute weights finished [Xs]: added impute weights (1 replicate x 1 block)" + )) + + withr::local_options(MarchR.verbose = NULL) + expect_no_message(add_impute_weights(proj, embedding_name = "IterativeLSI", knn_method = knn)) +}) + +test_that("impute_matrix reports its setup and result", { + withr::local_options(rlib_message_verbosity = "verbose") + mat <- as(matrix(1:8, 2, dimnames = list(c("g1", "g2"), c("A", "B", "C", "D"))), "IterableMatrix") + weights <- list(weights = list( + list(identity_impute_block(c("A", "B")), identity_impute_block(c("C", "D"))), + list(identity_impute_block(c("D", "A")), identity_impute_block(c("B", "C"))) + )) + lines <- .strip_log(capture_messages(impute_matrix(mat, weights, verbose = TRUE))) + expect_identical(lines, c( + "Imputation: 2 features x 4 cells, 2 replicates", + "Imputation finished [Xs]: 2 x 4 imputed matrix" + )) + expect_no_message(impute_matrix(mat, weights, verbose = FALSE)) +}) diff --git a/vignettes/marchr_hematopoiesis.Rmd b/vignettes/marchr_hematopoiesis.Rmd index b51f5d6..da0c962 100644 --- a/vignettes/marchr_hematopoiesis.Rmd +++ b/vignettes/marchr_hematopoiesis.Rmd @@ -345,7 +345,7 @@ Raw gene scores can be noisy at the single-cell level. `add_impute_weights()` computes [MAGIC](https://github.com/krishnaswamylab/MAGIC) diffusion weights from the LSI embedding. ```{r} -proj <- add_impute_weights(proj, embedding_name = "IterativeLSI") +proj <- add_impute_weights(proj, embedding_name = "IterativeLSI", verbose = TRUE) ``` ```{r fig.width=10, fig.height=10} diff --git a/vignettes/marchr_hematopoiesis.html b/vignettes/marchr_hematopoiesis.html index e8066f2..1c9e69c 100644 --- a/vignettes/marchr_hematopoiesis.html +++ b/vignettes/marchr_hematopoiesis.html @@ -1577,7 +1577,7 @@

Initialize a MarchRProject

} proj
Output
## MarchRProject Object
-## Directory: /tmp/RtmpVp380g/marchr_project
+## Directory: /tmp/RtmpdQmqNu/marchr_project
 ## 3 Datasets:
 ##   scATAC_BMMC_R1:
 ##     5000 cells: scATAC_BMMC_R1#TAGGAGGGTTAACCGT-1, scATAC_BMMC_R1#CCTTGGTAGTTCTCCC-1, scATAC_BMMC_R1#GCCAGCAGTTCTGAGT-1, scATAC_BMMC_R1#TAGCATGGTGACCAGA-1 ... scATAC_BMMC_R1#CTGCTCAAGTGTCGGA-1
@@ -1669,217 +1669,74 @@ 

Doublet Scoring and Filtering

assay_name = "TileMatrix", verbose = TRUE )
-
Output
## 2026-10-19 19:07:35 Processing dataset 1 of 3: scATAC_BMMC_R1
-## 2026-10-19 19:07:38 Simulating 20000 synthetic doublets (1000 doublets x 20 trials)
-## 2026-10-19 19:07:38 Running Iterative LSI on input matrix
-## 2026-10-19 19:07:39 Starting Iterative LSI
-## 2026-10-19 19:07:39 Starting Iterative LSI iteration 1 of 2
-## 2026-10-19 19:07:39 Selecting features
-## 2026-10-19 19:07:42 Running LSI
-## 2026-10-19 19:07:42 Starting LSI
-## 2026-10-19 19:07:42 Normalizing matrix
-## Warning: Matrix compression performs poorly with non-integers.
-## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
-## 2026-10-19 19:07:42 Calculating SVD
-## 
-## 2026-10-19 19:07:43 Clustering LSI results
-## 
-## 19:07:43 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 
-## 19:07:43 Finished building index
-## 
-## 19:07:43 Searching HNSW index with ef = 100 and 1 threads
-## 
-## 19:07:43 Finished searching
-## 
-## This message is displayed once every 8 hours.
-## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
+
Output
## 2026-10-20 13:57:15 Doublet scoring: 3 datasets, 10,681 cells, 4 threads
+## [scATAC_BMMC_R1]
+##   Transposed TileMatrix storage order [5.1s]
+##   Simulated 20,000 doublets (1,000 x 20 trials)
+##   Iterative LSI: 4,939 cells, 2 iterations, 30 dims, 4 threads
+##     [Iteration 1/2]
+##       Selected 25,000 features (top accessible) [2.7s]
+##       Fit LSI on 4,939 cells [1.3s]
+## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-## 2026-10-19 19:07:44 Merging 15 clusters down to 6 via hierarchical clustering
-## 2026-10-19 19:07:44 Pseudobulking matrix
-## 2026-10-19 19:07:44 Starting Iterative LSI iteration 2 of 2
-## 2026-10-19 19:07:44 Selecting features
-## 2026-10-19 19:07:45 Running LSI
-## 2026-10-19 19:07:45 Starting LSI
-## 2026-10-19 19:07:45 Normalizing matrix
-## 2026-10-19 19:07:45 Calculating SVD
-## 2026-10-19 19:07:46 Projecting simulated doublets on LSI space
-## 2026-10-19 19:07:53 Running UMAP fitting on LSI matrix
-## 19:07:53 Using HNSW for nearest neighbor search
-## 19:07:53 UMAP embedding parameters a = 0.7669 b = 1.223
-## 19:07:53 Setting random seed 1
-## 19:07:53 Read 4939 rows and found 30 numeric columns
-## 19:07:53 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 19:07:53 Finished building index
-## 19:07:53 Searching HNSW index with ef = 40 and 4 threads
-## 19:07:54 Finished searching
-## 19:07:55 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:07:56 Initializing from normalized Laplacian + noise (using RSpectra)
-## 19:07:56 Range-scaling initial input columns to 0-10
-## 19:07:56 Commencing optimization for 500 epochs, with 342252 positive edges using 4 threads
-## 19:07:56 Using rng type: pcg
-## 19:07:58 Optimization finished
-## 2026-10-19 19:07:58 Validating re-projection Pearson correlation
-## 19:07:58 Setting model random seed 1
-## 19:07:58 Read 4939 rows and found 30 numeric columns
-## 19:07:58 Processing block 1 of 1
-## 19:07:58 Searching HNSW index with ef = 40 and 4 threads
-## 19:07:58 Finished searching
-## 19:07:58 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:07:58 Initializing by weighted average of neighbor coordinates using 4 threads
-## 19:07:58 Commencing optimization for 167 epochs, with 197560 positive edges using 4 threads
-## 19:07:58 Finished
-## 2026-10-19 19:07:58 UMAP Re-projection Correlation: R^2 = 0.984
-## 2026-10-19 19:07:58 Projecting simulated doublets on UMAP space
-## 19:07:58 Setting model random seed 1
-## 19:07:58 Read 20000 rows and found 30 numeric columns
-## 19:07:58 Processing block 1 of 1
-## 19:07:58 Searching HNSW index with ef = 40 and 4 threads
-## 19:07:58 Finished searching
-## 19:07:58 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:07:59 Initializing by weighted average of neighbor coordinates using 4 threads
-## 19:07:59 Commencing optimization for 167 epochs, with 800000 positive edges using 4 threads
-## 19:08:00 Finished
-## 2026-10-19 19:08:00 Compute doublet scores and enrichments from UMAP
-## 19:08:00 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:08:00 Finished building index
-## 19:08:00 Searching HNSW index with ef = 200 and 1 threads
-## 19:08:00 Finished searching
-## 2026-10-19 19:08:00 Processing dataset 2 of 3: scATAC_CD34_BMMC_R1
-## 2026-10-19 19:08:06 Simulating 15000 synthetic doublets (1000 doublets x 15 trials)
-## 2026-10-19 19:08:06 Running Iterative LSI on input matrix
-## 2026-10-19 19:08:05 Starting Iterative LSI
-## 2026-10-19 19:08:05 Starting Iterative LSI iteration 1 of 2
-## 2026-10-19 19:08:05 Selecting features
-## 2026-10-19 19:08:06 Running LSI
-## 2026-10-19 19:08:06 Starting LSI
-## 2026-10-19 19:08:06 Normalizing matrix
-## 2026-10-19 19:08:07 Calculating SVD
-## 2026-10-19 19:08:07 Clustering LSI results
-## 19:08:07 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:08:08 Finished building index
-## 19:08:08 Searching HNSW index with ef = 100 and 1 threads
-## 19:08:08 Finished searching
-## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
+##       Found 15 clusters, merged to 6 [0.7s]
+##       Pseudobulked 6 clusters [0.7s]
+##       Iteration finished [5.4s]
+##     [Iteration 2/2]
+##       Selected 25,000 variable features [0.2s]
+##       Fit LSI on 4,939 cells [1.5s]
+##       Iteration finished [1.7s]
+##   Iterative LSI finished [8.2s]: 4,939 x 30 embedding
+##   Projected 20,000 doublets into LSI [6.6s]
+##   Fit UMAP, re-projection R^2 = 0.984 [4.9s]
+##   Projected 20,000 doublets into UMAP [1.3s]
+##   Scored 4,939 cells by doublet neighbors in UMAP [0.7s]
+##   Dataset finished [26.9s]
+## [scATAC_CD34_BMMC_R1]
+##   Transposed TileMatrix storage order [5.2s]
+##   Simulated 15,000 doublets (1,000 x 15 trials)
+##   Iterative LSI: 3,280 cells, 2 iterations, 30 dims, 4 threads
+##     [Iteration 1/2]
+##       Selected 25,000 features (top accessible) [1.1s]
+##       Fit LSI on 3,280 cells [0.9s]
+## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 16 datapoints. Try higher ef value
-## 2026-10-19 19:08:08 Merging 13 clusters down to 6 via hierarchical clustering
-## 2026-10-19 19:08:08 Pseudobulking matrix
-## 2026-10-19 19:08:08 Starting Iterative LSI iteration 2 of 2
-## 2026-10-19 19:08:08 Selecting features
-## 2026-10-19 19:08:09 Running LSI
-## 2026-10-19 19:08:09 Starting LSI
-## 2026-10-19 19:08:09 Normalizing matrix
-## 2026-10-19 19:08:09 Calculating SVD
-## 2026-10-19 19:08:10 Projecting simulated doublets on LSI space
-## 2026-10-19 19:08:15 Running UMAP fitting on LSI matrix
-## 19:08:15 Using HNSW for nearest neighbor search
-## 19:08:15 UMAP embedding parameters a = 0.7669 b = 1.223
-## 19:08:15 Setting random seed 1
-## 19:08:15 Read 3280 rows and found 30 numeric columns
-## 19:08:15 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 19:08:15 Finished building index
-## 19:08:15 Searching HNSW index with ef = 40 and 4 threads
-## 19:08:15 Finished searching
-## 19:08:16 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:08:17 Initializing from normalized Laplacian + noise (using RSpectra)
-## 19:08:17 Range-scaling initial input columns to 0-10
-## 19:08:17 Commencing optimization for 500 epochs, with 208246 positive edges using 4 threads
-## 19:08:17 Using rng type: pcg
-## 19:08:19 Optimization finished
-## 2026-10-19 19:08:19 Validating re-projection Pearson correlation
-## 19:08:19 Setting model random seed 1
-## 19:08:19 Read 3280 rows and found 30 numeric columns
-## 19:08:19 Processing block 1 of 1
-## 19:08:19 Searching HNSW index with ef = 40 and 4 threads
-## 19:08:19 Finished searching
-## 19:08:19 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:08:19 Initializing by weighted average of neighbor coordinates using 4 threads
-## 19:08:19 Commencing optimization for 167 epochs, with 131200 positive edges using 4 threads
-## 19:08:19 Finished
-## 2026-10-19 19:08:19 UMAP Re-projection Correlation: R^2 = 0.994
-## 2026-10-19 19:08:19 Projecting simulated doublets on UMAP space
-## 19:08:19 Setting model random seed 1
-## 19:08:19 Read 15000 rows and found 30 numeric columns
-## 19:08:19 Processing block 1 of 1
-## 19:08:19 Searching HNSW index with ef = 40 and 4 threads
-## 19:08:19 Finished searching
-## 19:08:19 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:08:19 Initializing by weighted average of neighbor coordinates using 4 threads
-## 19:08:19 Commencing optimization for 167 epochs, with 600000 positive edges using 4 threads
-## 19:08:20 Finished
-## 2026-10-19 19:08:20 Compute doublet scores and enrichments from UMAP
-## 19:08:20 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:08:20 Finished building index
-## 19:08:20 Searching HNSW index with ef = 200 and 1 threads
-## 19:08:21 Finished searching
-## 2026-10-19 19:08:21 Processing dataset 3 of 3: scATAC_PBMC_R1
-## 2026-10-19 19:08:26 Simulating 10000 synthetic doublets (1000 doublets x 10 trials)
-## 2026-10-19 19:08:26 Running Iterative LSI on input matrix
-## 2026-10-19 19:08:27 Starting Iterative LSI
-## 2026-10-19 19:08:27 Starting Iterative LSI iteration 1 of 2
-## 2026-10-19 19:08:27 Selecting features
-## 2026-10-19 19:08:29 Running LSI
-## 2026-10-19 19:08:29 Starting LSI
-## 2026-10-19 19:08:29 Normalizing matrix
-## 2026-10-19 19:08:29 Calculating SVD
-## 2026-10-19 19:08:30 Clustering LSI results
-## 19:08:30 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:08:30 Finished building index
-## 19:08:30 Searching HNSW index with ef = 100 and 1 threads
-## 19:08:30 Finished searching
-## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
+##       Found 13 clusters, merged to 6 [0.4s]
+##       Pseudobulked 6 clusters [0.6s]
+##       Iteration finished [3.1s]
+##     [Iteration 2/2]
+##       Selected 25,000 variable features [0.2s]
+##       Fit LSI on 3,280 cells [0.8s]
+##       Iteration finished [1.1s]
+##   Iterative LSI finished [5.3s]: 3,280 x 30 embedding
+##   Projected 15,000 doublets into LSI [4.9s]
+##   Fit UMAP, re-projection R^2 = 0.994 [4.2s]
+##   Projected 15,000 doublets into UMAP [0.7s]
+##   Scored 3,280 cells by doublet neighbors in UMAP [0.5s]
+##   Dataset finished [20.9s]
+## [scATAC_PBMC_R1]
+##   Transposed TileMatrix storage order [4.5s]
+##   Simulated 10,000 doublets (1,000 x 10 trials)
+##   Iterative LSI: 2,462 cells, 2 iterations, 30 dims, 4 threads
+##     [Iteration 1/2]
+##       Selected 25,000 features (top accessible) [1.1s]
+##       Fit LSI on 2,462 cells [1.0s]
+## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-## 2026-10-19 19:08:30 Merging 12 clusters down to 6 via hierarchical clustering
-## 2026-10-19 19:08:30 Pseudobulking matrix
-## 2026-10-19 19:08:30 Starting Iterative LSI iteration 2 of 2
-## 2026-10-19 19:08:30 Selecting features
-## 2026-10-19 19:08:31 Running LSI
-## 2026-10-19 19:08:31 Starting LSI
-## 2026-10-19 19:08:31 Normalizing matrix
-## 2026-10-19 19:08:31 Calculating SVD
-## 2026-10-19 19:08:32 Projecting simulated doublets on LSI space
-## 2026-10-19 19:08:36 Running UMAP fitting on LSI matrix
-## 19:08:36 Using HNSW for nearest neighbor search
-## 19:08:36 UMAP embedding parameters a = 0.7669 b = 1.223
-## 19:08:36 Setting random seed 1
-## 19:08:36 Read 2462 rows and found 30 numeric columns
-## 19:08:36 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 19:08:36 Finished building index
-## 19:08:36 Searching HNSW index with ef = 40 and 4 threads
-## 19:08:36 Finished searching
-## 19:08:35 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:08:36 Initializing from normalized Laplacian + noise (using RSpectra)
-## 19:08:36 Range-scaling initial input columns to 0-10
-## 19:08:36 Commencing optimization for 500 epochs, with 170712 positive edges using 4 threads
-## 19:08:36 Using rng type: pcg
-## 19:08:38 Optimization finished
-## 2026-10-19 19:08:38 Validating re-projection Pearson correlation
-## 19:08:38 Setting model random seed 1
-## 19:08:38 Read 2462 rows and found 30 numeric columns
-## 19:08:38 Processing block 1 of 1
-## 19:08:38 Searching HNSW index with ef = 40 and 4 threads
-## 19:08:38 Finished searching
-## 19:08:38 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:08:38 Initializing by weighted average of neighbor coordinates using 4 threads
-## 19:08:38 Commencing optimization for 167 epochs, with 98480 positive edges using 4 threads
-## 19:08:38 Finished
-## 2026-10-19 19:08:38 UMAP Re-projection Correlation: R^2 = 0.951
-## 2026-10-19 19:08:38 Projecting simulated doublets on UMAP space
-## 19:08:38 Setting model random seed 1
-## 19:08:38 Read 10000 rows and found 30 numeric columns
-## 19:08:38 Processing block 1 of 1
-## 19:08:38 Searching HNSW index with ef = 40 and 4 threads
-## 19:08:38 Finished searching
-## 19:08:38 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 19:08:38 Initializing by weighted average of neighbor coordinates using 4 threads
-## 19:08:38 Commencing optimization for 167 epochs, with 400000 positive edges using 4 threads
-## 19:08:39 Finished
-## 2026-10-19 19:08:39 Compute doublet scores and enrichments from UMAP
-## 19:08:39 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:08:39 Finished building index
-## 19:08:39 Searching HNSW index with ef = 200 and 1 threads
-## 19:08:39 Finished searching
-## 2026-10-19 19:08:39 Finished (64.0s)
+##       Found 12 clusters, merged to 6 [0.3s]
+##       Pseudobulked 6 clusters [0.3s]
+##       Iteration finished [2.7s]
+##     [Iteration 2/2]
+##       Selected 25,000 variable features [0.5s]
+##       Fit LSI on 2,462 cells [1.1s]
+##       Iteration finished [1.6s]
+##   Iterative LSI finished [5.4s]: 2,462 x 30 embedding
+##   Projected 10,000 doublets into LSI [4.0s]
+##   Fit UMAP, re-projection R^2 = 0.951 [4.0s]
+##   Projected 10,000 doublets into UMAP [0.5s]
+##   Scored 2,462 cells by doublet neighbors in UMAP [0.3s]
+##   Dataset finished [18.8s]
+## 2026-10-20 13:58:18 Doublet scoring finished [66.6s]: added doublet scores to 3 datasets (10,681 cells)
 
for (sample_name in names(input_files)) {
   print(plot_doublet_scores(proj, dataset_name = sample_name))
@@ -1887,20 +1744,11 @@ 

Doublet Scoring and Filtering

filter_doublets() removes the highest-enrichment predicted doublets from every dataset in the project.

proj <- filter_doublets(proj, verbose = TRUE)
-
Output
## 2026-10-19 19:08:43 Filtering doublets in 3 dataset(s): scATAC_BMMC_R1, scATAC_CD34_BMMC_R1, scATAC_PBMC_R1
-## 2026-10-19 19:08:43 filtering dataset: scATAC_BMMC_R1.
-## 2026-10-19 19:08:43 Filtering 243 doublets from 4939 cells (4.9%)
-## 2026-10-19 19:08:43 Dataset successfully filtered.
-## 2026-10-19 19:08:43 Removing stale doublet data
-## 2026-10-19 19:08:43 filtering dataset: scATAC_CD34_BMMC_R1.
-## 2026-10-19 19:08:43 Filtering 107 doublets from 3280 cells (3.3%)
-## 2026-10-19 19:08:43 Dataset successfully filtered.
-## 2026-10-19 19:08:43 Removing stale doublet data
-## 2026-10-19 19:08:43 filtering dataset: scATAC_PBMC_R1.
-## 2026-10-19 19:08:43 Filtering 60 doublets from 2462 cells (2.4%)
-## 2026-10-19 19:08:43 Dataset successfully filtered.
-## 2026-10-19 19:08:43 Removing stale doublet data
-## 2026-10-19 19:08:43 Finished (0.0s)
+
Output
## 2026-10-20 13:58:22 Doublet filtering: 3 datasets, 10,681 cells (enrichment >= 1, filter ratio 1)
+## scATAC_BMMC_R1: removed 243 of 4,939 cells (4.9%) [0.0s]
+## scATAC_CD34_BMMC_R1: removed 107 of 3,280 cells (3.3%) [0.0s]
+## scATAC_PBMC_R1: removed 60 of 2,462 cells (2.4%) [0.0s]
+## 2026-10-20 13:58:22 Doublet filtering finished [0.0s]: removed 410 of 10,681 cells (3.8%), cleared doublet data
 
@@ -1916,32 +1764,20 @@

Iterative LSI

max_clusters = 25, verbose = TRUE )
-
Output
## 2026-10-19 19:08:52 Starting Iterative LSI
-## 2026-10-19 19:08:52 Starting Iterative LSI iteration 1 of 2
-## 2026-10-19 19:08:52 Selecting features
-## 2026-10-19 19:08:53 Running LSI
-## 2026-10-19 19:08:54 Starting LSI
-## 2026-10-19 19:08:55 Filtering 404 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-19 19:08:56 Normalizing matrix
-## 2026-10-19 19:08:58 Calculating SVD
-## 2026-10-19 19:09:02 Dropping PCs 1 due to high correlation with sequencing depth
-## 2026-10-19 19:09:02 Re-projecting outlier cells into LSI space
-## 2026-10-19 19:09:04 Clustering LSI results
-## 19:09:04 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:09:05 Finished building index
-## 19:09:05 Searching HNSW index with ef = 100 and 1 threads
-## 19:09:05 Finished searching
-## 2026-10-19 19:09:05 Pseudobulking matrix
-## 2026-10-19 19:09:06 Starting Iterative LSI iteration 2 of 2
-## 2026-10-19 19:09:06 Selecting features
-## 2026-10-19 19:09:07 Running LSI
-## 2026-10-19 19:09:07 Starting LSI
-## 2026-10-19 19:09:08 Filtering 412 outlier cells (colSum quantiles 0.02-0.98) before SVD
-## 2026-10-19 19:09:08 Normalizing matrix
-## 2026-10-19 19:09:10 Calculating SVD
-## 2026-10-19 19:09:14 Dropping PCs 1 due to high correlation with sequencing depth
-## 2026-10-19 19:09:14 Re-projecting outlier cells into LSI space
-## 2026-10-19 19:09:16 Finished (32.8s)
+
Output
## 2026-10-20 13:58:25 Iterative LSI: 10,271 cells, 2 iterations, 30 dims, 4 threads
+## [Iteration 1/2]
+##   Selected 25,000 features (top accessible) [1.5s]
+##   Fit LSI on 9,596 cells, projected 404 depth outliers [9.8s]
+##   Dropped LSI component 1 (r = 0.80 with log10(nFrags))
+##   Found 8 clusters [1.4s]
+##   Pseudobulked 8 clusters [3.4s]
+##   Iteration finished [16.3s]
+## [Iteration 2/2]
+##   Selected 25,000 variable features [0.2s]
+##   Fit LSI on 9,859 cells, projected 412 depth outliers [8.3s]
+##   Dropped LSI component 1 (r = 0.77 with log10(nFrags))
+##   Iteration finished [8.6s]
+## 2026-10-20 13:58:51 Iterative LSI finished [27.9s]: added dim reduction 'IterativeLSI' (10,271 x 29)
 
@@ -1955,25 +1791,9 @@

Clustering

cluster_graph_method = cluster_graph_leiden(resolution = 0.8), knn_method = knn_hnsw(k = 20L) )
-
Output
## 2026-10-19 19:09:16 Extracting embedding 'IterativeLSI'
-## Warning: Converting to a dense matrix may use excessive memory
-## 2026-10-19 19:09:18 Clustering 10271 cells with 29 dimensions
-## 
-## 19:09:18 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 
-## 19:09:19 Finished building index
-## 
-## 19:09:19 Searching HNSW index with ef = 100 and 1 threads
-## 
-## 19:09:20 Finished searching
-## 
-## 2026-10-19 19:09:20 Found 11 clusters
-## 
-## 2026-10-19 19:09:20 Added 11 clusters as 'atac_clusters' in cell metadata
-## 
-## 2026-10-19 19:09:20 Finished (4.7s)
-## 
-## This message is displayed once every 8 hours.
+
Output
## 2026-10-20 13:58:54 Clustering: 10,271 cells on 'IterativeLSI' (29 dims)
+## Found 11 clusters [1.7s]
+## 2026-10-20 13:58:55 Clustering finished [1.8s]: added cell metadata column 'atac_clusters' (11 clusters)
 
@@ -1986,24 +1806,10 @@

UMAP Embedding

min_dist = 0.5, verbose = TRUE )
-
Output
## 2026-10-19 19:09:20 Extracting embedding 'IterativeLSI'
-## 2026-10-19 19:09:20 Computing UMAP on 10271 cells with 29 dimensions
-## 19:09:20 Using HNSW for nearest neighbor search
-## 19:09:20 UMAP embedding parameters a = 0.583 b = 1.334
-## 19:09:20 Setting random seed 1
-## 19:09:20 Read 10271 rows and found 29 numeric columns
-## 19:09:20 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 19:09:21 Finished building index
-## 19:09:21 Searching HNSW index with ef = 30 and 4 threads
-## 19:09:21 Finished searching
-## 19:09:23 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 30
-## 19:09:24 Initializing from normalized Laplacian + noise (using RSpectra)
-## 19:09:24 Range-scaling initial input columns to 0-10
-## 19:09:24 Commencing optimization for 500 epochs, with 464838 positive edges using 4 threads
-## 19:09:24 Using rng type: pcg
-## 19:09:27 Optimization finished
-## 2026-10-19 19:09:27 Added UMAP embedding as 'UMAP' (2 components)
-## 2026-10-19 19:09:27 Finished (7.0s)
+
Output
## 2026-10-20 13:58:55 UMAP: 10,271 cells on 'IterativeLSI' (29 dims), 4 threads
+## Fit 2D UMAP (30 neighbors, min_dist 0.5, cosine) [5.6s]
+## Saved UMAP model [0.2s]
+## 2026-10-20 13:59:01 UMAP finished [5.8s]: added cell metadata columns 'UMAP_1', 'UMAP_2', embedding model 'UMAP'
 

We can visualize the attributes of our cells, using the plot_embedding() function, specifying the coloration via the col_name parameter.

plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters") +
@@ -2029,28 +1835,15 @@ 

Assigning Clusters with Gene Scores

patchwork = TRUE )

+
Output
## Warning: Converting to a dense matrix may use excessive memory
+## This message is displayed once every 8 hours.
+

Raw gene scores can be noisy at the single-cell level. add_impute_weights() computes MAGIC diffusion weights from the LSI embedding.

-
proj <- add_impute_weights(proj, embedding_name = "IterativeLSI")
-
Output
## 2026-10-19 19:09:34 Computing MAGIC imputation weights (td=3, ka=4, blocks~5136 cells, 2 reps)
-## 2026-10-19 19:09:34   Replicate 1 of 2
-## 19:09:34 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:09:34 Finished building index
-## 19:09:34 Searching HNSW index with ef = 100 and 1 threads
-## 19:09:35 Finished searching
-## 19:09:36 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:09:36 Finished building index
-## 19:09:36 Searching HNSW index with ef = 100 and 1 threads
-## 19:09:36 Finished searching
-## 2026-10-19 19:09:37   Replicate 2 of 2
-## 19:09:37 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:09:37 Finished building index
-## 19:09:37 Searching HNSW index with ef = 100 and 1 threads
-## 19:09:37 Finished searching
-## 19:09:38 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 19:09:39 Finished building index
-## 19:09:39 Searching HNSW index with ef = 100 and 1 threads
-## 19:09:39 Finished searching
-## 2026-10-19 19:09:40 Finished (5.7s)
+
proj <- add_impute_weights(proj, embedding_name = "IterativeLSI", verbose = TRUE)
+
Output
## 2026-10-20 13:59:10 Impute weights: 10,271 cells on 'IterativeLSI' (29 dims), 2 replicates x 2 blocks (~5,136 cells), td = 3, ka = 4
+## Replicate 1/2: built 2 diffusion graphs [2.9s]
+## Replicate 2/2: built 2 diffusion graphs [2.7s]
+## 2026-10-20 13:59:16 Impute weights finished [5.6s]: added impute weights (2 replicates x 2 blocks)
 
plot_gene_scores(
   proj,
@@ -2061,8 +1854,8 @@ 

Assigning Clusters with Gene Scores

patchwork = TRUE )

-
Output
## 2026-10-19 19:09:42 Imputing gene scores with MAGIC weights
-## 2026-10-19 19:09:43 Finished (3.4s)
+
Output
## 2026-10-20 13:59:18 Imputing gene scores with MAGIC weights
+## 2026-10-20 13:59:19 Finished [3.1s]
 
@@ -2092,6 +1885,10 @@

Project Saving

save_project() writes a self-contained copy of the MarchRProject so you can run load_project() and load your project into a fresh R session.

saved_project_dir <- file.path(cache_dir, "saved_project")
 proj <- save_project(proj, path = saved_project_dir, overwrite = TRUE)
+
Output
## Warning: Matrix compression performs poorly with non-integers.
+## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
+## This message is displayed once every 8 hours.
+

When you are ready to load the saved project, simply provide the cached project directory,

proj <- load_project(saved_project_dir)
 proj
From d89f5db84faf016f1c97407bb19aaee731bd7096 Mon Sep 17 00:00:00 2001 From: erliuu Date: Fri, 23 Oct 2026 02:02:15 -0700 Subject: [PATCH 07/12] feat([r] logging): Update reporting for group coverages, peak calling and pseudobulk exports --- R/fragment_ops.R | 4 +- R/group_coverages.R | 92 ++++++--- R/peaks.R | 255 +++++++++++++++-------- R/pseudobulk.R | 214 ++++++++++++++----- R/utils.R | 5 + man/add_group_coverages.Rd | 6 +- man/add_motif_annotations.Rd | 4 +- man/add_peak_annotations.Rd | 4 +- man/add_peak_gc.Rd | 4 +- man/add_peak_matrix.Rd | 4 +- man/add_reproducible_peak_set.Rd | 4 +- man/pseudobulk_fragments.Rd | 4 +- man/write_pseudobulk_bigwig.Rd | 4 +- man/write_pseudobulk_coverage.Rd | 4 +- man/write_pseudobulk_fragments.Rd | 4 +- man/write_pseudobulk_peaks.Rd | 4 +- man/write_sce2g_inputs.Rd | 4 +- tests/testthat/test-group_coverages.R | 91 +++++++- tests/testthat/test-peak_annotations.R | 110 +++++++++- tests/testthat/test-peaks.R | 214 +++++++++++++++++-- tests/testthat/test-pseudobulk.R | 276 +++++++++++++++++++++++++ tests/testthat/test-utils.R | 9 + 22 files changed, 1100 insertions(+), 220 deletions(-) diff --git a/R/fragment_ops.R b/R/fragment_ops.R index 425207d..0d141b9 100644 --- a/R/fragment_ops.R +++ b/R/fragment_ops.R @@ -62,7 +62,7 @@ resolve_blacklist <- function(source, blacklist, keep_chr = NULL) { frags_name, blacklist = TRUE, exclude_chr = character(0), - verbose = TRUE + verbose ) { all_frags <- lapply(dataset_names, function(ds) { if (frags_name %in% get_fragment_names(proj, ds)) { @@ -83,7 +83,7 @@ resolve_blacklist <- function(source, blacklist, keep_chr = NULL) { if (!is.null(bl)) { merged_frags <- select_regions(merged_frags, bl, invert_selection = TRUE) } else if (isTRUE(blacklist) && verbose) { - log_progress("No blacklist found in project genome. Skipping blacklist filtering.") + .log_step("Skipped blacklist filtering (no blacklist in project genome)") } if (length(exclude_chr) > 0) { diff --git a/R/group_coverages.R b/R/group_coverages.R index 4d83a98..0bb6543 100644 --- a/R/group_coverages.R +++ b/R/group_coverages.R @@ -37,7 +37,7 @@ #' labels. NULL on the project method uses dataset membership; NULL on the #' default method disables label-aware assignment. Default NULL. #' @param seed (integer) Random seed for reproducibility. Default is 1. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return #' \itemize{ @@ -103,10 +103,11 @@ add_group_coverages.default <- function( max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assertthat::assert_that( !is.null(names(proj)), msg = "Input must be a named vector (names = cell names, values = group labels)." @@ -124,7 +125,13 @@ add_group_coverages.default <- function( labels <- sample_labels[all_cells] } - .build_group_coverages( + if (verbose) { + run <- .log_start("Group coverages", sprintf( + "%s in %s", .log_plural(length(all_cells), "cell"), .log_plural(length(unique(groups)), "group") + )) + } + + cell_groups <- .build_group_coverages( groups = groups, all_cells = all_cells, labels = labels, @@ -136,6 +143,14 @@ add_group_coverages.default <- function( seed = seed, verbose = verbose ) + + if (verbose) { + .log_finish(run, sprintf( + "%s, %s", .log_plural(length(cell_groups), "group"), + .log_plural(sum(lengths(cell_groups)), "replicate") + )) + } + cell_groups } #' @describeIn add_group_coverages Create pseudobulk replicates for a @@ -154,10 +169,11 @@ add_group_coverages.MarchRProject <- function( max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") assert_is_character(dataset_names) dataset_names <- select_dataset_names(proj, dataset_names) @@ -168,6 +184,7 @@ add_group_coverages.MarchRProject <- function( if (is.character(group_by) && length(group_by) == 1 && is.null(names(group_by))) { # Column name — extract from metadata group_by_name <- group_by + extra_cells <- character(0) all_cell_names <- unlist( lapply(dataset_names, function(ds) cell_names(proj$datasets[[ds]])), use.names = FALSE @@ -217,29 +234,34 @@ add_group_coverages.MarchRProject <- function( length(missing_cells) )) } - if (length(extra_cells) > 0 && verbose) { - log_progress(sprintf( - "Ignoring %d cells in group_by that are not in the project.", - length(extra_cells) - )) - groups <- groups[intersect(names(groups), all_cell_names)] - } + groups <- groups[intersect(names(groups), all_cell_names)] } # Drop cells with missing group assignments na_idx <- is.na(groups) - if (any(na_idx)) { - if (verbose) { - log_progress(sprintf("Removing %d cells with NA group assignments.", sum(na_idx))) - } - groups <- groups[!na_idx] - } + groups <- groups[!na_idx] # Resolve sample-of-origin labels for replicate-aware assignment labels <- .resolve_sample_labels(proj, sample_labels, dataset_names) all_cells <- names(groups) + if (verbose) { + run <- .log_start("Group coverages", sprintf( + "%s in %s by '%s', %s", .log_plural(length(all_cells), "cell"), + .log_plural(length(unique(groups)), "group"), group_by_name, + .log_plural(length(setdiff(labels[all_cells], NA)), "sample") + )) + if (any(na_idx)) { + .log_step(sprintf("Dropped %s with NA group labels", .log_plural(sum(na_idx), "cell"))) + } + if (length(extra_cells) > 0) { + .log_step(sprintf( + "Ignored %s not in the project", .log_plural(length(extra_cells), "group_by cell") + )) + } + } + cell_groups <- .build_group_coverages( groups = groups, all_cells = all_cells, @@ -256,6 +278,12 @@ add_group_coverages.MarchRProject <- function( # Attach the replicate assignments to the project for downstream peak calling proj$group_coverages[[group_by_name]] <- cell_groups + if (verbose) { + .log_finish(run, sprintf( + "added group coverages '%s' (%s, %s)", group_by_name, .log_plural(length(cell_groups), "group"), + .log_plural(sum(lengths(cell_groups)), "replicate") + )) + } return(proj) } @@ -357,16 +385,10 @@ get_group_coverages <- function(proj, group_by = character(0)) { seed, verbose ) { + t0 <- steady_clock_seconds_rcpp() unique_groups <- unique(groups) set.seed(seed) - if (verbose) { - log_progress(sprintf( - "Creating pseudobulk replicates for %d groups", - length(unique_groups) - )) - } - cell_groups <- lapply(purrr::set_names(unique_groups), function(grp) { grp_cells <- all_cells[groups == grp] n_cells <- length(grp_cells) @@ -385,19 +407,23 @@ get_group_coverages <- function(proj, group_by = character(0)) { sample_ratio = sample_ratio ) - if (verbose) { - log_progress(sprintf( - " Group '%s': %d cells -> %d replicates (%s cells each)", - grp, n_cells, length(reps), - paste(vapply(reps, length, integer(1)), collapse = ", ") - )) - } - reps }) # Remove NULL groups (empty) - Filter(Negate(is.null), cell_groups) + cell_groups <- Filter(Negate(is.null), cell_groups) + + if (verbose && length(cell_groups) > 0) { + sizes <- lengths(unlist(cell_groups, recursive = FALSE, use.names = FALSE)) + rng <- unique(range(sizes)) + span <- .log_plural(rng[length(rng)], "cell") + if (length(rng) == 2) span <- paste0(.log_count(rng[1]), "-", span) + .log_step(sprintf( + "Split %s into %s (%s each)", .log_plural(length(cell_groups), "group"), + .log_plural(length(sizes), "replicate"), span + ), since = t0) + } + cell_groups } diff --git a/R/peaks.R b/R/peaks.R index c1ec56c..e8df49d 100644 --- a/R/peaks.R +++ b/R/peaks.R @@ -53,7 +53,7 @@ #' or Python venv), pass the full path explicitly: #' \code{macs_executable = "/path/to/bin/macs3"}. #' @param threads (integer) Threads for parallel MACS execution. Default 1. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments. #' #' @return The modified MarchRProject with the peak set stored in @@ -132,10 +132,11 @@ add_reproducible_peak_set.MarchRProject <- function( dataset_names = character(0), macs_executable = NULL, threads = get_threads(), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") peak_method <- match.arg(peak_method) assert_for(proj, "MarchRProject") dataset_names <- select_dataset_names(proj, dataset_names) @@ -163,6 +164,14 @@ add_reproducible_peak_set.MarchRProject <- function( frags_name <- select_fragment_name(proj, frags_name = frags_name) } + if (verbose) { + n_cells <- length(unique(unlist(group_cov, use.names = FALSE))) + run <- .log_start("Peak calling", sprintf( + "%s in %s (%s), %s, reproducibility %s", .log_plural(sum(lengths(group_cov)), "replicate"), + .log_plural(length(group_cov), "group"), .log_plural(n_cells, "cell"), peak_method, reproducibility + )) + } + # Merge fragments across datasets, drop blacklist regions and excluded # chromosomes (all lazy) merged_frags <- .resolve_project_fragments( @@ -189,8 +198,6 @@ add_reproducible_peak_set.MarchRProject <- function( on.exit(unlink(peak_dir, recursive = TRUE), add = TRUE) # Call peaks per replicate - if (verbose) log_progress("Calling peaks per replicate...") - all_peaks <- .call_peaks_per_replicate( merged_frags = merged_frags, group_coverages = group_cov, @@ -214,8 +221,6 @@ add_reproducible_peak_set.MarchRProject <- function( all_peaks$end <- all_peaks$summit_pos + extend_summits + 1L # Build reproducible peak set - if (verbose) log_progress("Filtering for reproducible peaks...") - reproducible <- .build_reproducible_peak_set( all_peaks = all_peaks, group_coverages = group_cov, @@ -234,22 +239,27 @@ add_reproducible_peak_set.MarchRProject <- function( } # Annotate peaks with peakType if gene annotations are available + t0 <- steady_clock_seconds_rcpp() peak_set <- .annotate_peaks(proj, peak_set, promoter_region) - if (verbose) { - log_progress(sprintf("Final peak set: %d peaks", nrow(peak_set))) - if ("peakType" %in% names(peak_set)) { - type_counts <- table(peak_set$peakType) - for (tp in names(type_counts)) { - log_progress(sprintf(" %s: %d", tp, type_counts[[tp]])) - } - } + if (verbose && "peakType" %in% names(peak_set)) { + type_counts <- table(peak_set$peakType) + .log_step(sprintf( + "Annotated %s: %s", .log_plural(nrow(peak_set), "peak"), + paste(.log_count(as.integer(type_counts)), names(type_counts), collapse = ", ") + ), since = t0) } proj$peak_set <- peak_set # Per-group sets are kept alongside the union so downstream consumers that need # one peak set per cell type do not have to re-call peaks. proj$group_peak_sets <- reproducible$by_group + if (verbose) { + .log_finish(run, sprintf( + "added peak set (%s) and %s", .log_plural(nrow(peak_set), "peak"), + .log_plural(length(reproducible$by_group), "group peak set") + )) + } return(proj) } @@ -307,7 +317,7 @@ get_peak_set <- function(proj) { #' @param blacklist (logical or data.frame) Blacklist filtering for fragments. #' @param exclude_chr (character) Chromosomes to exclude from fragments. #' @param overwrite (logical) Overwrite existing assay. Default \code{FALSE}. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments. #' #' @return The modified MarchRProject with a \code{PeakMatrix} assay added to @@ -350,12 +360,14 @@ add_peak_matrix.MarchRProject <- function( blacklist = TRUE, exclude_chr = c("chrM", "chrY"), overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") mode <- match.arg(mode) assert_for(proj, "MarchRProject") + requested <- length(dataset_names) > 0 dataset_names <- select_dataset_names(proj, dataset_names) # Get peak set @@ -380,10 +392,22 @@ add_peak_matrix.MarchRProject <- function( # Resolve blacklist once bl <- resolve_blacklist(proj, blacklist) - if (verbose) log_progress("Creating peak matrix...") + if (verbose) { + run <- .log_start("Peak matrix", sprintf( + "%s, %s", .log_plural(nrow(ranges), "peak"), .log_plural(length(dataset_names), "dataset") + )) + } + n_added <- 0L + n_cells <- 0L for (dataset_name in dataset_names) { - if (!frags_name %in% get_fragment_names(proj, dataset_name)) next + if (!frags_name %in% get_fragment_names(proj, dataset_name)) { + if (requested) { + rlang::warn(sprintf("Dataset '%s' has no '%s' fragments; skipped.", dataset_name, frags_name)) + } + if (verbose) .log_step(sprintf("%s: no '%s' fragments, skipped", dataset_name, frags_name)) + next + } frags <- get_fragments(proj, dataset_name = dataset_name, frags_name) @@ -421,9 +445,8 @@ add_peak_matrix.MarchRProject <- function( } if (verbose) { - log_progress(sprintf( - " %s: %d peaks x %d cells", - dataset_name, nrow(mat), ncol(mat) + .log_step(sprintf( + "%s: built %s x %s matrix", dataset_name, .log_count(nrow(mat)), .log_count(ncol(mat)) )) } @@ -434,6 +457,8 @@ add_peak_matrix.MarchRProject <- function( dataset_name = dataset_name, overwrite = overwrite ) + n_added <- n_added + 1L + n_cells <- n_cells + ncol(mat) } # Store peak annotations as feature_metadata @@ -442,6 +467,12 @@ add_peak_matrix.MarchRProject <- function( rownames(peak_metadata) <- peak_names proj$feature_metadata[[output_assay_name]] <- peak_metadata + if (verbose) { + .log_finish(run, sprintf( + "added assay '%s' to %s (%s)", output_assay_name, .log_plural(n_added, "dataset"), + .log_plural(n_cells, "cell") + )) + } return(proj) } @@ -472,17 +503,14 @@ add_peak_matrix.MarchRProject <- function( for (rep_name in names(reps)) { cells <- reps[[rep_name]] rep_label <- paste0(group_name, "_", rep_name) - - if (verbose) { - log_progress(sprintf(" %s: %d cells", rep_label, length(cells))) - } + t0 <- steady_clock_seconds_rcpp() # Subset fragments to this replicate's cells (lazy) rep_frags <- select_cells(merged_frags, cells) peaks <- tryCatch({ rep_path <- file.path(peak_dir, rep_label) - call_peaks_macs( + suppressMessages(call_peaks_macs( rep_frags, path = rep_path, effective_genome_size = effective_genome_size, @@ -490,15 +518,25 @@ add_peak_matrix.MarchRProject <- function( macs_executable = macs_executable, threads = 1L, verbose = FALSE - ) + )) }, error = function(e) { - if (verbose) { - log_progress(sprintf(" Warning: peak calling failed for %s: %s", - rep_label, conditionMessage(e))) - } - tibble::tibble() + rlang::warn(sprintf( + "Peak calling failed for %s: %s", rep_label, sub("\n.*", "", conditionMessage(e)) + )) + NULL }) + if (is.null(peaks)) { + if (verbose) .log_step(paste0(rep_label, ": peak calling failed, skipped"), since = t0) + next + } + if (verbose) { + .log_step(sprintf( + "%s: called %s from %s", rep_label, .log_plural(nrow(peaks), "summit"), + .log_plural(length(cells), "cell") + ), since = t0) + } + if (nrow(peaks) > 0) { peaks$group_name <- group_name peaks$replicate <- rep_label @@ -543,24 +581,31 @@ add_peak_matrix.MarchRProject <- function( all_peaks$peak_score <- all_peaks$log10_pvalue group_peaks_list <- list() + log_no_peaks <- function(group_name, since) { + if (verbose) .log_step(paste0(group_name, ": no reproducible peaks"), since = since) + } for (group_name in names(group_coverages)) { + t0 <- steady_clock_seconds_rcpp() reps <- group_coverages[[group_name]] n_replicates <- length(reps) n_cells <- length(unique(unlist(reps, use.names = FALSE))) if (n_cells < min_cells) { if (verbose) { - log_progress(sprintf( - " Skipping group '%s': %d cells < min_cells (%d)", - group_name, n_cells, min_cells + .log_step(sprintf( + "%s: skipped (%s < min_cells %s)", group_name, .log_plural(n_cells, "cell"), + .log_count(min_cells) )) } next } group_peaks <- all_peaks[all_peaks$group_name == group_name, ] - if (nrow(group_peaks) == 0) next + if (nrow(group_peaks) == 0) { + log_no_peaks(group_name, t0) + next + } # Step 1-2: Per-replicate overlap resolution + quantile scoring rep_names <- unique(group_peaks$replicate) @@ -582,7 +627,10 @@ add_peak_matrix.MarchRProject <- function( } all_rep_peaks <- do.call(rbind, rep_peaks_list) - if (is.null(all_rep_peaks) || nrow(all_rep_peaks) == 0) next + if (is.null(all_rep_peaks) || nrow(all_rep_peaks) == 0) { + log_no_peaks(group_name, t0) + next + } # Step 3: Merge across replicates by replicateScoreQuantile all_rep_peaks <- all_rep_peaks[ @@ -602,7 +650,10 @@ add_peak_matrix.MarchRProject <- function( min_rep <- eval(parse(text = reproducibility), envir = list(n = n_replicates)) candidates <- candidates[candidates$reproducibility >= min_rep, ] } - if (nrow(candidates) == 0) next + if (nrow(candidates) == 0) { + log_no_peaks(group_name, t0) + next + } # Step 6: Compute groupScoreQuantile and cap candidates$groupScoreQuantile <- rank( @@ -619,25 +670,34 @@ add_peak_matrix.MarchRProject <- function( candidates$group_name <- group_name group_peaks_list <- c(group_peaks_list, list(candidates)) - if (verbose) { - log_progress(sprintf( - " Group '%s': %d reproducible peaks (from %d replicates)", - group_name, nrow(candidates), n_replicates - )) + .log_step(sprintf( + "%s: kept %s (%s)", group_name, .log_plural(nrow(candidates), "reproducible peak"), + .log_plural(n_replicates, "replicate") + ), since = t0) } } + kept_groups <- vapply(group_peaks_list, function(p) as.character(p$group_name[[1]]), character(1)) + n_group_peaks <- sum(vapply(group_peaks_list, nrow, integer(1))) + if (length(group_peaks_list) == 0) { return(list(union = tibble::tibble(), by_group = list())) } # Step 7: Merge across all groups by groupScoreQuantile + t0 <- steady_clock_seconds_rcpp() union_peaks <- do.call(rbind, group_peaks_list) union_peaks <- union_peaks[ order(union_peaks$groupScoreQuantile, decreasing = TRUE), ] union_peaks <- .safe_merge_peaks(union_peaks) + if (verbose) { + .log_step(sprintf( + "Merged %s into %s", .log_plural(n_group_peaks, "group peak"), + .log_plural(nrow(union_peaks), "peak") + ), since = t0) + } # summit_pos is retained so narrowPeak export can write an exact summit offset. # It is not simply extend_summits for peaks clamped at a chromosome start. @@ -652,9 +712,7 @@ add_peak_matrix.MarchRProject <- function( list( union = union_peaks[, keep_cols(union_peaks), drop = FALSE], by_group = lapply( - purrr::set_names(group_peaks_list, vapply( - group_peaks_list, function(p) as.character(p$group_name[[1]]), character(1) - )), + purrr::set_names(group_peaks_list, kept_groups), function(p) p[, keep_cols(p), drop = FALSE] ) ) @@ -1003,7 +1061,7 @@ add_peak_matrix.MarchRProject <- function( #' (set via `set_genome_sequence()`). #' @param overwrite (logical) Whether to recompute when `gc` already exists. #' Default `FALSE`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Currently unused. #' #' @return The modified MarchRProject with `peak_set$gc` and `peak_set$idx` @@ -1033,18 +1091,19 @@ add_peak_gc.MarchRProject <- function( proj, bsgenome = NULL, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { rlang::abort("Project has no peak set. Run add_reproducible_peak_set() first.") } - if (!is.null(proj$peak_set$gc) && !overwrite) { - if (verbose) log_progress("peak_set$gc already populated. Use overwrite = TRUE to replace.") - if (is.null(proj$peak_set$idx)) { + if ("gc" %in% names(proj$peak_set) && !overwrite) { + rlang::warn("peak_set$gc already exists; set overwrite = TRUE to recompute.") + if (!"idx" %in% names(proj$peak_set)) { proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) } return(proj) @@ -1074,7 +1133,12 @@ add_peak_gc.MarchRProject <- function( )) } - if (verbose) log_progress("Computing peak GC content...") + if (verbose) { + run <- .log_start("Peak GC", sprintf( + "%s on %s", .log_plural(nrow(proj$peak_set), "peak"), .log_plural(length(peak_chrs), "chromosome") + )) + } + t0 <- steady_clock_seconds_rcpp() chr_groups <- split(seq_len(nrow(proj$peak_set)), proj$peak_set$chr) gc <- numeric(nrow(proj$peak_set)) for (chr in names(chr_groups)) { @@ -1097,8 +1161,10 @@ add_peak_gc.MarchRProject <- function( proj$peak_set$gc <- gc proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) if (verbose) { - log_progress(sprintf(" GC mean: %.3f, range: [%.3f, %.3f]", - mean(gc), min(gc), max(gc))) + .log_step(sprintf( + "Computed GC content (mean %.3f, range %.3f-%.3f)", mean(gc), min(gc), max(gc) + ), since = t0) + .log_finish(run, "added peak_set columns 'gc', 'idx'") } proj } @@ -1120,7 +1186,7 @@ add_peak_gc.MarchRProject <- function( #' @param name (character) Name of the annotation. Default `"Region"`. #' @param overwrite (logical) Overwrite existing annotation with the same #' name. Default `FALSE`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Currently unused. #' #' @return The modified MarchRProject with the annotation stored at @@ -1153,10 +1219,11 @@ add_peak_annotations.MarchRProject <- function( regions, name = "Region", overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") assert_for(name, "character") assertthat::assert_that(length(name) == 1, msg = "`name` must be a single character string.") @@ -1174,11 +1241,12 @@ add_peak_annotations.MarchRProject <- function( peak_gr <- .peak_set_to_granges(proj$peak_set) if (verbose) { - log_progress(sprintf( - "Computing overlaps: %d peaks x %d annotation regions", - length(peak_gr), length(region_grl) + run <- .log_start("Peak annotation", sprintf( + "'%s', %s x %s", name, .log_plural(length(peak_gr), "peak"), + .log_plural(length(region_grl), "region set") )) } + t0 <- steady_clock_seconds_rcpp() unlisted <- unlist(region_grl) hits <- GenomicRanges::findOverlaps(peak_gr, unlisted, ignore.strand = TRUE) @@ -1196,12 +1264,12 @@ add_peak_annotations.MarchRProject <- function( colnames(m) <- names(region_grl) keep <- Matrix::colSums(m) > 0 - if (verbose && sum(keep) < length(region_grl)) { - log_progress(sprintf( - " Dropping %d annotation%s with zero peak overlaps", - length(region_grl) - sum(keep), - ifelse(length(region_grl) - sum(keep) == 1, "", "s") - )) + if (verbose) { + n_dropped <- sum(!keep) + .log_step(paste0( + sprintf("Matched %s", .log_plural(Matrix::nnzero(m), "peak-region pair")), + if (n_dropped > 0) sprintf(", dropped %s with no overlaps", .log_plural(n_dropped, "region set")) + ), since = t0) } m <- m[, keep, drop = FALSE] region_grl <- region_grl[keep] @@ -1214,9 +1282,8 @@ add_peak_annotations.MarchRProject <- function( ) if (verbose) { - log_progress(sprintf( - " Stored '%s' (%d annotations, %d non-zero entries)", - name, ncol(m), Matrix::nnzero(m) + .log_finish(run, sprintf( + "added peak annotation '%s' (%s)", name, .log_plural(ncol(m), "region set") )) } proj @@ -1256,7 +1323,7 @@ add_peak_annotations.MarchRProject <- function( #' (set via `set_genome_sequence()`). #' @param overwrite (logical) Overwrite existing annotation with the same #' name. Default `FALSE`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Currently unused. #' #' @return The modified `MarchRProject` with the motif annotation stored at @@ -1307,10 +1374,11 @@ add_motif_annotations.MarchRProject <- function( pwm_version = 2L, bsgenome = NULL, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") motif_set <- match.arg(motif_set) assert_for(proj, "MarchRProject") assert_for(anno_name, "character") @@ -1341,11 +1409,24 @@ add_motif_annotations.MarchRProject <- function( species <- BSgenome::organism(bsgenome) } + # Determine pwm_source label. + pwm_source <- if (!is.null(motif_pwms)) "user" + else if (motif_set == "JASPAR2020") sprintf("JASPAR2020_%s", collection) + else if (motif_set == "cisbp") sprintf("cisbp_v%d", pwm_version) + else motif_set + + if (verbose) { + run <- .log_start("Motif annotation", sprintf( + "'%s', %s, %s (p.cutoff %s, w %s)", anno_name, .log_plural(nrow(proj$peak_set), "peak"), + pwm_source, format(cutoff), format(width) + )) + } + # Resolve PWMatrixList. Three paths: # - motif_pwms non-NULL: pass user-supplied PWMatrixList through. # - motif_set == "JASPAR2020": load via TFBSTools::getMatrixSet. # - motif_set in {"cisbp","encode","homer"}: load chromVARmotifs data file. - if (verbose) log_progress("Resolving PWMs...") + t0 <- steady_clock_seconds_rcpp() if (!is.null(motif_pwms)) { raw_pwms <- motif_pwms } else if (identical(motif_set, "JASPAR2020")) { @@ -1409,11 +1490,11 @@ add_motif_annotations.MarchRProject <- function( raw_pwms <- e[[data_name]] } pwms <- .summarize_chromvar_motifs(raw_pwms) - if (verbose) log_progress(sprintf(" %d motifs to scan", length(pwms))) + if (verbose) .log_step(sprintf("Loaded %s", .log_plural(length(pwms), "motif")), since = t0) # Run motifmatchr to get positions. + t0 <- steady_clock_seconds_rcpp() peak_gr <- .peak_set_to_granges(proj$peak_set) - if (verbose) log_progress("Scanning motifs against peaks...") motif_positions <- motifmatchr::matchMotifs( pwms = pwms, subject = peak_gr, @@ -1425,15 +1506,16 @@ add_motif_annotations.MarchRProject <- function( # Drop motifs with zero hits. hit_counts <- lengths(motif_positions) + if (verbose) { + .log_step(sprintf( + "Scanned %s, found %s", .log_plural(length(pwms), "motif"), + .log_plural(sum(hit_counts), "motif site") + ), since = t0) + } motif_positions <- motif_positions[hit_counts > 0] if (length(motif_positions) == 0) { rlang::abort("No motif hits found in any peak. Lower `cutoff` or check inputs.") } - if (verbose && sum(hit_counts == 0) > 0) { - log_progress(sprintf( - " Dropping %d motifs with zero peak hits", sum(hit_counts == 0) - )) - } # Build peak x motif binary match matrix. unlisted <- unlist(motif_positions) @@ -1457,6 +1539,10 @@ add_motif_annotations.MarchRProject <- function( motif_positions <- motif_positions[keep] # Name-indexed (not %in%-filtered) so motif_summary rows align with motif_positions order. pwms_kept <- pwms[names(motif_positions)] + if (verbose && length(pwms_kept) < length(pwms)) { + n_dropped <- length(pwms) - length(pwms_kept) + .log_step(sprintf("Dropped %s with no peak hits", .log_plural(n_dropped, "motif"))) + } # Build motif_summary tibble. motif_summary <- tibble::tibble( @@ -1465,12 +1551,6 @@ add_motif_annotations.MarchRProject <- function( length = vapply(pwms_kept, function(p) ncol(p@profileMatrix), integer(1)) ) - # Determine pwm_source label. - pwm_source <- if (!is.null(motif_pwms)) "user" - else if (motif_set == "JASPAR2020") sprintf("JASPAR2020_%s", collection) - else if (motif_set == "cisbp") sprintf("cisbp_v%d", pwm_version) - else motif_set - proj$peak_annotations[[anno_name]] <- list( name = anno_name, type = "motif", @@ -1482,9 +1562,10 @@ add_motif_annotations.MarchRProject <- function( ) if (verbose) { - log_progress(sprintf( - " Stored '%s' (%d motifs, %d non-zero entries)", - anno_name, ncol(m), Matrix::nnzero(m) + n_matches <- Matrix::nnzero(m) + .log_finish(run, sprintf( + "added peak annotation '%s' (%s, %s %s)", anno_name, .log_plural(ncol(m), "motif"), + .log_count(n_matches), if (n_matches == 1) "match" else "matches" )) } proj diff --git a/R/pseudobulk.R b/R/pseudobulk.R index 8e80a32..f4496c7 100644 --- a/R/pseudobulk.R +++ b/R/pseudobulk.R @@ -130,7 +130,7 @@ pseudobulk_fragments <- function(proj, ...) { #' gating. Default `NULL`. #' @param on_low_depth (character) Response when a group falls below `min_fragments`. #' One of `"warn"`, `"abort"`, `"drop"`. Default `"warn"`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @export pseudobulk_fragments.MarchRProject <- function( proj, @@ -141,16 +141,31 @@ pseudobulk_fragments.MarchRProject <- function( exclude_chr = c("chrM"), min_fragments = NULL, on_low_depth = c("warn", "abort", "drop"), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") on_low_depth <- match.arg(on_low_depth) dataset_names <- select_dataset_names(proj, dataset_names) frags_name <- select_fragment_name(proj, frags_name) - groups <- .resolve_pseudobulk_groups(proj, group_by, dataset_names, verbose = verbose) + resolved <- .resolve_pseudobulk_groups(proj, group_by, dataset_names) + groups <- resolved$groups + + if (verbose) { + by <- if (is.null(group_by)) "" else { + sprintf(" by '%s'", if (is.null(names(group_by))) group_by else "custom_groups") + } + run <- .log_start("Pseudobulk", sprintf( + "%s in %s%s, %s", .log_plural(length(groups), "cell"), + .log_plural(length(unique(groups)), "group"), by, .log_plural(length(dataset_names), "dataset") + )) + if (resolved$n_na > 0) { + .log_step(sprintf("Dropped %s with NA group labels", .log_plural(resolved$n_na, "cell"))) + } + } merged_frags <- .resolve_project_fragments( proj = proj, @@ -178,7 +193,8 @@ pseudobulk_fragments.MarchRProject <- function( merged_frags = merged_frags, dataset_names = dataset_names, frags_name = frags_name, - min_fragments = min_fragments + min_fragments = min_fragments, + verbose = verbose ) # Gate before any writer runs so shallow groups never reach downstream training. @@ -194,13 +210,24 @@ pseudobulk_fragments.MarchRProject <- function( abort = rlang::abort(msg), warn = rlang::warn(msg), drop = { - if (verbose) log_progress(msg) + if (verbose) { + .log_step(sprintf( + "Dropped %s below %s fragments: %s", .log_plural(length(failing), "group"), + .log_count(min_fragments), .log_names(failing) + )) + } fragments <- fragments[setdiff(names(fragments), failing)] } ) } } + if (verbose) { + .log_finish(run, sprintf( + "%s (%s)", .log_plural(length(fragments), "fragment set"), + .log_plural(sum(manifest$n_fragments[manifest$group %in% names(fragments)]), "fragment") + )) + } structure( list( fragments = fragments, @@ -255,15 +282,20 @@ print.MarchRPseudobulk <- function(x, ...) { merged_frags, dataset_names, frags_name, - min_fragments + min_fragments, + verbose ) { qc <- .pseudobulk_cell_qc(proj, dataset_names, frags_name) depth <- qc$n_frags if (is.null(depth) || !all(names(groups) %in% names(depth))) { + t0 <- steady_clock_seconds_rcpp() depth <- stats::setNames( as.numeric(nucleosome_counts(merged_frags)$nFrags), cellNames(merged_frags) ) + if (verbose) { + .log_step(sprintf("Measured depth of %s", .log_plural(length(depth), "cell")), since = t0) + } } cells <- split(names(groups), groups)[group_levels] @@ -318,7 +350,7 @@ print.MarchRPseudobulk <- function(x, ...) { #' @param dir (character) Output directory. Files land in `/fragments/`. #' @param append_5th_column (logical) Write a 5th column. BPCells fills it with a #' literal `0`, not a duplicate count. Default `FALSE`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return `pb` with a `fragments_path` column added to its manifest. #' @@ -333,23 +365,40 @@ write_pseudobulk_fragments <- function( pb, dir, append_5th_column = FALSE, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(pb, "MarchRPseudobulk") out_dir <- .pseudobulk_subdir(dir, "fragments") + if (verbose) { + run <- .log_start( + "Fragment export", sprintf("%s to '%s'", .log_plural(length(pb$fragments), "group"), dir), + compact = TRUE + ) + } paths <- vapply(names(pb$fragments), function(grp) { path <- file.path(out_dir, paste0(.sanitize_group_name(grp), ".tsv.gz")) - if (verbose) log_progress(sprintf(" Writing fragments for group '%s'", grp)) + t0 <- steady_clock_seconds_rcpp() write_fragments_10x( pb$fragments[[grp]], path, append_5th_column = append_5th_column ) + if (verbose) { + .log_step(sprintf( + "%s: wrote fragments for %s", grp, .log_plural(length(cellNames(pb$fragments[[grp]])), "cell") + ), since = t0) + } path }, character(1)) + if (verbose) { + .log_finish(run, sprintf( + "added manifest column 'fragments_path' (%s)", .log_plural(length(paths), "file") + )) + } .pseudobulk_record(pb, "fragments_path", paths) } @@ -375,7 +424,7 @@ write_pseudobulk_fragments <- function( #' @param shift_end (integer) Basepairs to shift fragment ends. Default `0L`. #' @param chrom_sizes (data.frame or NULL) Chromosome sizes for clipping tiles. #' Default `NULL`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return `pb` with a `coverage_path` column added to its manifest. #' @@ -398,9 +447,10 @@ write_pseudobulk_coverage <- function( shift_start = 0L, shift_end = 0L, chrom_sizes = NULL, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(pb, "MarchRPseudobulk") insertion_mode <- match.arg(insertion_mode) normalization <- match.arg(normalization) @@ -418,11 +468,14 @@ write_pseudobulk_coverage <- function( ) if (verbose) { - log_progress(sprintf( - "Writing insertion coverage for %d groups in one pass", nlevels(cell_groups) + run <- .log_start("Coverage export", sprintf( + "%s (%s, %s normalization, %s bp tiles)", .log_plural(nlevels(cell_groups), "group"), + c(both = "both ends", start_only = "starts only", end_only = "ends only")[[insertion_mode]], + if (normalization == "none") "no" else normalization, .log_count(tile_width) )) } + t0 <- steady_clock_seconds_rcpp() write_insertion_bedgraph( frags, path = paths, @@ -433,6 +486,12 @@ write_pseudobulk_coverage <- function( chrom_sizes = chrom_sizes ) + if (verbose) { + .log_step(sprintf("Wrote %s in one pass", .log_plural(length(paths), "bedGraph")), since = t0) + .log_finish(run, sprintf( + "added manifest column 'coverage_path' (%s)", .log_plural(length(paths), "bedGraph") + )) + } .pseudobulk_record(pb, "coverage_path", paths) } @@ -497,7 +556,7 @@ write_pseudobulk_chrom_sizes <- function(pb, dir, chrom_sizes) { #' @param executable (character) Path or name of the converter. Default #' `"bedGraphToBigWig"`. #' @param keep_bedgraph (logical) Retain the source bedGraphs. Default `TRUE`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return `pb` with a `bigwig_path` column added to its manifest, `NA` for any group #' whose conversion was skipped or failed. @@ -515,9 +574,10 @@ write_pseudobulk_bigwig <- function( chrom_sizes, executable = "bedGraphToBigWig", keep_bedgraph = TRUE, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(pb, "MarchRPseudobulk") if (!"coverage_path" %in% names(pb$manifest)) { rlang::abort( @@ -540,17 +600,28 @@ write_pseudobulk_bigwig <- function( pb <- write_pseudobulk_chrom_sizes(pb, dir, chrom_sizes) sizes_path <- pb$params$chrom_sizes_path + n_bedgraphs <- sum(!is.na(pb$manifest$coverage_path)) + if (verbose) { + run <- .log_start("bigWig export", sprintf( + "%s with '%s'", .log_plural(n_bedgraphs, "bedGraph"), executable + )) + } paths <- stats::setNames( vapply(seq_len(nrow(pb$manifest)), function(i) { bedgraph <- pb$manifest$coverage_path[[i]] if (is.na(bedgraph)) return(NA_character_) bigwig <- sub("\\.bedGraph$", ".bw", bedgraph) - if (verbose) { - log_progress(sprintf(" Converting '%s' to bigWig", pb$manifest$group[[i]])) - } - status <- system2(executable, c(bedgraph, sizes_path, bigwig)) + t0 <- steady_clock_seconds_rcpp() + status <- system2( + executable, shQuote(c(bedgraph, sizes_path, bigwig)), stdout = FALSE, stderr = FALSE + ) if (!identical(as.integer(status), 0L)) { + if (verbose) { + .log_step( + sprintf("%s: conversion failed (exit %s)", pb$manifest$group[[i]], status), since = t0 + ) + } rlang::warn(sprintf( "bedGraphToBigWig failed for group '%s' (exit %s).", pb$manifest$group[[i]], status @@ -558,11 +629,18 @@ write_pseudobulk_bigwig <- function( return(NA_character_) } if (!keep_bedgraph) unlink(bedgraph) + if (verbose) .log_step(paste0(pb$manifest$group[[i]], ": converted to bigWig"), since = t0) bigwig }, character(1)), pb$manifest$group ) + if (verbose) { + n_ok <- sum(!is.na(paths)) + counts <- .log_plural(n_bedgraphs, "bigWig") + if (n_ok < n_bedgraphs) counts <- paste(.log_count(n_ok), "of", counts) + .log_finish(run, sprintf("added manifest column 'bigwig_path' (%s)", counts)) + } .pseudobulk_record(pb, "bigwig_path", paths) } @@ -577,7 +655,7 @@ write_pseudobulk_bigwig <- function( #' @param dir (character) Output directory. Files land in `/peaks/`. #' @param scope (character) Which peak sets to write. One of `"both"`, `"group"`, #' `"union"`. Default `"both"`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return `pb` with a `peaks_path` column added to its manifest. #' @@ -591,42 +669,68 @@ write_pseudobulk_peaks <- function( pb, dir, scope = c("both", "group", "union"), - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(pb, "MarchRPseudobulk") scope <- match.arg(scope) + with_union <- scope %in% c("both", "union") + + if (with_union && (is.null(pb$peak_set) || nrow(pb$peak_set) == 0)) { + rlang::abort( + "No union peak set found. Run add_reproducible_peak_set() before exporting peaks." + ) + } + if (scope != "union" && (is.null(pb$group_peak_sets) || length(pb$group_peak_sets) == 0)) { + rlang::abort(paste0( + "No per-group peak sets found. Run add_reproducible_peak_set() to populate ", + "`proj$group_peak_sets`, or use scope = \"union\"." + )) + } out_dir <- .pseudobulk_subdir(dir, "peaks") - if (scope %in% c("both", "union")) { - if (is.null(pb$peak_set) || nrow(pb$peak_set) == 0) { - rlang::abort( - "No union peak set found. Run add_reproducible_peak_set() before exporting peaks." - ) - } + if (verbose) { + targets <- c(if (with_union) "union", if (scope != "union") .log_plural(nrow(pb$manifest), "group")) + run <- .log_start("Peak export", sprintf("%s to '%s'", paste(targets, collapse = " and "), dir)) + union_msg <- if (with_union) sprintf("union (%s)", .log_plural(nrow(pb$peak_set), "peak")) + } + + t0 <- steady_clock_seconds_rcpp() + if (with_union) { .write_narrowpeak(pb$peak_set, file.path(out_dir, "union.narrowPeak"), "union") } if (scope == "union") { + if (verbose) { + .log_step(paste("Wrote", union_msg), since = t0) + .log_finish(run, "wrote union peak file") + } return(pb) } - if (is.null(pb$group_peak_sets) || length(pb$group_peak_sets) == 0) { - rlang::abort(paste0( - "No per-group peak sets found. Run add_reproducible_peak_set() to populate ", - "`proj$group_peak_sets`, or use scope = \"union\"." - )) - } - paths <- vapply(pb$manifest$group, function(grp) { peaks <- pb$group_peak_sets[[grp]] if (is.null(peaks) || nrow(peaks) == 0) return(NA_character_) path <- file.path(out_dir, paste0(.sanitize_group_name(grp), ".narrowPeak")) - if (verbose) log_progress(sprintf(" Writing peaks for group '%s'", grp)) .write_narrowpeak(peaks, path, grp) path }, character(1)) + if (verbose) { + sizes <- vapply(pb$group_peak_sets[pb$manifest$group[!is.na(paths)]], nrow, integer(1)) + files <- .log_plural(length(sizes), "group peak file") + if (length(sizes) > 0) { + rng <- unique(range(sizes)) + span <- .log_plural(rng[length(rng)], "peak") + if (length(rng) == 2) span <- paste0(.log_count(rng[1]), "-", span) + files <- sprintf("%s (%s)", files, span) + } + .log_step(paste("Wrote", paste(c(union_msg, files), collapse = " and ")), since = t0) + .log_finish(run, sprintf( + "added manifest column 'peaks_path' (%s)", .log_plural(length(sizes), "file") + )) + } .pseudobulk_record(pb, "peaks_path", paths) } @@ -731,7 +835,7 @@ write_pseudobulk_manifest <- function(pb, dir) { #' \code{proj[["RNA", by_dataset = FALSE]]}. `NULL` for ATAC-only. Default `NULL`. #' @param model (character) scE2G model folder names under its `models/` directory. Default #' `"multiome_powerlaw_v3"` when `rna` is given, else `"scATAC_powerlaw_v3"`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @return `pb` with `fragments_path` (and `rna_path` when `rna` is given) added to its #' manifest, and `params$sce2g_config_path` set to the cluster table. @@ -763,8 +867,9 @@ write_pseudobulk_manifest <- function(pb, dir) { #' #' @export write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, - verbose = getOption("MarchR.verbose", TRUE)) { + verbose = getOption("MarchR.verbose", FALSE)) { .start_log_clock() + assert_for(verbose, "logical") assert_for(pb, "MarchRPseudobulk") if (!requireNamespace("Rsamtools", quietly = TRUE)) { rlang::abort( @@ -816,27 +921,44 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, } } + if (verbose) { + run <- .log_start("scE2G inputs", sprintf( + "%s, model %s", .log_plural(length(groups), "cluster"), paste(model, collapse = ", ") + )) + } + pb <- write_pseudobulk_fragments(pb, dir, append_5th_column = TRUE, verbose = verbose) frag_paths <- stats::setNames(pb$manifest$fragments_path, pb$manifest$group)[groups] # BPCells writes plain gzip, and tabix can only index BGZF-compressed files. + t0 <- steady_clock_seconds_rcpp() purrr::walk(frag_paths, function(path) { tmp <- paste0(path, ".bgz") Rsamtools::bgzip(path, dest = tmp, overwrite = TRUE) file.rename(tmp, path) Rsamtools::indexTabix(path, format = "bed") }) + if (verbose) { + .log_step( + sprintf("Compressed and indexed %s", .log_plural(length(frag_paths), "fragment file")), since = t0 + ) + } if (!is.null(rna)) { rna_dir <- .pseudobulk_subdir(dir, "rna") rna_paths <- stats::setNames( file.path(rna_dir, paste0(.sanitize_group_name(groups), ".h5ad")), groups ) + t0 <- steady_clock_seconds_rcpp() purrr::iwalk(rna_paths, function(path, grp) { - if (verbose) log_progress(sprintf(" Writing RNA counts for group '%s'", grp)) unlink(path) write_matrix_anndata_hdf5(rna[, names(pb$cell_groups)[pb$cell_groups == grp]], path) }) + if (verbose) { + .log_step( + sprintf("Wrote RNA counts for %s", .log_plural(length(rna_paths), "cluster")), since = t0 + ) + } pb <- .pseudobulk_record(pb, "rna_path", rna_paths) } @@ -856,7 +978,7 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, utils::write.table(config, config_path, sep = "\t", quote = FALSE, row.names = FALSE) config_path <- normalizePath(config_path) - if (verbose) log_progress(paste0("Run scE2G with --config cell_clusters=", config_path)) + if (verbose) .log_finish(run, paste0("run scE2G with --config cell_clusters=", config_path)) pb$params$sce2g_config_path <- config_path pb } @@ -918,9 +1040,10 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, #' Accepts a metadata column name or a named vector, mirroring #' \code{add_group_coverages.MarchRProject()}. Cells with NA labels are dropped. #' +#' @return A list with `groups` (named cell -> group vector) and `n_na` (cells dropped for NA labels). #' @keywords internal #' @noRd -.resolve_pseudobulk_groups <- function(proj, group_by, dataset_names, verbose = TRUE) { +.resolve_pseudobulk_groups <- function(proj, group_by, dataset_names) { all_cell_names <- unlist( lapply(dataset_names, function(ds) cell_names(proj$datasets[[ds]])), use.names = FALSE @@ -929,7 +1052,7 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, # NULL collapses every cell into one bulk, matching the `cell_groups` default of # BPCells' insertion writers. if (is.null(group_by)) { - return(stats::setNames(rep("all", length(all_cell_names)), all_cell_names)) + return(list(groups = stats::setNames(rep("all", length(all_cell_names)), all_cell_names), n_na = 0L)) } if (is.character(group_by) && length(group_by) == 1 && is.null(names(group_by))) { @@ -959,16 +1082,11 @@ write_sce2g_inputs <- function(pb, dir, rna = NULL, model = NULL, groups <- groups[intersect(names(groups), all_cell_names)] na_idx <- is.na(groups) - if (any(na_idx)) { - if (verbose) { - log_progress(sprintf("Removing %d cells with NA group assignments.", sum(na_idx))) - } - groups <- groups[!na_idx] - } + groups <- groups[!na_idx] if (length(groups) == 0) { rlang::abort("No cells remain after resolving group assignments.") } - groups + list(groups = groups, n_na = sum(na_idx)) } diff --git a/R/utils.R b/R/utils.R index d0d8fab..ae92727 100644 --- a/R/utils.R +++ b/R/utils.R @@ -134,6 +134,11 @@ selection_index <- function(selection, dim_len, dimnames) { .log_plural <- function(n, word) paste(.log_count(n), if (isTRUE(n == 1)) word else paste0(word, "s")) +.log_names <- function(x, max = 5L) { + if (length(x) > max) x <- c(x[seq_len(max)], sprintf("and %s more", .log_count(length(x) - max))) + paste(x, collapse = ", ") +} + # Only the setup and finished lines of the outermost call carry a timestamp. .log_line <- function(msg, timestamp = FALSE) { if (timestamp) return(log_progress(msg)) diff --git a/man/add_group_coverages.Rd b/man/add_group_coverages.Rd index 052973b..992133e 100644 --- a/man/add_group_coverages.Rd +++ b/man/add_group_coverages.Rd @@ -15,7 +15,7 @@ max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -30,7 +30,7 @@ max_replicates = 5L, sample_ratio = 0.8, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -62,7 +62,7 @@ has fewer than \code{min_cells * min_replicates} cells. Default is 0.8 \item{seed}{(integer) Random seed for reproducibility. Default is 1.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{group_by}{(character or named character vector) Either a metadata column name (e.g., \code{"clusters"}) or a named character vector of diff --git a/man/add_motif_annotations.Rd b/man/add_motif_annotations.Rd index 3be13e3..7f158d7 100644 --- a/man/add_motif_annotations.Rd +++ b/man/add_motif_annotations.Rd @@ -17,7 +17,7 @@ pwm_version = 2L, bsgenome = NULL, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -57,7 +57,7 @@ extraction. When \code{NULL} (default), resolved from \code{proj$genome$sequence \item{overwrite}{(logical) Overwrite existing annotation with the same name. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Currently unused.} } diff --git a/man/add_peak_annotations.Rd b/man/add_peak_annotations.Rd index d628701..dfaf1e9 100644 --- a/man/add_peak_annotations.Rd +++ b/man/add_peak_annotations.Rd @@ -10,7 +10,7 @@ regions, name = "Region", overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -25,7 +25,7 @@ Input regions. See details for accepted forms.} \item{overwrite}{(logical) Overwrite existing annotation with the same name. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Currently unused.} } diff --git a/man/add_peak_gc.Rd b/man/add_peak_gc.Rd index 85a0bd5..c799a16 100644 --- a/man/add_peak_gc.Rd +++ b/man/add_peak_gc.Rd @@ -9,7 +9,7 @@ proj, bsgenome = NULL, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -23,7 +23,7 @@ sequences. When \code{NULL} (default), resolved from \code{proj$genome$sequence} \item{overwrite}{(logical) Whether to recompute when \code{gc} already exists. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Currently unused.} } diff --git a/man/add_peak_matrix.Rd b/man/add_peak_matrix.Rd index e08f841..1590419 100644 --- a/man/add_peak_matrix.Rd +++ b/man/add_peak_matrix.Rd @@ -17,7 +17,7 @@ blacklist = TRUE, exclude_chr = c("chrM", "chrY"), overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -52,7 +52,7 @@ each fragment end separately (0, 1, or 2 per fragment; matching ArchR), \item{overwrite}{(logical) Overwrite existing assay. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments.} } diff --git a/man/add_reproducible_peak_set.Rd b/man/add_reproducible_peak_set.Rd index 4d4d97e..7964cc7 100644 --- a/man/add_reproducible_peak_set.Rd +++ b/man/add_reproducible_peak_set.Rd @@ -24,7 +24,7 @@ dataset_names = character(0), macs_executable = NULL, threads = get_threads(), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -91,7 +91,7 @@ or Python venv), pass the full path explicitly: \item{threads}{(integer) Threads for parallel MACS execution. Default 1.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments.} } diff --git a/man/pseudobulk_fragments.Rd b/man/pseudobulk_fragments.Rd index 95f0679..98bf03d 100644 --- a/man/pseudobulk_fragments.Rd +++ b/man/pseudobulk_fragments.Rd @@ -14,7 +14,7 @@ exclude_chr = c("chrM"), min_fragments = NULL, on_low_depth = c("warn", "abort", "drop"), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -41,7 +41,7 @@ gating. Default \code{NULL}.} \item{on_low_depth}{(character) Response when a group falls below \code{min_fragments}. One of \code{"warn"}, \code{"abort"}, \code{"drop"}. Default \code{"warn"}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Passed to methods.} } diff --git a/man/write_pseudobulk_bigwig.Rd b/man/write_pseudobulk_bigwig.Rd index 1dfee6c..1948b75 100644 --- a/man/write_pseudobulk_bigwig.Rd +++ b/man/write_pseudobulk_bigwig.Rd @@ -10,7 +10,7 @@ write_pseudobulk_bigwig( chrom_sizes, executable = "bedGraphToBigWig", keep_bedgraph = TRUE, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -25,7 +25,7 @@ write_pseudobulk_bigwig( \item{keep_bedgraph}{(logical) Retain the source bedGraphs. Default \code{TRUE}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ \code{pb} with a \code{bigwig_path} column added to its manifest, \code{NA} for any group diff --git a/man/write_pseudobulk_coverage.Rd b/man/write_pseudobulk_coverage.Rd index 1fbd6f7..a8e2dc8 100644 --- a/man/write_pseudobulk_coverage.Rd +++ b/man/write_pseudobulk_coverage.Rd @@ -13,7 +13,7 @@ write_pseudobulk_coverage( shift_start = 0L, shift_end = 0L, chrom_sizes = NULL, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -37,7 +37,7 @@ write_pseudobulk_coverage( \item{chrom_sizes}{(data.frame or NULL) Chromosome sizes for clipping tiles. Default \code{NULL}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ \code{pb} with a \code{coverage_path} column added to its manifest. diff --git a/man/write_pseudobulk_fragments.Rd b/man/write_pseudobulk_fragments.Rd index 07afacf..3bc9e55 100644 --- a/man/write_pseudobulk_fragments.Rd +++ b/man/write_pseudobulk_fragments.Rd @@ -8,7 +8,7 @@ write_pseudobulk_fragments( pb, dir, append_5th_column = FALSE, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -19,7 +19,7 @@ write_pseudobulk_fragments( \item{append_5th_column}{(logical) Write a 5th column. BPCells fills it with a literal \code{0}, not a duplicate count. Default \code{FALSE}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ \code{pb} with a \code{fragments_path} column added to its manifest. diff --git a/man/write_pseudobulk_peaks.Rd b/man/write_pseudobulk_peaks.Rd index 8b659be..9bbc887 100644 --- a/man/write_pseudobulk_peaks.Rd +++ b/man/write_pseudobulk_peaks.Rd @@ -8,7 +8,7 @@ write_pseudobulk_peaks( pb, dir, scope = c("both", "group", "union"), - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -19,7 +19,7 @@ write_pseudobulk_peaks( \item{scope}{(character) Which peak sets to write. One of \code{"both"}, \code{"group"}, \code{"union"}. Default \code{"both"}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ \code{pb} with a \code{peaks_path} column added to its manifest. diff --git a/man/write_sce2g_inputs.Rd b/man/write_sce2g_inputs.Rd index 01c29de..a3a08ea 100644 --- a/man/write_sce2g_inputs.Rd +++ b/man/write_sce2g_inputs.Rd @@ -9,7 +9,7 @@ write_sce2g_inputs( dir, rna = NULL, model = NULL, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -25,7 +25,7 @@ and \verb{/config_cell_clusters.tsv}.} \item{model}{(character) scE2G model folder names under its \verb{models/} directory. Default \code{"multiome_powerlaw_v3"} when \code{rna} is given, else \code{"scATAC_powerlaw_v3"}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ \code{pb} with \code{fragments_path} (and \code{rna_path} when \code{rna} is given) added to its diff --git a/tests/testthat/test-group_coverages.R b/tests/testthat/test-group_coverages.R index 0bab6b4..6dd7870 100644 --- a/tests/testthat/test-group_coverages.R +++ b/tests/testthat/test-group_coverages.R @@ -217,6 +217,26 @@ test_that("add_group_coverages.default handles multiple groups", { expect_equal(sort(names(result)), c("A", "B", "C")) }) +test_that("add_group_coverages.default reports its split", { + withr::local_options(rlib_message_verbosity = "verbose") + groups <- setNames(rep(c("A", "B"), each = 50), paste0("cell_", 1:100)) + + lines <- .strip_log(capture_messages(add_group_coverages(groups, verbose = TRUE))) + expect_length(lines, 3) + expect_identical(lines, c( + "Group coverages: 100 cells in 2 groups", + "Split 2 groups into 4 replicates (40 cells each) [Xs]", + "Group coverages finished [Xs]: 2 groups, 4 replicates" + )) + expect_no_message(add_group_coverages(groups, verbose = FALSE)) + + tiny <- setNames(rep(c("A", "B"), each = 2), paste0("cell_", 1:4)) + lines <- .strip_log(capture_messages( + add_group_coverages(tiny, min_cells = 1L, max_cells = 1L, verbose = TRUE) + )) + expect_identical(lines[2], "Split 2 groups into 4 replicates (1 cell each) [Xs]") +}) + ######################################################################## # add_group_coverages.MarchRProject tests ######################################################################## @@ -333,15 +353,15 @@ test_that("add_group_coverages.MarchRProject warns and ignores extra cells in na c(all_cells, paste0("extra_", 1:5)) ) - expect_message( + msgs <- capture_messages( proj2 <- add_group_coverages( proj, group_by = extra_groups, , verbose = TRUE - ), - "Ignoring" + ) ) + expect_match(msgs, "Ignored 5 group_by cells not in the project", all = FALSE) expect_s3_class(proj2, "MarchRProject") }) @@ -358,19 +378,78 @@ test_that("add_group_coverages.MarchRProject handles NAs in groups", { all_cells ) - expect_message( + msgs <- capture_messages( proj2 <- add_group_coverages( proj, group_by = groups_with_na, , verbose = TRUE - ), - "Removing.*NA" + ) ) + expect_match(msgs, "Dropped 10 cells with NA group labels", all = FALSE) expect_true("custom_groups" %in% names(proj2$group_coverages)) }) +test_that("add_group_coverages.MarchRProject drops extra group_by cells when not verbose", { + proj <- create_gc_test_project(n_cells = c(50, 50)) + all_cells <- unlist(cell_names(proj), use.names = FALSE) + groups <- c(setNames(rep("A", 100), all_cells), setNames(rep("Z", 5), paste0("extra_", 1:5))) + + cov <- add_group_coverages(proj, group_by = groups, verbose = FALSE)$group_coverages$custom_groups + expect_identical(names(cov), "A") + expect_true(all(unlist(cov) %in% all_cells)) +}) + +test_that("add_group_coverages.MarchRProject logs all-NA group_by without warnings", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_gc_test_project(n_cells = c(50, 50)) + groups <- setNames(rep(NA_character_, 100), unlist(cell_names(proj), use.names = FALSE)) + + expect_no_warning(lines <- .strip_log(capture_messages( + add_group_coverages(proj, group_by = groups, verbose = TRUE) + ))) + expect_identical(lines, c( + "Group coverages: 0 cells in 0 groups by 'custom_groups', 0 samples", + "Dropped 100 cells with NA group labels", + "Group coverages finished [Xs]: added group coverages 'custom_groups' (0 groups, 0 replicates)" + )) +}) + +test_that("add_group_coverages.MarchRProject reports dropped cells and its split", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_gc_test_project(n_cells = c(50, 50)) + all_cells <- unlist(cell_names(proj), use.names = FALSE) + groups <- setNames(rep(c("A", "B"), each = 50), all_cells) + groups[1:10] <- NA + groups <- c(groups, setNames(rep("A", 5), paste0("extra_", 1:5))) + + lines <- .strip_log(capture_messages( + add_group_coverages(proj, group_by = groups, min_cells = 10L, verbose = TRUE) + )) + expect_length(lines, 5) + expect_identical(lines, c( + "Group coverages: 90 cells in 2 groups by 'custom_groups', 2 samples", + "Dropped 10 cells with NA group labels", + "Ignored 5 group_by cells not in the project", + "Split 2 groups into 4 replicates (20-25 cells each) [Xs]", + paste0( + "Group coverages finished [Xs]: added group coverages 'custom_groups' ", + "(2 groups, 4 replicates)" + ) + )) + expect_no_message(add_group_coverages(proj, group_by = groups, min_cells = 10L, verbose = FALSE)) + + lines <- .strip_log(capture_messages( + add_group_coverages(proj, group_by = "clusters", min_cells = 10L, verbose = TRUE) + )) + expect_identical(lines, c( + "Group coverages: 100 cells in 3 groups by 'clusters', 2 samples", + "Split 3 groups into 6 replicates (16-17 cells each) [Xs]", + "Group coverages finished [Xs]: added group coverages 'clusters' (3 groups, 6 replicates)" + )) +}) + test_that("add_group_coverages.MarchRProject works with single dataset", { proj <- create_gc_test_project(n_cells = c(100)) diff --git a/tests/testthat/test-peak_annotations.R b/tests/testthat/test-peak_annotations.R index b61c1f4..5f749b3 100644 --- a/tests/testthat/test-peak_annotations.R +++ b/tests/testthat/test-peak_annotations.R @@ -96,7 +96,10 @@ test_that("add_peak_gc respects overwrite = FALSE", { proj <- create_test_project_with_peaks() proj <- add_peak_gc(proj, bsg, verbose = FALSE) proj$peak_set$gc[1] <- 0.999 # corrupt sentinel - proj <- add_peak_gc(proj, bsg, overwrite = FALSE, verbose = FALSE) + expect_warning( + proj <- add_peak_gc(proj, bsg, overwrite = FALSE, verbose = FALSE), + "already exists" + ) expect_equal(proj$peak_set$gc[1], 0.999) }) @@ -123,6 +126,38 @@ test_that("add_peak_gc matches direct Biostrings computation", { expect_equal(proj$peak_set$gc, expected) }) +test_that("add_peak_gc reports GC content", { + skip_if_not_installed("BSgenome.Hsapiens.UCSC.hg19") + withr::local_options(rlib_message_verbosity = "verbose") + bsg <- BSgenome.Hsapiens.UCSC.hg19::BSgenome.Hsapiens.UCSC.hg19 + proj <- create_test_project_with_peaks() + + lines <- .strip_log(capture_messages(result <- add_peak_gc(proj, bsg, verbose = TRUE))) + gc <- result$peak_set$gc + expect_length(lines, 3) + expect_identical(lines, c( + "Peak GC: 10 peaks on 2 chromosomes", + sprintf("Computed GC content (mean %.3f, range %.3f-%.3f) [Xs]", mean(gc), min(gc), max(gc)), + "Peak GC finished [Xs]: added peak_set columns 'gc', 'idx'" + )) + expect_no_message(add_peak_gc(proj, bsg, verbose = FALSE)) +}) + +test_that("add_peak_gc warns and keeps an existing gc column without logging", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project_with_peaks() + proj$peak_set$gc <- 0.5 + + expect_no_message(expect_warning( + result <- add_peak_gc(proj, verbose = TRUE), + "peak_set$gc already exists; set overwrite = TRUE to recompute.", + fixed = TRUE + )) + expect_equal(result$peak_set$gc, rep(0.5, 10)) + expect_equal(result$peak_set$idx, 1:10) + expect_warning(add_peak_gc(proj, verbose = FALSE), "already exists") +}) + test_that("add_peak_annotations errors when project has no peak set", { skip_if_not_installed("GenomicRanges") proj <- create_test_project() @@ -221,6 +256,33 @@ test_that("add_peak_annotations match matrix matches manual findOverlaps", { expect_equal(observed_rows, expected_rows) }) +test_that("add_peak_annotations reports matched pairs and dropped region sets", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project_with_peaks() + grl <- GenomicRanges::GRangesList( + A = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + B = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)), + Miss = GenomicRanges::GRanges("chr1", IRanges::IRanges(5000000, 5001000)) + ) + + lines <- .strip_log(capture_messages(add_peak_annotations(proj, grl, verbose = TRUE))) + expect_length(lines, 3) + expect_identical(lines, c( + "Peak annotation: 'Region', 10 peaks x 3 region sets", + "Matched 8 peak-region pairs, dropped 1 region set with no overlaps [Xs]", + "Peak annotation finished [Xs]: added peak annotation 'Region' (2 region sets)" + )) + + lines <- .strip_log(capture_messages(add_peak_annotations(proj, grl["A"], verbose = TRUE))) + expect_identical(lines, c( + "Peak annotation: 'Region', 10 peaks x 1 region set", + "Matched 4 peak-region pairs [Xs]", + "Peak annotation finished [Xs]: added peak annotation 'Region' (1 region set)" + )) + expect_no_message(add_peak_annotations(proj, grl, verbose = FALSE)) +}) + test_that("names(proj$peak_annotations) returns the names of stored annotations", { skip_if_not_installed("GenomicRanges") proj <- create_test_project_with_peaks() @@ -546,6 +608,52 @@ test_that("add_motif_annotations retains motif profiles aligned with positions", expect_equal(names(anno$pwms), colnames(anno$matches)) }) +test_that("add_motif_annotations reports loaded, scanned and dropped motifs", { + skip_if_not_installed("motifmatchr") + skip_if_not_installed("TFBSTools") + skip_if_not_installed("BSgenome.Hsapiens.UCSC.hg19") + withr::local_options(rlib_message_verbosity = "verbose") + + proj <- create_test_project_with_peaks() + bsg <- BSgenome.Hsapiens.UCSC.hg19::BSgenome.Hsapiens.UCSC.hg19 + bases <- c("A", "C", "G", "T") + no_hit <- matrix(1, 4, 8, dimnames = list(bases, NULL)) + no_hit[cbind(match(strsplit("ACGTTGCA", "")[[1]], bases), 1:8)] <- 97 + pwms <- TFBSTools::PFMatrixList( + MOTIF_A = TFBSTools::PFMatrix( + ID = "MA9001", name = "MOTIF_A", + profileMatrix = matrix( + c(40, 10, 10, 10, + 10, 40, 10, 10, + 10, 10, 40, 10, + 10, 10, 10, 40), + nrow = 4L, byrow = TRUE, + dimnames = list(bases, NULL) + ) + ), + NO_HIT = TFBSTools::PFMatrix(ID = "MA9002", name = "NO_HIT", profileMatrix = no_hit) + ) + add_motifs <- function(verbose) { + add_motif_annotations(proj, motif_pwms = pwms, bsgenome = bsg, verbose = verbose) + } + + lines <- .strip_log(capture_messages(result <- add_motifs(TRUE))) + anno <- get_peak_annotation(result, "Motif") + expect_identical(colnames(anno$matches), "MOTIF_A_1") + expect_length(lines, 5) + expect_identical(lines, c( + "Motif annotation: 'Motif', 10 peaks, user (p.cutoff 5e-05, w 7)", + "Loaded 2 motifs [Xs]", + sprintf("Scanned 2 motifs, found %d motif sites [Xs]", length(anno$positions[[1]])), + "Dropped 1 motif with no peak hits", + sprintf( + "Motif annotation finished [Xs]: added peak annotation 'Motif' (1 motif, %d matches)", + Matrix::nnzero(anno$matches) + ) + )) + expect_no_message(add_motifs(FALSE)) +}) + test_that("get_motifs returns the stored profiles", { proj <- create_test_project_with_peaks() proj$peak_annotations$Motif <- list( diff --git a/tests/testthat/test-peaks.R b/tests/testthat/test-peaks.R index cc9041a..59447b0 100644 --- a/tests/testthat/test-peaks.R +++ b/tests/testthat/test-peaks.R @@ -568,6 +568,54 @@ test_that(".build_reproducible_peak_set retains summit_pos for narrowPeak export expect_equal(result$union$summit_pos, 350L) }) +test_that(".build_reproducible_peak_set reports one line per group", { + all_peaks <- tibble::tibble( + chr = "chr1", + start = c(100L, 100L, 3000L), + end = c(600L, 600L, 3500L), + log10_pvalue = c(10, 8, 9), + group_name = c("C1", "C1", "C2"), + replicate = c("C1_Rep1", "C1_Rep2", "C2_Rep1") + ) + two_reps <- function(offset) { + list(Rep1 = paste0("cell_", offset + 1:50), Rep2 = paste0("cell_", offset + 51:100)) + } + small <- lapply(4:8, function(i) list(Rep1 = paste0("small_", i, "_", 1:5))) + group_cov <- c( + list(C1 = two_reps(0), C2 = two_reps(100), C3 = two_reps(200)), + purrr::set_names(small, paste0("C", 4:8)) + ) + + lines <- .strip_log(capture_messages(MarchR:::.build_reproducible_peak_set( + all_peaks = all_peaks, + group_coverages = group_cov, + reproducibility = "2", + max_peaks = 150000L, + peaks_per_cell = 500L, + min_cells = 10L, + verbose = TRUE + ))) + expect_length(lines, 9) + expect_identical(lines, c( + "C1: kept 1 reproducible peak (2 replicates) [Xs]", + "C2: no reproducible peaks [Xs]", + "C3: no reproducible peaks [Xs]", + sprintf("C%d: skipped (5 cells < min_cells 10)", 4:8), + "Merged 1 group peak into 1 peak [Xs]" + )) + + lines <- .strip_log(capture_messages(MarchR:::.build_reproducible_peak_set( + all_peaks = all_peaks, + group_coverages = group_cov["C4"], + reproducibility = "2", + max_peaks = 150000L, + peaks_per_cell = 500L, + min_cells = 10L, + verbose = TRUE + ))) + expect_identical(lines, "C4: skipped (5 cells < min_cells 10)") +}) + ######################################################################## # get_peak_set() @@ -644,22 +692,116 @@ test_that("add_reproducible_peak_set caps via max_peaks", { expect_true(nrow(result$peak_set) <= 5 * 3 + 5) # rough bound }) -test_that("add_reproducible_peak_set prints messages when verbose", { +test_that("add_reproducible_peak_set reports replicates, groups, merge and annotation", { macs_method <- resolve_macs_or_skip() + withr::local_options(rlib_message_verbosity = "verbose") + withr::local_seed(1L) proj <- create_peaks_test_project() - - expect_message( + call_peaks <- function(verbose) { add_reproducible_peak_set( proj, group_by = "clusters", peak_method = macs_method, reproducibility = 1L, + min_cells = 53L, + exclude_chr = character(0), + verbose = verbose + ) + } + + lines <- .strip_log(capture_messages(result <- call_peaks(TRUE))) + n_peaks <- nrow(result$peak_set) + n_kept <- vapply(result$group_peak_sets, nrow, integer(1)) + types <- table(result$peak_set$peakType) + expect_identical(names(n_kept), c("C1", "C2")) + expect_length(lines, 14) + expect_identical(lines[1:2], c( + sprintf("Peak calling: 6 replicates in 3 groups (160 cells), %s, reproducibility 1", macs_method), + "Skipped blacklist filtering (no blacklist in project genome)" + )) + expect_match( + lines[3:8], "^C[1-3]_Rep[12]: called [0-9,]+ summits? from 2[67] cells \\[Xs\\]$", perl = TRUE + ) + expect_identical( + sub(" called [0-9,]+ summits? from", "", lines[3:8]), + paste0(c("C1_Rep1", "C1_Rep2", "C2_Rep1", "C2_Rep2", "C3_Rep1", "C3_Rep2"), ": ", + c(27, 27, 27, 27, 26, 26), " cells [Xs]") + ) + expect_identical(lines[9:14], c( + sprintf("%s: kept %d reproducible peaks (2 replicates) [Xs]", names(n_kept), n_kept), + "C3: skipped (52 cells < min_cells 53)", + sprintf("Merged %d group peaks into %d peaks [Xs]", sum(n_kept), n_peaks), + sprintf("Annotated %d peaks: %s [Xs]", n_peaks, paste(types, names(types), collapse = ", ")), + sprintf("Peak calling finished [Xs]: added peak set (%d peaks) and 2 group peak sets", n_peaks) + )) + expect_no_message(call_peaks(FALSE)) +}) + +test_that("add_reproducible_peak_set logs a failed replicate and keeps the others", { + macs_method <- resolve_macs_or_skip() + skip_on_os("windows") + withr::local_options(rlib_message_verbosity = "verbose") + withr::local_seed(1L) + proj <- create_peaks_test_project() + macs_wrapper <- withr::local_tempfile(fileext = ".sh") + writeLines(c( + "#!/bin/sh", + 'case "$*" in *C2_Rep1*) exit 1 ;; esac', + sprintf('exec "%s" "$@"', Sys.which(macs_method)) + ), macs_wrapper) + Sys.chmod(macs_wrapper, "0755") + call_peaks <- function(verbose) { + add_reproducible_peak_set( + proj, + group_by = "clusters", + macs_executable = macs_wrapper, + reproducibility = 1L, + min_cells = 1L, + exclude_chr = character(0), + blacklist = FALSE, + verbose = verbose + ) + } + + expect_warning( + lines <- .strip_log(capture_messages(result <- call_peaks(TRUE))), + "^Peak calling failed for C2_Rep1: MACS calls encountered 1 failures" + ) + expect_length(lines, 13) + expect_identical(lines[4], "C2_Rep1: peak calling failed, skipped [Xs]") + expect_match(lines[c(2:3, 5:7)], "^C[1-3]_Rep[12]: called [0-9,]+ summits? from 2[67] cells \\[Xs\\]$") + expect_true(nrow(result$peak_set) > 0) + expect_no_message(expect_warning(call_peaks(FALSE), "Peak calling failed for C2_Rep1")) +}) + +test_that("add_reproducible_peak_set warns for every failed MACS replicate", { + skip_on_os("windows") + proj <- create_peaks_test_project() + failing_macs <- withr::local_tempfile(fileext = ".sh") + writeLines(c( + "#!/bin/sh", + 'if [ "$1" = "--version" ]; then echo "macs3 3.0.0"; exit 0; fi', + "exit 1" + ), failing_macs) + Sys.chmod(failing_macs, "0755") + + expect_no_message(warns <- capture_warnings(expect_error( + add_reproducible_peak_set( + proj, + group_by = "clusters", + macs_executable = failing_macs, + reproducibility = 1L, min_cells = 1L, exclude_chr = character(0), blacklist = FALSE, - verbose = TRUE + verbose = FALSE ), - "Calling peaks" + "No peaks called" + ))) + labels <- c("C1_Rep1", "C1_Rep2", "C2_Rep1", "C2_Rep2", "C3_Rep1", "C3_Rep2") + expect_length(warns, 6) + expect_identical( + warns, paste0("Peak calling failed for ", labels, ": MACS calls encountered 1 failures") ) }) @@ -912,21 +1054,57 @@ test_that("add_peak_matrix validates peak_set columns", { ) }) -test_that("add_peak_matrix prints messages when verbose", { +test_that("add_peak_matrix reports each dataset", { + withr::local_options(rlib_message_verbosity = "verbose") proj <- create_peaks_test_project() - proj$peak_set <- tibble::tibble( - chr = "chr1", start = 0L, end = 200L - ) + proj$peak_set <- tibble::tibble(chr = c("chr1", "chr2"), start = c(0L, 200L), end = c(200L, 400L)) + + lines <- .strip_log(capture_messages( + add_peak_matrix(proj, exclude_chr = character(0), verbose = TRUE) + )) + expect_length(lines, 4) + expect_identical(lines, c( + "Peak matrix: 2 peaks, 2 datasets", + "dataset_1: built 2 x 80 matrix", + "dataset_2: built 2 x 80 matrix", + "Peak matrix finished [Xs]: added assay 'PeakMatrix' to 2 datasets (160 cells)" + )) + expect_no_message(add_peak_matrix(proj, exclude_chr = character(0), verbose = FALSE)) +}) - expect_message( - add_peak_matrix( - proj, - exclude_chr = character(0), - blacklist = FALSE, - verbose = TRUE - ), - "Creating peak matrix" - ) +test_that("add_peak_matrix warns for a requested dataset without the fragments", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_peaks_test_project() + proj$peak_set <- tibble::tibble(chr = "chr1", start = 0L, end = 200L) + proj$datasets$dataset_2$fragments <- list() + build <- function(verbose, ...) { + add_peak_matrix(proj, exclude_chr = character(0), verbose = verbose, ...) + } + expected <- c( + "Peak matrix: 1 peak, 2 datasets", + "dataset_1: built 1 x 80 matrix", + "dataset_2: no 'fragments' fragments, skipped", + "Peak matrix finished [Xs]: added assay 'PeakMatrix' to 1 dataset (80 cells)" + ) + + expect_warning( + lines <- .strip_log(capture_messages( + result <- build(TRUE, dataset_names = c("dataset_1", "dataset_2")) + )), + "Dataset 'dataset_2' has no 'fragments' fragments; skipped.", + fixed = TRUE + ) + expect_identical(lines, expected) + expect_false("PeakMatrix" %in% names(result$datasets$dataset_2$matrices)) + expect_no_message(expect_warning( + build(FALSE, dataset_names = c("dataset_1", "dataset_2")), + "Dataset 'dataset_2' has no 'fragments' fragments; skipped.", + fixed = TRUE + )) + + expect_no_warning(lines <- .strip_log(capture_messages(build(TRUE)))) + expect_identical(lines, expected) + expect_no_warning(expect_no_message(build(FALSE))) }) diff --git a/tests/testthat/test-pseudobulk.R b/tests/testthat/test-pseudobulk.R index ae34fe4..86c6773 100644 --- a/tests/testthat/test-pseudobulk.R +++ b/tests/testthat/test-pseudobulk.R @@ -118,6 +118,73 @@ test_that("pseudobulk_fragments partitions fragments without loss or overlap", { expect_length(intersect(cellNames(pb$fragments$A), cellNames(pb$fragments$B)), 0L) }) +test_that("pseudobulk_fragments logs NA labels, blacklist, depth, and dropped groups", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + cells <- unlist(cell_names(proj), use.names = FALSE) + groups <- stats::setNames(rep(c("A", "B", "C"), c(8, 6, 2)), cells) + groups[1:2] <- NA + run <- function(verbose) { + pseudobulk_fragments( + proj, group_by = groups, min_fragments = 50, on_low_depth = "drop", verbose = verbose + ) + } + + lines <- .strip_log(capture_messages(pb <- run(TRUE))) + expect_length(lines, 6) + expect_identical(lines, c( + "Pseudobulk: 14 cells in 3 groups by 'custom_groups', 3 datasets", + "Dropped 2 cells with NA group labels", + "Skipped blacklist filtering (no blacklist in project genome)", + "Measured depth of 14 cells [Xs]", + "Dropped 1 group below 50 fragments: C", + "Pseudobulk finished [Xs]: 2 fragment sets (156 fragments)" + )) + expect_named(pb$fragments, c("A", "B")) + expect_no_message(run(FALSE)) + + many <- stats::setNames(paste0("G", rep(1:8, each = 2)), cells) + lines <- .strip_log(capture_messages(pseudobulk_fragments( + proj, group_by = many, min_fragments = 1e9, on_low_depth = "drop", verbose = TRUE + ))) + expect_identical( + lines[4], "Dropped 8 groups below 1,000,000,000 fragments: G1, G2, G3, G4, G5, and 3 more" + ) +}) + +test_that("pseudobulk_fragments omits the group_by clause for a single bulk", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + + lines <- .strip_log(capture_messages(pseudobulk_fragments(proj, group_by = NULL, verbose = TRUE))) + expect_identical(lines, c( + "Pseudobulk: 16 cells in 1 group, 3 datasets", + "Skipped blacklist filtering (no blacklist in project genome)", + "Measured depth of 16 cells [Xs]", + "Pseudobulk finished [Xs]: 1 fragment set (208 fragments)" + )) +}) + +test_that("pseudobulk_fragments reads depth from stored fragment QC without a depth pass", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + for (ds in names(proj$datasets)) { + proj$datasets[[ds]]$qc_frags$fragments <- data.frame( + cellName = cell_names(proj$datasets[[ds]]), nFrags = 10, TSSEnrichment = 5 + ) + } + + lines <- .strip_log(capture_messages( + pb <- pseudobulk_fragments(proj, group_by = NULL, verbose = TRUE) + )) + expect_identical(lines, c( + "Pseudobulk: 16 cells in 1 group, 3 datasets", + "Skipped blacklist filtering (no blacklist in project genome)", + "Pseudobulk finished [Xs]: 1 fragment set (160 fragments)" + )) + expect_equal(pb$manifest$median_tss_enrichment, 5) +}) + ######################################################################## # write_pseudobulk_fragments() @@ -139,6 +206,23 @@ test_that("write_pseudobulk_fragments round-trips each group's fragments", { expect_equal(sorted_key(written), sorted_key(as.data.frame(pb$fragments$A))) }) +test_that("write_pseudobulk_fragments logs one line per group", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + pb <- pseudobulk_fragments(proj, group_by = pseudobulk_test_groups(proj), verbose = FALSE) + out <- withr::local_tempdir() + + lines <- .strip_log(capture_messages(write_pseudobulk_fragments(pb, out, verbose = TRUE))) + expect_length(lines, 4) + expect_identical(lines, c( + sprintf("Fragment export: 2 groups to '%s'", out), + "A: wrote fragments for 8 cells [Xs]", + "B: wrote fragments for 8 cells [Xs]", + "Fragment export finished [Xs]: added manifest column 'fragments_path' (2 files)" + )) + expect_no_message(write_pseudobulk_fragments(pb, out, verbose = FALSE)) +}) + ######################################################################## # write_pseudobulk_coverage() @@ -177,6 +261,22 @@ test_that("write_pseudobulk_coverage keeps groups separate", { expect_equal(total, 2 * all_frags) }) +test_that("write_pseudobulk_coverage logs its single pass", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + pb <- pseudobulk_fragments(proj, group_by = pseudobulk_test_groups(proj), verbose = FALSE) + out <- withr::local_tempdir() + + lines <- .strip_log(capture_messages(write_pseudobulk_coverage(pb, out, verbose = TRUE))) + expect_length(lines, 3) + expect_identical(lines, c( + "Coverage export: 2 groups (both ends, no normalization, 1 bp tiles)", + "Wrote 2 bedGraphs in one pass [Xs]", + "Coverage export finished [Xs]: added manifest column 'coverage_path' (2 bedGraphs)" + )) + expect_no_message(write_pseudobulk_coverage(pb, out, verbose = FALSE)) +}) + ######################################################################## # write_pseudobulk_bigwig() @@ -281,6 +381,96 @@ test_that("write_pseudobulk_bigwig converts bedGraphs when the converter exists" expect_true(all(file.exists(pb$manifest$bigwig_path))) }) +test_that("write_pseudobulk_bigwig quotes paths with spaces for the converter", { + skip_on_os("windows") + proj <- create_test_project(include_fragments = TRUE) + pb <- pseudobulk_fragments( + proj, group_by = pseudobulk_test_groups(proj), verbose = FALSE + ) + out <- file.path(withr::local_tempdir(), "out dir") + pb <- write_pseudobulk_coverage(pb, out, verbose = FALSE) + converter <- withr::local_tempfile(fileext = ".sh") + writeLines(c("#!/bin/sh", '[ "$#" -eq 3 ] || exit 2', 'touch "$3"'), converter) + Sys.chmod(converter, "0755") + + pb <- write_pseudobulk_bigwig( + pb, out, chrom_sizes = pseudobulk_test_chrom_sizes(), executable = converter, verbose = FALSE + ) + + expect_true(all(file.exists(pb$manifest$bigwig_path))) +}) + +# Fake converter that prints to stdout and stderr, succeeds only when both are discarded, and exits 3 +# for `fail_group`. +fake_bigwig_converter <- function(fail_group = "none", env = parent.frame()) { + path <- withr::local_tempfile(fileext = ".sh", .local_envir = env) + writeLines(c( + "#!/bin/sh", + "echo converter stdout", + "echo converter stderr >&2", + sprintf('case "$1" in */%s.bedGraph) exit 3 ;; esac', fail_group), + "[ /dev/stdout -ef /dev/null ] && [ /dev/stderr -ef /dev/null ] || exit 9", + 'touch "$3"' + ), path) + Sys.chmod(path, "0755") + path +} + +test_that("write_pseudobulk_bigwig logs each conversion and silences the converter", { + skip_on_os("windows") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + pb <- pseudobulk_fragments(proj, group_by = pseudobulk_test_groups(proj), verbose = FALSE) + out <- withr::local_tempdir() + pb <- write_pseudobulk_coverage(pb, out, verbose = FALSE) + converter <- fake_bigwig_converter() + convert <- function(verbose) { + write_pseudobulk_bigwig( + pb, out, chrom_sizes = pseudobulk_test_chrom_sizes(), executable = converter, verbose = verbose + ) + } + + expect_output(lines <- .strip_log(capture_messages(res <- convert(TRUE))), NA) + expect_length(lines, 4) + expect_identical(lines, c( + sprintf("bigWig export: 2 bedGraphs with '%s'", converter), + "A: converted to bigWig [Xs]", + "B: converted to bigWig [Xs]", + "bigWig export finished [Xs]: added manifest column 'bigwig_path' (2 bigWigs)" + )) + expect_true(all(file.exists(res$manifest$bigwig_path))) + expect_no_message(expect_output(convert(FALSE), NA)) +}) + +test_that("write_pseudobulk_bigwig warns and logs a failed conversion", { + skip_on_os("windows") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + pb <- pseudobulk_fragments(proj, group_by = pseudobulk_test_groups(proj), verbose = FALSE) + out <- withr::local_tempdir() + pb <- write_pseudobulk_coverage(pb, out, verbose = FALSE) + converter <- fake_bigwig_converter(fail_group = "B") + convert <- function(verbose) { + write_pseudobulk_bigwig( + pb, out, chrom_sizes = pseudobulk_test_chrom_sizes(), executable = converter, verbose = verbose + ) + } + + expect_warning( + lines <- .strip_log(capture_messages(res <- convert(TRUE))), + "bedGraphToBigWig failed for group 'B' (exit 3).", fixed = TRUE + ) + expect_length(lines, 4) + expect_identical(lines, c( + sprintf("bigWig export: 2 bedGraphs with '%s'", converter), + "A: converted to bigWig [Xs]", + "B: conversion failed (exit 3) [Xs]", + "bigWig export finished [Xs]: added manifest column 'bigwig_path' (1 of 2 bigWigs)" + )) + expect_identical(is.na(res$manifest$bigwig_path), c(FALSE, TRUE)) + expect_no_message(expect_warning(convert(FALSE), "group 'B'")) +}) + ######################################################################## # write_pseudobulk_peaks() @@ -349,6 +539,39 @@ test_that("write_pseudobulk_peaks writes the union set when scope is union", { expect_true(file.exists(file.path(out, "peaks", "union.narrowPeak"))) }) +test_that("write_pseudobulk_peaks logs one collapsed write step", { + withr::local_options(rlib_message_verbosity = "verbose") + pb <- pseudobulk_with_peaks() + out <- withr::local_tempdir() + export <- function(pb, scope) { + .strip_log(capture_messages(write_pseudobulk_peaks(pb, out, scope = scope, verbose = TRUE))) + } + + expect_identical(export(pb, "group"), c( + sprintf("Peak export: 2 groups to '%s'", out), + "Wrote 2 group peak files (2 peaks) [Xs]", + "Peak export finished [Xs]: added manifest column 'peaks_path' (2 files)" + )) + expect_identical(export(pb, "union"), c( + sprintf("Peak export: union to '%s'", out), + "Wrote union (2 peaks) [Xs]", + "Peak export finished [Xs]: wrote union peak file" + )) + + pb$group_peak_sets$B <- pb$group_peak_sets$B[1, ] + lines <- export(pb, "both") + expect_length(lines, 3) + expect_identical(lines, c( + sprintf("Peak export: union and 2 groups to '%s'", out), + "Wrote union (2 peaks) and 2 group peak files (1-2 peaks) [Xs]", + "Peak export finished [Xs]: added manifest column 'peaks_path' (2 files)" + )) + expect_no_message(write_pseudobulk_peaks(pb, out, verbose = FALSE)) + + pb$group_peak_sets$A <- pb$group_peak_sets$A[1, ] + expect_identical(export(pb, "group")[2], "Wrote 2 group peak files (1 peak) [Xs]") +}) + test_that("write_pseudobulk_peaks errors for group scope without per-group sets", { proj <- create_test_project(include_fragments = TRUE) pb <- pseudobulk_fragments( @@ -362,6 +585,16 @@ test_that("write_pseudobulk_peaks errors for group scope without per-group sets" ) }) +test_that("write_pseudobulk_peaks checks peak sets before writing any peak file", { + pb <- pseudobulk_with_peaks() + pb$group_peak_sets <- NULL + out <- withr::local_tempdir() + + expect_error(write_pseudobulk_peaks(pb, out, verbose = FALSE), "per-group peak sets") + expect_false(file.exists(file.path(out, "peaks", "union.narrowPeak"))) + expect_false(dir.exists(file.path(out, "peaks"))) +}) + ######################################################################## # Depth gate @@ -408,6 +641,18 @@ test_that("pseudobulk_fragments drops shallow groups when on_low_depth is drop", expect_true(all(!pb$manifest$passed_depth_gate)) }) +test_that("pseudobulk_fragments warns below min_fragments by default", { + proj <- create_test_project(include_fragments = TRUE) + + expect_warning( + pb <- pseudobulk_fragments( + proj, group_by = pseudobulk_test_groups(proj), min_fragments = 1e9, verbose = FALSE + ), + "below the min_fragments depth floor" + ) + expect_length(pb$fragments, 2L) +}) + ######################################################################## # write_pseudobulk_manifest() @@ -494,6 +739,37 @@ test_that("write_sce2g_inputs writes indexed 5-column fragments, h5ad RNA, and t expect_equal(config$atac_frag_file[config$cluster == "A"], normalizePath(frag)) }) +test_that("write_sce2g_inputs logs nested fragment lines and collapsed steps", { + skip_if_not_installed("Rsamtools") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project(include_fragments = TRUE) + pb <- sce2g_test_pb(proj) + rna <- proj[["RNA", by_dataset = FALSE]] + out <- withr::local_tempdir() + finished <- "scE2G inputs finished [Xs]: run scE2G with --config cell_clusters=" + + lines <- .strip_log(capture_messages(res <- write_sce2g_inputs(pb, out, rna = rna, verbose = TRUE))) + expect_length(lines, 6) + expect_identical(lines, c( + "scE2G inputs: 2 clusters, model multiome_powerlaw_v3", + "A: wrote fragments for 8 cells [Xs]", + "B: wrote fragments for 8 cells [Xs]", + "Compressed and indexed 2 fragment files [Xs]", + "Wrote RNA counts for 2 clusters [Xs]", + paste0(finished, res$params$sce2g_config_path) + )) + expect_no_message(write_sce2g_inputs(pb, out, rna = rna, verbose = FALSE)) + + lines <- .strip_log(capture_messages(res <- write_sce2g_inputs(pb, out, verbose = TRUE))) + expect_identical(lines, c( + "scE2G inputs: 2 clusters, model scATAC_powerlaw_v3", + "A: wrote fragments for 8 cells [Xs]", + "B: wrote fragments for 8 cells [Xs]", + "Compressed and indexed 2 fragment files [Xs]", + paste0(finished, res$params$sce2g_config_path) + )) +}) + test_that("write_sce2g_inputs defaults to the ATAC-only model without RNA", { skip_if_not_installed("Rsamtools") proj <- create_test_project(include_fragments = TRUE) diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index 3b7de66..30ea630 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -201,3 +201,12 @@ test_that("log durations come from a monotonic clock in seconds", { expect_gte(steady_clock_seconds_rcpp(), t0) expect_match(.log_secs(t0 - 2), "^\\[2\\.[0-9]s\\]$", perl = TRUE) }) + +test_that(".log_names shows the first five names and counts the rest", { + ids <- paste0("C", 1:8) + expect_identical(.log_names(character(0)), "") + expect_identical(.log_names(ids[1]), "C1") + expect_identical(.log_names(ids[1:5]), "C1, C2, C3, C4, C5") + expect_identical(.log_names(ids[1:6]), "C1, C2, C3, C4, C5, and 1 more") + expect_identical(.log_names(ids), "C1, C2, C3, C4, C5, and 3 more") +}) From 8431c876c99f360a16fe745392d6df8a27dc95bc Mon Sep 17 00:00:00 2001 From: erliuu Date: Fri, 23 Oct 2026 02:03:34 -0700 Subject: [PATCH 08/12] feat([r] logging): Update reporting for PCA, bulk projection and rna gene integration --- R/bulk_projection.R | 142 ++++++++--- R/dimensionality_reduction.R | 115 ++++++--- R/rna_integration.R | 221 ++++++++++++------ man/add_gene_integration_matrix.Rd | 4 +- man/project_bulk_atac.Rd | 2 +- man/run_harmony.Rd | 3 +- tests/testthat/test-bulk_projection.R | 170 ++++++++++++++ .../testthat/test-dimensionality_reduction.R | 109 ++++++++- tests/testthat/test-rna_integration.R | 156 ++++++++++++- 9 files changed, 761 insertions(+), 161 deletions(-) diff --git a/R/bulk_projection.R b/R/bulk_projection.R index e80dfdb..33f1943 100644 --- a/R/bulk_projection.R +++ b/R/bulk_projection.R @@ -27,19 +27,22 @@ ) } -# Overlap bulk ATAC peaks onto the reduction's feature ranges and return a sparse -# (reduction features x bulk samples) count matrix in reduction feature order. -# @noRd -.match_bulk_features <- function(se_atac, feature_gr, assay_name = "counts", - force = FALSE, verbose = TRUE) { - assert_has_package(c("SummarizedExperiment", "GenomicRanges", "S4Vectors")) - +.assert_bulk_se <- function(se_atac) { if (!methods::is(se_atac, "RangedSummarizedExperiment")) { rlang::abort(paste0( "`se_atac` must be a RangedSummarizedExperiment carrying rowRanges. ", "Build one with SummarizedExperiment(assays = ..., rowRanges = )." )) } +} + +# Overlap bulk ATAC peaks onto the reduction's feature ranges and return a sparse +# (reduction features x bulk samples) count matrix in reduction feature order. +# @noRd +.match_bulk_features <- function(se_atac, feature_gr, assay_name = "counts", + force = FALSE, verbose) { + assert_has_package(c("SummarizedExperiment", "GenomicRanges", "S4Vectors")) + .assert_bulk_se(se_atac) available <- SummarizedExperiment::assayNames(se_atac) if (!assay_name %in% available) { rlang::abort(sprintf( @@ -84,9 +87,9 @@ } } if (verbose) { - log_progress(sprintf( - "Matched %d of %d reduction features to bulk peaks (%.1f%%)", - length(covered), length(feature_gr), 100 * overlap_ratio + .log_step(sprintf( + "Matched %s of %s reduction features to bulk peaks (%.1f%%)", + .log_count(length(covered)), .log_count(length(feature_gr)), 100 * overlap_ratio )) } @@ -180,15 +183,10 @@ # Simulate every bulk sample and bind into one (features x pseudo-cells) matrix. # @noRd .simulate_all_bulk_samples <- function(mapped_counts, feature_names, depth_n, n, - seed, verbose = TRUE) { + seed, verbose) { + t0 <- steady_clock_seconds_rcpp() sample_names <- colnames(mapped_counts) sims <- lapply(seq_along(sample_names), function(s) { - if (verbose) { - log_progress(sprintf( - "Simulating pseudo-cells for sample %d of %d (%s)", - s, length(sample_names), sample_names[s] - )) - } one <- .simulate_bulk_pseudocells( feature_counts = mapped_counts[, s], n_features = nrow(mapped_counts), @@ -201,6 +199,12 @@ }) combined <- do.call(cbind, sims) rownames(combined) <- feature_names + if (verbose) { + .log_step(sprintf( + "Simulated %s from %s (%s each, mean depth %s)", .log_plural(ncol(combined), "pseudo-cell"), + .log_plural(length(sample_names), "sample"), .log_count(ncol(sims[[1]])), .log_count(depth_n) + ), since = t0) + } combined } @@ -236,7 +240,7 @@ #' @param seed (numeric) Random seed. Default: 1. #' @param threads (integer) Threads for the UMAP transform in the MarchRProject method. Default #' `get_threads()`. The DimReduction method projects single-threaded (default NULL). -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Passed to methods. #' #' @return A list with \code{simulated_reduced_dims}, \code{overlap_ratio} and @@ -278,11 +282,13 @@ project_bulk_atac.DimReduction <- function( force = FALSE, seed = 1L, threads = NULL, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_has_package(c("SummarizedExperiment", "GenomicRanges", "IRanges", "S4Vectors")) + .assert_bulk_se(se_atac) assert_is_wholenumber(n) assert_greater_than_zero(n) .resolve_threads(threads, default = 1L, warn_as = "project_bulk_atac() on a DimReduction") @@ -294,24 +300,38 @@ project_bulk_atac.DimReduction <- function( selected <- .reduction_selected_features(x, iteration) feature_gr <- .feature_keys_to_granges(selected) + iterative <- !is.null(x$fitted_params$iter_info) + if (verbose) { + run <- .log_start("Bulk projection", sprintf( + "%s into %s (%s%s)", .log_plural(ncol(se_atac), "sample"), class(x)[1], + if (iterative) sprintf("iteration %d, ", iteration) else "", + .log_plural(length(selected), "feature") + )) + } matched <- .match_bulk_features( se_atac, feature_gr, assay_name = assay_name, force = force, verbose = verbose ) depth_n <- .reduction_depth(x, iteration) - if (verbose) { - log_progress(sprintf("Simulating pseudo-cells at a mean depth of %d counts", depth_n)) - } sim <- .simulate_all_bulk_samples( matched$counts, selected, depth_n = depth_n, n = n, seed = seed, verbose = verbose ) - if (verbose) log_progress("Projecting simulated pseudo-cells into the fitted space") + t0 <- steady_clock_seconds_rcpp() project_args <- list(x, as(sim, "IterableMatrix")) - if (!is.null(x$fitted_params$iter_info)) { + if (iterative) { project_args$iteration <- iteration } simulated_reduced_dims <- as.matrix(do.call(project, project_args)) + if (verbose) { + .log_step(sprintf( + "Projected %s into %s", .log_plural(nrow(simulated_reduced_dims), "pseudo-cell"), + sub("^Iterative", "", class(x)[1]) + ), since = t0) + .log_finish(run, sprintf( + "%s x %d reduced dims", .log_count(nrow(simulated_reduced_dims)), ncol(simulated_reduced_dims) + )) + } list( simulated_reduced_dims = simulated_reduced_dims, @@ -355,7 +375,9 @@ project_bulk_atac.DimReduction <- function( "Assay '%s' not found in dataset '%s'.", assay_name, dset )) } - as.matrix(x$datasets[[dset]]$matrices[[assay_name]]) + rlang::with_options( + as.matrix(x$datasets[[dset]]$matrices[[assay_name]]), rlib_message_verbosity = "quiet" + ) }) if (is.null(feature_names)) feature_names <- rownames(mats[[1]]) if (is.null(feature_names)) { @@ -394,10 +416,11 @@ project_bulk_atac.MarchRProject <- function( force = FALSE, seed = 1L, threads = get_threads(), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRProject") threads <- .resolve_threads(threads) dim_reduction_name <- select_embedding_name(x, dim_reduction_name) @@ -405,24 +428,51 @@ project_bulk_atac.MarchRProject <- function( dim_reduction <- get_dim_reduction(x, dim_reduction_name) # The cell-embedding assay usually shares the reduction's name. IterativeLSI() sets output_assay_name. if (is.null(reduced_dims_assay)) reduced_dims_assay <- dim_reduction_name + .assert_bulk_se(se_atac) + if (is.null(iteration)) { + iteration <- dim_reduction$fitted_params$iterations %||% 1L + } + assert_is_wholenumber(iteration) + assert_is_wholenumber(n) + assert_greater_than_zero(n) + + if (!is.null(embedding_name)) { + available_assays <- unique(unlist(get_assay_names(x))) + if (!reduced_dims_assay %in% available_assays) { + rlang::abort(sprintf( + "Assay '%s' not found. Pass `reduced_dims_assay` naming the cell embeddings. Available: %s", + reduced_dims_assay, paste(available_assays, collapse = ", ") + )) + } + } + if (verbose) { + n_cells <- sum(purrr::map_int( + x$datasets[dataset_names], ~ ncol(.x$matrices[[reduced_dims_assay]]) %||% 0L + )) + run <- .log_start("Bulk projection", sprintf( + "%s into '%s' (%s%s)%s", .log_plural(ncol(se_atac), "sample"), dim_reduction_name, + if (is.null(dim_reduction$fitted_params$iter_info)) "" else sprintf("iteration %d, ", iteration), + .log_plural(length(.reduction_selected_features(dim_reduction, iteration)), "feature"), + if (is.null(embedding_name)) "" else paste0(", ", .log_plural(n_cells, "cell")) + )) + } res <- project_bulk_atac( dim_reduction, se_atac, embedding_name = NULL, assay_name = assay_name, n = n, iteration = iteration, force = force, seed = seed, verbose = verbose ) + if (verbose) { + sim_summary <- sprintf( + "%s from %s in %s", .log_plural(nrow(res$simulated_reduced_dims), "pseudo-cell"), + .log_plural(ncol(se_atac), "sample"), sub("^Iterative", "", class(dim_reduction)[1]) + ) + } if (is.null(embedding_name)) { + if (verbose) .log_finish(run, sim_summary) return(res) } - available_assays <- unique(unlist(get_assay_names(x))) - if (!reduced_dims_assay %in% available_assays) { - rlang::abort(sprintf( - "Assay '%s' not found. Pass `reduced_dims_assay` naming the cell embeddings. Available: %s", - reduced_dims_assay, paste(available_assays, collapse = ", ") - )) - } - embedding_record <- x$embeddings[[embedding_name]] %||% NULL if (!is.null(embedding_record)) { if (!identical(embedding_record$method, "umap")) { @@ -478,22 +528,25 @@ project_bulk_atac.MarchRProject <- function( "Stored UMAP model archive is missing: %s", model_path )) } - if (verbose) log_progress("Loading the fitted UMAP transform model") + t0 <- steady_clock_seconds_rcpp() model <- uwot::load_uwot(model_path) on.exit(uwot::unload_uwot(model), add = TRUE) + if (verbose) .log_step(sprintf("Loaded UMAP model '%s'", embedding_name), since = t0) } else { rlang::warn(paste0( "No project-level UMAP transform model is stored for '", embedding_name, "'. Reconstructing a legacy pinned model; re-run add_umap() for exact projection." )) - if (verbose) log_progress("Reconstructing the legacy fitted UMAP model") + t0 <- steady_clock_seconds_rcpp() model <- .pinned_umap_model( reduced_dims, umap_coords, umap_params = umap_params, threads = threads, verbose = FALSE ) on.exit(uwot::unload_uwot(model), add = TRUE) + if (verbose) .log_step("Rebuilt legacy UMAP model from stored coordinates", since = t0) } + t0 <- steady_clock_seconds_rcpp() set.seed(seed) check_idx <- sort(sample( nrow(reduced_dims), min(nrow(reduced_dims), n_check_cells) @@ -506,7 +559,14 @@ project_bulk_atac.MarchRProject <- function( dim1 = stats::cor(reprojected[, 1], umap_coords[check_idx, 1]), dim2 = stats::cor(reprojected[, 2], umap_coords[check_idx, 2]) ) - if (min(projection_corr) < min_corr) { + below <- min(projection_corr) < min_corr + if (verbose) { + .log_step(sprintf( + "Re-projected %s to check UMAP, r = %.3f%s", .log_plural(length(check_idx), "cell"), + min(projection_corr), if (below) sprintf(" (below %.2f)", min_corr) else "" + ), since = t0) + } + if (below) { rlang::warn(sprintf( paste0( "UMAP reprojection correlation is %.4f, below the %.2f threshold. ", @@ -516,11 +576,17 @@ project_bulk_atac.MarchRProject <- function( )) } - if (verbose) log_progress("Projecting bulk samples into the UMAP embedding") + t0 <- steady_clock_seconds_rcpp() simulated_umap <- uwot::umap_transform( res$simulated_reduced_dims, model, n_threads = threads, n_sgd_threads = .umap_sgd_threads(model), verbose = FALSE ) + if (verbose) { + .log_step( + sprintf("Projected %s into UMAP", .log_plural(nrow(simulated_umap), "pseudo-cell")), since = t0 + ) + .log_finish(run, paste(sim_summary, "and UMAP")) + } sim_names <- rownames(res$simulated_reduced_dims) list( diff --git a/R/dimensionality_reduction.R b/R/dimensionality_reduction.R index 1316051..af31ecc 100644 --- a/R/dimensionality_reduction.R +++ b/R/dimensionality_reduction.R @@ -340,7 +340,8 @@ project_dim_reduction.MarchRProject <- function( #' assignments. Provide only one of `group_by` or `group_values`. #' @param group_values (vector) Group assignments for each cell. When unnamed, #' values are matched to the order of the embeddings. -#' @param ... Additional arguments forwarded to `harmony::RunHarmony()`. +#' @param ... Additional arguments forwarded to `harmony::RunHarmony()`; its `verbose` defaults to +#' `FALSE`. #' #' @return For matrix-like inputs, a harmonized matrix. For dataset and project #' inputs, the updated object with a harmonized assay. @@ -384,12 +385,15 @@ run_harmony.matrix <- function( colnames(meta_data) <- "harmony_group" rownames(meta_data) <- cell_names - harmony_res <- harmony::RunHarmony( + harmony_args <- list(...) + harmony_args[["verbose"]] <- harmony_args[["verbose"]] %||% FALSE + harmony_res <- rlang::exec( + harmony::RunHarmony, data_mat = cell_matrix, meta_data = meta_data, vars_use = colnames(meta_data), return_object = FALSE, - ... + !!!harmony_args ) if (!inherits(harmony_res, "matrix")) { @@ -413,7 +417,7 @@ run_harmony.dgCMatrix <- function(x, ...) { #' @rdname run_harmony #' @export run_harmony.IterableMatrix <- function(x, ...) { - run_harmony.matrix(as.matrix(x), ...) + run_harmony.matrix(rlang::with_options(as.matrix(x), rlib_message_verbosity = "quiet"), ...) } #' @rdname run_harmony @@ -431,7 +435,7 @@ run_harmony.MarchRDataset <- function( ... ) { assay_name <- select_assay_name(x, assay_name) - embeddings <- as.matrix(x[[assay_name, ]]) + embeddings <- rlang::with_options(as.matrix(x[[assay_name, ]]), rlib_message_verbosity = "quiet") groups <- resolve_harmony_groups( x, colnames(embeddings), @@ -475,7 +479,9 @@ run_harmony.MarchRProject <- function( assert_is_character(dataset_names) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) - embeddings <- as.matrix(x[[assay_name, dataset_names]]) + embeddings <- rlang::with_options( + as.matrix(x[[assay_name, dataset_names]]), rlib_message_verbosity = "quiet" + ) groups <- resolve_harmony_groups( x, colnames(embeddings), @@ -973,6 +979,8 @@ LSI.MarchRProject <- function( assert_for(verbose, "logical") assert_is_wholenumber(threads) assert_len(threads, 1) + assert_is_wholenumber(n_dimensions) + assert_len(n_dimensions, 1) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) @@ -1363,8 +1371,12 @@ IterativeLSI.default <- function( assert_is_mat(x) assert_greater_than_zero(n_iterations) assert_is_wholenumber(n_iterations) + assert_len(n_iterations, 1) + assert_is_wholenumber(n_dimensions) + assert_len(n_dimensions, 1) knn_threads <- .resolve_threads(threads, default = 1L) threads <- .resolve_threads(threads) + assert_len(threads, 1) assert_for(verbose, "logical") assert_for(scale_dims, "logical") assert_greater_than_zero(filter_top_features) @@ -1785,6 +1797,14 @@ IterativeLSI.MarchRProject <- function( .start_log_clock() assert_is_character(dataset_names) assert_for(verbose, "logical") + assert_is_wholenumber(n_iterations) + assert_len(n_iterations, 1) + assert_is_wholenumber(n_dimensions) + assert_len(n_dimensions, 1) + if (!is.null(threads)) { + assert_is_wholenumber(threads) + assert_len(threads, 1) + } dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) @@ -1985,16 +2005,15 @@ PCA.default <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_mat(x) assert_is_wholenumber(n_features) + assert_len(n_features, 1) assert_is_wholenumber(n_dimensions) assert_len(n_dimensions, 1) assert_greater_than_zero(n_dimensions) assert_is_wholenumber(threads) - assert_for(verbose, "logical") - - # Adjust n_features to not exceed the number of available features - n_features <- min(nrow(x), n_features) + assert_len(threads, 1) # Preliminary check for minimum matrix size for PCA if (min(ncol(x), nrow(x)) < 2) { @@ -2004,30 +2023,27 @@ PCA.default <- function( } if (verbose) { - log_progress("Starting PCA workflow...") - } - if (verbose) { - log_progress(paste( - "Using", - n_features, - "variable features (limited by matrix dimensions)" + run <- .log_start("PCA", sprintf( + "%s, %s, %s, %s", .log_plural(ncol(x), "cell"), .log_plural(nrow(x), "feature"), + .log_plural(n_dimensions, "dim"), .log_plural(threads, "thread") )) + if (n_features > nrow(x)) { + .log_step(sprintf( + "Reduced n_features from %s to %s (%s)", .log_count(n_features), .log_count(nrow(x)), + .log_plural(nrow(x), "feature") + )) + } } - # Log normalization - if (verbose) { - log_progress("Performing log normalization...") - } + # Adjust n_features to not exceed the number of available features + n_features <- min(nrow(x), n_features) + # Log normalization # Use MarchR's normalize_log function which implements Seurat-style normalization x_norm <- normalize_log(x, scale_factor = scale_factor, threads = threads) # Variable gene selection - if (verbose) { - log_progress("Selecting variable features...") - } - # Calculate statistics for normalization stats <- BPCells::matrix_stats(x_norm, row_stats = "variance") mean_stats <- stats$row_stats['mean', ] @@ -2051,25 +2067,26 @@ PCA.default <- function( head(n_features) %>% sort() } + if (verbose) { + .log_step(paste("Selected", .log_plural(length(variable_features), "variable feature")), + since = run$start) + } # Subset to variable features x_norm <- x_norm[variable_features, ] feature_means <- mean_stats[variable_features] feature_vars <- var_stats[variable_features] - if (verbose) { - log_progress("Caching normalized matrix...") - } + t0 <- steady_clock_seconds_rcpp() cache_dir <- tempfile("marchr_pca_") on.exit(unlink(cache_dir, recursive = TRUE), add = TRUE) - + # Compressed float to keep cache smaller - x_norm <- write_matrix_dir(convert_matrix_type(x_norm, "float"), cache_dir) + x_norm <- rlang::with_options( + write_matrix_dir(convert_matrix_type(x_norm, "float"), cache_dir), rlib_message_verbosity = "quiet" + ) # Z-score normalization - if (verbose) { - log_progress("Applying z-score normalization...") - } feature_sds <- sqrt(feature_vars) feature_sds[feature_sds == 0] <- 1 x_norm <- (x_norm - feature_means) / feature_sds @@ -2084,6 +2101,12 @@ PCA.default <- function( } max_dimensions <- min(nrow(x_norm), ncol(x_norm)) - 1 + if (verbose && n_dimensions > max_dimensions) { + .log_step(sprintf( + "Reduced dims from %s to %s (%s)", .log_count(n_dimensions), .log_count(max_dimensions), + .log_plural(max_dimensions + 1, if (nrow(x_norm) <= ncol(x_norm)) "feature" else "cell") + )) + } n_dimensions <- min(n_dimensions, max_dimensions) # Ensure we have at least 1 dimension @@ -2093,10 +2116,8 @@ PCA.default <- function( ) } - if (verbose) { - log_progress(paste("Computing SVD with", n_dimensions, "dimensions...")) - } svd_result <- BPCells::svds(x_norm, k = n_dimensions, threads = threads) + if (verbose) .log_step(paste("Fit PCA on", .log_plural(ncol(x), "cell")), since = t0) # Create PC embeddings (cells x PCs) pc_embeddings <- multiply_cols(svd_result$v, svd_result$d) @@ -2137,6 +2158,9 @@ PCA.default <- function( class = c("PCA", "DimReduction") ) + if (verbose) { + .log_finish(run, sprintf("%s x %d embedding", .log_count(nrow(pc_embeddings)), ncol(pc_embeddings))) + } return(list( cell_embeddings = pc_embeddings, dim_reduction = dim_reduction @@ -2160,12 +2184,24 @@ PCA.MarchRProject <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_is_character(dataset_names) + assert_is_wholenumber(threads) + assert_len(threads, 1) + assert_is_wholenumber(n_dimensions) + assert_len(n_dimensions, 1) dataset_names <- select_dataset_names(x, dataset_names) assay_name <- select_assay_name(x, assay_name) # Get matrices from all specified datasets matrices <- x[[assay_name, dataset_names]] + if (verbose) { + run <- .log_start("PCA", sprintf( + "%s, %s, %s, %s", .log_plural(ncol(matrices), "cell"), + .log_plural(nrow(matrices), "feature"), .log_plural(n_dimensions, "dim"), + .log_plural(threads, "thread") + )) + } # Perform PCA pca_result <- PCA( @@ -2195,7 +2231,12 @@ PCA.MarchRProject <- function( output_assay_name, overwrite = overwrite ) - + if (verbose) { + .log_finish(run, sprintf( + "added dim reduction '%s' (%s x %d)", dim_reduction_name, + .log_count(nrow(pca_result$cell_embeddings)), ncol(pca_result$cell_embeddings) + )) + } return(x) } diff --git a/R/rna_integration.R b/R/rna_integration.R index 0aa2c41..efa391b 100644 --- a/R/rna_integration.R +++ b/R/rna_integration.R @@ -53,7 +53,7 @@ #' @param threads (integer) Threads for the normalization and `matrix_stats()` passes. Default `1L`; #' not read from `set_threads()`. #' @param seed (integer) Random seed. Default 1. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param overwrite (logical) Overwrite existing columns / assay. Default FALSE. #' @param ... Passed to methods. #' @@ -115,14 +115,17 @@ add_gene_integration_matrix.MarchRProject <- function( genes_use = NULL, threads = 1L, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") assert_for(reference_dataset_name, "character") assert_for(group_rna, "character") + assert_len(sample_cells_atac, 1) + assert_greater_than_zero(sample_cells_atac) method <- match.arg(method) if (identical(method, "seurat") && !requireNamespace("Seurat", quietly = TRUE)) { rlang::abort( @@ -145,10 +148,10 @@ add_gene_integration_matrix.MarchRProject <- function( )) } } - if (identical(method, "marchr") && verbose && + if (identical(method, "marchr") && (!is.null(embedding_atac) || !identical(as.integer(sample_cells_atac), 10000L))) { - log_progress(paste0("method = 'marchr' integrates all cells at once; ", - "sample_cells_atac and embedding_atac are ignored.")) + rlang::warn(paste0("method = 'marchr' integrates all cells at once; ", + "sample_cells_atac and embedding_atac are ignored.")) } if (length(atac_dataset_names) == 0L) { @@ -173,22 +176,7 @@ add_gene_integration_matrix.MarchRProject <- function( ) feature_set <- if (is.null(genes_use)) shared_genes else genes_use - if (verbose) { - log_progress(sprintf("Integrating %d ATAC dataset(s) against '%s' (%d shared genes)...", - length(atac_dataset_names), reference_dataset_name, length(shared_genes))) - } - - # A dense cast would allocate ~5 GB on a large reference; keep counts sparse. - if (identical(method, "seurat")) { - rna_counts <- as(rna_mat[shared_genes, ], "dgCMatrix") - rna_ids <- colnames(rna_counts) - seurat_rna <- suppressWarnings(Seurat::CreateSeuratObject(counts = rna_counts)) - seurat_rna$Group <- as.character(ref_meta[rna_ids, group_rna]) - seurat_rna <- Seurat::NormalizeData(seurat_rna, verbose = FALSE) - } else { - rna_ids <- colnames(rna_mat) - } - + rna_ids <- colnames(rna_mat) atac_cells <- colnames(gene_score) weight_emb <- .get_weight_reduction(proj, reduced_dims, atac_dataset_names, dims_to_use, corr_cutoff, scale_dims) @@ -198,6 +186,7 @@ add_gene_integration_matrix.MarchRProject <- function( } else { NULL } + constrained <- !is.null(group_list) || !is.null(group_atac) groups <- .build_integration_groups( atac_cells = atac_cells, rna_cells = rna_ids, @@ -224,6 +213,42 @@ add_gene_integration_matrix.MarchRProject <- function( on.exit(unlink(staging_dir, recursive = TRUE), add = TRUE) } + if (identical(method, "seurat")) { + block_specs <- list() + for (gname in names(groups)) { + blocks <- .assign_integration_blocks(groups[[gname]]$ATAC, sample_cells_atac, + embedding_atac, seed) + rna_g <- groups[[gname]]$RNA + for (bi in seq_along(blocks)) { + rna_sample <- if (length(rna_g) <= sample_cells_rna) { + rna_g + } else { + .sample_rna_cells(rna_g, sample_cells_rna, embedding_rna, seed) + } + block_specs[[length(block_specs) + 1L]] <- list( + atac = blocks[[bi]], rna = rna_sample + ) + } + } + n_blocks <- length(block_specs) + } + + if (verbose) { + run <- .log_start("Gene integration", paste0( + sprintf( + "%s (%s) vs '%s' (%s), %s", .log_plural(length(atac_cells), "ATAC cell"), + .log_plural(length(atac_dataset_names), "dataset"), reference_dataset_name, + .log_plural(length(rna_ids), "cell"), .log_plural(length(shared_genes), "shared gene") + ), + if (constrained) paste0(", ", .log_plural(length(groups), "constrained group")), + if (identical(method, "seurat")) { + sprintf(", %s (~%s)", .log_plural(n_blocks, "block"), + .log_plural(ceiling(length(atac_cells) / n_blocks), "cell")) + }, + sprintf(", method '%s'", method) + )) + } + if (identical(method, "marchr")) { results <- .run_integration_marchr( gene_score = gene_score, @@ -244,35 +269,22 @@ add_gene_integration_matrix.MarchRProject <- function( embedding_rna = embedding_rna, seed = seed, threads = threads, + constrained = constrained, verbose = verbose ) } else { - block_specs <- list() - for (gname in names(groups)) { - blocks <- .assign_integration_blocks(groups[[gname]]$ATAC, sample_cells_atac, - embedding_atac, seed) - rna_g <- groups[[gname]]$RNA - for (bi in seq_along(blocks)) { - rna_sample <- if (length(rna_g) <= sample_cells_rna) { - rna_g - } else { - .sample_rna_cells(rna_g, sample_cells_rna, embedding_rna, seed) - } - block_specs[[length(block_specs) + 1L]] <- list( - atac = blocks[[bi]], rna = rna_sample - ) - } - } + # A dense cast would allocate ~5 GB on a large reference; keep counts sparse. + rna_counts <- as(rna_mat[shared_genes, ], "dgCMatrix") + seurat_rna <- suppressWarnings(Seurat::CreateSeuratObject(counts = rna_counts)) + seurat_rna$Group <- as.character(ref_meta[rna_ids, group_rna]) + seurat_rna <- Seurat::NormalizeData(seurat_rna, verbose = FALSE) # Restrict every per-block step to the RNA reference subset's variable features # (~2k) so ScaleData / CCA / TransferData don't operate on the full shared set. - n_blocks <- length(block_specs) results <- lapply(seq_along(block_specs), function(i) { + t0 <- steady_clock_seconds_rcpp() spec <- block_specs[[i]] block_cells <- spec$atac - if (verbose) { - log_progress(sprintf(" Block %d of %d (%d ATAC cells)", i, n_blocks, length(block_cells))) - } ref <- Seurat::FindVariableFeatures(seurat_rna[, spec$rna], nfeatures = n_genes, verbose = FALSE) @@ -283,7 +295,9 @@ add_gene_integration_matrix.MarchRProject <- function( # Dense only when imputation needs the matmul; otherwise sparse keeps the # peak dominated by Seurat's scale.data instead of a duplicate dense input. if (isTRUE(use_imputation)) { - block_mat <- as.matrix(gene_score[use_features, block_cells]) + block_mat <- rlang::with_options( + as.matrix(gene_score[use_features, block_cells]), rlib_message_verbosity = "quiet" + ) block_mat <- .impute_block(block_mat, we, seed = seed) } else { block_mat <- as(gene_score[use_features, block_cells], "dgCMatrix") @@ -313,6 +327,13 @@ add_gene_integration_matrix.MarchRProject <- function( res$matched_rna <- block_dir gc() } + if (verbose) { + .log_step(sprintf( + "Block %d/%d: transferred %s to %s", i, n_blocks, + if (isTRUE(add_matrix_to_project)) "labels and expression" else "labels", + .log_plural(length(block_cells), "cell") + ), since = t0) + } res }) } @@ -333,10 +354,13 @@ add_gene_integration_matrix.MarchRProject <- function( proj <- write_pred(proj, name_cell, df_all$predicted_cell) if (isTRUE(add_matrix_to_project)) { + t0 <- steady_clock_seconds_rcpp() gim <- if (identical(method, "marchr")) { group_mats <- lapply(results, `[[`, "matched_rna") combined <- if (length(group_mats) == 1L) group_mats[[1]] else do.call(cbind, group_mats) - write_matrix_dir(combined, out_dir, compress = TRUE) + rlang::with_options( + write_matrix_dir(combined, out_dir, compress = TRUE), rlib_message_verbosity = "quiet" + ) open_matrix_dir(out_dir) } else { block_paths <- vapply(results, `[[`, character(1), "matched_rna") @@ -348,6 +372,17 @@ add_gene_integration_matrix.MarchRProject <- function( dataset_name = d, prefix_cells = FALSE, overwrite = overwrite) } + if (verbose) { + .log_step(sprintf("Wrote %s (%s x %s)", matrix_name, .log_plural(nrow(gim), "gene"), + .log_plural(ncol(gim), "cell")), since = t0) + } + } + if (verbose) { + .log_finish(run, paste0( + "added cell metadata columns ", + paste0("'", c(name_group, name_score, name_cell), "'", collapse = ", "), + if (isTRUE(add_matrix_to_project)) sprintf(", assay '%s'", matrix_name) + )) } proj } @@ -511,12 +546,12 @@ add_gene_integration_matrix.MarchRProject <- function( on.exit(unlink(c(ref_dir, query_dir), recursive = TRUE), add = TRUE) # Flushed because the operator re-reads both matrices on every Lanczos step. - ref_flushed <- write_matrix_dir( + ref_flushed <- rlang::with_options(write_matrix_dir( convert_matrix_type(ref_scaled, type = "float"), ref_dir, compress = TRUE - ) - query_flushed <- write_matrix_dir( + ), rlib_message_verbosity = "quiet") + query_flushed <- rlang::with_options(write_matrix_dir( convert_matrix_type(query_scaled, type = "float"), query_dir, compress = TRUE - ) + ), rlib_message_verbosity = "quiet") fit <- RSpectra::svds( A = function(w, args) as.numeric(t(args$ref) %*% as.numeric(args$query %*% w)), @@ -594,7 +629,7 @@ add_gene_integration_matrix.MarchRProject <- function( .mutual_nearest_neighbors <- function(nn_ab, nn_ba, k_anchor = 5L) { k <- min(as.integer(k_anchor), ncol(nn_ab), ncol(nn_ba)) if (k < k_anchor) { - message(sprintf("k_anchor = %d exceeds available neighbours; using %d.", k_anchor, k)) + rlang::warn(sprintf("k_anchor = %d exceeds available neighbours; using %d.", k_anchor, k)) } ab <- nn_ab[, seq_len(k), drop = FALSE] ba <- nn_ba[, seq_len(k), drop = FALSE] @@ -645,14 +680,12 @@ add_gene_integration_matrix.MarchRProject <- function( b <- cca$query k <- min(max(as.integer(k_anchor), as.integer(k_score)), nrow(a), nrow(b)) - knn_k <- partial_apply(knn_method, k = k, .overwrite = TRUE, + knn_k <- partial_apply(knn_method, k = k, verbose = FALSE, .overwrite = TRUE, .missing_args_error = FALSE) - suppressMessages({ - nn_aa <- knn_k(a)$idx - nn_bb <- knn_k(b)$idx - nn_ab <- knn_k(b, query = a)$idx - nn_ba <- knn_k(a, query = b)$idx - }) + nn_aa <- knn_k(a)$idx + nn_bb <- knn_k(b)$idx + nn_ab <- knn_k(b, query = a)$idx + nn_ba <- knn_k(a, query = b)$idx anchors <- .mutual_nearest_neighbors(nn_ab, nn_ba, k_anchor = k_anchor) if (nrow(anchors) == 0L) { @@ -663,7 +696,8 @@ add_gene_integration_matrix.MarchRProject <- function( i = "Increase k_anchor, widen the feature set, or relax group constraints." )) } - .score_anchors(anchors, nn_aa, nn_ab, nn_ba, nn_bb, k_score = k_score) + structure(.score_anchors(anchors, nn_aa, nn_ab, nn_ba, nn_bb, k_score = k_score), + n_dims = ncol(a)) } .anchor_weights <- function(anchors, weight_emb, k_weight = 50L, sd_weight = 1, @@ -671,16 +705,14 @@ add_gene_integration_matrix.MarchRProject <- function( anchor_cells <- sort(unique(anchors$cell2)) k <- min(as.integer(k_weight), length(anchor_cells)) if (k < k_weight) { - message(sprintf("k_weight = %d exceeds %d anchor cells; using %d.", - k_weight, length(anchor_cells), k)) + rlang::warn(sprintf("k_weight = %d exceeds %d anchor cells; using %d.", + k_weight, length(anchor_cells), k)) } n_query <- nrow(weight_emb) - nn <- suppressMessages( - partial_apply(knn_method, k = k, .overwrite = TRUE, - .missing_args_error = FALSE)( - weight_emb[anchor_cells, , drop = FALSE], query = weight_emb - ) + nn <- partial_apply(knn_method, k = k, verbose = FALSE, .overwrite = TRUE, + .missing_args_error = FALSE)( + weight_emb[anchor_cells, , drop = FALSE], query = weight_emb ) sim <- 1 - nn$dist / nn$dist[, k] sim[!is.finite(sim)] <- 0 @@ -785,7 +817,9 @@ add_gene_integration_matrix.MarchRProject <- function( # Cells x dims embedding used as the TransferData weight.reduction. .get_weight_reduction <- function(proj, reduced_dims, dataset_names, dims_to_use, corr_cutoff, scale_dims) { - mat_dr <- as.matrix(t(proj[[reduced_dims, dataset_names]])) + mat_dr <- rlang::with_options( + as.matrix(t(proj[[reduced_dims, dataset_names]])), rlib_message_verbosity = "quiet" + ) if (!is.null(dims_to_use)) { dims_to_use <- dims_to_use[dims_to_use <= ncol(mat_dr)] mat_dr <- mat_dr[, dims_to_use, drop = FALSE] @@ -862,23 +896,32 @@ add_gene_integration_matrix.MarchRProject <- function( group_rna, weight_emb, n_genes, knn_method, use_imputation, transfer_params, build_matrix, scale_to, staging_dir, sample_cells_rna, embedding_rna, - seed, threads, verbose) { + seed, threads, constrained, verbose) { k_weight <- transfer_params$k.weight if (is.null(k_weight)) k_weight <- 50L sd_weight <- transfer_params$sd.weight if (is.null(sd_weight)) sd_weight <- 1 + chunk_size <- 10000L - lapply(names(groups), function(gname) { + lapply(seq_along(groups), function(gi) { + gname <- names(groups)[gi] atac_cells <- groups[[gname]]$ATAC rna_cells <- .sample_rna_cells(groups[[gname]]$RNA, sample_cells_rna, embedding_rna, seed) - if (verbose) { - log_progress(sprintf(" Group '%s': %d ATAC cells vs %d RNA cells", - gname, length(atac_cells), length(rna_cells))) + if (verbose && constrained) { + pass <- .log_pass(sprintf( + "Group %d/%d '%s' (%s ATAC vs %s RNA cells)", gi, length(groups), gname, + .log_count(length(atac_cells)), .log_count(length(rna_cells)) + ), "Group") } + t0 <- steady_clock_seconds_rcpp() ref_block <- rna_mat[feature_set, rna_cells] features <- .select_features_vst(ref_block, n_features = n_genes, threads = threads) + if (verbose) { + .log_step(sprintf("Selected %s from %s", .log_plural(length(features), "variable gene"), + .log_plural(length(rna_cells), "RNA cell")), since = t0) + } # Depth normalization uses total counts across every shared gene, so it must happen # before subsetting to the variable features; those features carry a share of each # cell's counts that varies by an order of magnitude between cells. @@ -887,15 +930,27 @@ add_gene_integration_matrix.MarchRProject <- function( we <- weight_emb[atac_cells, , drop = FALSE] query_block <- gene_score[features, atac_cells] if (isTRUE(use_imputation)) { - imputed <- .impute_block(as.matrix(query_block), we, seed = seed) + t0 <- steady_clock_seconds_rcpp() + dense_query <- rlang::with_options(as.matrix(query_block), rlib_message_verbosity = "quiet") + imputed <- .impute_block(dense_query, we, seed = seed) query_block <- as(as(imputed, "dgCMatrix"), "IterableMatrix") + if (verbose && length(atac_cells) > 15L) { + .log_step(sprintf("Imputed gene scores for %s", .log_plural(length(atac_cells), "cell")), + since = t0) + } } + t0 <- steady_clock_seconds_rcpp() anchors <- .find_transfer_anchors_marchr( ref_norm[features, ], query_block, features = features, normalization_reference = "none", knn_method = knn_method, threads = threads ) + if (verbose) { + .log_step(sprintf("Found %s (%s)", .log_plural(nrow(anchors), "anchor"), + .log_plural(attr(anchors, "n_dims"), "CCA dim")), since = t0) + } + t0 <- steady_clock_seconds_rcpp() transferred <- .transfer_data_marchr( anchors, refdata = as.character(ref_meta[rna_cells, group_rna]), @@ -906,17 +961,29 @@ add_gene_integration_matrix.MarchRProject <- function( sd_weight = sd_weight, knn_method = knn_method ) - + if (verbose) { + .log_step(sprintf("Transferred labels to %s", .log_plural(length(atac_cells), "cell")), + since = t0) + } matched <- NULL if (isTRUE(build_matrix)) { + t0 <- steady_clock_seconds_rcpp() anchor_expr <- .anchor_reference_expression(ref_block, anchors$cell1) matched <- .transfer_expression_chunked( transferred$weights, anchor_expr, query_cells = atac_cells, scale_to = scale_to, - out_dir = file.path(staging_dir, paste0("group_", make.names(gname))) + out_dir = file.path(staging_dir, paste0("group_", make.names(gname))), + chunk_size = chunk_size ) + if (verbose) { + .log_step(sprintf( + "Transferred expression for %s (%s)", .log_plural(length(atac_cells), "cell"), + .log_plural(ceiling(length(atac_cells) / chunk_size), "chunk") + ), since = t0) + } } + if (verbose && constrained) .log_pass_end(pass) list( match_df = data.frame( @@ -944,8 +1011,10 @@ add_gene_integration_matrix.MarchRProject <- function( block_dgc <- as(matched_rna, "dgCMatrix") block_dgc@x <- exp(block_dgc@x) - 1 scaled <- .normalize_cols_to(block_dgc, scale_to = scale_to) - write_matrix_dir(as(as(scaled, "dgCMatrix"), "IterableMatrix"), - out_dir, compress = TRUE) + rlang::with_options( + write_matrix_dir(as(as(scaled, "dgCMatrix"), "IterableMatrix"), out_dir, compress = TRUE), + rlib_message_verbosity = "quiet" + ) invisible(out_dir) } @@ -958,7 +1027,9 @@ add_gene_integration_matrix.MarchRProject <- function( rlang::abort("Gene rows are inconsistent across integration blocks.") } combined <- do.call(cbind, blocks) - write_matrix_dir(combined, out_dir, compress = TRUE) + rlang::with_options( + write_matrix_dir(combined, out_dir, compress = TRUE), rlib_message_verbosity = "quiet" + ) open_matrix_dir(out_dir) } diff --git a/man/add_gene_integration_matrix.Rd b/man/add_gene_integration_matrix.Rd index afc6140..f2ad037 100644 --- a/man/add_gene_integration_matrix.Rd +++ b/man/add_gene_integration_matrix.Rd @@ -40,7 +40,7 @@ add_gene_integration_matrix(proj, ...) genes_use = NULL, threads = 1L, seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ... ) @@ -120,7 +120,7 @@ not read from \code{set_threads()}.} \item{seed}{(integer) Random seed. Default 1.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{overwrite}{(logical) Overwrite existing columns / assay. Default FALSE.} } diff --git a/man/project_bulk_atac.Rd b/man/project_bulk_atac.Rd index a0391ac..ccb3652 100644 --- a/man/project_bulk_atac.Rd +++ b/man/project_bulk_atac.Rd @@ -50,7 +50,7 @@ Default: \code{FALSE}.} \item{threads}{(integer) Threads for the UMAP transform in the MarchRProject method. Default \code{get_threads()}. The DimReduction method projects single-threaded (default NULL).} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A list with \code{simulated_reduced_dims}, \code{overlap_ratio} and diff --git a/man/run_harmony.Rd b/man/run_harmony.Rd index a267b12..b052529 100644 --- a/man/run_harmony.Rd +++ b/man/run_harmony.Rd @@ -40,7 +40,8 @@ run_harmony(x, ...) \item{x}{(matrix; IterableMatrix; dgCMatrix; MarchRDataset; MarchRProject) Object containing embeddings to harmonize.} -\item{...}{Additional arguments forwarded to \code{harmony::RunHarmony()}.} +\item{...}{Additional arguments forwarded to \code{harmony::RunHarmony()}; its \code{verbose} defaults to +\code{FALSE}.} \item{group_values}{(vector) Group assignments for each cell. When unnamed, values are matched to the order of the embeddings.} diff --git a/tests/testthat/test-bulk_projection.R b/tests/testthat/test-bulk_projection.R index be30d1e..4e2ada0 100644 --- a/tests/testthat/test-bulk_projection.R +++ b/tests/testthat/test-bulk_projection.R @@ -679,3 +679,173 @@ test_that("project.IterativeLSI leaves counts alone when fit without binarize", from_binary <- project(lsi$dim_reduction, binarize(atac$mat), threads = 1L) expect_false(isTRUE(all.equal(as.matrix(from_counts), as.matrix(from_binary)))) }) + +######################################################################## +# Verbose logging tests +######################################################################## + +make_test_bulk_inputs <- function() { + atac <- make_test_atac_matrix(n_cell = 200L) + proj <- add_matrix(MarchRProject(), atac$mat, mat_name = "TileMatrix", dataset_name = "d1") + proj <- IterativeLSI( + proj, assay_name = "TileMatrix", n_iterations = 2, n_dimensions = 10L, + first_selection = "var", + feature_selection_method = select_features_variance(num_feats = 300L), + binarize = FALSE, outlier_quantiles = NULL, + cluster_method = cluster_cells_graph(knn_method = knn_annoy), verbose = FALSE + ) + set.seed(4) + n_pk <- 400L + bulk <- matrix(stats::rpois(n_pk * 2L, 20), n_pk, 2) + bulk[1:120, 1] <- bulk[1:120, 1] + stats::rpois(120, 400) + bulk[250:380, 2] <- bulk[250:380, 2] + stats::rpois(131, 400) + se <- make_test_bulk_se( + starts = seq(200L, by = 700L, length.out = n_pk), + widths = rep(400L, n_pk), counts = bulk + ) + list(atac = atac, proj = proj, se = se) +} + +expected_matched_line <- function(res, n_feat) { + sprintf( + "Matched %s of %s reduction features to bulk peaks (%.1f%%)", + .log_count(round(res$overlap_ratio * n_feat)), .log_count(n_feat), 100 * res$overlap_ratio + ) +} + +test_that("project_bulk_atac.DimReduction reports one block with its steps", { + skip_if_not_installed("RcppAnnoy") + skip_if_not_installed("SummarizedExperiment") + withr::local_options(rlib_message_verbosity = "verbose") + inputs <- make_test_bulk_inputs() + dr <- get_dim_reduction(inputs$proj, "IterativeLSI") + n_feat <- length(.reduction_selected_features(dr, 2L)) + + res <- NULL + lines <- .strip_log(capture_messages( + res <- project_bulk_atac(dr, inputs$se, n = 50L, threads = 1L, verbose = TRUE) + )) + expect_identical(lines, c( + sprintf( + "Bulk projection: 2 samples into IterativeLSI (iteration 2, %s features)", .log_count(n_feat) + ), + expected_matched_line(res, n_feat), + sprintf( + "Simulated 100 pseudo-cells from 2 samples (50 each, mean depth %s) [Xs]", .log_count(res$depth_n) + ), + "Projected 100 pseudo-cells into LSI [Xs]", + sprintf("Bulk projection finished [Xs]: 100 x %d reduced dims", ncol(res$simulated_reduced_dims)) + )) + expect_no_message(project_bulk_atac(dr, inputs$se, n = 50L, threads = 1L, verbose = FALSE)) + + # A non-iterative reduction has no iteration to report. + lsi <- LSI( + inputs$atac$mat, n_dimensions = 10L, outlier_quantiles = NULL, threads = 1L, verbose = FALSE + ) + lines <- .strip_log(capture_messages( + res <- project_bulk_atac(lsi$dim_reduction, inputs$se, n = 50L, verbose = TRUE) + )) + expect_identical(lines, c( + "Bulk projection: 2 samples into LSI (600 features)", + expected_matched_line(res, 600), + sprintf( + "Simulated 100 pseudo-cells from 2 samples (50 each, mean depth %s) [Xs]", .log_count(res$depth_n) + ), + "Projected 100 pseudo-cells into LSI [Xs]", + "Bulk projection finished [Xs]: 100 x 10 reduced dims" + )) +}) + +test_that("project_bulk_atac.MarchRProject reports one block with the stored UMAP model", { + skip_if_not_installed("RcppAnnoy") + skip_if_not_installed("uwot") + skip_if_not_installed("SummarizedExperiment") + withr::local_options(rlib_message_verbosity = "verbose") + inputs <- make_test_bulk_inputs() + proj <- add_umap(inputs$proj, embedding_name = "IterativeLSI", n_neighbors = 15L, verbose = FALSE) + n_feat <- length(.reduction_selected_features(get_dim_reduction(proj, "IterativeLSI"), 2L)) + setup <- sprintf( + "Bulk projection: 2 samples into 'IterativeLSI' (iteration 2, %s features)", .log_count(n_feat) + ) + + res <- NULL + lines <- .strip_log(capture_messages(res <- project_bulk_atac( + proj, inputs$se, dim_reduction_name = "IterativeLSI", n = 50L, threads = 1L, verbose = TRUE + ))) + expect_identical(lines, c( + paste0(setup, ", 200 cells"), + expected_matched_line(res, n_feat), + sprintf( + "Simulated 100 pseudo-cells from 2 samples (50 each, mean depth %s) [Xs]", .log_count(res$depth_n) + ), + "Projected 100 pseudo-cells into LSI [Xs]", + "Loaded UMAP model 'UMAP' [Xs]", + sprintf("Re-projected 200 cells to check UMAP, r = %.3f [Xs]", min(res$projection_corr)), + "Projected 100 pseudo-cells into UMAP [Xs]", + "Bulk projection finished [Xs]: 100 pseudo-cells from 2 samples in LSI and UMAP" + )) + expect_no_message(project_bulk_atac( + proj, inputs$se, dim_reduction_name = "IterativeLSI", n = 50L, threads = 1L, verbose = FALSE + )) + + lines <- .strip_log(capture_messages(project_bulk_atac( + proj, inputs$se, dim_reduction_name = "IterativeLSI", embedding_name = NULL, n = 50L, + verbose = TRUE + ))) + expect_length(lines, 5) + expect_identical(lines[1], setup) + expect_identical(lines[5], "Bulk projection finished [Xs]: 100 pseudo-cells from 2 samples in LSI") +}) + +test_that("project_bulk_atac.MarchRProject reports a rebuilt legacy UMAP model", { + skip_if_not_installed("RcppAnnoy") + skip_if_not_installed("uwot") + skip_if_not_installed("SummarizedExperiment") + withr::local_options(rlib_message_verbosity = "verbose") + inputs <- make_test_bulk_inputs() + proj <- add_umap( + inputs$proj, embedding_name = "IterativeLSI", n_neighbors = 15L, return_model = FALSE, + verbose = FALSE + ) + + lines <- NULL + expect_warning( + lines <- .strip_log(capture_messages(project_bulk_atac( + proj, inputs$se, dim_reduction_name = "IterativeLSI", n = 50L, + umap_params = list(n_neighbors = 15L), threads = 1L, verbose = TRUE + ))), + "legacy pinned model" + ) + expect_length(lines, 8) + expect_identical(lines[5], "Rebuilt legacy UMAP model from stored coordinates [Xs]") + expect_match(lines[6], "^Re-projected 200 cells to check UMAP, r = [0-9.-]+ \\[Xs\\]$") +}) + +test_that("project_bulk_atac.MarchRProject reports a reprojection check below min_corr", { + skip_if_not_installed("RcppAnnoy") + skip_if_not_installed("uwot") + skip_if_not_installed("SummarizedExperiment") + withr::local_options(rlib_message_verbosity = "verbose") + inputs <- make_test_bulk_inputs() + proj <- add_umap(inputs$proj, embedding_name = "IterativeLSI", n_neighbors = 15L, verbose = FALSE) + set.seed(5) + cell_ids <- rownames(get_cell_metadata(proj)) + for (col in c("UMAP_1", "UMAP_2")) { + noise <- stats::setNames(stats::rnorm(length(cell_ids)), cell_ids) + proj <- add_cell_metadata_col(proj, values = noise, col_name = col, overwrite = TRUE) + } + + res <- NULL + lines <- NULL + expect_warning( + lines <- .strip_log(capture_messages(res <- project_bulk_atac( + proj, inputs$se, dim_reduction_name = "IterativeLSI", n = 50L, threads = 1L, verbose = TRUE + ))), + "correlation" + ) + expect_length(lines, 8) + expect_identical( + lines[6], + sprintf("Re-projected 200 cells to check UMAP, r = %.3f (below 0.80) [Xs]", min(res$projection_corr)) + ) +}) diff --git a/tests/testthat/test-dimensionality_reduction.R b/tests/testthat/test-dimensionality_reduction.R index fcfebd0..1e886b1 100644 --- a/tests/testthat/test-dimensionality_reduction.R +++ b/tests/testthat/test-dimensionality_reduction.R @@ -328,6 +328,7 @@ test_that("run_harmony on matrix works with explicit groups", { test_that("run_harmony works with metadata column for MarchRDataset", { skip_if_not_installed("harmony") + withr::local_options(rlib_message_verbosity = "verbose") proj <- create_test_project(ncol1 = 30, ncol2 = 0) dataset <- proj$datasets[["dataset1"]] @@ -349,14 +350,14 @@ test_that("run_harmony works with metadata column for MarchRDataset", { "embeddings" ) - dataset <- suppressWarnings(run_harmony( + expect_no_message(dataset <- suppressWarnings(run_harmony( dataset, group_by = "batch", assay_name = "embeddings", output_assay_name = "embeddings_harmony", nclust = 2, .options = harmony::harmony_options(block.size = 0.2) - )) + ))) expect_true("embeddings_harmony" %in% get_assay_names(dataset)) harmonized_assay <- dataset[["embeddings_harmony", ]] @@ -365,6 +366,7 @@ test_that("run_harmony works with metadata column for MarchRDataset", { test_that("run_harmony stores harmonized reductions in MarchRProject", { skip_if_not_installed("harmony") + withr::local_options(rlib_message_verbosity = "verbose") proj <- create_test_project(ncol1 = 30, ncol2 = 30) dataset1_cells <- cell_names(proj$datasets[["dataset1"]]) @@ -401,7 +403,7 @@ test_that("run_harmony stores harmonized reductions in MarchRProject", { overwrite = TRUE ) - proj <- suppressWarnings(run_harmony( + expect_no_message(proj <- suppressWarnings(run_harmony( proj, group_by = "batch", dataset_names = c("dataset1", "dataset2"), @@ -409,7 +411,7 @@ test_that("run_harmony stores harmonized reductions in MarchRProject", { output_assay_name = "lsi_harmony", nclust = 2, .options = harmony::harmony_options(block.size = 0.2) - )) + ))) expect_true("lsi_harmony" %in% get_assay_names(proj$datasets[["dataset1"]])) expect_true("lsi_harmony" %in% get_assay_names(proj$datasets[["dataset2"]])) @@ -1185,3 +1187,102 @@ test_that("IterativeLSI on a project prints one setup and one finished line", { expect_equal(sum(grepl("^Iterative LSI", lines)), 2L) expect_false(any(grepl("Finished \\[", lines))) }) + +test_that("PCA reports its variable features and fit, then its result", { + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(12345) + mat <- matrix(runif(240), nrow = 10) %>% + as("dgCMatrix") %>% + as("IterableMatrix") + rownames(mat) <- paste0("feat", seq_len(nrow(mat))) + colnames(mat) <- paste0("cell", seq_len(ncol(mat))) + + msgs <- capture_messages(PCA(mat, n_dimensions = 5, n_features = 8, threads = 1L, verbose = TRUE)) + expect_match(msgs[c(1, length(msgs))], "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} ", perl = TRUE) + lines <- .strip_log(msgs) + expect_length(lines, 4) + expect_identical(lines, c( + "PCA: 24 cells, 10 features, 5 dims, 1 thread", + "Selected 8 variable features [Xs]", + "Fit PCA on 24 cells [Xs]", + "PCA finished [Xs]: 24 x 5 embedding" + )) + expect_null(.log_clock$start) + expect_no_message(PCA(mat, n_dimensions = 5, n_features = 8, threads = 1L, verbose = FALSE)) +}) + +test_that("PCA reports n_features and dims only when they are capped", { + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(12345) + mat <- matrix(runif(60), nrow = 5) %>% + as("dgCMatrix") %>% + as("IterableMatrix") + rownames(mat) <- paste0("feat", seq_len(nrow(mat))) + colnames(mat) <- paste0("cell", seq_len(ncol(mat))) + + lines <- .strip_log(capture_messages( + PCA(mat, n_features = 2000, n_dimensions = 10, threads = 1L, verbose = TRUE) + )) + expect_length(lines, 6) + expect_identical(lines, c( + "PCA: 12 cells, 5 features, 10 dims, 1 thread", + "Reduced n_features from 2,000 to 5 (5 features)", + "Selected 5 variable features [Xs]", + "Reduced dims from 10 to 4 (5 features)", + "Fit PCA on 12 cells [Xs]", + "PCA finished [Xs]: 12 x 4 embedding" + )) + + wide <- matrix(runif(60), nrow = 10) %>% + as("dgCMatrix") %>% + as("IterableMatrix") + rownames(wide) <- paste0("feat", seq_len(nrow(wide))) + colnames(wide) <- paste0("cell", seq_len(ncol(wide))) + lines <- .strip_log(capture_messages( + PCA(wide, n_features = 8, n_dimensions = 50, threads = 1L, verbose = TRUE) + )) + expect_length(lines, 5) + expect_identical(lines[3], "Reduced dims from 50 to 5 (6 cells)") +}) + +test_that("PCA on a project prints one setup and one finished line naming the dim reduction", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project() + lines <- .strip_log(capture_messages(proj <- PCA( + proj, dim_reduction_name = "test_pca", n_dimensions = 5, n_features = 8, threads = 1L, verbose = TRUE + ))) + expect_length(lines, 4) + expect_identical(lines, c( + "PCA: 48 cells, 10 features, 5 dims, 1 thread", + "Selected 8 variable features [Xs]", + "Fit PCA on 48 cells [Xs]", + "PCA finished [Xs]: added dim reduction 'test_pca' (48 x 5)" + )) + expect_no_message(PCA( + proj, assay_name = "RNA", dim_reduction_name = "test_pca", n_dimensions = 5, n_features = 8, + overwrite = TRUE, threads = 1L, verbose = FALSE + )) +}) + +test_that("Project dim reductions validate dims and threads before their setup line", { + proj <- create_test_project() + expect_error(LSI(proj, n_dimensions = NA, verbose = TRUE), "\"n_dimensions\" must be numeric") + expect_error(PCA(proj, threads = NA, verbose = TRUE), "\"threads\" must be numeric") +}) + +test_that("run_harmony prints nothing unless verbose is passed through to harmony", { + skip_if_not_installed("harmony") + withr::local_options(rlib_message_verbosity = "verbose") + set.seed(123) + embeddings <- matrix(rnorm(60), nrow = 3, ncol = 20, + dimnames = list(paste0("dim", 1:3), paste0("cell", 1:20))) + groups <- stats::setNames(rep(letters[1:2], each = 10), colnames(embeddings)) + opts <- harmony::harmony_options(block.size = 0.2) + + expect_no_message(suppressWarnings(run_harmony( + as(embeddings, "IterableMatrix"), group_values = groups, nclust = 2, .options = opts + ))) + expect_message(suppressWarnings(run_harmony( + embeddings, group_values = groups, nclust = 2, .options = opts, verbose = TRUE + ))) +}) diff --git a/tests/testthat/test-rna_integration.R b/tests/testthat/test-rna_integration.R index fba8b67..485de46 100644 --- a/tests/testthat/test-rna_integration.R +++ b/tests/testthat/test-rna_integration.R @@ -407,7 +407,7 @@ test_that(".mutual_nearest_neighbors keeps only reciprocated pairs", { test_that(".mutual_nearest_neighbors clamps k_anchor to available neighbours", { nn_ab <- matrix(1L, nrow = 2, ncol = 2) nn_ba <- matrix(1L, nrow = 2, ncol = 2) - expect_message( + expect_warning( .mutual_nearest_neighbors(nn_ab, nn_ba, k_anchor = 10L), "exceeds available" ) @@ -487,7 +487,7 @@ test_that(".anchor_weights clamps k_weight to the number of anchor cells", { set.seed(14) weight_emb <- matrix(rnorm(10 * 3), nrow = 10) anchors <- data.frame(cell1 = 1:2, cell2 = 1:2, score = c(1, 1)) - expect_message( + expect_warning( .anchor_weights(anchors, weight_emb, k_weight = 50L), "exceeds" ) @@ -613,11 +613,12 @@ test_that("add_gene_integration_matrix method='marchr' combines constrained grou col_name = "lineage", dataset_name = "ref" ) + # Each group has 30 ATAC cells, so at most 30 anchor cells, below the default k.weight of 50. proj <- add_gene_integration_matrix( proj, reference_dataset_name = "ref", group_rna = "cell_type", group_atac = "lineage", group_rna_constraint = "lineage", method = "marchr", add_matrix_to_project = TRUE, - use_imputation = FALSE, verbose = FALSE + use_imputation = FALSE, transfer_params = list(k.weight = 20L), verbose = FALSE ) gim <- get_matrix(proj, assay_name = "GeneIntegrationMatrix", dataset_name = "atac") @@ -642,6 +643,155 @@ test_that("add_gene_integration_matrix method='seurat' still builds the assay", expect_true(all(cm$predictedGroup %in% c("T", "B"))) }) +integration_columns <- "added cell metadata columns 'predictedGroup', 'predictedScore', 'predictedCell'" + +test_that("add_gene_integration_matrix logs marchr steps for the default group", { + withr::local_options(rlib_message_verbosity = "verbose") + run <- function(...) { + add_gene_integration_matrix(make_integration_project(), reference_dataset_name = "ref", + group_rna = "cell_type", ...) + } + setup <- paste0( + "Gene integration: 60 ATAC cells (1 dataset) vs 'ref' (80 cells), 40 shared genes, ", + "method 'marchr'" + ) + anchors <- "^Found [0-9,]+ anchors \\(30 CCA dims\\) \\[Xs\\]$" + + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_length(lines, 8L) + expect_match(lines[4], anchors, perl = TRUE) + expect_identical(lines[-4], c( + setup, + "Selected 40 variable genes from 80 RNA cells [Xs]", + "Imputed gene scores for 60 cells [Xs]", + "Transferred labels to 60 cells [Xs]", + "Transferred expression for 60 cells (1 chunk) [Xs]", + "Wrote GeneIntegrationMatrix (40 genes x 60 cells) [Xs]", + paste0("Gene integration finished [Xs]: ", integration_columns, + ", assay 'GeneIntegrationMatrix'") + )) + + lines <- .strip_log(capture_messages( + run(use_imputation = FALSE, add_matrix_to_project = FALSE, verbose = TRUE) + )) + expect_length(lines, 5L) + expect_match(lines[3], anchors, perl = TRUE) + expect_identical(lines[-3], c( + setup, + "Selected 40 variable genes from 80 RNA cells [Xs]", + "Transferred labels to 60 cells [Xs]", + paste0("Gene integration finished [Xs]: ", integration_columns) + )) + + expect_no_message(run(verbose = FALSE)) +}) + +test_that("add_gene_integration_matrix logs a block per constrained group", { + withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) + atac <- paste0("atac#c", 1:60) + rna <- paste0("ref#r", 1:80) + group_list <- list( + L1 = list(ATAC = atac[1:30], RNA = rna[1:40]), + L2 = list(ATAC = atac[31:60], RNA = rna[41:80]) + ) + run <- function(...) { + add_gene_integration_matrix( + make_integration_project(), reference_dataset_name = "ref", group_rna = "cell_type", + group_list = group_list, use_imputation = FALSE, transfer_params = list(k.weight = 20L), ... + ) + } + group_pass <- function(i, name) { + c(sprintf("[Group %d/2 '%s' (30 ATAC vs 40 RNA cells)]", i, name), + " Selected 40 variable genes from 40 RNA cells [Xs]", + " Transferred labels to 30 cells [Xs]", + " Transferred expression for 30 cells (1 chunk) [Xs]", + " Group finished [Xs]") + } + + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_length(lines, 15L) + expect_match(lines[c(4, 10)], "^ Found [0-9,]+ anchors \\(29 CCA dims\\) \\[Xs\\]$", perl = TRUE) + expect_identical(lines[-c(4, 10)], c( + paste0( + "Gene integration: 60 ATAC cells (1 dataset) vs 'ref' (80 cells), 40 shared genes, ", + "2 constrained groups, method 'marchr'" + ), + group_pass(1, "L1"), + group_pass(2, "L2"), + "Wrote GeneIntegrationMatrix (40 genes x 60 cells) [Xs]", + paste0("Gene integration finished [Xs]: ", integration_columns, + ", assay 'GeneIntegrationMatrix'") + )) + + expect_no_message(run()) +}) + +test_that("add_gene_integration_matrix logs one line per seurat block", { + skip_if_not_installed("Seurat") + withr::local_options(rlib_message_verbosity = "verbose") + run <- function(...) { + suppressWarnings(add_gene_integration_matrix( + make_integration_project(), reference_dataset_name = "ref", group_rna = "cell_type", + method = "seurat", ... + )) + } + + lines <- .strip_log(capture_messages(run(use_imputation = FALSE, verbose = TRUE))) + expect_identical(lines, c( + paste0( + "Gene integration: 60 ATAC cells (1 dataset) vs 'ref' (80 cells), 40 shared genes, ", + "1 block (~60 cells), method 'seurat'" + ), + "Block 1/1: transferred labels and expression to 60 cells [Xs]", + "Wrote GeneIntegrationMatrix (40 genes x 60 cells) [Xs]", + paste0("Gene integration finished [Xs]: ", integration_columns, + ", assay 'GeneIntegrationMatrix'") + )) + expect_length(lines, 4L) + + lines <- .strip_log(capture_messages( + run(use_imputation = FALSE, add_matrix_to_project = FALSE, verbose = TRUE) + )) + expect_identical(lines, c( + paste0( + "Gene integration: 60 ATAC cells (1 dataset) vs 'ref' (80 cells), 40 shared genes, ", + "1 block (~60 cells), method 'seurat'" + ), + "Block 1/1: transferred labels to 60 cells [Xs]", + paste0("Gene integration finished [Xs]: ", integration_columns) + )) + + expect_no_message(run(verbose = FALSE)) +}) + +test_that("add_gene_integration_matrix logs imputation only for groups large enough to impute", { + withr::local_options(rlib_message_verbosity = "verbose") + atac <- paste0("atac#c", 1:60) + rna <- paste0("ref#r", 1:80) + group_list <- list( + small = list(ATAC = atac[1:12], RNA = rna[1:40]), + large = list(ATAC = atac[13:60], RNA = rna[41:80]) + ) + lines <- .strip_log(capture_messages(add_gene_integration_matrix( + make_integration_project(), reference_dataset_name = "ref", group_rna = "cell_type", + group_list = group_list, add_matrix_to_project = FALSE, + transfer_params = list(k.weight = 5L), verbose = TRUE + ))) + expect_identical(lines[2], "[Group 1/2 'small' (12 ATAC vs 40 RNA cells)]") + expect_identical(grep("Imputed", lines, value = TRUE), " Imputed gene scores for 48 cells [Xs]") +}) + +test_that("add_gene_integration_matrix warns that marchr ignores the ATAC block arguments", { + expect_warning( + add_gene_integration_matrix( + make_integration_project(), reference_dataset_name = "ref", group_rna = "cell_type", + sample_cells_atac = 30L, add_matrix_to_project = FALSE, use_imputation = FALSE, + verbose = FALSE + ), + "sample_cells_atac and embedding_atac are ignored" + ) +}) + test_that("add_gene_integration_matrix rejects non-cca reduction under marchr", { proj <- make_integration_project() expect_error( From fd0230885c16b895da458435afc1cbbac64c90c2 Mon Sep 17 00:00:00 2001 From: erliuu Date: Fri, 23 Oct 2026 02:10:16 -0700 Subject: [PATCH 09/12] feat([r] logging): Update analysis module reporting: markers, enrichment, deviations, footprinting, module scores, and linkages --- R/coaccessibility.R | 48 +++++- R/deviations.R | 168 ++++++++++++------ R/enrichment.R | 114 ++++++++++--- R/linkage.R | 29 +++- R/markers.R | 124 ++++++++++---- R/module_scores.R | 155 +++++++++++------ R/peak2gene.R | 90 +++++++--- man/add_background_peaks.Rd | 4 +- man/add_co_accessibility.Rd | 4 +- man/add_deviations_matrix.Rd | 4 +- man/add_kmer_bias.Rd | 4 +- man/add_marker_features.Rd | 6 +- man/add_module_score.Rd | 3 + man/add_peak2gene_links.Rd | 4 +- man/get_footprints.Rd | 4 +- man/make_knn_pseudobulks.Rd | 4 +- man/peak_annotation_enrichment.Rd | 4 +- tests/testthat/test-background-reference.R | 9 +- tests/testthat/test-coaccessibility.R | 40 +++++ tests/testthat/test-deviations.R | 187 ++++++++++++++++++++- tests/testthat/test-enrichment.R | 113 +++++++++++++ tests/testthat/test-footprinting.R | 134 +++++++++++++++ tests/testthat/test-linkage.R | 20 ++- tests/testthat/test-markers.R | 113 ++++++++++++- tests/testthat/test-module_scores.R | 150 +++++++++++++++-- tests/testthat/test-peak2gene.R | 110 +++++++++++- 26 files changed, 1399 insertions(+), 246 deletions(-) diff --git a/R/coaccessibility.R b/R/coaccessibility.R index 4021a06..8ece2a8 100644 --- a/R/coaccessibility.R +++ b/R/coaccessibility.R @@ -30,7 +30,7 @@ add_co_accessibility <- function(proj, ...) { #' @param log2_norm (logical) Apply log2(x + 1) after depth normalization. Default TRUE. #' @param knn_method (function) KNN engine (BPCells partial-application). Default `knn_hnsw()`. #' @param seed (integer) Random seed for metacell sampling. Default 1L. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param overwrite (logical) Replace an existing `co_accessibility` result. Default FALSE. #' #' @return `proj` with `proj$co_accessibility` populated as a data.frame with columns @@ -59,13 +59,14 @@ add_co_accessibility.MarchRProject <- function( log2_norm = TRUE, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ...) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") if (!is.null(proj$co_accessibility) && !overwrite) { - if (verbose) log_progress("co_accessibility exists; set overwrite = TRUE to recompute.") + rlang::warn("co_accessibility already exists; set overwrite = TRUE to recompute.") return(proj) } if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { @@ -74,15 +75,13 @@ add_co_accessibility.MarchRProject <- function( embedding_name <- select_embedding_name(proj, embedding_name) dataset_names <- select_dataset_names(proj, dataset_names) - emb <- as.matrix(t(proj[[embedding_name, dataset_names]])) + emb <- rlang::with_options( + as.matrix(t(proj[[embedding_name, dataset_names]])), rlib_message_verbosity = "quiet" + ) if (!is.null(cells_to_use)) emb <- emb[cells_to_use, , drop = FALSE] dims_to_use <- intersect(dims_to_use, seq_len(ncol(emb))) emb <- emb[, dims_to_use, drop = FALSE] - groups <- make_knn_pseudobulks(emb, knn_iteration = knn_iteration, k = k, - overlap_cutoff = overlap_cutoff, - knn_method = knn_method, seed = seed, verbose = verbose) - peak_mat <- proj[[atac_assay_name, dataset_names]] if (!is.null(cells_to_use)) peak_mat <- peak_mat[, cells_to_use] @@ -92,6 +91,18 @@ add_co_accessibility.MarchRProject <- function( "PeakMatrix rownames do not reconcile with proj$peak_set coordinates." ) } + if (verbose) { + run <- .log_start("Co-accessibility", sprintf( + "%s on '%s' (%s), %s, max distance %s bp", .log_plural(nrow(emb), "cell"), embedding_name, + .log_plural(ncol(emb), "dim"), .log_plural(nrow(peak_mat), "peak"), .log_count(max_dist) + )) + } + + groups <- make_knn_pseudobulks(emb, knn_iteration = knn_iteration, k = k, + overlap_cutoff = overlap_cutoff, + knn_method = knn_method, seed = seed, verbose = verbose) + + t0 <- steady_clock_seconds_rcpp() peaks <- proj$peak_set[ord, ] summit <- as.integer((peaks$start + peaks$end) / 2L) peak_gr <- GenomicRanges::GRanges(peaks$chr, IRanges::IRanges(summit, width = 1L)) @@ -102,13 +113,27 @@ add_co_accessibility.MarchRProject <- function( keep <- q < s if (!is.null(exclude_chr)) keep <- keep & !(peaks$chr[q] %in% exclude_chr) pairs <- data.frame(a = q[keep], b = s[keep]) + if (verbose) { + .log_step(sprintf( + "Found %s within %s bp", .log_plural(nrow(pairs), "peak pair"), .log_count(max_dist) + ), since = t0) + } + t0 <- steady_clock_seconds_rcpp() agg_dir <- file.path(proj$dir %||% tempdir(), "coaccessibility_peaks") agg <- .aggregate_metacells(peak_mat, groups, scale_to = scale_to, log2_norm = log2_norm, out_dir = agg_dir) - agg_dense <- as.matrix(agg$matrix) + agg_dense <- rlang::with_options(as.matrix(agg$matrix), rlib_message_verbosity = "quiet") + if (verbose) { + .log_step(sprintf( + "Aggregated %s into %s", .log_plural(nrow(peak_mat), "peak"), + .log_plural(length(groups), "metacell") + ), since = t0) + } + t0 <- steady_clock_seconds_rcpp() res <- .correlate_pairs(agg_dense, agg_dense, pairs, n = length(groups)) + if (verbose) .log_step(sprintf("Correlated %s", .log_plural(nrow(pairs), "peak pair")), since = t0) query_hits <- if (nrow(res) > 0) ord[res$a] else integer(0) subject_hits <- if (nrow(res) > 0) ord[res$b] else integer(0) proj$co_accessibility <- data.frame( @@ -124,6 +149,11 @@ add_co_accessibility.MarchRProject <- function( embedding_name = embedding_name ) attr(proj$co_accessibility, "agg_path") <- agg$path + if (verbose) { + .log_finish(run, sprintf( + "added co_accessibility (%s)", .log_plural(nrow(proj$co_accessibility), "peak pair") + )) + } proj } diff --git a/R/deviations.R b/R/deviations.R index ffe845a..0618172 100644 --- a/R/deviations.R +++ b/R/deviations.R @@ -30,8 +30,12 @@ x = rep(1, length(row_map)), dims = c(length(bins$bin_density), length(row_map)) ) - bin_counts <- as.matrix(bin_membership %*% peak_mat) - bin_sumsq <- as.matrix(bin_membership %*% (peak_mat^2)) + bin_counts <- rlang::with_options( + as.matrix(bin_membership %*% peak_mat), rlib_message_verbosity = "quiet" + ) + bin_sumsq <- rlang::with_options( + as.matrix(bin_membership %*% (peak_mat^2)), rlib_message_verbosity = "quiet" + ) e_bin <- as.matrix(bins$bin_probs %*% bin_counts) v_bin <- as.matrix(bins$bin_probs %*% bin_sumsq) - e_bin^2 @@ -56,7 +60,9 @@ ) motif_bins <- Matrix::t(bin_membership %*% matches_aligned) - observed <- as.matrix(BPCells::t(matches_aligned) %*% peak_mat) + observed <- rlang::with_options( + as.matrix(BPCells::t(matches_aligned) %*% peak_mat), rlib_message_verbosity = "quiet" + ) bg_exp <- as.matrix(motif_bins %*% moments$e) bg_sd <- sqrt(pmax(0, as.matrix(motif_bins %*% moments$v))) residual <- observed - bg_exp @@ -72,7 +78,9 @@ # Welford online mean/variance over iterations bounds RAM to two motif x cell accumulators. .deviations_sampled <- function(bgd, matches, matches_aligned, peak_mat, row_map, expectation, cell_depth) { - observed <- as.matrix(BPCells::t(matches_aligned) %*% peak_mat) + observed <- rlang::with_options( + as.matrix(BPCells::t(matches_aligned) %*% peak_mat), rlib_message_verbosity = "quiet" + ) motif_exp_per_peak <- as.numeric(BPCells::t(matches_aligned) %*% expectation) expected <- outer(motif_exp_per_peak, cell_depth) obs_dev <- (observed - expected) / expected @@ -83,7 +91,9 @@ # Permute in peak_set space, where bgd's indices live, then gather onto the # matrix row order. M_k <- .permute_matches(matches, bgd[, k])[row_map, , drop = FALSE] - obs_k <- as.matrix(BPCells::t(M_k) %*% peak_mat) + obs_k <- rlang::with_options( + as.matrix(BPCells::t(M_k) %*% peak_mat), rlib_message_verbosity = "quiet" + ) motif_exp_k <- as.numeric(BPCells::t(M_k) %*% expectation) exp_k <- outer(motif_exp_k, cell_depth) dev_k <- (obs_k - exp_k) / exp_k @@ -114,7 +124,7 @@ #' reference population configured by `add_background_peaks()`. #' @param chunk_size (integer) Cells per chunk; bounds dense per-chunk memory. Default 20000. #' @param overwrite (logical) Replace existing matrices. Default FALSE. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Unused. #' #' @return Modified MarchRProject. @@ -169,10 +179,11 @@ add_deviations_matrix.MarchRProject <- function( dataset_names = character(0), chunk_size = 20000L, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") if (!is.numeric(chunk_size) || length(chunk_size) != 1L || !is.finite(chunk_size) || chunk_size < 1 || chunk_size != round(chunk_size)) { @@ -189,7 +200,6 @@ add_deviations_matrix.MarchRProject <- function( i = "Re-run add_peak_annotations() or add_motif_annotations() after changing the peak set." )) } - reference <- .validate_background_reference(proj, bgd) analytic <- inherits(bgd, "MarchRBinBackground") if (!analytic && ncol(bgd) < 2L) { rlang::abort("Deviations require at least two background iterations to estimate variance.") @@ -198,77 +208,114 @@ add_deviations_matrix.MarchRProject <- function( dev_name <- paste0(matrix_name, "Deviations") z_name <- paste0(matrix_name, "ZScore") - if (length(dataset_names) == 0L) { - dataset_names <- vapply(names(proj$datasets), function(ds) { - if ("PeakMatrix" %in% names(proj$datasets[[ds]]$matrices)) ds else NA_character_ - }, character(1)) - dataset_names <- dataset_names[!is.na(dataset_names)] - } + peak_datasets <- names(proj$datasets)[purrr::map_lgl(proj$datasets, function(ds) { + "PeakMatrix" %in% names(ds$matrices) + })] + if (length(dataset_names) == 0L) dataset_names <- peak_datasets if (length(dataset_names) == 0L) { rlang::abort("No dataset has a PeakMatrix. Run add_peak_matrix() first.") } + bad <- setdiff(dataset_names, peak_datasets) + if (length(bad) > 0L) { + rlang::abort(sprintf("Dataset(s) %s not found or without a PeakMatrix.", + paste0("'", bad, "'", collapse = ", "))) + } + if (anyDuplicated(dataset_names)) { + rlang::abort("`dataset_names` must not contain duplicates.") + } + # Checked before the loop so an abort never leaves earlier datasets' outputs on disk. + existing <- Filter(function(ds) { + any(c(dev_name, z_name) %in% names(proj$datasets[[ds]]$matrices)) + }, dataset_names) + if (length(existing) > 0L && !overwrite) { + rlang::abort(sprintf( + "Assay '%s' or '%s' already exists on dataset '%s'. Use overwrite = TRUE to replace.", + dev_name, z_name, existing[1] + )) + } - scratch <- NULL - on.exit(unlink(scratch, recursive = TRUE, expand = FALSE), add = TRUE) + if (verbose) { + n_cells <- sum(purrr::map_dbl(dataset_names, function(ds) { + ncol(proj$datasets[[ds]]$matrices[["PeakMatrix"]]) + })) + run <- .log_start("Deviations", sprintf( + "'%s' (%s), %s, %s, %s", peak_annotation, .log_plural(ncol(matches), "motif"), + .log_plural(length(dataset_names), "dataset"), .log_plural(n_cells, "cell"), + if (analytic) { + sprintf("analytic background (%s)", .log_plural(length(bgd$bin_density), "bias bin")) + } else { + sprintf("sampled background (%s)", .log_plural(ncol(bgd), "iteration")) + } + )) + } + + t0 <- steady_clock_seconds_rcpp() + reference <- .validate_background_reference(proj, bgd) + if (verbose) { + .log_step(sprintf( + "Validated background reference (%s)", .log_plural(length(reference$dataset_names), "dataset") + ), since = t0) + } + + # Every dataset is checked before any is written. + t0 <- steady_clock_seconds_rcpp() + cell_depths <- list() for (ds in dataset_names) { - if (verbose) log_progress(sprintf("Computing deviations for dataset '%s'...", ds)) peak_mat <- proj$datasets[[ds]]$matrices[["PeakMatrix"]] - - if ((dev_name %in% names(proj$datasets[[ds]]$matrices) || - z_name %in% names(proj$datasets[[ds]]$matrices)) && !overwrite) { - rlang::abort(sprintf( - "Assay '%s' or '%s' already exists on dataset '%s'. Use overwrite = TRUE to replace.", - dev_name, z_name, ds + .assert_peak_rows_match(proj$peak_set, peak_mat) + cell_depth <- BPCells::matrix_stats(peak_mat, col_stats = "mean")$col_stats["mean", ] * + nrow(peak_mat) + n_zero <- sum(cell_depth <= 0) + if (n_zero > 0L) { + rlang::abort(c( + sprintf("Dataset '%s' has %d cell%s with zero peak counts.", + ds, n_zero, ifelse(n_zero == 1, "", "s")), + i = "Deviations are undefined for them. Remove them with subset_cells() first." )) } + cell_depths[[ds]] <- cell_depth + } + if (verbose) { + .log_step(sprintf("Measured depth of %s", .log_plural(n_cells, "cell")), since = t0) + } + + peak_keys <- .peak_set_keys(proj$peak_set) + scratch <- NULL + on.exit(unlink(scratch, recursive = TRUE, expand = FALSE), add = TRUE) + for (ds in dataset_names) { + if (verbose) pass <- .log_pass(ds, "Dataset") + peak_mat <- proj$datasets[[ds]]$matrices[["PeakMatrix"]] # PeakMatrix rows are genomically sorted while peak_set (and therefore the # match matrix and background indices) are score-sorted, so everything below # is gathered onto the matrix row order before any positional arithmetic. - peak_keys <- .assert_peak_rows_match(proj$peak_set, peak_mat) - row_map <- match(rownames(peak_mat), peak_keys) + row_map <- match(rownames(peak_mat), peak_keys) # All output datasets use the same explicitly scoped, validated baseline. # Cell depth is local, while peak accessibility is pooled over the reference. peak_sums <- reference$row_sums[rownames(peak_mat)] - cell_depth <- BPCells::matrix_stats(peak_mat, col_stats = "mean")$col_stats["mean", ] * - nrow(peak_mat) + cell_depth <- cell_depths[[ds]] expectation <- peak_sums / sum(peak_sums) - n_zero <- sum(cell_depth <= 0) - if (n_zero > 0L) { - rlang::abort(c( - sprintf("Dataset '%s' has %d cell%s with zero peak counts.", - ds, n_zero, ifelse(n_zero == 1, "", "s")), - i = "Deviations are undefined for them. Remove them with subset_cells() first." - )) - } - matches_aligned <- matches[row_map, , drop = FALSE] scratch <- tempfile("deviations_", tmpdir = proj$dir) dir.create(scratch, recursive = TRUE) # Column-major lets the multiplies stream cells instead of seeking each match. if (BPCells::storage_order(peak_mat) == "row") { - if (verbose) log_progress(" Transposing PeakMatrix to column-major...") + t0 <- steady_clock_seconds_rcpp() peak_mat <- BPCells::transpose_storage_order( peak_mat, outdir = file.path(scratch, "PeakMatrix"), tmpdir = scratch ) - } - if (verbose) { - bg <- if (analytic) sprintf("Analytic background over %d bias bins", length(bgd$bin_density)) - else sprintf("Sampled background over %d iterations", ncol(bgd)) - log_progress(sprintf(" %s (%d motifs x %d cells)...", bg, ncol(matches), ncol(peak_mat))) + if (verbose) .log_step("Transposed PeakMatrix storage order", since = t0) } chunks <- split(seq_len(ncol(peak_mat)), ceiling(seq_len(ncol(peak_mat)) / chunk_size)) dev_parts <- file.path(scratch, paste0("dev_", seq_along(chunks))) z_parts <- file.path(scratch, paste0("z_", seq_along(chunks))) for (i in seq_along(chunks)) { + t0 <- steady_clock_seconds_rcpp() cols <- chunks[[i]] - if (verbose && length(chunks) > 1L) { - log_progress(sprintf(" Cells %d-%d of %d...", cols[1], cols[length(cols)], ncol(peak_mat))) - } out <- if (analytic) { .deviations_analytic(bgd, matches_aligned, peak_mat[, cols], row_map, expectation, cell_depth[cols]) @@ -277,12 +324,24 @@ add_deviations_matrix.MarchRProject <- function( .deviations_sampled(bgd, matches, matches_aligned, peak_mat[, cols], row_map, expectation, cell_depth[cols]) } - BPCells::write_matrix_dir(as(out$deviations, "IterableMatrix"), dev_parts[i], - compress = TRUE) - BPCells::write_matrix_dir(as(out$z, "IterableMatrix"), z_parts[i], compress = TRUE) + rlang::with_options({ + BPCells::write_matrix_dir(as(out$deviations, "IterableMatrix"), dev_parts[i], + compress = TRUE) + BPCells::write_matrix_dir(as(out$z, "IterableMatrix"), z_parts[i], compress = TRUE) + }, rlib_message_verbosity = "quiet") rm(out) + if (verbose) { + .log_step(if (length(chunks) > 1L) { + sprintf("Cells %s-%s of %s: computed deviations", .log_count(cols[1]), + .log_count(cols[length(cols)]), .log_count(ncol(peak_mat))) + } else { + sprintf("Computed deviations for %s x %s", .log_plural(ncol(matches), "motif"), + .log_plural(ncol(peak_mat), "cell")) + }, since = t0) + } } + t0 <- steady_clock_seconds_rcpp() dev_path <- file.path(proj$dir, "datasets", ds, "matrices", dev_name) z_path <- file.path(proj$dir, "datasets", ds, "matrices", z_name) if (overwrite) { @@ -291,12 +350,17 @@ add_deviations_matrix.MarchRProject <- function( } proj$datasets[[ds]]$matrices[[dev_name]] <- .build_integration_matrix(dev_parts, dev_path) proj$datasets[[ds]]$matrices[[z_name]] <- .build_integration_matrix(z_parts, z_path) + if (verbose) .log_step(sprintf("Wrote '%s' and '%s'", dev_name, z_name), since = t0) - if (verbose) { - log_progress(sprintf(" Stored '%s' and '%s' on dataset '%s'", - dev_name, z_name, ds)) - } unlink(scratch, recursive = TRUE, expand = FALSE) + if (verbose) .log_pass_end(pass) + } + + if (verbose) { + .log_finish(run, sprintf( + "added assays '%s', '%s' to %s (%s)", dev_name, z_name, + .log_plural(length(dataset_names), "dataset"), .log_plural(n_cells, "cell") + )) } proj } diff --git a/R/enrichment.R b/R/enrichment.R index 87dc1d6..2ebfc19 100644 --- a/R/enrichment.R +++ b/R/enrichment.R @@ -30,7 +30,7 @@ #' used when `method = "bpcells"`). #' @param overwrite (logical) Replace existing background_peaks. Default FALSE #' keeps the stored background, warning if it was built with another `method`. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param dataset_names (character or NULL) Reference datasets whose PeakMatrix #' counts are pooled for background matching and deviation expectations. #' NULL (default) uses all datasets with a PeakMatrix. An explicit selection @@ -90,11 +90,12 @@ add_background_peaks.MarchRProject <- function( seed = 1L, knn_ef = 200L, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), dataset_names = NULL, ... ) { .start_log_clock() + assert_for(verbose, "logical") method <- match.arg(method) assert_for(proj, "MarchRProject") if (method == "betterChromVAR" && bin_size^2 > 1e5) { @@ -120,28 +121,60 @@ add_background_peaks.MarchRProject <- function( "was ignored. Use overwrite = TRUE to switch."), stored_method, method )) - } else if (verbose) { - log_progress("background_peaks already populated. Use overwrite = TRUE to recompute.") + } else { + rlang::warn("Background peaks already exist; set overwrite = TRUE to recompute.") } return(proj) } + if (verbose) { + n_ref <- length(dataset_names %||% + Filter(function(ds) "PeakMatrix" %in% names(ds$matrices), proj$datasets)) + bins <- sprintf("%s x %s bias bins, w = %s", .log_count(bin_size), .log_count(bin_size), w) + run <- .log_start("Background peaks", sprintf( + "%s, %s, %s, %s", .log_plural(nrow(proj$peak_set), "peak"), method, + if (method == "betterChromVAR") bins else .log_plural(n_iterations, "iteration"), + .log_plural(n_ref, "reference dataset") + )) + } + + t0 <- steady_clock_seconds_rcpp() reference <- .background_reference(proj, dataset_names) + if (verbose) { + n_cells <- sum(purrr::map_dbl(reference$dataset_names, function(ds) { + ncol(proj$datasets[[ds]]$matrices[["PeakMatrix"]]) + })) + .log_step(sprintf( + "Summed peak counts over %s (%s)", .log_plural(length(reference$dataset_names), "dataset"), + .log_plural(n_cells, "cell") + ), since = t0) + } peak_keys <- names(reference$row_sums) row_sums <- reference$row_sums gc <- proj$peak_set$gc len <- proj$peak_set$end - proj$peak_set$start + t0 <- steady_clock_seconds_rcpp() bgd <- switch(method, chromVAR = .background_peaks_chromvar(row_sums, gc, proj$peak_set, n_iterations, w, bin_size, seed), bpcells = .background_peaks_bpcells(row_sums, gc, len, n_iterations, - seed, knn_ef, verbose), + seed, knn_ef), betterChromVAR = structure( .background_bins(row_sums, gc, bs = c(bin_size, bin_size), w = w), class = "MarchRBinBackground" ) ) + if (verbose) { + .log_step(switch(method, + chromVAR = sprintf("Sampled %s per peak (%s)", .log_plural(n_iterations, "background peak"), bins), + bpcells = sprintf("Matched %s per peak by KNN", .log_plural(n_iterations, "background peak")), + betterChromVAR = sprintf( + "Built %s (%s occupied)", .log_plural(length(bgd$bin_density), "bias bin"), + .log_count(sum(bgd$bin_density > 0)) + ) + ), since = t0) + } attr(bgd, "method") <- method attr(bgd, "seed") <- seed @@ -159,13 +192,13 @@ add_background_peaks.MarchRProject <- function( proj$background_peaks <- bgd if (verbose) { - if (inherits(bgd, "MarchRBinBackground")) { - log_progress(sprintf(" Stored background_peaks: %d peaks in %d bias bins (method = %s)", - length(bgd$peak2bin), length(bgd$bin_density), method)) + .log_finish(run, if (inherits(bgd, "MarchRBinBackground")) { + sprintf("added background bias bins (%s in %s)", .log_plural(length(bgd$peak2bin), "peak"), + .log_plural(length(bgd$bin_density), "bin")) } else { - log_progress(sprintf(" Stored background_peaks: %d peaks x %d iterations (method = %s)", - nrow(bgd), ncol(bgd), method)) - } + sprintf("added background peaks (%s x %s)", .log_plural(nrow(bgd), "peak"), + .log_plural(ncol(bgd), "iteration")) + }) } proj } @@ -199,7 +232,7 @@ add_background_peaks.MarchRProject <- function( } # Path B: BPCells knn_hnsw on quantile-normalized (log10(rowSums+1), gc, length). -.background_peaks_bpcells <- function(row_sums, gc, len, n_iter, seed, knn_ef = 200L, verbose) { +.background_peaks_bpcells <- function(row_sums, gc, len, n_iter, seed, knn_ef = 200L) { bias_mat <- cbind( qnorm(rank(log10(row_sums + 1)) / (length(row_sums) + 1)), qnorm(rank(gc) / (length(gc) + 1)), @@ -207,7 +240,7 @@ add_background_peaks.MarchRProject <- function( ) set.seed(seed) knn <- suppressWarnings(BPCells::knn_hnsw( - bias_mat, k = n_iter + 1L, ef = knn_ef, verbose = verbose + bias_mat, k = n_iter + 1L, ef = knn_ef, verbose = FALSE )$idx) t(vapply(seq_len(nrow(knn)), function(i) { neighbors <- knn[i, ] @@ -444,7 +477,7 @@ get_background_peaks.MarchRProject <- function(proj, ...) { #' @param background (character) `"all"` (whole peak set) or #' `"background_peaks"` (GC/accessibility-matched peers via #' `add_background_peaks()`). -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Unused. #' #' @return Long `tibble` with one row per (group x annotation) pair. @@ -473,10 +506,11 @@ peak_annotation_enrichment.MarchRProject <- function( matches = NULL, cutoff = "p_val_adj <= 0.1 & log2_fc >= 0.5", background = c("all", "background_peaks"), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") background <- match.arg(background) @@ -490,21 +524,40 @@ peak_annotation_enrichment.MarchRProject <- function( fg_groups <- split(results_df, results_df$foreground) - if (verbose) { - log_progress(sprintf("Running enrichment: %d groups x %d annotations", - length(fg_groups), ncol(matches))) - } - if (background == "background_peaks") { bgd <- get_background_peaks(proj) if (is.null(bgd)) { rlang::abort("background = 'background_peaks' requires add_background_peaks() to have been run.") } - .validate_background_reference(proj, bgd) - bgd <- .background_peak_indices(bgd) } - purrr::map_dfr(fg_groups, function(group_df) { + if (verbose) { + label <- if (missing(peak_annotation)) "supplied matches" else sprintf("'%s'", peak_annotation) + run <- .log_start("Peak annotation enrichment", sprintf( + "%s (%s), %s, background %s", label, .log_plural(ncol(matches), "annotation"), + .log_plural(length(fg_groups), "group"), + if (background == "all") { + sprintf("all peaks (%s)", .log_count(nrow(matches))) + } else { + sprintf("matched peaks (%s)", attr(bgd, "method")) + } + )) + } + + if (background == "background_peaks") { + t0 <- steady_clock_seconds_rcpp() + reference <- .validate_background_reference(proj, bgd) + if (verbose) { + .log_step(sprintf( + "Validated background reference (%s)", .log_plural(length(reference$dataset_names), "dataset") + ), since = t0) + } + } + + t0 <- steady_clock_seconds_rcpp() + if (background == "background_peaks") bgd <- .background_peak_indices(bgd) + + results <- purrr::map(fg_groups, function(group_df) { pass <- rlang::eval_tidy(expr, data = group_df) pass[is.na(pass)] <- FALSE fg_idx <- match(group_df$feature[pass], peak_keys) @@ -519,6 +572,21 @@ peak_annotation_enrichment.MarchRProject <- function( .compute_enrichment(matches, fg_idx, bg_idx, group_df$foreground[1]) }) + out <- dplyr::bind_rows(results) + + if (verbose) { + empty <- names(results)[purrr::map_lgl(results, is.null)] + n_tested <- length(results) - length(empty) + .log_step(paste0( + "Tested ", .log_plural(n_tested, "group"), " with marker peaks", + if (length(empty) > 0) sprintf(" (%s had none)", .log_names(empty)) + ), since = t0) + .log_finish(run, sprintf( + "%s (%s x %s)", .log_plural(nrow(out), "test"), .log_plural(n_tested, "group"), + .log_plural(ncol(matches), "annotation") + )) + } + out } # Hypergeometric per-motif enrichment for one (group, fg_idx, bg_idx) tuple. diff --git a/R/linkage.R b/R/linkage.R index 88cf3e8..a3ffd87 100644 --- a/R/linkage.R +++ b/R/linkage.R @@ -15,7 +15,7 @@ #' \code{floor(overlap_cutoff * k)} cells with any accepted group. Default 0.8. #' @param knn_method (function) KNN engine (BPCells partial-app). Default \code{knn_hnsw()}. #' @param seed (integer) Random seed for anchor sampling. Default 1L. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' #' @details Mirrors ArchR's random-KNN aggregation (\code{.computeKNN} + #' \code{determineOverlapCpp}); uses BPCells \code{knn_hnsw} (approximate NN) @@ -25,8 +25,9 @@ #' @export make_knn_pseudobulks <- function(embedding, knn_iteration = 500L, k = 100L, overlap_cutoff = 0.8, knn_method = knn_hnsw(), - seed = 1L, verbose = getOption("MarchR.verbose", TRUE)) { + seed = 1L, verbose = getOption("MarchR.verbose", FALSE)) { .start_log_clock() + assert_for(verbose, "logical") assert_for(embedding, "matrix") if (is.null(rownames(embedding))) { rlang::abort("`embedding` must have cell names as rownames.") @@ -37,20 +38,31 @@ make_knn_pseudobulks <- function(embedding, knn_iteration = 500L, k = 100L, set.seed(seed) n_anchors <- min(as.integer(knn_iteration), n_cells) anchor_idx <- sample(n_cells, n_anchors) + if (verbose) { + run <- .log_start("KNN metacells", sprintf( + "%s, %s, %s x %s", .log_plural(n_cells, "cell"), .log_plural(ncol(embedding), "dim"), + .log_plural(n_anchors, "anchor"), .log_plural(k, "neighbor") + ), compact = TRUE) + } + t0 <- steady_clock_seconds_rcpp() # Override any k/verbose baked into knn_method - knn_call <- partial_apply(knn_method, k = k, verbose = verbose, + knn_call <- partial_apply(knn_method, k = k, verbose = FALSE, .missing_args_error = FALSE) knn <- knn_call(data = embedding, query = embedding[anchor_idx, , drop = FALSE]) idx <- knn$idx keep <- .overlap_dedup(idx, floor(overlap_cutoff * k)) if (verbose) { - log_progress(sprintf("Kept %d of %d KNN groups after overlap pruning.", - length(keep), nrow(idx))) + .log_step(sprintf( + "Kept %s of %s after overlap pruning", .log_count(length(keep)), + .log_plural(nrow(idx), "KNN group") + ), since = t0) } cell_names <- rownames(embedding) - lapply(keep, function(i) cell_names[idx[i, ]]) + groups <- lapply(keep, function(i) cell_names[idx[i, ]]) + if (verbose) .log_finish(run, .log_plural(length(groups), "metacell")) + groups } # Overlap pruning @@ -85,7 +97,10 @@ make_knn_pseudobulks <- function(embedding, knn_iteration = 500L, k = 100L, colnames(agg_lazy) <- paste0("metacell_", seq_len(n_groups)) agg <- if (!is.null(out_dir)) { - write_matrix_dir(convert_matrix_type(agg_lazy, "float"), out_dir, overwrite = TRUE) + rlang::with_options( + write_matrix_dir(convert_matrix_type(agg_lazy, "float"), out_dir, overwrite = TRUE), + rlib_message_verbosity = "quiet" + ) } else { agg_lazy } diff --git a/R/markers.R b/R/markers.R index d24af9c..cc4c8df 100644 --- a/R/markers.R +++ b/R/markers.R @@ -79,7 +79,7 @@ as.data.frame.MarkerResult <- function(x, ...) { #' @param scale_to (numeric) Column-sum normalization target. Default 1e4. #' @param knn_method (function) BPCells KNN method. Default \code{knn_hnsw()}. #' @param seed (integer) Random seed. Default 1L. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param overwrite (logical) If TRUE, overwrite existing marker result for #' this assay. Default FALSE. (MarchRProject method only.) #' @param dataset_names (character) Datasets to include. Default all. @@ -120,7 +120,7 @@ add_marker_features <- function( scale_to = 1e4, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { UseMethod("add_marker_features") @@ -144,16 +144,45 @@ add_marker_features.default <- function( scale_to = 1e4, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") mat <- proj groups <- group_by + if (!is.null(bias)) { + assertthat::assert_that(!is.null(cell_metadata), + msg = "cell_metadata is required when bias is not NULL.") + assertthat::assert_that(is.function(knn_method), + msg = "knn_method must be a function (e.g., knn_hnsw()).") + } + + if (verbose) { + run <- .log_start("Marker features", sprintf( + "%s x %s, %s, %s", .log_plural(nrow(mat), "feature"), .log_plural(ncol(mat), "cell"), + .log_plural(length(unique(groups)), "group"), + if (is.null(bias)) "one-vs-all" else paste("bias-matched on", toString(bias)) + )) + } + if (is.null(bias)) { - result <- BPCells::marker_features(mat, groups, method = method) + t0 <- steady_clock_seconds_rcpp() + result <- rlang::with_options( + BPCells::marker_features(mat, groups, method = method), + rlib_message_verbosity = "quiet" + ) result <- .annotate_markers(result, p_adjust_method) + if (verbose) { + .log_step(sprintf( + "Tested %s across %s", .log_plural(nrow(mat), "feature"), + .log_plural(length(unique(groups)), "group") + ), since = t0) + .log_finish(run, sprintf( + "%s x %s marker table", .log_count(nrow(mat)), .log_count(length(unique(result$foreground))) + )) + } return(MarkerResult( results = result, matrix = mat, @@ -162,28 +191,10 @@ add_marker_features.default <- function( )) } - assertthat::assert_that(!is.null(cell_metadata), - msg = "cell_metadata is required when bias is not NULL.") - assertthat::assert_that(is.function(knn_method), - msg = "knn_method must be a function (e.g., knn_hnsw()).") - - if (verbose) log_progress("Matching bias cell groups...") - cells_with_groups <- intersect(names(groups), rownames(cell_metadata)) cell_metadata <- cell_metadata[cells_with_groups, , drop = FALSE] groups <- groups[cells_with_groups] - match_obj <- .match_bias_cell_groups( - cell_metadata = cell_metadata, - groups = groups, - bias = bias, - k = as.integer(k), - max_cells = as.integer(max_cells), - buffer_ratio = buffer_ratio, - knn_method = partial_apply(knn_method, verbose = verbose, .missing_args_error = FALSE), - seed = as.integer(seed) - ) - # Compute per-cell normalization factors (lazy via multiply_cols) norm_factors <- NULL if (is.null(norm_by) || !identical(norm_by, "none")) { @@ -192,7 +203,18 @@ add_marker_features.default <- function( names(vals) <- rownames(cell_metadata) norm_factors <- stats::median(vals) / vals } else { + if (!is.null(norm_by)) { + rlang::warn(sprintf( + "norm_by column '%s' not in cell metadata; normalized by column sums.", norm_by + )) + } + t0 <- steady_clock_seconds_rcpp() norm_factors <- scale_to / BPCells::colSums(mat) + if (verbose) { + .log_step(sprintf( + "Normalized %s to %s counts", .log_plural(ncol(mat), "cell"), .log_count(scale_to) + ), since = t0) + } } } @@ -200,30 +222,43 @@ add_marker_features.default <- function( mat <- BPCells::multiply_cols(mat, norm_factors[colnames(mat)]) } + t0 <- steady_clock_seconds_rcpp() + match_obj <- .match_bias_cell_groups( + cell_metadata = cell_metadata, + groups = groups, + bias = bias, + k = as.integer(k), + max_cells = as.integer(max_cells), + buffer_ratio = buffer_ratio, + knn_method = partial_apply(knn_method, verbose = FALSE, .missing_args_error = FALSE), + seed = as.integer(seed) + ) + if (verbose) { + .log_step(paste("Matched bias backgrounds for", .log_plural(length(match_obj), "group")), since = t0) + } + use_groups <- names(match_obj) - if (verbose) log_progress(sprintf("Testing %d groups with bias-matched backgrounds...", - length(use_groups))) results <- lapply(use_groups, function(grp) { fg_cells <- match_obj[[grp]]$fg_cells bg_cells <- match_obj[[grp]]$bg_cells if (length(fg_cells) == 0 || length(bg_cells) == 0) { - if (verbose) log_progress(sprintf(" Skipping group '%s': insufficient matched cells", grp)) + if (verbose) .log_step(paste0(grp, ": no bias-matched background cells, skipped")) return(NULL) } - if (verbose) { - log_progress(sprintf(" Group '%s': %d fg, %d bg cells", grp, length(fg_cells), length(bg_cells))) - } - + t0 <- steady_clock_seconds_rcpp() all_cells <- c(fg_cells, bg_cells) sub_groups <- stats::setNames( c(rep(grp, length(fg_cells)), rep("background", length(bg_cells))), all_cells ) - sub_result <- BPCells::marker_features(mat[, all_cells], sub_groups, method = method) + sub_result <- rlang::with_options( + BPCells::marker_features(mat[, all_cells], sub_groups, method = method), + rlib_message_verbosity = "quiet" + ) sub_result <- sub_result[sub_result$foreground == grp, ] # Foreground and background hold equal cell counts (n) from the paired bias @@ -231,12 +266,23 @@ add_marker_features.default <- function( sub_result$log2_fc <- .archr_log2fc( sub_result$foreground_mean, sub_result$background_mean, length(fg_cells) ) + if (verbose) { + .log_step(sprintf( + "%s: tested %s, %s vs %s cells", grp, .log_plural(nrow(sub_result), "feature"), + .log_count(length(fg_cells)), .log_count(length(bg_cells)) + ), since = t0) + } sub_result }) result <- dplyr::bind_rows(results) result <- .annotate_markers(result, p_adjust_method) + if (verbose) { + .log_finish(run, sprintf( + "%s x %s marker table", .log_count(nrow(mat)), .log_count(length(unique(result$foreground))) + )) + } MarkerResult( results = result, matrix = mat, @@ -262,11 +308,12 @@ add_marker_features.MarchRProject <- function( scale_to = 1e4, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ... ) { .start_log_clock() + assert_for(verbose, "logical") assay_name <- select_assay_name(proj, assay_name) dataset_names <- select_dataset_names(proj, dataset_names = dataset_names) @@ -304,6 +351,15 @@ add_marker_features.MarchRProject <- function( combined_mat <- do.call(cbind, matrices) } + if (verbose) { + run <- .log_start("Marker features", sprintf( + "'%s' (%s), %s, %s, %s, %s", assay_name, .log_plural(nrow(combined_mat), "feature"), + .log_plural(length(available_dsets), "dataset"), .log_plural(ncol(combined_mat), "cell"), + .log_plural(length(unique(all_groups)), "group"), + if (is.null(bias)) "one-vs-all" else paste("bias-matched on", toString(bias)) + )) + } + combined_metadata <- if (!is.null(bias)) { do.call(rbind, purrr::map(available_dsets, function(ds) { .collect_bias_metadata_dataset(proj$datasets[[ds]]) @@ -333,6 +389,12 @@ add_marker_features.MarchRProject <- function( marker_result$params$assay_name <- assay_name proj$marker_results[[assay_name]] <- marker_result + if (verbose) { + .log_finish(run, sprintf( + "added marker features '%s' (%s x %s)", assay_name, .log_plural(nrow(combined_mat), "feature"), + .log_plural(length(unique(marker_result$results$foreground)), "group") + )) + } return(proj) } diff --git a/R/module_scores.R b/R/module_scores.R index aafc6a6..a8bdc7b 100644 --- a/R/module_scores.R +++ b/R/module_scores.R @@ -35,6 +35,9 @@ #' \item ArchR parameter \code{nBgd} maps to MarchR \code{n_background}. #' \item MarchR accepts any matrix assay (GeneScoreMatrix, RNA, etc.), #' while ArchR restricts to GeneScoreMatrix and TileMatrix. +#' \item When a module has no expression-matched background features (all of +#' its features are zero-signal), ArchR returns \code{NaN}, while MarchR +#' scores the module against all other features and warns. #' } #' #' @seealso \code{\link{get_marker_features}} for differential marker analysis, @@ -88,69 +91,41 @@ add_module_score.MarchRDataset <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRDataset") - assertthat::assert_that( - is.list(features), - msg = "`features` must be a non-empty list of character vectors." - ) - assertthat::assert_that( - length(features) > 0, - msg = "`features` must be a non-empty list of character vectors." - ) - assertthat::assert_that( - all(vapply(features, is.character, logical(1))), - msg = "Each element of `features` must be a character vector of gene names." - ) + features <- .check_module_features(features) assay_name <- select_assay_name(proj, assay_name) mat <- proj[[assay_name]] - # Name modules sequentially if unnamed - if (is.null(names(features))) { - names(features) <- seq_along(features) - } - all_feature_names <- rownames(mat) assertthat::assert_that( !is.null(all_feature_names), msg = "Matrix must have rownames (feature names)." ) - - # Validate that at least some features match - for (mod_name in names(features)) { - matched <- features[[mod_name]] %in% all_feature_names - if (!any(matched)) { - rlang::abort(sprintf( - "No features in module '%s' found in assay '%s'. Check feature names.", - mod_name, assay_name - )) - } - if (!all(matched)) { - missing <- features[[mod_name]][!matched] - if (verbose) { - log_progress(sprintf( - "Module '%s': %d of %d features not found in assay, skipping: %s", - mod_name, length(missing), length(features[[mod_name]]), - paste(head(missing, 5), collapse = ", ") - )) - } - features[[mod_name]] <- features[[mod_name]][matched] - } + features <- .match_module_features(features, all_feature_names, assay_name) + if (verbose) { + run <- .log_start("Module scores", sprintf( + "%s on '%s' (%s x %s), %s, %s each", .log_plural(length(features), "module"), assay_name, + .log_plural(nrow(mat), "feature"), .log_plural(ncol(mat), "cell"), .log_plural(n_bins, "bin"), + .log_plural(n_background, "background feature") + )) } # Compute per-feature mean signal (disk-backed via BPCells) - if (verbose) log_progress("Computing per-feature mean signal") + t0 <- steady_clock_seconds_rcpp() feature_means <- matrix_stats( mat, row_stats = "mean", threads = threads )$row_stats["mean", ] # Exclude zero-signal features from binning (matches ArchR behavior) nonzero_mask <- feature_means > 0 - if (verbose && any(!nonzero_mask)) { - log_progress(sprintf( - "Excluding %d zero-signal features from expression bins", - sum(!nonzero_mask) - )) + if (verbose) { + n_zero <- sum(!nonzero_mask) + .log_step(paste0( + "Computed means for ", .log_plural(length(feature_means), "feature"), + if (n_zero > 0) paste0(", excluded ", .log_plural(n_zero, "zero-signal feature")) + ), since = t0) } # Bin only non-zero features by mean signal into n_bins quantile groups @@ -182,8 +157,7 @@ add_module_score.MarchRDataset <- function( # Score each module for (mod_name in names(features)) { - if (verbose) log_progress(sprintf("Scoring module '%s'", mod_name)) - + t0 <- steady_clock_seconds_rcpp() fg_genes <- features[[mod_name]] fg_idx <- match(fg_genes, all_feature_names) @@ -195,6 +169,10 @@ add_module_score.MarchRDataset <- function( # Fallback: if no background genes sampled (e.g. very few features), # use all non-foreground features as background if (length(bg_idx) == 0) { + rlang::warn(sprintf( + "Module '%s': no expression-matched background features; scored against all other features.", + mod_name + )) bg_idx <- setdiff(seq_along(all_feature_names), fg_idx) } @@ -218,8 +196,15 @@ add_module_score.MarchRDataset <- function( col_name = col_name, overwrite = overwrite ) + if (verbose) { + .log_step(sprintf( + "%s: scored %s against %s", mod_name, .log_plural(length(fg_idx), "feature"), + .log_plural(length(bg_idx), "background feature") + ), since = t0) + } } + if (verbose) .log_finish(run, .module_columns_added(name, names(features))) return(proj) } @@ -247,15 +232,26 @@ add_module_score.MarchRProject <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") assert_is_character(dataset_names) + features <- .check_module_features(features) dataset_names <- select_dataset_names(proj, dataset_names) + assay_name <- select_assay_name(proj, assay_name) + mats <- purrr::map( + rlang::set_names(dataset_names), ~ get_matrix(proj, dataset_name = .x, assay_name = assay_name) + ) + features <- .match_module_features(features, unique(unlist(purrr::map(mats, rownames))), assay_name) + if (verbose) { + n_cells <- sum(purrr::map_dbl(mats, ncol)) + run <- .log_start("Module scores", sprintf( + "%s on '%s', %s, %s", .log_plural(length(features), "module"), assay_name, + .log_plural(length(dataset_names), "dataset"), .log_plural(n_cells, "cell") + )) + } for (ds in dataset_names) { - if (verbose) { - log_progress(sprintf("Computing module scores for dataset '%s'", ds)) - } - + if (verbose) pass <- .log_pass(ds, "Dataset") proj$datasets[[ds]] <- add_module_score( proj$datasets[[ds]], features = features, @@ -268,8 +264,15 @@ add_module_score.MarchRProject <- function( threads = threads, verbose = verbose ) + if (verbose) .log_pass_end(pass) } + if (verbose) { + .log_finish(run, sprintf( + "%s to %s (%s)", .module_columns_added(name, names(features)), + .log_plural(length(dataset_names), "dataset"), .log_plural(n_cells, "cell") + )) + } return(proj) } @@ -277,6 +280,58 @@ add_module_score.MarchRProject <- function( # Internal helpers ######################################################################## +.check_module_features <- function(features) { + assertthat::assert_that( + is.list(features), + msg = "`features` must be a non-empty list of character vectors." + ) + assertthat::assert_that( + length(features) > 0, + msg = "`features` must be a non-empty list of character vectors." + ) + assertthat::assert_that( + all(vapply(features, is.character, logical(1))), + msg = "Each element of `features` must be a character vector of gene names." + ) + + # Name modules sequentially if unnamed + if (is.null(names(features))) { + names(features) <- seq_along(features) + } + features +} + +# Drops module features absent from the assay, warning once per module. +.match_module_features <- function(features, feature_names, assay_name) { + # Validate that at least some features match + for (mod_name in names(features)) { + matched <- features[[mod_name]] %in% feature_names + if (!any(matched)) { + rlang::abort(sprintf( + "No features in module '%s' found in assay '%s'. Check feature names.", + mod_name, assay_name + )) + } + if (!all(matched)) { + missing <- features[[mod_name]][!matched] + rlang::warn(sprintf( + "Module '%s': %s of %s features not in '%s' (%s); scored the rest.", + mod_name, .log_count(length(missing)), .log_count(length(features[[mod_name]])), assay_name, + .log_names(missing) + )) + features[[mod_name]] <- features[[mod_name]][matched] + } + } + features +} + +.module_columns_added <- function(name, modules) { + paste0( + "added cell metadata ", if (length(modules) == 1) "column " else "columns ", + paste0("'", name, ".", modules, "'", collapse = ", ") + ) +} + #' Assign features to quantile bins based on mean signal #' #' @param feature_means Named numeric vector of per-feature means. Should diff --git a/R/peak2gene.R b/R/peak2gene.R index 889755b..470c6c6 100644 --- a/R/peak2gene.R +++ b/R/peak2gene.R @@ -91,7 +91,7 @@ add_peak2gene_links <- function(proj, ...) { #' @param n_perm (integer) Permutations for `add_permuted_pval`. Default 100L. #' @param knn_method (function) KNN engine (BPCells partial-application). Default `knn_hnsw()`. #' @param seed (integer) Random seed for metacell sampling and p-value resampling. Default 1L. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param overwrite (logical) Replace an existing `peak2gene_links` result. Default FALSE. #' #' @return `proj` with `proj$peak2gene_links` populated as a data.frame with columns @@ -148,13 +148,14 @@ add_peak2gene_links.MarchRProject <- function( n_perm = 100L, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ...) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") if (!is.null(proj$peak2gene_links) && !overwrite) { - if (verbose) log_progress("peak2gene_links exists; set overwrite = TRUE to recompute.") + rlang::warn("peak2gene_links already exists; set overwrite = TRUE to recompute.") return(proj) } if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { @@ -184,31 +185,53 @@ add_peak2gene_links.MarchRProject <- function( } } - emb_full <- as.matrix(t(proj[[embedding_name, dataset_names]])) + emb_full <- rlang::with_options( + as.matrix(t(proj[[embedding_name, dataset_names]])), rlib_message_verbosity = "quiet" + ) peak_mat_full <- proj[[atac_assay_name, dataset_names]] gene_mat_full <- proj[[use_matrix, dataset_names]] + # PeakMatrix rows are genomically sorted + ord <- match(rownames(peak_mat_full), .peak_set_keys(proj$peak_set)) + if (anyNA(ord)) { + rlang::abort("PeakMatrix rownames do not reconcile with proj$peak_set coordinates.") + } + metadata <- get_cell_metadata(proj, dataset_names) - cell_sets <- list(rownames(emb_full), colnames(peak_mat_full), - colnames(gene_mat_full)) + cells <- Reduce(intersect, list(rownames(emb_full), colnames(peak_mat_full), + colnames(gene_mat_full))) + if (!is.null(cells_to_use)) cells <- intersect(cells, cells_to_use) + dims_to_use <- intersect(dims_to_use, seq_len(ncol(emb_full))) + if (verbose) { + run <- .log_start("Peak-to-gene links", sprintf( + "%s on '%s' (%s), '%s' x '%s', max distance %s bp", .log_plural(length(cells), "cell"), + embedding_name, .log_plural(length(dims_to_use), "dim"), atac_assay_name, use_matrix, + .log_count(max_dist) + )) + } + keep_cells <- cells if ("predictedScore" %in% colnames(metadata)) { score_cells <- rownames(metadata)[ !is.na(metadata$predictedScore) & metadata$predictedScore >= prediction_cutoff ] - cell_sets <- c(cell_sets, list(score_cells)) + keep_cells <- intersect(cells, score_cells) + if (verbose) { + .log_step(sprintf( + "Kept %s of %s with predictedScore >= %s", .log_count(length(keep_cells)), + .log_plural(length(cells), "cell"), format(prediction_cutoff) + )) + } + } else if (identical(use_matrix, "GeneIntegrationMatrix")) { + rlang::warn("No 'predictedScore' column; prediction_cutoff not applied.") } else if (verbose) { - log_progress("No 'predictedScore' column found; skipping prediction_cutoff filtering.") + .log_step("No 'predictedScore' column; prediction_cutoff not applied") } - - keep_cells <- Reduce(intersect, cell_sets) - if (!is.null(cells_to_use)) keep_cells <- intersect(keep_cells, cells_to_use) if (length(keep_cells) == 0) { rlang::abort("No cells remain after prediction_cutoff filtering and cell selection.") } emb <- emb_full[keep_cells, , drop = FALSE] - dims_to_use <- intersect(dims_to_use, seq_len(ncol(emb))) emb <- emb[, dims_to_use, drop = FALSE] peak_mat <- peak_mat_full[, keep_cells] @@ -218,11 +241,7 @@ add_peak2gene_links.MarchRProject <- function( overlap_cutoff = overlap_cutoff, knn_method = knn_method, seed = seed, verbose = verbose) - # PeakMatrix rows are genomically sorted - ord <- match(rownames(peak_mat), .peak_set_keys(proj$peak_set)) - if (anyNA(ord)) { - rlang::abort("PeakMatrix rownames do not reconcile with proj$peak_set coordinates.") - } + t0 <- steady_clock_seconds_rcpp() peaks <- proj$peak_set[ord, ] summit <- as.integer((peaks$start + peaks$end) / 2L) peak_gr <- GenomicRanges::GRanges(peaks$chr, IRanges::IRanges(summit, width = 1L)) @@ -243,18 +262,42 @@ add_peak2gene_links.MarchRProject <- function( a = sh[keep], b = qh[keep], distance = abs(GenomicRanges::start(gene_gr)[qh[keep]] - summit[sh[keep]]) ) + if (verbose) { + .log_step(sprintf( + "Found %s within %s bp of a TSS (%s)", .log_plural(nrow(pairs), "peak-gene pair"), + .log_count(max_dist), .log_plural(nrow(geneset), "gene") + ), since = t0) + } atac_dir <- file.path(proj$dir %||% tempdir(), "peak2gene", "atac") rna_dir <- file.path(proj$dir %||% tempdir(), "peak2gene", "rna") + t0 <- steady_clock_seconds_rcpp() agg_atac <- .aggregate_metacells(peak_mat, groups, scale_to = scale_to, log2_norm = log2_norm, out_dir = atac_dir) + agg_atac_dense <- rlang::with_options(as.matrix(agg_atac$matrix), rlib_message_verbosity = "quiet") + if (verbose) { + .log_step(sprintf( + "Aggregated %s into %s", .log_plural(nrow(peak_mat), "peak"), + .log_plural(length(groups), "metacell") + ), since = t0) + } + t0 <- steady_clock_seconds_rcpp() agg_rna <- .aggregate_metacells(gene_mat, groups, scale_to = scale_to, log2_norm = log2_norm, out_dir = rna_dir) - agg_atac_dense <- as.matrix(agg_atac$matrix) - agg_rna_dense <- as.matrix(agg_rna$matrix) + agg_rna_dense <- rlang::with_options(as.matrix(agg_rna$matrix), rlib_message_verbosity = "quiet") + if (verbose) { + .log_step(sprintf( + "Aggregated %s into %s", .log_plural(nrow(gene_mat), "gene"), + .log_plural(length(groups), "metacell") + ), since = t0) + } + t0 <- steady_clock_seconds_rcpp() res <- .correlate_pairs(agg_atac_dense, agg_rna_dense, pairs[, c("a", "b")], n = length(groups)) + if (verbose) { + .log_step(sprintf("Correlated %s", .log_plural(nrow(pairs), "peak-gene pair")), since = t0) + } p2g <- data.frame( idxATAC = if (nrow(res) > 0) ord[res$a] else integer(0), @@ -265,18 +308,26 @@ add_peak2gene_links.MarchRProject <- function( ) if (add_empirical_pval) { + t0 <- steady_clock_seconds_rcpp() set.seed(seed) emp <- .p2g_empirical_pval(res$correlation, agg_atac_dense, agg_rna_dense, pairs[, c("a", "b")], peaks$chr, n = 1000L) p2g$EmpPval <- emp$pval p2g$EmpFDR <- emp$fdr + if (verbose) .log_step("Computed empirical p-values from a trans-chromosome null", since = t0) } if (add_permuted_pval) { + t0 <- steady_clock_seconds_rcpp() set.seed(seed) perm_pval <- .p2g_permuted_pval(agg_atac_dense, agg_rna_dense, pairs[, c("a", "b")], n = length(groups), n_perm = n_perm) p2g$PermPval <- perm_pval p2g$PermFDR <- .p2g_permuted_fdr(perm_pval, p2g$Pval) + if (verbose) { + .log_step(sprintf( + "Computed permuted p-values from %s", .log_plural(n_perm, "permutation") + ), since = t0) + } } attr(p2g, "params") <- list( @@ -290,6 +341,7 @@ add_peak2gene_links.MarchRProject <- function( attr(p2g, "rna_path") <- agg_rna$path attr(p2g, "geneSet") <- geneset proj$peak2gene_links <- p2g + if (verbose) .log_finish(run, sprintf("added peak2gene_links (%s)", .log_plural(nrow(p2g), "pair"))) proj } diff --git a/man/add_background_peaks.Rd b/man/add_background_peaks.Rd index 5ac1617..06be463 100644 --- a/man/add_background_peaks.Rd +++ b/man/add_background_peaks.Rd @@ -14,7 +14,7 @@ seed = 1L, knn_ef = 200L, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), dataset_names = NULL, ... ) @@ -47,7 +47,7 @@ used when \code{method = "bpcells"}).} \item{overwrite}{(logical) Replace existing background_peaks. Default FALSE keeps the stored background, warning if it was built with another \code{method}.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{dataset_names}{(character or NULL) Reference datasets whose PeakMatrix counts are pooled for background matching and deviation expectations. diff --git a/man/add_co_accessibility.Rd b/man/add_co_accessibility.Rd index b5007be..8fa68d5 100644 --- a/man/add_co_accessibility.Rd +++ b/man/add_co_accessibility.Rd @@ -23,7 +23,7 @@ add_co_accessibility(proj, ...) log2_norm = TRUE, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ... ) @@ -61,7 +61,7 @@ add_co_accessibility(proj, ...) \item{seed}{(integer) Random seed for metacell sampling. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{overwrite}{(logical) Replace an existing \code{co_accessibility} result. Default FALSE.} } diff --git a/man/add_deviations_matrix.Rd b/man/add_deviations_matrix.Rd index 1f9c1f6..2917ba1 100644 --- a/man/add_deviations_matrix.Rd +++ b/man/add_deviations_matrix.Rd @@ -12,7 +12,7 @@ dataset_names = character(0), chunk_size = 20000L, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -33,7 +33,7 @@ reference population configured by \code{add_background_peaks()}.} \item{overwrite}{(logical) Replace existing matrices. Default FALSE.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Unused.} } diff --git a/man/add_kmer_bias.Rd b/man/add_kmer_bias.Rd index 687feb0..5dc484b 100644 --- a/man/add_kmer_bias.Rd +++ b/man/add_kmer_bias.Rd @@ -15,7 +15,7 @@ threads = 1L, seed = 1L, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -41,7 +41,7 @@ NULL resolves from proj$genome$sequence.} \item{overwrite}{(logical) Replace existing entry. Default FALSE.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Unused.} } diff --git a/man/add_marker_features.Rd b/man/add_marker_features.Rd index ed5d914..60a193b 100644 --- a/man/add_marker_features.Rd +++ b/man/add_marker_features.Rd @@ -20,7 +20,7 @@ scale_to = 10000, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -39,7 +39,7 @@ scale_to = 10000, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ... ) @@ -81,7 +81,7 @@ backgrounds. Default 0.8.} \item{seed}{(integer) Random seed. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Additional arguments passed to methods.} diff --git a/man/add_module_score.Rd b/man/add_module_score.Rd index 42ecd7b..685edc8 100644 --- a/man/add_module_score.Rd +++ b/man/add_module_score.Rd @@ -106,6 +106,9 @@ This function corresponds to ArchR's \code{addModuleScore()}. \item ArchR parameter \code{nBgd} maps to MarchR \code{n_background}. \item MarchR accepts any matrix assay (GeneScoreMatrix, RNA, etc.), while ArchR restricts to GeneScoreMatrix and TileMatrix. +\item When a module has no expression-matched background features (all of +its features are zero-signal), ArchR returns \code{NaN}, while MarchR +scores the module against all other features and warns. } } \section{Methods (by class)}{ diff --git a/man/add_peak2gene_links.Rd b/man/add_peak2gene_links.Rd index 0f66077..1ccd9bb 100644 --- a/man/add_peak2gene_links.Rd +++ b/man/add_peak2gene_links.Rd @@ -28,7 +28,7 @@ add_peak2gene_links(proj, ...) n_perm = 100L, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), overwrite = FALSE, ... ) @@ -77,7 +77,7 @@ dim reduction.} \item{seed}{(integer) Random seed for metacell sampling and p-value resampling. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{overwrite}{(logical) Replace an existing \code{peak2gene_links} result. Default FALSE.} } diff --git a/man/get_footprints.Rd b/man/get_footprints.Rd index 9ca61e8..034200f 100644 --- a/man/get_footprints.Rd +++ b/man/get_footprints.Rd @@ -18,7 +18,7 @@ dataset_name = NULL, bsgenome = NULL, min_chrom_distance = 50L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -51,7 +51,7 @@ proj$genome$sequence. Ignored when norm_method = "none".} \item{min_chrom_distance}{(integer) bp from chrom edge required beyond flank. Default 50L.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Unused.} } diff --git a/man/make_knn_pseudobulks.Rd b/man/make_knn_pseudobulks.Rd index c616a2b..d7829d8 100644 --- a/man/make_knn_pseudobulks.Rd +++ b/man/make_knn_pseudobulks.Rd @@ -11,7 +11,7 @@ make_knn_pseudobulks( overlap_cutoff = 0.8, knn_method = knn_hnsw(), seed = 1L, - verbose = getOption("MarchR.verbose", TRUE) + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -28,7 +28,7 @@ make_knn_pseudobulks( \item{seed}{(integer) Random seed for anchor sampling. Default 1L.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A list of character vectors (cell names per accepted group). diff --git a/man/peak_annotation_enrichment.Rd b/man/peak_annotation_enrichment.Rd index 3efd876..9a46a6b 100644 --- a/man/peak_annotation_enrichment.Rd +++ b/man/peak_annotation_enrichment.Rd @@ -12,7 +12,7 @@ matches = NULL, cutoff = "p_val_adj <= 0.1 & log2_fc >= 0.5", background = c("all", "background_peaks"), - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -34,7 +34,7 @@ to filter foreground peaks per group. Default \code{"background_peaks"} (GC/accessibility-matched peers via \code{add_background_peaks()}).} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{...}{Unused.} } diff --git a/tests/testthat/test-background-reference.R b/tests/testthat/test-background-reference.R index c240d38..123edfe 100644 --- a/tests/testthat/test-background-reference.R +++ b/tests/testthat/test-background-reference.R @@ -28,7 +28,8 @@ test_that("background consumers reject legacy and changed references", { proj <- add_background_peaks(proj, method = "bpcells", n_iterations = 3L, verbose = FALSE) bgd <- get_background_peaks(proj) expect_silent(MarchR:::.validate_background_reference(proj, bgd)) - expect_silent(add_background_peaks(proj, method = "bpcells", verbose = FALSE)) + expect_warning(add_background_peaks(proj, method = "bpcells", verbose = FALSE), + "Background peaks already exist") legacy <- bgd attr(legacy, "reference") <- NULL expect_error(MarchR:::.validate_background_reference(proj, legacy), "Re-run add_background_peaks") @@ -336,8 +337,10 @@ test_that("add_background_peaks warns when a method switch is ignored", { ) expect_identical(attr(get_background_peaks(kept), "method"), "bpcells") - expect_no_warning( - add_background_peaks(proj, method = "bpcells", n_iterations = 5L, verbose = FALSE) + expect_warning( + add_background_peaks(proj, method = "bpcells", n_iterations = 5L, verbose = FALSE), + "Background peaks already exist; set overwrite = TRUE to recompute.", + fixed = TRUE ) switched <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, diff --git a/tests/testthat/test-coaccessibility.R b/tests/testthat/test-coaccessibility.R index 9226126..c6cb569 100644 --- a/tests/testthat/test-coaccessibility.R +++ b/tests/testthat/test-coaccessibility.R @@ -35,6 +35,46 @@ test_that("add_co_accessibility finds the injected correlated peak pair", { expect_gt(max(hit$correlation), 0.8) }) +test_that("add_co_accessibility reports each step and its result", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_linkage_project() + run <- function(verbose) { + add_co_accessibility(proj, embedding_name = "IterativeLSI", k = 20L, knn_iteration = 40L, + seed = 1L, verbose = verbose) + } + + lines <- .strip_log(capture_messages(res <- run(TRUE))) + expect_length(lines, 6) + m <- sub("^Kept ([0-9]+) of 40 KNN groups after overlap pruning \\[Xs\\]$", "\\1", lines[2]) + expect_match(m, "^[0-9]+$") + expect_identical(lines, c( + "Co-accessibility: 120 cells on 'IterativeLSI' (5 dims), 10 peaks, max distance 100,000 bp", + sprintf("Kept %s of 40 KNN groups after overlap pruning [Xs]", m), + "Found 29 peak pairs within 100,000 bp [Xs]", + sprintf("Aggregated 10 peaks into %s metacells [Xs]", m), + "Correlated 29 peak pairs [Xs]", + "Co-accessibility finished [Xs]: added co_accessibility (29 peak pairs)" + )) + expect_identical(nrow(res$co_accessibility), 29L) + expect_false(any(grepl("HNSW", lines))) + expect_no_message(run(FALSE)) +}) + +test_that("add_co_accessibility warns and keeps an existing result without logging", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_linkage_project() + proj$co_accessibility <- data.frame(queryHits = 1L, subjectHits = 2L, correlation = 0.5) + + expect_no_message(expect_warning( + res <- add_co_accessibility(proj, embedding_name = "IterativeLSI", verbose = TRUE), + "co_accessibility already exists; set overwrite = TRUE to recompute.", + fixed = TRUE + )) + expect_identical(res$co_accessibility, proj$co_accessibility) + expect_warning(add_co_accessibility(proj, verbose = FALSE), "already exists") +}) + test_that("add_co_accessibility aligns indices when peak_set order differs from PeakMatrix", { skip_if_not_installed("GenomicRanges") proj <- create_test_linkage_project() diff --git a/tests/testthat/test-deviations.R b/tests/testthat/test-deviations.R index 6163735..d7e766b 100644 --- a/tests/testthat/test-deviations.R +++ b/tests/testthat/test-deviations.R @@ -711,11 +711,11 @@ test_that("add_deviations_matrix gives the same result in chunks of cells", { c(list(proj), args, list(overwrite = TRUE, verbose = FALSE))) whole <- add_deviations_matrix(p, "TestMotif", matrix_name = "Whole", overwrite = TRUE, verbose = FALSE) - expect_message( + msgs <- .strip_log(capture_messages( add_deviations_matrix(p, "TestMotif", matrix_name = "Progress", chunk_size = 3L, - overwrite = TRUE, verbose = TRUE), - "Cells 1-3 of 8" - ) + overwrite = TRUE, verbose = TRUE) + )) + expect_match(msgs, "Cells 1-3 of 8", all = FALSE) for (size in c(3L, 7L)) { chunked <- add_deviations_matrix(p, "TestMotif", matrix_name = "Chunked", chunk_size = size, overwrite = TRUE, verbose = FALSE) @@ -730,6 +730,185 @@ test_that("add_deviations_matrix gives the same result in chunks of cells", { } }) +deviations_fixture <- function(env = parent.frame()) { + proj <- background_reference_fixture() + withr::defer(unlink(proj$dir, recursive = TRUE), envir = env) + gr <- GenomicRanges::GRangesList( + A = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1002500)), + B = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2002500)) + ) + add_peak_annotations(proj, gr, name = "Test", verbose = FALSE) +} + +test_that("add_deviations_matrix checks every dataset for outputs before writing any", { + skip_if_not_installed("GenomicRanges") + proj <- deviations_fixture() + proj <- add_background_peaks(proj, method = "bpcells", n_iterations = 3L, verbose = FALSE) + + second <- add_deviations_matrix(proj, "Test", dataset_names = "dataset_2", verbose = FALSE) + expect_error( + add_deviations_matrix(second, "Test", verbose = FALSE), + "already exists on dataset 'dataset_2'" + ) + expect_false(dir.exists(file.path(proj$dir, "datasets", "dataset_1"))) + + both <- add_deviations_matrix(second, "Test", dataset_names = "dataset_1", verbose = FALSE) + expect_true(all(c("TestDeviations", "TestZScore") %in% names(both$datasets$dataset_1$matrices))) +}) + +test_that("add_deviations_matrix rejects unknown or repeated datasets before writing any", { + skip_if_not_installed("GenomicRanges") + proj <- deviations_fixture() + proj <- add_background_peaks(proj, method = "bpcells", n_iterations = 3L, verbose = FALSE) + + expect_error( + add_deviations_matrix(proj, "Test", dataset_names = c("dataset_1", "nope"), verbose = FALSE), + "Dataset(s) 'nope' not found or without a PeakMatrix.", fixed = TRUE + ) + expect_error( + add_deviations_matrix(proj, "Test", dataset_names = c("dataset_1", "dataset_1"), verbose = FALSE), + "must not contain duplicates" + ) + expect_false(dir.exists(file.path(proj$dir, "datasets"))) +}) + +test_that("add_deviations_matrix checks every dataset's rows and depths before writing any", { + skip_if_not_installed("GenomicRanges") + proj <- deviations_fixture() + zeroed <- proj + zeroed$datasets[[2]]$matrices$PeakMatrix <- BPCells::multiply_cols( + proj$datasets[[2]]$matrices$PeakMatrix, c(0, rep(1, 5)) + ) + zeroed <- add_background_peaks(zeroed, method = "bpcells", n_iterations = 3L, verbose = FALSE) + expect_error( + add_deviations_matrix(zeroed, "Test", verbose = FALSE), + "Dataset 'dataset_2' has 1 cell with zero peak counts." + ) + expect_false(dir.exists(file.path(proj$dir, "datasets", "dataset_1"))) + + # A dataset outside the background reference is only checked by the deviations pass. + trimmed <- deviations_fixture() + trimmed <- add_background_peaks(trimmed, method = "bpcells", n_iterations = 3L, + dataset_names = "dataset_1", verbose = FALSE) + trimmed$datasets[[2]]$matrices$PeakMatrix <- trimmed$datasets[[2]]$matrices$PeakMatrix[-1, ] + expect_error( + add_deviations_matrix(trimmed, "Test", verbose = FALSE), + "PeakMatrix rows do not describe the same peaks as the project peak set." + ) + expect_false(dir.exists(file.path(trimmed$dir, "datasets", "dataset_1"))) +}) + +deviations_log_pass <- function(ds, ...) { + c(sprintf("[%s]", ds), paste0(" ", c(...)), " Dataset finished [Xs]") +} + +test_that("add_deviations_matrix reports each dataset and chunk on a sampled background", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- deviations_fixture() + proj <- add_background_peaks(proj, method = "bpcells", n_iterations = 3L, verbose = FALSE) + run <- function(p, ...) add_deviations_matrix(p, "Test", overwrite = TRUE, ...) + setup <- "Deviations: 'Test' (2 motifs), 2 datasets, 10 cells, sampled background (3 iterations)" + checks <- c("Validated background reference (2 datasets) [Xs]", "Measured depth of 10 cells [Xs]") + wrote <- "Wrote 'TestDeviations' and 'TestZScore' [Xs]" + finished <- paste0( + "Deviations finished [Xs]: added assays 'TestDeviations', 'TestZScore' ", + "to 2 datasets (10 cells)" + ) + + lines <- .strip_log(capture_messages(run(proj, verbose = TRUE))) + expect_identical(lines, c( + setup, checks, + deviations_log_pass("dataset_1", "Computed deviations for 2 motifs x 4 cells [Xs]", wrote), + deviations_log_pass("dataset_2", "Computed deviations for 2 motifs x 6 cells [Xs]", wrote), + finished + )) + expect_length(lines, 12L) + + lines <- .strip_log(capture_messages(run(proj, chunk_size = 3L, verbose = TRUE))) + expect_identical(lines, c( + setup, checks, + deviations_log_pass( + "dataset_1", "Cells 1-3 of 4: computed deviations [Xs]", + "Cells 4-4 of 4: computed deviations [Xs]", wrote + ), + deviations_log_pass( + "dataset_2", "Cells 1-3 of 6: computed deviations [Xs]", + "Cells 4-6 of 6: computed deviations [Xs]", wrote + ), + finished + )) + expect_no_message(run(proj, chunk_size = 3L, verbose = FALSE)) + + row_major <- proj + for (ds in names(row_major$datasets)) { + row_major$datasets[[ds]]$matrices$PeakMatrix <- BPCells::transpose_storage_order( + row_major$datasets[[ds]]$matrices$PeakMatrix, outdir = file.path(withr::local_tempdir(), ds) + ) + } + expect_identical(BPCells::storage_order(row_major$datasets[[1]]$matrices$PeakMatrix), "row") + lines <- .strip_log(capture_messages(run(row_major, verbose = TRUE))) + expect_identical(lines, c( + setup, checks, + deviations_log_pass( + "dataset_1", "Transposed PeakMatrix storage order [Xs]", + "Computed deviations for 2 motifs x 4 cells [Xs]", wrote + ), + deviations_log_pass( + "dataset_2", "Transposed PeakMatrix storage order [Xs]", + "Computed deviations for 2 motifs x 6 cells [Xs]", wrote + ), + finished + )) + expect_no_message(run(row_major, verbose = FALSE)) +}) + +test_that("add_deviations_matrix reports an analytic background", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- deviations_fixture() + proj <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, w = 0.75, + verbose = FALSE) + + lines <- .strip_log(capture_messages(add_deviations_matrix(proj, "Test", verbose = TRUE))) + wrote <- "Wrote 'TestDeviations' and 'TestZScore' [Xs]" + expect_identical(lines, c( + "Deviations: 'Test' (2 motifs), 2 datasets, 10 cells, analytic background (36 bias bins)", + "Validated background reference (2 datasets) [Xs]", + "Measured depth of 10 cells [Xs]", + deviations_log_pass("dataset_1", "Computed deviations for 2 motifs x 4 cells [Xs]", wrote), + deviations_log_pass("dataset_2", "Computed deviations for 2 motifs x 6 cells [Xs]", wrote), + paste0( + "Deviations finished [Xs]: added assays 'TestDeviations', 'TestZScore' ", + "to 2 datasets (10 cells)" + ) + )) + expect_length(lines, 12L) + expect_no_message( + add_deviations_matrix(proj, "Test", chunk_size = 3L, overwrite = TRUE, verbose = FALSE) + ) +}) + +test_that("add_deviations_matrix aborts on existing outputs before logging", { + skip_if_not_installed("GenomicRanges") + proj <- deviations_fixture() + proj <- add_background_peaks(proj, method = "bpcells", n_iterations = 3L, verbose = FALSE) + done <- add_deviations_matrix(proj, "Test", verbose = FALSE) + + msgs <- character() + expect_error( + withCallingHandlers( + add_deviations_matrix(done, "Test", verbose = TRUE), + message = function(m) { + msgs <<- c(msgs, conditionMessage(m)) + invokeRestart("muffleMessage") + } + ), + "already exists on dataset 'dataset_1'" + ) + expect_identical(msgs, character(0)) +}) + test_that("add_deviations_matrix rejects an invalid chunk_size", { proj <- create_test_project_with_peaks() for (bad in list(0L, -5L, 2.5, "10", c(10L, 20L), NA_integer_, Inf, TRUE)) { diff --git a/tests/testthat/test-enrichment.R b/tests/testthat/test-enrichment.R index 17edc64..bf11a32 100644 --- a/tests/testthat/test-enrichment.R +++ b/tests/testthat/test-enrichment.R @@ -237,3 +237,116 @@ test_that("analytic background expands to the requested n_iterations", { expect_equal(ncol(MarchR:::.background_peak_indices(get_background_peaks(proj))), 11L) expect_equal(ncol(MarchR:::.background_peak_indices(get_background_peaks(proj), 3L)), 3L) }) + +test_that("add_background_peaks reports each step and its result", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- background_reference_fixture() + run <- function(verbose, ...) add_background_peaks(proj, ..., verbose = verbose) + + lines <- .strip_log(capture_messages(run(TRUE, method = "bpcells", n_iterations = 3L))) + expect_length(lines, 4) + expect_identical(lines, c( + "Background peaks: 10 peaks, bpcells, 3 iterations, 2 reference datasets", + "Summed peak counts over 2 datasets (10 cells) [Xs]", + "Matched 3 background peaks per peak by KNN [Xs]", + "Background peaks finished [Xs]: added background peaks (10 peaks x 3 iterations)" + )) + expect_false(any(grepl("HNSW", lines))) + expect_no_message(run(FALSE, method = "bpcells", n_iterations = 3L)) + + lines <- .strip_log(capture_messages(run(TRUE, method = "betterChromVAR", bin_size = 6L, w = 0.75))) + expect_length(lines, 4) + expect_identical(lines, c( + "Background peaks: 10 peaks, betterChromVAR, 6 x 6 bias bins, w = 0.75, 2 reference datasets", + "Summed peak counts over 2 datasets (10 cells) [Xs]", + "Built 36 bias bins (9 occupied) [Xs]", + "Background peaks finished [Xs]: added background bias bins (10 peaks in 36 bins)" + )) + expect_no_message(run(FALSE, method = "betterChromVAR", bin_size = 6L, w = 0.75)) +}) + +test_that("add_background_peaks reports the chromVAR sampling step", { + skip_if_not_installed("chromVAR") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- background_reference_fixture() + run <- function(verbose) { + add_background_peaks(proj, method = "chromVAR", n_iterations = 3L, bin_size = 6L, w = 0.75, + verbose = verbose) + } + + lines <- .strip_log(capture_messages(run(TRUE))) + expect_length(lines, 4) + expect_identical(lines, c( + "Background peaks: 10 peaks, chromVAR, 3 iterations, 2 reference datasets", + "Summed peak counts over 2 datasets (10 cells) [Xs]", + "Sampled 3 background peaks per peak (6 x 6 bias bins, w = 0.75) [Xs]", + "Background peaks finished [Xs]: added background peaks (10 peaks x 3 iterations)" + )) + expect_no_message(run(FALSE)) +}) + +test_that("add_background_peaks warns and keeps an existing background without logging", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- add_background_peaks(background_reference_fixture(), method = "bpcells", + n_iterations = 3L, verbose = FALSE) + + expect_no_message(expect_warning( + res <- add_background_peaks(proj, method = "bpcells", verbose = TRUE), + "Background peaks already exist; set overwrite = TRUE to recompute.", + fixed = TRUE + )) + expect_identical(res$background_peaks, proj$background_peaks) + expect_warning(add_background_peaks(proj, method = "bpcells", verbose = FALSE), "already exist") +}) + +test_that("peak_annotation_enrichment reports the groups tested and the tests run", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- analytic_enrichment_fixture("bpcells", n_iterations = 5L) + peak_keys <- MarchR:::.peak_set_keys(proj$peak_set) + marker_result <- structure( + list(results = tibble::tibble( + foreground = rep(paste0("C", 1:8), each = 2), + feature = rep(peak_keys[c(2, 4)], 8), + p_val_adj = rep(c(0.01, 0.5), c(2, 14)), + log2_fc = 1.5 + )), + class = c("MarkerResult", "list") + ) + run <- function(verbose, ...) { + peak_annotation_enrichment(proj, marker_result, "TestMotif", ..., verbose = verbose) + } + + lines <- .strip_log(capture_messages(res <- run(TRUE))) + expect_length(lines, 3) + expect_identical(lines, c( + "Peak annotation enrichment: 'TestMotif' (2 annotations), 8 groups, background all peaks (10)", + "Tested 1 group with marker peaks (C2, C3, C4, C5, C6, and 2 more had none) [Xs]", + "Peak annotation enrichment finished [Xs]: 2 tests (1 group x 2 annotations)" + )) + expect_identical(nrow(res), 2L) + expect_no_message(run(FALSE)) + + lines <- .strip_log(capture_messages(run(TRUE, background = "background_peaks"))) + expect_length(lines, 4) + expect_identical(lines, c( + paste("Peak annotation enrichment: 'TestMotif' (2 annotations), 8 groups,", + "background matched peaks (bpcells)"), + "Validated background reference (2 datasets) [Xs]", + "Tested 1 group with marker peaks (C2, C3, C4, C5, C6, and 2 more had none) [Xs]", + "Peak annotation enrichment finished [Xs]: 2 tests (1 group x 2 annotations)" + )) + expect_no_message(run(FALSE, background = "background_peaks")) + + lines <- .strip_log(capture_messages(peak_annotation_enrichment( + proj, marker_result, matches = get_matches(proj, "TestMotif"), verbose = TRUE + ))) + expect_identical( + lines[1], + "Peak annotation enrichment: supplied matches (2 annotations), 8 groups, background all peaks (10)" + ) + + marker_result$results <- marker_result$results[1:2, ] + lines <- .strip_log(capture_messages(run(TRUE))) + expect_identical(lines[2], "Tested 1 group with marker peaks [Xs]") +}) diff --git a/tests/testthat/test-footprinting.R b/tests/testthat/test-footprinting.R index 10c6318..e9c0621 100644 --- a/tests/testthat/test-footprinting.R +++ b/tests/testthat/test-footprinting.R @@ -1,3 +1,24 @@ +create_footprint_test_project <- function() { + proj <- create_test_project(include_fragments = TRUE) + ds1_cells <- cell_names(proj)[["dataset_1"]] + all_cells <- unlist(cell_names(proj), use.names = FALSE) + groups <- setNames(rep(NA_character_, length(all_cells)), all_cells) + groups[ds1_cells] <- rep(c("A", "B"), length.out = length(ds1_cells)) + proj <- add_group_coverages( + proj, group_by = groups, min_cells = 2L, min_replicates = 2L, + max_replicates = 2L, sample_ratio = 1, verbose = FALSE + ) + proj$genome$chromosome_size <- tibble::tibble(chr = "chr1", start = 0, end = 1000L) + proj +} + +create_footprint_test_genome <- function() { + withr::local_seed(42) + Biostrings::DNAStringSet( + c(chr1 = paste(sample(c("A", "C", "G", "T"), 1000L, replace = TRUE), collapse = "")) + ) +} + test_that(".kmers returns lex-ordered k-mer strings of length 4^k", { ks <- MarchR:::.kmers(1L) expect_equal(ks, c("A", "C", "G", "T")) @@ -86,6 +107,52 @@ test_that("add_kmer_bias populates observed and expected with correct shapes", { expect_true(all(colSums(kb$observed) > 0)) }) +test_that("add_kmer_bias reports each replicate and the stored table", { + skip_if_not_installed("Biostrings") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_footprint_test_project() + # dataset_2 cells have no fragments in dataset_1, so this replicate is empty. + proj$group_coverages$custom_groups$C <- list(Rep1 = cell_names(proj)[["dataset_2"]]) + bsg <- create_footprint_test_genome() + run <- function(verbose, n_sample = 30L) { + add_kmer_bias( + proj, group_by = "custom_groups", k = 2L, n_sample = n_sample, + bsgenome = bsg, dataset_name = "dataset_1", verbose = verbose + ) + } + + lines <- .strip_log(capture_messages(res <- run(TRUE))) + expect_length(lines, 8) + expect_identical(lines, c( + "K-mer bias: 'custom_groups', 5 replicates in 3 groups, k = 2, up to 30 insertions each", + "Counted 2-mers over 1 genome sequence [Xs]", + paste0(c("A.Rep1", "A.Rep2", "B.Rep1", "B.Rep2"), ": counted 2-mers at 30 of 52 insertions [Xs]"), + "C.Rep1: no cells, skipped", + "K-mer bias finished [Xs]: added k-mer bias 'custom_groups' (16 k-mers x 5 replicates)" + )) + expect_identical(dim(res$kmer_bias$custom_groups$observed), c(16L, 5L)) + expect_identical( + .strip_log(capture_messages(run(TRUE, n_sample = NULL)))[c(1, 3)], + c("K-mer bias: 'custom_groups', 5 replicates in 3 groups, k = 2, all insertions", + "A.Rep1: counted 2-mers at 52 of 52 insertions [Xs]") + ) + expect_no_message(run(FALSE)) +}) + +test_that("add_kmer_bias warns and keeps an existing entry without logging", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_footprint_test_project() + proj$kmer_bias[["custom_groups"]] <- list(k = 2L) + + expect_no_message(expect_warning( + res <- add_kmer_bias(proj, group_by = "custom_groups", verbose = TRUE), + "kmer_bias[['custom_groups']] already exists; set overwrite = TRUE to recompute.", + fixed = TRUE + )) + expect_identical(res$kmer_bias, proj$kmer_bias) + expect_warning(add_kmer_bias(proj, group_by = "custom_groups", verbose = FALSE), "already exists") +}) + test_that("get_kmer_bias auto-selects single entry, errors on ambiguity", { proj <- MarchRProject(dir = tempdir()) proj$kmer_bias[["clusters"]] <- list(observed = NULL, expected = NULL, k = 6L) @@ -188,6 +255,73 @@ test_that("get_footprints with norm_method='subtract' populates bias rows", { expect_true(all(abs(colSums(bias_assay) - 1) < 1e-9)) }) +test_that("get_footprints reports each motif and the footprint table", { + skip_if_not_installed("SummarizedExperiment") + skip_if_not_installed("Biostrings") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_footprint_test_project() + bsg <- create_footprint_test_genome() + proj <- add_kmer_bias( + proj, group_by = "custom_groups", k = 2L, n_sample = NULL, + bsgenome = bsg, dataset_name = "dataset_1", verbose = FALSE + ) + positions <- GenomicRanges::GRangesList( + motif1 = GenomicRanges::GRanges( + "chr1", IRanges::IRanges(start = c(100L, 200L), end = c(110L, 210L)), strand = "+" + ), + motif2 = GenomicRanges::GRanges("chr1", IRanges::IRanges(start = 300L, end = 310L), strand = "+") + ) + run <- function(verbose, norm_method = "subtract") { + get_footprints( + proj, positions = positions, group_by = "custom_groups", + flank = 50L, norm_method = norm_method, min_cells = 1L, + min_chrom_distance = 10L, dataset_name = "dataset_1", + bsgenome = bsg, verbose = verbose + ) + } + + lines <- .strip_log(capture_messages(se <- run(TRUE))) + expect_length(lines, 4) + expect_identical(lines, c( + "Footprints: 2 motifs, 4 replicates ('custom_groups'), flank 50 bp, bias-normalized (subtract)", + "motif1: footprinted 2 positions [Xs]", + "motif2: footprinted 1 position [Xs]", + "Footprints finished [Xs]: 2 motif footprints x 4 replicates" + )) + expect_identical(dim(se), c(202L, 4L)) + expect_identical( + .strip_log(capture_messages(run(TRUE, "none")))[1], + "Footprints: 2 motifs, 4 replicates ('custom_groups'), flank 50 bp, not normalized" + ) + expect_no_message(run(FALSE)) +}) + +test_that("get_footprints reports motifs dropped by the chromosome-edge filter", { + skip_if_not_installed("SummarizedExperiment") + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_footprint_test_project() + positions <- GenomicRanges::GRangesList( + valid = GenomicRanges::GRanges("chr1", IRanges::IRanges(start = 100L, end = 110L), strand = "+"), + edge = GenomicRanges::GRanges("chr1", IRanges::IRanges(start = 30L, end = 40L), strand = "+"), + other_chr = GenomicRanges::GRanges("chr2", IRanges::IRanges(start = 100L, end = 110L), strand = "+") + ) + + lines <- .strip_log(capture_messages(se <- get_footprints( + proj, positions = positions, group_by = "custom_groups", + flank = 50L, norm_method = "none", min_cells = 1L, + min_chrom_distance = 10L, dataset_name = "dataset_1", verbose = TRUE + ))) + expect_length(lines, 4) + expect_identical(lines, c( + "Footprints: 1 motif, 4 replicates ('custom_groups'), flank 50 bp, not normalized", + "Dropped 2 motifs with no positions more than 60 bp from chromosome ends: edge, other_chr", + "valid: footprinted 1 position [Xs]", + "Footprints finished [Xs]: 1 motif footprint x 4 replicates" + )) + expect_identical(names(SummarizedExperiment::assays(se)), "valid") +}) + test_that("get_footprints errors when norm_method != 'none' and kmer_bias missing", { skip_if_not_installed("GenomicRanges") proj <- create_test_project(include_fragments = TRUE) diff --git a/tests/testthat/test-linkage.R b/tests/testthat/test-linkage.R index a76cd91..fdc0f88 100644 --- a/tests/testthat/test-linkage.R +++ b/tests/testthat/test-linkage.R @@ -221,12 +221,22 @@ test_that(".make_linkage_loops returns an empty GRanges for zero-row links", { expect_equal(length(gr), 0L) }) -test_that("make_knn_pseudobulks reports overlap pruning through log_progress", { +test_that("make_knn_pseudobulks reports its setup, pruning step and metacells", { + withr::local_options(rlib_message_verbosity = "verbose") set.seed(1) emb <- matrix(rnorm(200 * 5), nrow = 200, ncol = 5) rownames(emb) <- paste0("cell_", seq_len(200)) - expect_message( - make_knn_pseudobulks(emb, knn_iteration = 50L, k = 20L, seed = 1L, verbose = TRUE), - "[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9:]{8} Kept [0-9]+ of 50 KNN groups" - ) + run <- function(verbose) { + make_knn_pseudobulks(emb, knn_iteration = 50L, k = 20L, seed = 1L, verbose = verbose) + } + + lines <- .strip_log(capture_messages(groups <- run(TRUE))) + expect_length(lines, 3) + expect_identical(lines, c( + "KNN metacells: 200 cells, 5 dims, 50 anchors x 20 neighbors", + sprintf("Kept %d of 50 KNN groups after overlap pruning [Xs]", length(groups)), + sprintf("KNN metacells finished [Xs]: %d metacells", length(groups)) + )) + expect_false(any(grepl("HNSW", lines))) + expect_no_message(run(FALSE)) }) diff --git a/tests/testthat/test-markers.R b/tests/testthat/test-markers.R index 576570f..7d335cb 100644 --- a/tests/testthat/test-markers.R +++ b/tests/testthat/test-markers.R @@ -556,7 +556,7 @@ test_that(".match_bias_cell_groups returns matched cells from correct groups", { k = 50L, max_cells = 100L, buffer_ratio = 0.8, - knn_method = BPCells::knn_hnsw(k = 50L), + knn_method = BPCells::knn_hnsw(k = 50L, verbose = FALSE), seed = 1L ) @@ -595,7 +595,7 @@ test_that(".match_bias_cell_groups respects max_cells", { k = 50L, max_cells = 50L, buffer_ratio = 0.8, - knn_method = BPCells::knn_hnsw(k = 50L), + knn_method = BPCells::knn_hnsw(k = 50L, verbose = FALSE), seed = 1L ) @@ -653,6 +653,25 @@ test_that("add_marker_features with bias matching returns valid MarkerResult", { expect_true(all(is.finite(mr$results$log2_fc))) }) +test_that("add_marker_features warns when norm_by names a missing metadata column", { + skip_if_not_installed("RcppHNSW") + test_data <- create_bias_marker_test_project() + dataset <- test_data$proj$datasets[["demo"]] + mat <- get_matrix(dataset, assay_name = "GeneScoreMatrix") + groups <- MarchR:::.resolve_groups(dataset, "cluster") + cell_metadata <- MarchR:::.collect_bias_metadata_dataset(dataset) + run <- function(norm_by) { + add_marker_features( + mat, group_by = groups, cell_metadata = cell_metadata, norm_by = norm_by, + knn_method = BPCells::knn_hnsw(k = 50L), verbose = FALSE + ) + } + + expect_warning(run("not_a_column"), "norm_by column 'not_a_column' not in cell metadata") + expect_no_warning(run(NULL)) + expect_no_warning(run("none")) +}) + test_that("add_marker_features with bias=NULL gives one-vs-all behavior", { test_data <- create_bias_marker_test_project() @@ -670,6 +689,96 @@ test_that("add_marker_features with bias=NULL gives one-vs-all behavior", { expect_true(all(is.na(mr$results$background))) }) +test_that("add_marker_features.MarchRProject reports its setup, per-group tests and result", { + skip_if_not_installed("RcppHNSW") + withr::local_options(rlib_message_verbosity = "verbose") + test_data <- create_bias_marker_test_project() + run <- function(verbose, bias = c("TSSEnrichment", "log10(nFrags)")) { + add_marker_features( + test_data$proj, group_by = "cluster", assay_name = "GeneScoreMatrix", bias = bias, + knn_method = BPCells::knn_hnsw(k = 50L), verbose = verbose + ) + } + n_cells <- formatC(length(test_data$cluster_labels), format = "d", big.mark = ",") + + lines <- .strip_log(capture_messages(run(TRUE))) + expect_length(lines, 7L) + expect_identical(lines[c(1:3, 7)], c( + paste0( + "Marker features: 'GeneScoreMatrix' (5 features), 1 dataset, ", n_cells, " cells, 3 groups, ", + "bias-matched on TSSEnrichment, log10(nFrags)" + ), + paste0("Normalized ", n_cells, " cells to 10,000 counts [Xs]"), + "Matched bias backgrounds for 3 groups [Xs]", + "Marker features finished [Xs]: added marker features 'GeneScoreMatrix' (5 features x 3 groups)" + )) + for (i in 1:3) { + expect_match(lines[3 + i], sprintf("^%s: tested 5 features, [0-9]+ vs [0-9]+ cells \\[Xs\\]$", + LETTERS[i]), perl = TRUE) + } + expect_false(any(grepl("HNSW", lines))) + + expect_identical(.strip_log(capture_messages(run(TRUE, bias = NULL))), c( + paste0( + "Marker features: 'GeneScoreMatrix' (5 features), 1 dataset, ", n_cells, " cells, 3 groups, ", + "one-vs-all" + ), + "Tested 5 features across 3 groups [Xs]", + "Marker features finished [Xs]: added marker features 'GeneScoreMatrix' (5 features x 3 groups)" + )) + + expect_no_message(run(FALSE)) + expect_no_message(run(FALSE, bias = NULL)) +}) + +test_that("add_marker_features.default reports per-group tests and skips unmatched groups", { + skip_if_not_installed("RcppHNSW") + withr::local_options(rlib_message_verbosity = "verbose") + test_data <- create_bias_marker_test_project() + dataset <- test_data$proj$datasets[["demo"]] + # Column-major input makes BPCells::marker_features emit its transpose notices + mat <- BPCells::transpose_storage_order( + get_matrix(dataset, assay_name = "GeneScoreMatrix"), outdir = withr::local_tempfile() + ) + groups <- MarchR:::.resolve_groups(dataset, "cluster") + groups[1] <- "D" + cell_metadata <- MarchR:::.collect_bias_metadata_dataset(dataset) + run <- function(verbose, bias = c("TSSEnrichment", "log10(nFrags)")) { + add_marker_features( + mat, group_by = groups, cell_metadata = cell_metadata, bias = bias, + knn_method = BPCells::knn_hnsw(k = 50L), verbose = verbose + ) + } + n_cells <- formatC(ncol(mat), format = "d", big.mark = ",") + + lines <- .strip_log(capture_messages(run(TRUE))) + expect_length(lines, 8L) + expect_identical(lines[c(1:3, 7:8)], c( + paste0( + "Marker features: 5 features x ", n_cells, " cells, 4 groups, ", + "bias-matched on TSSEnrichment, log10(nFrags)" + ), + paste0("Normalized ", n_cells, " cells to 10,000 counts [Xs]"), + "Matched bias backgrounds for 4 groups [Xs]", + "D: no bias-matched background cells, skipped", + "Marker features finished [Xs]: 5 x 3 marker table" + )) + for (i in 1:3) { + expect_match(lines[3 + i], sprintf("^%s: tested 5 features, [0-9]+ vs [0-9]+ cells \\[Xs\\]$", + LETTERS[i]), perl = TRUE) + } + expect_false(any(grepl("HNSW", lines))) + + expect_identical(.strip_log(capture_messages(run(TRUE, bias = NULL))), c( + paste0("Marker features: 5 features x ", n_cells, " cells, 4 groups, one-vs-all"), + "Tested 5 features across 4 groups [Xs]", + "Marker features finished [Xs]: 5 x 4 marker table" + )) + + expect_no_message(run(FALSE)) + expect_no_message(run(FALSE, bias = NULL)) +}) + test_that("add_marker_features.default with bias matching works directly", { test_data <- create_bias_marker_test_project() dataset <- test_data$proj$datasets[["demo"]] diff --git a/tests/testthat/test-module_scores.R b/tests/testthat/test-module_scores.R index b0ef08e..745e8db 100644 --- a/tests/testthat/test-module_scores.R +++ b/tests/testthat/test-module_scores.R @@ -129,13 +129,17 @@ test_that("add_module_score.MarchRDataset scores have expected properties", { features <- list(All = c("GENE_A", "GENE_B", "GENE_C", "GENE_D", "GENE_E")) - result <- add_module_score( - dataset, - features = features, - assay_name = "GeneScoreMatrix", - name = "Test", - n_bins = 1L, - n_background = 1L + expect_warning( + result <- add_module_score( + dataset, + features = features, + assay_name = "GeneScoreMatrix", + name = "Test", + n_bins = 1L, + n_background = 1L + ), + "Module 'All': no expression-matched background features", + fixed = TRUE ) meta <- get_cell_metadata(result) @@ -186,20 +190,54 @@ test_that("add_module_score.MarchRDataset warns and skips missing features", { features <- list(Partial = c("GENE_A", "NONEXISTENT")) - # Should succeed with verbose logging about missing feature - result <- add_module_score( - dataset, - features = features, - assay_name = "GeneScoreMatrix", - n_bins = 1L, - n_background = 1L, - verbose = TRUE + # Should succeed with a warning about the missing feature + expect_warning( + result <- add_module_score( + dataset, + features = features, + assay_name = "GeneScoreMatrix", + n_bins = 1L, + n_background = 1L + ), + "Module 'Partial': 1 of 2 features not in 'GeneScoreMatrix' (NONEXISTENT); scored the rest.", + fixed = TRUE ) meta <- get_cell_metadata(result) expect_true("Module.Partial" %in% colnames(meta)) }) +test_that("add_module_score.MarchRDataset names at most 5 missing features", { + features <- list(A = c("gene_1", paste0("MISSING_", 1:7))) + expect_warning( + add_module_score(test_dataset, features, assay_name = "RNA", n_bins = 1L, n_background = 1L), + paste0( + "Module 'A': 7 of 8 features not in 'RNA' (MISSING_1, MISSING_2, MISSING_3, MISSING_4, ", + "MISSING_5, and 2 more); scored the rest." + ), + fixed = TRUE + ) +}) + +test_that("add_module_score.MarchRDataset reports its setup, steps and columns", { + withr::local_options(rlib_message_verbosity = "verbose") + features <- list(A = "gene_1", B = c("gene_4", "gene_5")) + run <- function(...) { + add_module_score(test_dataset, features, assay_name = "RNA", n_bins = 1L, n_background = 2L, ...) + } + + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_identical(lines, c( + "Module scores: 2 modules on 'RNA' (5 features x 5 cells), 1 bin, 2 background features each", + "Computed means for 5 features [Xs]", + "A: scored 1 feature against 2 background features [Xs]", + "B: scored 2 features against 3 background features [Xs]", + "Module scores finished [Xs]: added cell metadata columns 'Module.A', 'Module.B'" + )) + expect_length(lines, 5L) + expect_no_message(run(verbose = FALSE)) +}) + test_that("add_module_score.MarchRDataset errors on invalid features input", { proj <- create_module_score_test_project() dataset <- proj$datasets[["demo"]] @@ -234,6 +272,22 @@ test_that("add_module_score.MarchRDataset validates background bin size", { ) }) +test_that("add_module_score.MarchRDataset warns when a module falls back to all background features", { + rna <- as(test_dataset$matrices$RNA, "dgCMatrix") + rna["gene_5", ] <- 0 + dataset <- test_dataset + dataset$matrices$RNA <- as(rna, "IterableMatrix") + + expect_warning( + result <- add_module_score( + dataset, features = list(Z = "gene_5"), assay_name = "RNA", n_bins = 1L, n_background = 1L + ), + "Module 'Z': no expression-matched background features; scored against all other features.", + fixed = TRUE + ) + expect_true(all(is.finite(get_cell_metadata(result)$Module.Z))) +}) + test_that("add_module_score.MarchRDataset respects overwrite", { proj <- create_module_score_test_project() dataset <- proj$datasets[["demo"]] @@ -358,13 +412,16 @@ test_that("add_module_score.MarchRProject works with multi-dataset project", { features <- list(Score = c("GENE_A", "GENE_C")) - result <- add_module_score( + warns <- capture_warnings(result <- add_module_score( proj, features = features, assay_name = "GeneScoreMatrix", n_bins = 1L, n_background = 1L - ) + )) + expect_identical(warns, rep(paste( + "Module 'Score': no expression-matched background features;", "scored against all other features." + ), 2L)) meta_ds1 <- get_cell_metadata(result, dataset_name = "ds1", add_dataset_column = FALSE) meta_ds2 <- get_cell_metadata(result, dataset_name = "ds2", add_dataset_column = FALSE) @@ -372,6 +429,65 @@ test_that("add_module_score.MarchRProject works with multi-dataset project", { expect_true("Module.Score" %in% colnames(meta_ds2)) }) +test_that("add_module_score.MarchRProject reports each dataset as a pass", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- test_project + rna <- as(proj$datasets$dataset_1$matrices$RNA, "dgCMatrix") + rna["gene_5", ] <- 0 + proj$datasets$dataset_1$matrices$RNA <- as(rna, "IterableMatrix") + features <- list(A = "gene_1", B = c("gene_2", "gene_3")) + run <- function(...) { + add_module_score(proj, features, assay_name = "RNA", n_bins = 1L, n_background = 1L, ...) + } + pass <- function(ds, means, b_background) { + c( + sprintf("[%s]", ds), paste0(" ", means), + " A: scored 1 feature against 1 background feature [Xs]", + sprintf(" B: scored 2 features against %s [Xs]", b_background), " Dataset finished [Xs]" + ) + } + + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_identical(lines, c( + "Module scores: 2 modules on 'RNA', 3 datasets, 16 cells", + pass("dataset_1", "Computed means for 5 features, excluded 1 zero-signal feature [Xs]", + "2 background features"), + pass("dataset_2", "Computed means for 5 features [Xs]", "2 background features"), + pass("dataset_3", "Computed means for 5 features [Xs]", "2 background features"), + paste0( + "Module scores finished [Xs]: added cell metadata columns 'Module.A', 'Module.B' ", + "to 3 datasets (16 cells)" + ) + )) + expect_length(lines, 17L) + expect_no_message(run(verbose = FALSE)) +}) + +test_that("add_module_score.MarchRProject names a single column in the singular", { + withr::local_options(rlib_message_verbosity = "verbose") + lines <- .strip_log(capture_messages(add_module_score( + test_project, list(A = "gene_1"), assay_name = "RNA", n_bins = 1L, n_background = 1L, + verbose = TRUE + ))) + expect_identical( + lines[length(lines)], + "Module scores finished [Xs]: added cell metadata column 'Module.A' to 3 datasets (16 cells)" + ) +}) + +test_that("add_module_score.MarchRProject warns once per module for missing features", { + features <- list(A = c("gene_1", "GENE_X", "GENE_Y"), B = "gene_2") + run <- function() { + add_module_score(test_project, features, assay_name = "RNA", n_bins = 1L, n_background = 1L) + } + expected <- "Module 'A': 2 of 3 features not in 'RNA' (GENE_X, GENE_Y); scored the rest." + + expect_warning(result <- run(), expected, fixed = TRUE) + expect_identical(capture_warnings(run()), expected) + meta <- get_cell_metadata(result, dataset_name = "dataset_3", add_dataset_column = FALSE) + expect_true(all(c("Module.A", "Module.B") %in% colnames(meta))) +}) + ######################################################################## # Integration: end-to-end module score workflow diff --git a/tests/testthat/test-peak2gene.R b/tests/testthat/test-peak2gene.R index 5c10b0f..5dd62b7 100644 --- a/tests/testthat/test-peak2gene.R +++ b/tests/testthat/test-peak2gene.R @@ -218,13 +218,113 @@ test_that("get_peak2gene_links loops connect peak summit to gene TSS", { test_that("add_peak2gene_links skips prediction filtering when predictedScore is absent", { skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") proj <- create_test_linkage_project() proj <- remove_cell_metadata(proj, "predictedScore") expect_false("predictedScore" %in% colnames(get_cell_metadata(proj))) - proj <- add_peak2gene_links(proj, embedding_name = "IterativeLSI", - use_matrix = "GeneIntegrationMatrix", - k = 20L, knn_iteration = 40L, seed = 1L, verbose = FALSE) - expect_s3_class(proj$peak2gene_links, "data.frame") - expect_gt(nrow(proj$peak2gene_links), 0L) + run <- function(verbose) { + add_peak2gene_links(proj, embedding_name = "IterativeLSI", use_matrix = "GeneIntegrationMatrix", + k = 20L, knn_iteration = 40L, seed = 1L, verbose = verbose) + } + + expect_warning( + lines <- .strip_log(capture_messages(res <- run(TRUE))), + "No 'predictedScore' column; prediction_cutoff not applied.", + fixed = TRUE + ) + expect_length(lines, 7) + expect_false(any(grepl("predictedScore", lines))) + expect_match(lines[2], "^Kept [0-9]+ of 40 KNN groups after overlap pruning \\[Xs\\]$") + expect_s3_class(res$peak2gene_links, "data.frame") + expect_gt(nrow(res$peak2gene_links), 0L) + expect_warning(expect_no_message(run(FALSE)), "predictedScore") +}) + +test_that("add_peak2gene_links logs the missing predictedScore for a non-integration matrix", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_linkage_project() + proj <- remove_cell_metadata(proj, "predictedScore") + proj <- add_matrix(proj, proj[["GeneIntegrationMatrix", "dataset_1"]], "GeneExpressionMatrix", + dataset_name = "dataset_1", prefix_cells = FALSE) + run <- function(verbose) { + add_peak2gene_links(proj, embedding_name = "IterativeLSI", use_matrix = "GeneExpressionMatrix", + k = 20L, knn_iteration = 40L, seed = 1L, verbose = verbose) + } + + expect_no_warning(lines <- .strip_log(capture_messages(res <- run(TRUE)))) + expect_length(lines, 8) + expect_match(lines[1], "'PeakMatrix' x 'GeneExpressionMatrix'", fixed = TRUE) + expect_identical(lines[2], "No 'predictedScore' column; prediction_cutoff not applied") + expect_match(lines[3], "^Kept [0-9]+ of 40 KNN groups after overlap pruning \\[Xs\\]$") + expect_gt(nrow(res$peak2gene_links), 0L) + expect_no_warning(expect_no_message(run(FALSE))) +}) + +test_that("add_peak2gene_links reports each step and its result", { + skip_if_not_installed("GenomicRanges") + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_linkage_project() + n_scored <- sum(get_cell_metadata(proj)$predictedScore >= 0.75) + run <- function(verbose, ...) { + add_peak2gene_links(proj, embedding_name = "IterativeLSI", k = 20L, knn_iteration = 40L, + prediction_cutoff = 0.75, seed = 1L, verbose = verbose, ...) + } + + lines <- .strip_log(capture_messages(res <- run(TRUE))) + expect_length(lines, 8) + m <- sub("^Kept ([0-9]+) of 40 KNN groups after overlap pruning \\[Xs\\]$", "\\1", lines[3]) + expect_match(m, "^[0-9]+$") + expect_identical(lines, c( + paste0( + "Peak-to-gene links: 120 cells on 'IterativeLSI' (5 dims), ", + "'PeakMatrix' x 'GeneIntegrationMatrix', max distance 250,000 bp" + ), + sprintf("Kept %d of 120 cells with predictedScore >= 0.75", n_scored), + sprintf("Kept %s of 40 KNN groups after overlap pruning [Xs]", m), + "Found 24 peak-gene pairs within 250,000 bp of a TSS (3 genes) [Xs]", + sprintf("Aggregated 10 peaks into %s metacells [Xs]", m), + sprintf("Aggregated 3 genes into %s metacells [Xs]", m), + "Correlated 24 peak-gene pairs [Xs]", + "Peak-to-gene links finished [Xs]: added peak2gene_links (24 pairs)" + )) + expect_identical(nrow(res$peak2gene_links), 24L) + expect_false(any(grepl("HNSW", lines))) + expect_no_message(run(FALSE)) + + lines <- .strip_log(capture_messages( + run(TRUE, add_empirical_pval = TRUE, add_permuted_pval = TRUE, n_perm = 5L) + )) + expect_length(lines, 10) + expect_identical(lines[8:10], c( + "Computed empirical p-values from a trans-chromosome null [Xs]", + "Computed permuted p-values from 5 permutations [Xs]", + "Peak-to-gene links finished [Xs]: added peak2gene_links (24 pairs)" + )) + expect_false(any(grepl("HNSW", lines))) + expect_no_message(run(FALSE, add_empirical_pval = TRUE, add_permuted_pval = TRUE, n_perm = 5L)) + + meta <- get_cell_metadata(proj) + subset_cells <- rownames(meta)[1:70] + n_subset_scored <- sum(meta[subset_cells, "predictedScore"] >= 0.75) + lines <- .strip_log(capture_messages(run(TRUE, cells_to_use = c(subset_cells, "not_a_cell")))) + expect_match(lines[1], "^Peak-to-gene links: 70 cells on 'IterativeLSI' \\(5 dims\\), ") + expect_identical( + lines[2], sprintf("Kept %d of 70 cells with predictedScore >= 0.75", n_subset_scored) + ) +}) + +test_that("add_peak2gene_links warns and keeps an existing result without logging", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_linkage_project() + proj$peak2gene_links <- data.frame(idxATAC = 1L, idxRNA = 1L, Correlation = 0.5) + + expect_no_message(expect_warning( + res <- add_peak2gene_links(proj, embedding_name = "IterativeLSI", verbose = TRUE), + "peak2gene_links already exists; set overwrite = TRUE to recompute.", + fixed = TRUE + )) + expect_identical(res$peak2gene_links, proj$peak2gene_links) + expect_warning(add_peak2gene_links(proj, verbose = FALSE), "already exists") }) From fee89ec591559bed830c737c7fe8777debdfa321 Mon Sep 17 00:00:00 2001 From: erliuu Date: Fri, 23 Oct 2026 02:11:07 -0700 Subject: [PATCH 10/12] feat([r] logging): Add footprinting logging update --- R/footprinting.R | 87 ++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 69 insertions(+), 18 deletions(-) diff --git a/R/footprinting.R b/R/footprinting.R index f312d57..3597e5e 100644 --- a/R/footprinting.R +++ b/R/footprinting.R @@ -84,7 +84,7 @@ #' @param threads (integer) Parallelism over replicates. Default 1L. #' @param seed (integer) Random seed. Default 1L. #' @param overwrite (logical) Replace existing entry. Default FALSE. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Unused. #' #' @return Modified MarchRProject with `proj$kmer_bias[[group_by]]` populated. @@ -114,10 +114,11 @@ add_kmer_bias.MarchRProject <- function( threads = 1L, seed = 1L, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") reps <- proj$group_coverages[[group_by]] if (is.null(reps) || length(reps) == 0L) { @@ -127,8 +128,8 @@ add_kmer_bias.MarchRProject <- function( )) } if (!is.null(proj$kmer_bias[[group_by]]) && !overwrite) { - if (verbose) log_progress(sprintf( - "kmer_bias[['%s']] already populated. Use overwrite = TRUE to recompute.", group_by + rlang::warn(sprintf( + "kmer_bias[['%s']] already exists; set overwrite = TRUE to recompute.", group_by )) return(proj) } @@ -146,7 +147,16 @@ add_kmer_bias.MarchRProject <- function( } } - if (verbose) log_progress("Computing expected k-mer frequencies (genome-wide)...") + if (verbose) { + run <- .log_start("K-mer bias", sprintf( + "'%s', %s in %s, k = %d, %s", group_by, .log_plural(length(rep_cells), "replicate"), + .log_plural(length(reps), "group"), k, + if (is.null(n_sample)) "all insertions" else + sprintf("up to %s insertions each", .log_count(n_sample)) + )) + } + + t0 <- steady_clock_seconds_rcpp() chrs <- if (methods::is(bsgenome, "BSgenome")) { GenomicRanges::seqnames(bsgenome) } else { @@ -159,10 +169,12 @@ add_kmer_bias.MarchRProject <- function( })) # Lock name order to .kmers(k) so downstream sweep() against observed aligns by index. expected <- expected[.kmers(k)] + if (verbose) { + .log_step(sprintf( + "Counted %d-mers over %s", k, .log_plural(length(chrs), "genome sequence") + ), since = t0) + } - if (verbose) log_progress(sprintf( - "Computing observed k-mers for %d replicates...", length(rep_cells) - )) set.seed(seed) observed <- matrix( 0, nrow = 4L^k, ncol = length(rep_cells), @@ -171,9 +183,14 @@ add_kmer_bias.MarchRProject <- function( for (rep_name in names(rep_cells)) { cells <- rep_cells[[rep_name]] - if (length(cells) == 0L) next + if (length(cells) == 0L) { + if (verbose) .log_step(paste0(rep_name, ": no cells, skipped")) + next + } + t0 <- steady_clock_seconds_rcpp() frags_r <- select_cells(fragments, cells) insertions <- .collect_insertions(frags_r) + n_total <- length(insertions) if (!is.null(n_sample) && length(insertions) > n_sample) { insertions <- insertions[sample(length(insertions), n_sample)] } @@ -183,6 +200,12 @@ add_kmer_bias.MarchRProject <- function( observed[, rep_name] <- as.integer( Biostrings::oligonucleotideFrequency(seqs, width = k, simplify.as = "collapsed") ) + if (verbose) { + .log_step(sprintf( + "%s: counted %d-mers at %s of %s", rep_name, k, .log_count(length(insertions)), + .log_plural(n_total, "insertion") + ), since = t0) + } } proj$kmer_bias[[group_by]] <- list( @@ -197,10 +220,12 @@ add_kmer_bias.MarchRProject <- function( date = Sys.Date() ) - if (verbose) log_progress(sprintf( - "Stored kmer_bias[['%s']]: %d k-mers x %d replicates", - group_by, nrow(observed), ncol(observed) - )) + if (verbose) { + .log_finish(run, sprintf( + "added k-mer bias '%s' (%s x %s)", group_by, .log_plural(nrow(observed), "k-mer"), + .log_plural(ncol(observed), "replicate") + )) + } proj } @@ -287,7 +312,7 @@ get_kmer_bias.MarchRProject <- function(proj, group_by = character(0), ...) { #' proj$genome$sequence. Ignored when norm_method = "none". #' @param min_chrom_distance (integer) bp from chrom edge required beyond flank. #' Default 50L. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Unused. #' #' @return SummarizedExperiment with one assay per motif, two stacked channels @@ -321,10 +346,11 @@ get_footprints.MarchRProject <- function( dataset_name = NULL, bsgenome = NULL, min_chrom_distance = 50L, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") norm_method <- match.arg(norm_method) @@ -369,6 +395,7 @@ get_footprints.MarchRProject <- function( BiocGenerics::end(gr) + flank + min_chrom_distance < cl gr[ok & !is.na(ok)] }) + dropped <- names(positions)[lengths(positions) == 0L] positions <- positions[lengths(positions) > 0L] positions <- as(positions, "GRangesList") if (length(positions) == 0L) { @@ -415,12 +442,25 @@ get_footprints.MarchRProject <- function( window <- 2L * flank + 1L bsgenome <- if (norm_method != "none") .resolve_bsgenome(proj, bsgenome) else NULL + if (verbose) { + run <- .log_start("Footprints", sprintf( + "%s, %s ('%s'), flank %s bp, %s", .log_plural(length(positions), "motif"), + .log_plural(length(rep_labels), "replicate"), group_by, .log_count(flank), + if (norm_method == "none") "not normalized" else sprintf("bias-normalized (%s)", norm_method) + )) + if (length(dropped) > 0) { + .log_step(sprintf( + "Dropped %s with no positions more than %s bp from chromosome ends: %s", + .log_plural(length(dropped), "motif"), .log_count(flank + min_chrom_distance), + .log_names(dropped) + )) + } + } + assays <- list() for (motif_name in names(positions)) { + t0 <- steady_clock_seconds_rcpp() gr <- positions[[motif_name]] - if (verbose) log_progress(sprintf( - "Footprint for motif '%s' (%d positions)...", motif_name, length(gr) - )) # Pass a tibble instead of GRanges so BPCells does not require GenomeInfoDb # (BPCells::normalize_ranges calls GenomeInfoDb::seqlevels on a GRanges). ranges_df <- tibble::tibble( @@ -451,6 +491,11 @@ get_footprints.MarchRProject <- function( } assays[[motif_name]] <- rbind(count_mat, bias_mat) + if (verbose) { + .log_step(sprintf( + "%s: footprinted %s", motif_name, .log_plural(length(gr), "position") + ), since = t0) + } } se <- SummarizedExperiment::SummarizedExperiment( @@ -476,6 +521,12 @@ get_footprints.MarchRProject <- function( group_by = group_by, dataset_name = dataset_name ) + if (verbose) { + .log_finish(run, sprintf( + "%s x %s", .log_plural(length(assays), "motif footprint"), + .log_plural(length(rep_labels), "replicate") + )) + } se } From 255c59dbafa8846121a1ae31d1fe0545ae62ae8b Mon Sep 17 00:00:00 2001 From: erliuu Date: Fri, 23 Oct 2026 02:12:28 -0700 Subject: [PATCH 11/12] feat([r] logging): Update reporting for output plotting and import/saving steps --- R/multi_modal.R | 55 +++++++---- R/plotting.R | 127 +++++++++++++++++++------ R/save_load.R | 5 +- R/track_plotting.R | 51 ++++++---- R/trajectory.R | 81 ++++++++++++---- man/add_trajectory.Rd | 5 +- man/import_feature_matrix_10x.Rd | 13 +-- man/plot_embedding.Rd | 6 +- man/plot_gene_scores.Rd | 4 +- tests/testthat/test-multi_modal.R | 77 ++++++++++++++- tests/testthat/test-plotting.R | 136 +++++++++++++++++++++++++++ tests/testthat/test-project-io.R | 17 ++++ tests/testthat/test-track-plotting.R | 67 +++++++++++++ tests/testthat/test-trajectory.R | 91 ++++++++++++++++++ 14 files changed, 634 insertions(+), 101 deletions(-) diff --git a/R/multi_modal.R b/R/multi_modal.R index 036dd03..0858659 100644 --- a/R/multi_modal.R +++ b/R/multi_modal.R @@ -80,7 +80,10 @@ add_combined_dims.MarchRProject <- function( # Extract each modality (cells x dims), variance-normalize globally, weight. blocks <- lapply(seq_along(embedding_names), function(i) { - reduced_dims <- as.matrix(t(x[[embedding_names[i], dataset_names]])) + reduced_dims <- rlang::with_options( + as.matrix(t(x[[embedding_names[i], dataset_names]])), + rlib_message_verbosity = "quiet" + ) norm_factor <- 1 / sqrt(sum(apply(reduced_dims, 2, stats::var))) reduced_dims * norm_factor * dim_weights[i] }) @@ -113,22 +116,23 @@ add_combined_dims.MarchRProject <- function( #' @param feature_type (character) 10x feature type to keep. Default `"Gene Expression"`. #' @param genes_to_exclude (character; optional) Features to drop after import, matched by ID or symbol. #' @param overwrite (logical) Overwrite an existing assay named `matrix_name`. Default FALSE. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Passed to methods. #' #' @return The MarchRProject with the RNA assay added to `dataset_name`, both #' modalities aligned to shared barcodes. #' #' @details -#' Barcodes are intersected between the RNA matrix and the target dataset, dropping -#' non-shared cells from both sides with a message. The RNA assay is added into the -#' existing dataset rather than creating a new one. +#' Barcodes are intersected between the RNA matrix and the target dataset, and +#' non-shared cells are dropped from both sides (counts are logged when `verbose = TRUE`). +#' The RNA assay is added into the existing dataset rather than creating a new one. #' #' Feature IDs (the 10x `features/id` field, typically Ensembl IDs) are used as the #' assay row names, and gene symbols (`features/name`) are stored in the assay's #' feature metadata under `gene_symbol`. Accordingly, `genes_to_exclude` drops a #' feature when it matches either the ID or the symbol. When symbols cannot be read -#' from the file, exclusion falls back to ID matching only. +#' from the file, the function warns, matches `genes_to_exclude` by ID only, and adds +#' no `gene_symbol` metadata. #' #' @section ArchR correspondence: #' Analogous to ArchR's \code{import10xFeatureMatrix()}, scoped to a single file. @@ -149,10 +153,11 @@ import_feature_matrix_10x.MarchRProject <- function( feature_type = "Gene Expression", genes_to_exclude = NULL, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(x, "MarchRProject") assert_is_character(input) assert_len(input, 1) @@ -168,6 +173,13 @@ import_feature_matrix_10x.MarchRProject <- function( length(dataset_name) == 1, msg = "Specify a single dataset_name to import RNA into." ) + if (!is.null(genes_to_exclude)) assert_is_character(genes_to_exclude) + + if (verbose) { + run <- .log_start("Feature import", sprintf( + "'%s' (%s) into '%s'", basename(input), feature_type, dataset_name + )) + } rna <- open_matrix_10x_hdf5(input, feature_type = feature_type) @@ -175,22 +187,25 @@ import_feature_matrix_10x.MarchRProject <- function( # the 10x features/name field via a BPCells internal reader. id2sym <- tryCatch({ ids <- BPCells:::read_hdf5_string_cpp(input, "matrix/features/id", 16384L) - syms <- BPCells:::read_hdf5_string_cpp(input, "matrix/features/name", 16384L) + has_syms <- "name" %in% BPCells:::hdf5_group_objnames_cpp(input, "matrix/features") + syms <- if (has_syms) BPCells:::read_hdf5_string_cpp(input, "matrix/features/name", 16384L) if (length(ids) == length(syms)) stats::setNames(syms, ids) else NULL }, error = function(e) NULL) - if (is.null(id2sym) && verbose) { - log_progress( - "Gene symbols unavailable; genes_to_exclude matched IDs only, no symbol metadata added." + if (is.null(id2sym)) { + rlang::warn( + "Gene symbols unavailable; genes_to_exclude matched IDs only and no symbol metadata was added." ) } if (!is.null(genes_to_exclude)) { - assert_is_character(genes_to_exclude) ids_now <- rownames(rna) syms_now <- if (!is.null(id2sym)) unname(id2sym[ids_now]) else rep(NA_character_, length(ids_now)) drop <- ids_now %in% genes_to_exclude | (!is.na(syms_now) & syms_now %in% genes_to_exclude) rna <- rna[!drop, ] + if (verbose && any(drop)) { + .log_step(sprintf("Excluded %s matching genes_to_exclude", .log_plural(sum(drop), "feature"))) + } } atac_cells <- cell_names(x$datasets[[dataset_name]]) @@ -202,11 +217,11 @@ import_feature_matrix_10x.MarchRProject <- function( ) if (verbose) { - log_progress(sprintf( - "Barcode intersection: %d shared, %d ATAC-only dropped, %d RNA-only dropped.", - length(shared), - length(setdiff(atac_bc, shared)), - length(setdiff(colnames(rna), shared)) + .log_step(sprintf( + "Matched %s, dropped %s ATAC-only and %s RNA-only cells", + .log_plural(length(shared), "barcode"), + .log_count(length(setdiff(atac_bc, shared))), + .log_count(length(setdiff(colnames(rna), shared))) )) } @@ -236,5 +251,11 @@ import_feature_matrix_10x.MarchRProject <- function( ) x <- add_feature_metadata(x, sym_df, assay_name = matrix_name, overwrite = overwrite) } + if (verbose) { + .log_finish(run, sprintf( + "added assay '%s' (%s x %s)%s", matrix_name, .log_plural(nrow(rna), "feature"), + .log_plural(ncol(rna), "cell"), if (!is.null(id2sym)) ", feature metadata 'gene_symbol'" else "" + )) + } x } diff --git a/R/plotting.R b/R/plotting.R index d4cb5a1..a2e8e50 100644 --- a/R/plotting.R +++ b/R/plotting.R @@ -393,7 +393,7 @@ palette_continuous <- function(set = "solarExtra", n = 256L) { #' @param legend_position (character) Legend position. Default \code{"bottom"}. #' @param legend_text_size (numeric) Legend text size. Default 5. #' @param legend_title (character) Legend title. NULL for auto. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Additional arguments (unused). #' @return A ggplot object, or named list of ggplot objects for multiple features. #' @@ -445,11 +445,22 @@ plot_embedding.default <- function( legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_that(is.matrix(embedding), ncol(embedding) == 2) + is_mat <- is.matrix(x) || inherits(x, "IterableMatrix") + if (is_mat) { + assert_that(!is.null(features), msg = "features required when x is a matrix") + missing_features <- setdiff(features, rownames(x)) + if (length(missing_features) > 0) { + rlang::warn(sprintf("Features not found in x: %s", paste(missing_features, collapse = ", "))) + } + features <- intersect(features, rownames(x)) + if (length(features) == 0) rlang::abort("None of the requested features found in x.") + } # Auto-derive axis labels from embedding column names # Insert "Dimension" between prefix and number (e.g., "UMAP1" -> "UMAP Dimension 1") @@ -457,11 +468,18 @@ plot_embedding.default <- function( if (is.null(xlabel)) xlabel <- .format_axis_label(col_nms[1]) if (is.null(ylabel)) ylabel <- .format_axis_label(col_nms[2]) + if (verbose) { + run <- .log_start("Embedding plots", sprintf( + "%s on '%s', %s", if (is_mat) .log_plural(length(features), "feature") else "values", + sub("_?[0-9]+$", "", col_nms[1]), .log_plural(nrow(embedding), "cell") + )) + } + # Subsample cells for performance on large datasets if (!is.null(sample_cells) && sample_cells < nrow(embedding)) { keep <- sort(sample.int(nrow(embedding), sample_cells)) embedding <- embedding[keep, , drop = FALSE] - if (is.matrix(x) || inherits(x, "IterableMatrix")) { + if (is_mat) { x <- x[, keep, drop = FALSE] } else { x <- x[keep] @@ -474,11 +492,14 @@ plot_embedding.default <- function( } # Matrix source: produce one plot per feature - if (is.matrix(x) || inherits(x, "IterableMatrix")) { - assert_that(!is.null(features), msg = "features required when x is a matrix") - features <- intersect(features, rownames(x)) - if (length(features) == 0) rlang::abort("None of the requested features found in x.") - mat <- as.matrix(x[features, , drop = FALSE]) + if (is_mat) { + t0 <- steady_clock_seconds_rcpp() + mat <- rlang::with_options(as.matrix(x[features, , drop = FALSE]), rlib_message_verbosity = "quiet") + if (verbose) { + .log_step(sprintf( + "Fetched %s for %s", .log_plural(length(features), "feature"), .log_plural(ncol(mat), "cell") + ), since = t0) + } plots <- lapply(features, function(feat) { plot_embedding.default( x = mat[feat, ], embedding = embedding, features = NULL, @@ -495,10 +516,11 @@ plot_embedding.default <- function( title = feat, xlabel = xlabel, ylabel = ylabel, extend = extend, legend_position = legend_position, legend_text_size = legend_text_size, legend_title = legend_title, - verbose = verbose, ... + verbose = FALSE, ... ) }) names(plots) <- features + if (verbose) .log_finish(run, .log_plural(length(plots), "plot")) if (length(plots) == 1) return(plots[[1]]) return(plots) } @@ -644,6 +666,7 @@ plot_embedding.default <- function( ) } + if (verbose) .log_finish(run, "1 plot") gg } @@ -692,14 +715,16 @@ plot_embedding.MarchRProject <- function( legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_that(inherits(x, "MarchRProject")) cell_meta <- get_cell_metadata(x) emb_mat <- .fetch_embedding(cell_meta, embedding) + emb_prefix <- gsub("_\\d+$", "", colnames(emb_mat)[1]) # Resolve color source if (color_by == "cell_metadata") { @@ -707,8 +732,9 @@ plot_embedding.MarchRProject <- function( rlang::abort(sprintf("Column '%s' not found in cell metadata.", col_name[1])) } source_data <- cell_meta[[col_name[1]]] - emb_prefix <- gsub("_\\d+$", "", colnames(emb_mat)[1]) if (is.null(title)) title <- paste0(emb_prefix, " of ", col_name[1]) + n_plots <- 1L + source_label <- sprintf("'%s'", col_name[1]) } else { # Matrix assay source: retrieve concatenated features-by-cells matrix mat <- x[[color_by]] @@ -723,12 +749,18 @@ plot_embedding.MarchRProject <- function( if (length(available) == 0) rlang::abort("None of the requested features found.") source_data <- mat[available, , drop = FALSE] if (is.null(title) && length(available) == 1) { - emb_prefix <- gsub("_\\d+$", "", colnames(emb_mat)[1]) title <- paste0(emb_prefix, " of ", available[1]) } + n_plots <- length(available) + source_label <- sprintf("%s from '%s'", .log_plural(n_plots, "feature"), color_by) } - plot_embedding.default( + if (verbose) { + run <- .log_start("Embedding plots", sprintf( + "%s on '%s', %s", source_label, emb_prefix, .log_plural(nrow(emb_mat), "cell") + )) + } + plots <- plot_embedding.default( x = source_data, embedding = emb_mat, features = if (color_by != "cell_metadata") available else NULL, colors_discrete = colors_discrete, colors_continuous = colors_continuous, @@ -746,6 +778,8 @@ plot_embedding.MarchRProject <- function( legend_text_size = legend_text_size, legend_title = legend_title, verbose = verbose, ... ) + if (verbose) .log_finish(run, .log_plural(n_plots, "plot")) + plots } @@ -766,7 +800,7 @@ plot_embedding.MarchRProject <- function( #' @param log_transform (logical) Apply \code{log2(x + 1)}. Default TRUE. #' @param limits Absolute value clipping: \code{c(min, max)} or \code{"range"}. #' @param patchwork (logical) Returns multi-gene output as patchwork object if TRUE. Default FALSE. -#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @param ... Passed to \code{\link{plot_embedding}} (e.g. \code{plot_as}, #' \code{colors_continuous}, \code{size}, \code{rastr}, \code{quant_cut}). #' @return A named list of ggplot objects, keyed by gene name. @@ -796,10 +830,11 @@ plot_gene_scores.MarchRProject <- function( log_transform = TRUE, limits = NULL, patchwork = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) { .start_log_clock() + assert_for(verbose, "logical") assert_that(inherits(x, "MarchRProject")) assert_that(is.character(genes), length(genes) >= 1) assert_that(is.logical(patchwork), length(patchwork) == 1, !is.na(patchwork)) @@ -819,16 +854,34 @@ plot_gene_scores.MarchRProject <- function( } if (length(available_genes) == 0) rlang::abort("None of the requested genes were found.") - if (impute && !is.null(x$impute_weights)) { - if (verbose) log_progress("Imputing gene scores with MAGIC weights") + imputed <- impute && !is.null(x$impute_weights) + genes_label <- .log_plural(length(available_genes), "gene") + if (verbose) { + run <- .log_start("Gene score plots", sprintf( + "%s on '%s', %s, %s", genes_label, gsub("_\\d+$", "", colnames(emb_mat)[1]), + .log_plural(nrow(emb_mat), "cell"), if (imputed) "imputed" else "raw scores" + )) + } + + t0 <- steady_clock_seconds_rcpp() + if (imputed) { mat <- impute_matrix( gene_score_mat[available_genes, , drop = FALSE], x$impute_weights, verbose = FALSE ) } else { - if (impute && is.null(x$impute_weights)) { + if (impute) { rlang::warn("Impute weights not found, plotting raw scores. Run add_impute_weights() first.") } - mat <- as.matrix(gene_score_mat[available_genes, , drop = FALSE]) + mat <- rlang::with_options( + as.matrix(gene_score_mat[available_genes, , drop = FALSE]), + rlib_message_verbosity = "quiet" + ) + } + if (verbose) { + .log_step(sprintf( + if (imputed) "Imputed %s over %s" else "Fetched %s for %s", genes_label, + .log_plural(ncol(mat), "cell") + ), since = t0) } if (log_transform) mat <- log2(mat + 1) @@ -851,21 +904,25 @@ plot_gene_scores.MarchRProject <- function( plots <- lapply(available_genes, function(gene) { do.call(plot_embedding.default, c( - list(x = mat[gene, ], embedding = emb_mat, title = gene), + list(x = mat[gene, ], embedding = emb_mat, title = gene, verbose = FALSE), dot_args )) }) names(plots) <- available_genes - if (length(plots) == 1) return(plots[[1]]) - if (patchwork) { - return(.combine_gene_score_plots( + res <- if (length(plots) == 1) { + plots[[1]] + } else if (patchwork) { + .combine_gene_score_plots( plots, colors_continuous = dot_args$colors_continuous, legend_title = dot_args$legend_title - )) + ) + } else { + plots } - plots + if (verbose) .log_finish(run, .log_plural(length(plots), "plot")) + res } #' Assemble per-gene score plots into one shared-legend figure @@ -1301,6 +1358,7 @@ plot_doublet_scores.MarchRDataset <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") plot <- match.arg(plot, several.ok = TRUE) if (is.null(x$doublet_data) || is.null(x$doublet_data$scores)) { @@ -1314,6 +1372,7 @@ plot_doublet_scores.MarchRDataset <- function( } umap_cells <- as.matrix(cell_umap[, c("UMAP1", "UMAP2")]) rownames(umap_cells) <- NULL + if (verbose) run <- .log_start("Doublet score plots", .log_plural(nrow(umap_cells), "cell")) # Default doublet plot style dot_args <- list(...) @@ -1330,14 +1389,16 @@ plot_doublet_scores.MarchRDataset <- function( if ("enrichment" %in% plot) { panels$enrichment <- do.call(plot_embedding.default, c( list(x = scores$doublet_enrichment, embedding = umap_cells, - title = "Simulated Doublet Enrichment", legend_title = "Enrichment (Quantile)"), + title = "Simulated Doublet Enrichment", legend_title = "Enrichment (Quantile)", + verbose = FALSE), dot_args )) } if ("score" %in% plot) { panels$score <- do.call(plot_embedding.default, c( list(x = scores$doublet_score, embedding = umap_cells, - title = "Doublet Score [-log10(P-adj)]", legend_title = "Score (Quantile)"), + title = "Doublet Score [-log10(P-adj)]", legend_title = "Score (Quantile)", + verbose = FALSE), dot_args )) } @@ -1392,6 +1453,7 @@ plot_doublet_scores.MarchRDataset <- function( } } + if (verbose) .log_finish(run, .log_plural(length(panels), "plot")) if (length(panels) == 1) return(panels[[1]]) if (!requireNamespace("patchwork", quietly = TRUE)) return(panels) patchwork::wrap_plots(panels, ncol = length(panels)) @@ -1407,11 +1469,18 @@ plot_doublet_scores.MarchRProject <- function( ... ) { .start_log_clock() + assert_for(verbose, "logical") dataset_name <- select_dataset_name(x, dataset_name) - plot_doublet_scores( + if (verbose) run <- .log_start("Doublet score plots", sprintf("'%s'", dataset_name)) + p <- plot_doublet_scores( x$datasets[[dataset_name]], - plot = plot, verbose = verbose, ... + plot = plot, verbose = FALSE, ... ) + if (verbose) { + n_plots <- if (inherits(p, "ggplot") && !inherits(p, "patchwork")) 1L else length(p) + .log_finish(run, .log_plural(n_plots, "plot")) + } + p } ######################################################################## diff --git a/R/save_load.R b/R/save_load.R index a6a3320..ce90cd4 100644 --- a/R/save_load.R +++ b/R/save_load.R @@ -49,7 +49,10 @@ new_ondisk_ref <- function(kind, path, relative) { target_dir )) } - handle <- writer(obj, target_dir, overwrite = overwrite) + handle <- rlang::with_options( + writer(obj, target_dir, overwrite = overwrite), + rlib_message_verbosity = "quiet" + ) ref_path <- target_norm } diff --git a/R/track_plotting.R b/R/track_plotting.R index 9f40300..c6e4fb0 100644 --- a/R/track_plotting.R +++ b/R/track_plotting.R @@ -230,6 +230,7 @@ plot_browser_track <- function( verbose = getOption("MarchR.verbose", FALSE) ) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") assert_is_character(group_by) assert_len(group_by, 1) @@ -256,7 +257,6 @@ plot_browser_track <- function( region <- gene_region(transcripts, gene_symbol, upstream = upstream, downstream = downstream, extend_bp = extend_bp, strand_aware = TRUE) - if (verbose) log_progress(sprintf("Region for %s: %s", gene_symbol, region)) } # Merge fragments across datasets @@ -297,9 +297,16 @@ plot_browser_track <- function( # Subset fragments to cells that have group assignments merged_frags <- merged_frags %>% select_cells(names(groups)) + if (verbose) { + run <- .log_start("Browser track", sprintf( + "%s%s, %s (%s)", if (is.null(gene_symbol)) "" else paste(gene_symbol, "at "), region, + .log_plural(nlevels(groups), "group"), .log_plural(length(groups), "cell") + )) + } + # Build cell read counts cell_read_counts <- .get_cell_read_counts( - proj, dataset_names, frags_name, norm_method, names(groups), verbose + proj, dataset_names, frags_name, norm_method, names(groups) ) # Assemble tracks @@ -333,6 +340,7 @@ plot_browser_track <- function( if (!is.null(colors)) { coverage_args$colors <- colors } + t0 <- steady_clock_seconds_rcpp() coverage_plot <- do.call(trackplot_coverage, coverage_args) track_list$coverage <- .apply_archr_coverage_theme( coverage_plot, @@ -341,6 +349,7 @@ plot_browser_track <- function( ylab_style = ylab_style, norm_method = norm_method ) + if (verbose) .log_step(sprintf("Computed coverage in %s bins", .log_count(bins)), since = t0) } if ("peaks" %in% tracks) { @@ -354,11 +363,12 @@ plot_browser_track <- function( } if (!is.null(peak_input)) { track_list$peaks <- .trackplot_peaks(peak_input, region, base_size = base_size) - } else if (verbose) { - log_progress("No peaks available for 'peaks' track; skipping.") + } else { + rlang::warn("No peak set; skipped the peaks track.") } } + if ("loop" %in% tracks && is.null(loops)) rlang::warn("No loops; skipped the loop track.") if ("loop" %in% tracks && !is.null(loops)) { if (loop_within_region) { # ArchR keeps only loops with both anchors inside the region. @@ -463,6 +473,19 @@ plot_browser_track <- function( suffix <- if (!is.null(title)) title else (gene_symbol %||% "") full_title <- trimws(sprintf("%s %s", region, suffix)) + if (combine == "patchwork" && !requireNamespace("patchwork", quietly = TRUE)) { + rlang::abort(c( + "Package 'patchwork' is required for the default combine method.", + i = 'Install: install.packages("patchwork")', + i = 'Or use combine = "bpcells" / combine = "none".' + )) + } + if (verbose) { + .log_finish(run, sprintf( + "%s (%s)", .log_plural(length(track_list), "track"), paste(names(track_list), collapse = ", ") + )) + } + if (combine == "none") { return(list(tracks = track_list, title = full_title, region = region)) } @@ -472,14 +495,6 @@ plot_browser_track <- function( } # Default: patchwork composition keeps the x-axis on the coverage track only. - if (!requireNamespace("patchwork", quietly = TRUE)) { - rlang::abort(c( - "Package 'patchwork' is required for the default combine method.", - i = 'Install: install.packages("patchwork")', - i = 'Or use combine = "bpcells" / combine = "none".' - )) - } - for (nm in names(track_list)) { if (nm == "coverage") next track_list[[nm]] <- track_list[[nm]] + @@ -508,7 +523,7 @@ plot_browser_track <- function( #' @keywords internal #' @noRd .get_cell_read_counts <- function( - proj, dataset_names, frags_name, norm_method, cell_names_ordered, verbose + proj, dataset_names, frags_name, norm_method, cell_names_ordered ) { if (norm_method == "nCells") { # Uniform weighting — all cells contribute equally @@ -539,12 +554,10 @@ plot_browser_track <- function( # Warn about missing values n_missing <- sum(is.na(counts)) if (n_missing > 0) { - if (verbose) { - warning(sprintf( - "%d cells missing QC data for '%s'. Using median as fallback.", - n_missing, col_name - ), call. = FALSE) - } + rlang::warn(sprintf( + "%d cells missing QC data for '%s'. Using median as fallback.", + n_missing, col_name + )) counts[is.na(counts)] <- stats::median(counts, na.rm = TRUE) } diff --git a/R/trajectory.R b/R/trajectory.R index 7173b0d..69ebe0f 100644 --- a/R/trajectory.R +++ b/R/trajectory.R @@ -54,7 +54,7 @@ reduced_dims )) } - coords <- as.matrix(t(proj[[reduced_dims]])) + coords <- rlang::with_options(as.matrix(t(proj[[reduced_dims]])), rlib_message_verbosity = "quiet") } storage.mode(coords) <- "double" coords @@ -88,7 +88,10 @@ # where G is a cells x bins 0/1 indicator with rows matching colnames(mat). # @noRd .get_trajectory_group_matrix <- function(mat, group_list) { - as.matrix(.aggregate_by_groups(mat, group_list, method = "sum")) + rlang::with_options( + as.matrix(.aggregate_by_groups(mat, group_list, method = "sum")), + rlib_message_verbosity = "quiet" + ) } # rowData for a trajectory SE: use proj$feature_metadata[[assay_name]] when its @@ -123,6 +126,7 @@ #' @param knn_method (function) BPCells KNN partial. Default `knn_hnsw(k = 3L)`. #' @param force (logical) Allow < 3 groups and overwrite existing column. Default FALSE. #' @param seed (integer) RNG seed. Default 1. +#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}. #' @return The project with a 0-100 pseudotime column (`NA` off-trajectory). #' @details Ports ArchR's `addTrajectory`. Deviations: uses BPCells KNN instead of #' `nabor::knn`; writes a full named vector over all cells so datasets with no @@ -132,7 +136,8 @@ add_trajectory <- function(proj, trajectory, name = "trajectory", group_by = "cl reduced_dims = "IterativeLSI", embedding = NULL, pre_filter_quantile = 0.9, post_filter_quantile = 0.9, use_all = FALSE, dof = 250L, spar = 1, - knn_method = knn_hnsw(k = 3L), force = FALSE, seed = 1L) { + knn_method = knn_hnsw(k = 3L), force = FALSE, seed = 1L, + verbose = getOption("MarchR.verbose", FALSE)) { UseMethod("add_trajectory") } @@ -143,17 +148,16 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", pre_filter_quantile = 0.9, post_filter_quantile = 0.9, use_all = FALSE, dof = 250L, spar = 1, knn_method = knn_hnsw(k = 3L), - force = FALSE, seed = 1L) { + force = FALSE, seed = 1L, + verbose = getOption("MarchR.verbose", FALSE)) { .start_log_clock() + assert_for(verbose, "logical") assert_for(proj, "MarchRProject") assert_for(trajectory, "character") assert_for(name, "character") assert_for(group_by, "character") assertthat::assert_that(is.function(knn_method)) - verbose_opt <- getOption("MarchR.verbose") - if (!is.null(verbose_opt)) { - knn_method <- partial_apply(knn_method, verbose = verbose_opt, .missing_args_error = FALSE) - } + knn_method <- partial_apply(knn_method, verbose = FALSE, .missing_args_error = FALSE) assertthat::assert_that( is.numeric(pre_filter_quantile), length(pre_filter_quantile) == 1, pre_filter_quantile >= 0, pre_filter_quantile <= 1, @@ -186,6 +190,14 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", traj_cells <- names(groups)[groups %in% trajectory] traj_coords <- coords[traj_cells, , drop = FALSE] traj_groups <- groups[traj_cells] + if (verbose) { + shown <- if (length(present) > 4) c(present[1], "...", present[length(present)]) else present + path <- sprintf("%s (%s)", .log_plural(length(present), "group"), paste(shown, collapse = " -> ")) + run <- .log_start("Trajectory", sprintf( + "%s, %s on '%s' (%s)", path, .log_plural(length(traj_cells), "cell"), + if (is.null(embedding)) reduced_dims else embedding, .log_plural(ncol(coords), "dim") + )) + } # Per-group centroid outlier filter. keep <- unlist(lapply(trajectory, function(g) { @@ -198,8 +210,15 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", }), use.names = FALSE) mat_filter <- traj_coords[keep, , drop = FALSE] groups_filter <- traj_groups[keep] + if (verbose) { + .log_step(sprintf( + "Kept %s of %s cells near group centroids", .log_count(length(keep)), + .log_count(length(traj_cells)) + )) + } # Initial time: distance to the next (or previous, for last) group centroid. + t0 <- steady_clock_seconds_rcpp() initial_time <- unlist(lapply(seq_along(trajectory), function(i) { g <- trajectory[i] gc <- names(groups_filter)[groups_filter == g] @@ -227,8 +246,10 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", df = dof, spar = spar )[[2]] })) + if (verbose) .log_step(paste("Fit", .log_plural(ncol(mat_filter), "smoothing spline")), since = t0) # KNN of every trajectory cell onto the spline point cloud. + t0 <- steady_clock_seconds_rcpp() knn_res <- knn_method(data = spline_pts, query = coords[traj_cells, , drop = FALSE]) knn_idx <- knn_res$idx knn_dist <- knn_res$dist @@ -244,11 +265,18 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", keep_post <- traj_cells[nearest <= stats::quantile(nearest, post_filter_quantile)] distance_idx <- distance_idx[keep_post] + if (verbose) { + .log_step(sprintf( + "Aligned %s to the spline, kept %s", .log_plural(length(traj_cells), "cell"), + .log_count(length(keep_post)) + ), since = t0) + } # Optionally align off-trajectory cells to the same spline. if (use_all) { other_cells <- setdiff(rownames(coords), traj_cells) if (length(other_cells) > 0) { + t0 <- steady_clock_seconds_rcpp() knn2 <- knn_method(data = spline_pts, query = coords[other_cells, , drop = FALSE]) dir2 <- ifelse(knn2$idx[, 2] > knn2$idx[, 3], 1, -1) distq2 <- .get_quantiles(knn2$dist[, 1]) @@ -256,6 +284,12 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", names(didx2) <- other_cells keep2 <- other_cells[knn2$dist[, 1] < max(nearest[keep_post])] distance_idx <- c(distance_idx, didx2[keep2]) + if (verbose) { + .log_step(sprintf( + "Aligned %s, kept %s", .log_plural(length(other_cells), "off-trajectory cell"), + .log_count(length(keep2)) + ), since = t0) + } } } @@ -265,7 +299,14 @@ add_trajectory.MarchRProject <- function(proj, trajectory, name = "trajectory", values <- stats::setNames(rep(NA_real_, length(all_cells)), all_cells) values[names(pseudotime)] <- pseudotime - add_cell_metadata_col(proj, values = values, col_name = name, overwrite = force) + proj <- add_cell_metadata_col(proj, values = values, col_name = name, overwrite = force) + if (verbose) { + .log_finish(run, sprintf( + "added cell metadata column '%s' (%s with pseudotime)", name, + .log_plural(length(pseudotime), "cell") + )) + } + proj } ######################################################################## @@ -341,16 +382,13 @@ get_trajectory.MarchRProject <- function(proj, name = "trajectory", }) names(group_list) <- paste0("T.", breaks[-length(breaks)], "_", breaks[-1]) empty <- lengths(group_list) == 0 - if (any(empty)) { - message(sprintf("Dropping %d empty trajectory bin(s).", sum(empty))) - group_list <- group_list[!empty] - } + group_list <- group_list[!empty] group_mat <- .get_trajectory_group_matrix(mat, group_list) if (!is.null(scale_to)) { if (any(group_mat < 0)) { - message("Negative values present; skipping CPM scaling.") + rlang::warn("Negative values present; skipping CPM scaling.") } else { cs <- colSums(group_mat) if (any(cs == 0)) rlang::abort("A trajectory bin has zero total signal after filtering.") @@ -359,7 +397,7 @@ get_trajectory.MarchRProject <- function(proj, name = "trajectory", } if (log2_norm) { if (any(group_mat < 0)) { - message("Negative values present; skipping log2 normalization.") + rlang::warn("Negative values present; skipping log2 normalization.") } else { group_mat <- log2(group_mat + 1) } @@ -399,7 +437,9 @@ get_trajectory.MarchRProject <- function(proj, name = "trajectory", }, character(1)) SummarizedExperiment::colData(se)$label <- labels } else { - message(sprintf("trajectory_label '%s' not found in metadata; skipping labels.", trajectory_label)) + rlang::warn(sprintf( + "trajectory_label '%s' not found in metadata; skipping labels.", trajectory_label + )) } } @@ -616,7 +656,10 @@ plot_trajectory_heatmap <- function(se_trajectory, var_cutoff = 0.9, max_feature dense <- impute_matrix(fmat[col_name, , drop = FALSE], impute_weights, verbose = FALSE) vals <- as.numeric(dense[1, cells]) } else { - vals <- as.numeric(as.matrix(fmat[col_name, cells, drop = FALSE])) + vals <- as.numeric(rlang::with_options( + as.matrix(fmat[col_name, cells, drop = FALSE]), + rlib_message_verbosity = "quiet" + )) } if (is.null(log2_norm)) log2_norm <- tolower(color_by) == "genescorematrix" if (isTRUE(log2_norm)) vals <- log2(vals + 1) @@ -680,7 +723,7 @@ plot_trajectory.MarchRProject <- function(proj, trajectory = "trajectory", embed colors_continuous = palette_continuous(continuous_set), colors_discrete = palette_discrete(discrete_set), quant_cut = if (clip) quant_cut else c(0, 1), - size = size, plot_as = plot_as, rastr = rastr + size = size, plot_as = plot_as, rastr = rastr, verbose = FALSE ) } else { vals <- .trajectory_feature_values( @@ -689,7 +732,7 @@ plot_trajectory.MarchRProject <- function(proj, trajectory = "trajectory", embed p <- plot_embedding.default( x = vals, embedding = emb, colors_continuous = palette_continuous(continuous_set), - quant_cut = quant_cut, size = size, plot_as = plot_as, rastr = rastr + quant_cut = quant_cut, size = size, plot_as = plot_as, rastr = rastr, verbose = FALSE ) } diff --git a/man/add_trajectory.Rd b/man/add_trajectory.Rd index 360db8d..93bb648 100644 --- a/man/add_trajectory.Rd +++ b/man/add_trajectory.Rd @@ -18,7 +18,8 @@ add_trajectory( spar = 1, knn_method = knn_hnsw(k = 3L), force = FALSE, - seed = 1L + seed = 1L, + verbose = getOption("MarchR.verbose", FALSE) ) } \arguments{ @@ -50,6 +51,8 @@ add_trajectory( \item{force}{(logical) Allow < 3 groups and overwrite existing column. Default FALSE.} \item{seed}{(integer) RNG seed. Default 1.} + +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ The project with a 0-100 pseudotime column (\code{NA} off-trajectory). diff --git a/man/import_feature_matrix_10x.Rd b/man/import_feature_matrix_10x.Rd index 5c7690c..c65fadb 100644 --- a/man/import_feature_matrix_10x.Rd +++ b/man/import_feature_matrix_10x.Rd @@ -15,7 +15,7 @@ import_feature_matrix_10x(x, ...) feature_type = "Gene Expression", genes_to_exclude = NULL, overwrite = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -36,7 +36,7 @@ import_feature_matrix_10x(x, ...) \item{overwrite}{(logical) Overwrite an existing assay named \code{matrix_name}. Default FALSE.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ The MarchRProject with the RNA assay added to \code{dataset_name}, both @@ -47,15 +47,16 @@ Imports the RNA (feature) modality of a 10x multiome HDF5 file into an existing ATAC dataset, aligned by cell barcode. } \details{ -Barcodes are intersected between the RNA matrix and the target dataset, dropping -non-shared cells from both sides with a message. The RNA assay is added into the -existing dataset rather than creating a new one. +Barcodes are intersected between the RNA matrix and the target dataset, and +non-shared cells are dropped from both sides (counts are logged when \code{verbose = TRUE}). +The RNA assay is added into the existing dataset rather than creating a new one. Feature IDs (the 10x \code{features/id} field, typically Ensembl IDs) are used as the assay row names, and gene symbols (\code{features/name}) are stored in the assay's feature metadata under \code{gene_symbol}. Accordingly, \code{genes_to_exclude} drops a feature when it matches either the ID or the symbol. When symbols cannot be read -from the file, exclusion falls back to ID matching only. +from the file, the function warns, matches \code{genes_to_exclude} by ID only, and adds +no \code{gene_symbol} metadata. } \section{ArchR correspondence}{ diff --git a/man/plot_embedding.Rd b/man/plot_embedding.Rd index 5480e15..37fc156 100644 --- a/man/plot_embedding.Rd +++ b/man/plot_embedding.Rd @@ -41,7 +41,7 @@ plot_embedding(x, ...) legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) @@ -79,7 +79,7 @@ plot_embedding(x, ...) legend_position = "bottom", legend_text_size = 5, legend_title = NULL, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -157,7 +157,7 @@ plotting. NULL plots all cells. Default NULL.} \item{legend_title}{(character) Legend title. NULL for auto.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} \item{color_by}{(character) \code{"cell_metadata"} or matrix assay name.} diff --git a/man/plot_gene_scores.Rd b/man/plot_gene_scores.Rd index 5a5c525..52b1d7c 100644 --- a/man/plot_gene_scores.Rd +++ b/man/plot_gene_scores.Rd @@ -16,7 +16,7 @@ plot_gene_scores(x, ...) log_transform = TRUE, limits = NULL, patchwork = FALSE, - verbose = getOption("MarchR.verbose", TRUE), + verbose = getOption("MarchR.verbose", FALSE), ... ) } @@ -40,7 +40,7 @@ plot_gene_scores(x, ...) \item{patchwork}{(logical) Returns multi-gene output as patchwork object if TRUE. Default FALSE.} -\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", TRUE)}.} +\item{verbose}{(logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.} } \value{ A named list of ggplot objects, keyed by gene name. diff --git a/tests/testthat/test-multi_modal.R b/tests/testthat/test-multi_modal.R index 35e13aa..361f933 100644 --- a/tests/testthat/test-multi_modal.R +++ b/tests/testthat/test-multi_modal.R @@ -72,6 +72,12 @@ test_that("add_combined_dims validates inputs", { ) }) +test_that("add_combined_dims prints no BPCells notices", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- make_embedding_proj() + expect_no_message(add_combined_dims(proj, c("LSI_ATAC", "LSI_RNA"))) +}) + test_that("add_umap consumes the combined embedding by name", { skip_if_not_installed("uwot") proj <- make_embedding_proj() @@ -136,10 +142,7 @@ test_that("import_feature_matrix_10x intersects barcodes and stays aligned", { write_test_10x_h5(h5, rna_bc) proj <- make_atac_proj(atac_bc) - expect_message( - proj <- import_feature_matrix_10x(proj, h5, dataset_name = "sampleA", verbose = TRUE), - "Barcode intersection" - ) + proj <- import_feature_matrix_10x(proj, h5, dataset_name = "sampleA") rna <- proj[["GeneExpressionMatrix", "sampleA"]] atac <- proj[["TileMatrix", "sampleA"]] @@ -216,3 +219,69 @@ test_that("import_feature_matrix_10x genes_to_exclude matches symbol or ID", { expect_equal(nrow(rna_id), 4L) # 5 genes - 1 dropped by ID expect_false("GENE1" %in% rownames(rna_id)) }) + +test_that("import_feature_matrix_10x reports its steps and what it added", { + withr::local_options(rlib_message_verbosity = "verbose") + h5 <- withr::local_tempfile(fileext = ".h5") + write_test_10x_h5(h5, paste0("bc_", 4:12)) + proj <- make_atac_proj(paste0("bc_", 1:10)) + + lines <- .strip_log(capture_messages(import_feature_matrix_10x( + proj, h5, dataset_name = "sampleA", genes_to_exclude = c("GENE1", "GENE2"), verbose = TRUE + ))) + expect_length(lines, 4) + expect_identical(lines, c( + sprintf("Feature import: '%s' (Gene Expression) into 'sampleA'", basename(h5)), + "Excluded 2 features matching genes_to_exclude", + "Matched 7 barcodes, dropped 3 ATAC-only and 2 RNA-only cells", + paste( + "Feature import finished [Xs]: added assay 'GeneExpressionMatrix' (3 features x 7 cells),", + "feature metadata 'gene_symbol'" + ) + )) + + lines <- .strip_log(capture_messages(import_feature_matrix_10x( + proj, h5, dataset_name = "sampleA", genes_to_exclude = "MISSING", verbose = TRUE + ))) + expect_length(lines, 3) + expect_identical(lines[2], "Matched 7 barcodes, dropped 3 ATAC-only and 2 RNA-only cells") + + expect_no_message(import_feature_matrix_10x(proj, h5, dataset_name = "sampleA", verbose = FALSE)) +}) + +test_that("import_feature_matrix_10x warns when gene symbols are unreadable", { + withr::local_options(rlib_message_verbosity = "verbose") + bc <- paste0("bc_", 1:8) + h5 <- withr::local_tempfile(fileext = ".h5") + write_test_10x_h5(h5, bc) + list_objects <- BPCells:::hdf5_group_objnames_cpp + # BPCells' writer always writes features/name, so hide it to simulate a file without symbols. + testthat::local_mocked_bindings( + hdf5_group_objnames_cpp = function(path, group) { + objs <- list_objects(path, group) + if (group == "matrix/features") setdiff(objs, "name") else objs + }, + .package = "BPCells" + ) + fallback <- paste0( + "^Gene symbols unavailable; genes_to_exclude matched IDs only and no symbol metadata was added\\.$" + ) + + expect_warning( + lines <- .strip_log(capture_messages( + proj <- import_feature_matrix_10x(make_atac_proj(bc), h5, dataset_name = "sampleA", verbose = TRUE) + )), + fallback + ) + expect_identical(lines, c( + sprintf("Feature import: '%s' (Gene Expression) into 'sampleA'", basename(h5)), + "Matched 8 barcodes, dropped 0 ATAC-only and 0 RNA-only cells", + "Feature import finished [Xs]: added assay 'GeneExpressionMatrix' (5 features x 8 cells)" + )) + fmeta <- get_feature_metadata(proj, assay_names = "GeneExpressionMatrix") + expect_false("gene_symbol" %in% colnames(fmeta)) + expect_warning( + import_feature_matrix_10x(make_atac_proj(bc), h5, dataset_name = "sampleA", verbose = FALSE), + fallback + ) +}) diff --git a/tests/testthat/test-plotting.R b/tests/testthat/test-plotting.R index a1c5e06..9f56a33 100644 --- a/tests/testthat/test-plotting.R +++ b/tests/testthat/test-plotting.R @@ -196,6 +196,61 @@ test_that("plot_embedding.MarchRProject works with matrix source", { expect_length(plots, 2) }) +test_that("plot_embedding reports each step and its result", { + withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) + proj <- create_test_trajectory_project()$proj + run <- function(...) plot_embedding(proj, plot_as = "points", ...) + + lines <- .strip_log(capture_messages( + run(color_by = "GeneScoreMatrix", col_name = c("gene_1", "gene_2", "gene_3"), verbose = TRUE) + )) + expect_identical(lines, c( + "Embedding plots: 3 features from 'GeneScoreMatrix' on 'UMAP', 120 cells", + "Fetched 3 features for 120 cells [Xs]", + "Embedding plots finished [Xs]: 3 plots" + )) + lines <- .strip_log(capture_messages( + run(color_by = "GeneScoreMatrix", col_name = "gene_1", verbose = TRUE) + )) + expect_identical(lines[c(1, 3)], c( + "Embedding plots: 1 feature from 'GeneScoreMatrix' on 'UMAP', 120 cells", + "Embedding plots finished [Xs]: 1 plot" + )) + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_identical(lines, c( + "Embedding plots: 'clusters' on 'UMAP', 120 cells", + "Embedding plots finished [Xs]: 1 plot" + )) + + set.seed(1) + emb <- matrix(rnorm(200), ncol = 2, dimnames = list(NULL, c("UMAP_1", "UMAP_2"))) + mat <- matrix(rnorm(300), nrow = 3, dimnames = list(c("G1", "G2", "G3"), NULL)) + lines <- .strip_log(capture_messages( + plot_embedding(mat, emb, features = c("G1", "G2"), plot_as = "points", verbose = TRUE) + )) + expect_identical(lines, c( + "Embedding plots: 2 features on 'UMAP', 100 cells", + "Fetched 2 features for 100 cells [Xs]", + "Embedding plots finished [Xs]: 2 plots" + )) + lines <- .strip_log(capture_messages(plot_embedding(rnorm(100), emb, verbose = TRUE))) + expect_identical(lines, c( + "Embedding plots: values on 'UMAP', 100 cells", + "Embedding plots finished [Xs]: 1 plot" + )) + expect_warning( + plot_embedding(mat, emb, features = c("G1", "nope"), plot_as = "points"), + "Features not found in x: nope" + ) + + expect_warning( + run(color_by = "GeneScoreMatrix", col_name = c("gene_1", "nope")), + "Features not found in GeneScoreMatrix: nope" + ) + expect_no_message(run(color_by = "GeneScoreMatrix", col_name = c("gene_1", "gene_2"), verbose = FALSE)) + expect_no_message(run(color_by = "GeneScoreMatrix", col_name = c("gene_1", "gene_2"))) +}) + test_that("plot_gene_scores produces ggplot list with ArchR theme", { # Single dataset project; add GeneScoreMatrix as a copy of RNA directly on the dataset proj <- create_test_project(cells = c(20), rna_val_method = "pois") @@ -262,6 +317,44 @@ test_that("plot_gene_scores patchwork = TRUE yields one shared bottom legend", { for (lim in fill_limits) expect_equal(lim, c(0, 1)) }) +test_that("plot_gene_scores reports each step and its result", { + withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) + proj <- create_test_trajectory_project()$proj + run <- function(genes = c("gene_1", "gene_2", "gene_3"), ...) { + plot_gene_scores(proj, genes = genes, plot_as = "points", ...) + } + + lines <- .strip_log(capture_messages(run(impute = FALSE, verbose = TRUE))) + expect_identical(lines, c( + "Gene score plots: 3 genes on 'UMAP', 120 cells, raw scores", + "Fetched 3 genes for 120 cells [Xs]", + "Gene score plots finished [Xs]: 3 plots" + )) + expect_warning( + lines <- .strip_log(capture_messages(run(verbose = TRUE))), + "Impute weights not found" + ) + expect_identical(lines[1], "Gene score plots: 3 genes on 'UMAP', 120 cells, raw scores") + expect_no_message(run(impute = FALSE)) + + cells <- colnames(proj[["GeneScoreMatrix"]]) + w <- Matrix::Diagonal(length(cells)) + dimnames(w) <- list(cells, cells) + proj$impute_weights <- list(weights = list(list(w))) + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_identical(lines, c( + "Gene score plots: 3 genes on 'UMAP', 120 cells, imputed", + "Imputed 3 genes over 120 cells [Xs]", + "Gene score plots finished [Xs]: 3 plots" + )) + lines <- .strip_log(capture_messages(run(genes = "gene_1", verbose = TRUE))) + expect_identical(lines[3], "Gene score plots finished [Xs]: 1 plot") + + expect_warning(run(genes = c("gene_1", "nope")), "Genes not found in GeneScoreMatrix: nope") + expect_no_message(run(verbose = FALSE)) + expect_no_message(run()) +}) + test_that("plot_doublet_scores uses plot_embedding for enrichment/score panels", { n <- 50 scores <- data.frame( @@ -277,6 +370,49 @@ test_that("plot_doublet_scores uses plot_embedding for enrichment/score panels", expect_equal(p$theme$legend.position, "bottom") }) +test_that("plot_doublet_scores reports its setup and result", { + withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) + n <- 50 + doublet_data <- list( + scores = data.frame(doublet_enrichment = rnorm(n), doublet_score = runif(n, 0, 5)), + cell_umap = data.frame(UMAP1 = rnorm(n), UMAP2 = rnorm(n)) + ) + ds <- MarchRDataset() + ds$doublet_data <- doublet_data + panels <- c("enrichment", "score") + + lines <- .strip_log(capture_messages(plot_doublet_scores(ds, plot = panels, verbose = TRUE))) + expect_identical(lines, c( + "Doublet score plots: 50 cells", + "Doublet score plots finished [Xs]: 2 plots" + )) + expect_warning( + lines <- .strip_log(capture_messages(plot_doublet_scores(ds, verbose = TRUE))), + "'density' panel skipped: sim_umap not found." + ) + expect_identical(lines[2], "Doublet score plots finished [Xs]: 2 plots") + + proj <- create_test_project(cells = n) + proj$datasets$dataset_1$doublet_data <- doublet_data + lines <- .strip_log(capture_messages(plot_doublet_scores(proj, plot = "score", verbose = TRUE))) + expect_identical(lines, c( + "Doublet score plots: 'dataset_1'", + "Doublet score plots finished [Xs]: 1 plot" + )) + lines <- .strip_log(capture_messages(plot_doublet_scores(proj, plot = panels, verbose = TRUE))) + expect_identical(lines[2], "Doublet score plots finished [Xs]: 2 plots") + for (src in list(ds, proj)) { + expect_warning( + lines <- .strip_log(capture_messages(plot_doublet_scores(src, plot = "density", verbose = TRUE))), + "'density' panel skipped: sim_umap not found." + ) + expect_identical(lines[2], "Doublet score plots finished [Xs]: 0 plots") + } + + expect_no_message(plot_doublet_scores(ds, plot = panels, verbose = FALSE)) + expect_no_message(plot_doublet_scores(proj, plot = panels)) +}) + test_that(".fetch_embedding auto-detects UMAP columns", { meta <- data.frame( cell_name = paste0("c", 1:5), diff --git a/tests/testthat/test-project-io.R b/tests/testthat/test-project-io.R index a76eb7d..f0c253f 100644 --- a/tests/testthat/test-project-io.R +++ b/tests/testthat/test-project-io.R @@ -242,3 +242,20 @@ test_that("save_project persists arbitrary on-disk iterables anywhere in the pro # Non-iterable fields survive untouched. expect_equal(loaded$marker_results[["GeneScoreMatrix"]]$params$assay_name, "GeneScoreMatrix") }) + +test_that("save_project muffles BPCells write notices and keeps its own notices", { + withr::local_options(rlib_message_verbosity = "verbose") + proj <- create_test_project() + expect_no_message(save_project(proj, path = tempfile("saveproj"))) + + proj$datasets[["dataset_1"]]$matrices[["RNA"]] <- write_matrix_dir( + proj$datasets[["dataset_1"]]$matrices[["RNA"]], tempfile("ext_mat"), compress = FALSE + ) + msgs <- capture_messages(save_project(proj, path = tempfile("saveproj"), copy = FALSE)) + expect_match( + msgs[-length(msgs)], "^Writing '.*' into the project directory: it was not already stored on disk" + ) + expect_match( + msgs[length(msgs)], "^Saved project references data outside its directory \\(not self-contained\\):" + ) +}) diff --git a/tests/testthat/test-track-plotting.R b/tests/testthat/test-track-plotting.R index b696b9a..15c4b29 100644 --- a/tests/testthat/test-track-plotting.R +++ b/tests/testthat/test-track-plotting.R @@ -284,3 +284,70 @@ test_that(".trackplot_peaks renders an empty track when no peaks overlap", { expect_equal(nrow(gg$layers[[1]]$data), 0) }) +browser_test_project <- function() { + proj <- create_test_project(include_fragments = TRUE) + cells <- unlist(cell_names(proj), use.names = FALSE) + proj <- add_cell_metadata_col( + proj, setNames(rep(c("C1", "C2"), length.out = length(cells)), cells), "clusters" + ) + proj$genome$annotations$transcripts <- data.frame( + gene_name = "GENEA", feature = c("transcript", "exon"), chr = "chr1", + start = 20L, end = c(40L, 30L), strand = "+", stringsAsFactors = FALSE + ) + proj$genome$annotations$genes <- data.frame( + gene_name = "GENEA", chr = "chr1", start = 20L, end = 40L, strand = "+", + stringsAsFactors = FALSE + ) + proj +} + +test_that("plot_browser_track warns about cells missing QC data when not verbose", { + proj <- browser_test_project() + for (ds in names(proj$datasets)) { + proj$datasets[[ds]]$qc_frags$fragments <- data.frame( + cellName = cell_names(proj$datasets[[ds]]), nFrags = 10 + ) + } + qc <- proj$datasets$dataset_1$qc_frags$fragments + proj$datasets$dataset_1$qc_frags$fragments <- qc[-(1:2), ] + expect_warning( + plot_browser_track(proj, region = "chr1:0-50", tracks = "coverage", bins = 10L, verbose = FALSE), + "2 cells missing QC data for 'nFrags'. Using median as fallback.", fixed = TRUE + ) +}) + +test_that("plot_browser_track reports each step and its result", { + withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) + proj <- browser_test_project() + peaks <- data.frame(chr = "chr1", start = 10L, end = 20L) + run <- function(...) plot_browser_track(proj, bins = 10L, norm_method = "nCells", ...) + + lines <- .strip_log(capture_messages( + run(gene_symbol = "GENEA", upstream = 30, downstream = 30, features = peaks, verbose = TRUE) + )) + expect_identical(lines, c( + "Browser track: GENEA at chr1:0-50, 2 groups (16 cells)", + "Computed coverage in 10 bins [Xs]", + "Browser track finished [Xs]: 3 tracks (coverage, peaks, gene)" + )) + expect_warning( + lines <- .strip_log(capture_messages(run(region = "chr1:0-50", verbose = TRUE))), + "No peak set; skipped the peaks track.", fixed = TRUE + ) + expect_identical(lines, c( + "Browser track: chr1:0-50, 2 groups (16 cells)", + "Computed coverage in 10 bins [Xs]", + "Browser track finished [Xs]: 2 tracks (coverage, gene)" + )) + expect_warning(run(region = "chr1:0-50"), "No peak set; skipped the peaks track.", fixed = TRUE) + expect_warning( + lines <- .strip_log(capture_messages( + run(region = "chr1:0-50", tracks = c("coverage", "loop"), verbose = TRUE) + )), + "No loops; skipped the loop track.", fixed = TRUE + ) + expect_identical(lines[3], "Browser track finished [Xs]: 1 track (coverage)") + + expect_no_message(run(region = "chr1:0-50", features = peaks, verbose = FALSE)) + expect_no_message(run(region = "chr1:0-50", features = peaks)) +}) diff --git a/tests/testthat/test-trajectory.R b/tests/testthat/test-trajectory.R index e26e72b..f51d8ee 100644 --- a/tests/testthat/test-trajectory.R +++ b/tests/testthat/test-trajectory.R @@ -92,6 +92,53 @@ test_that("add_trajectory embedding path agrees with reduced-dims ordering", { expect_gt(abs(cor(a[ok], b[ok], method = "spearman")), 0.7) }) +test_that("add_trajectory reports each step and its result", { + withr::local_options(rlib_message_verbosity = "verbose", MarchR.verbose = NULL) + f <- create_test_trajectory_project() + run <- function(proj = f$proj, trajectory = c("C1", "C2", "C3"), ...) { + add_trajectory(proj, trajectory = trajectory, dof = 20L, ...) + } + + lines <- .strip_log(capture_messages(run(verbose = TRUE))) + expect_identical(lines, c( + "Trajectory: 3 groups (C1 -> C2 -> C3), 90 cells on 'IterativeLSI' (5 dims)", + "Kept 81 of 90 cells near group centroids", + "Fit 5 smoothing splines [Xs]", + "Aligned 90 cells to the spline, kept 81 [Xs]", + "Trajectory finished [Xs]: added cell metadata column 'trajectory' (81 cells with pseudotime)" + )) + + lines <- .strip_log(capture_messages(proj <- run(use_all = TRUE, verbose = TRUE))) + expect_length(lines, 6) + kept <- sub("^Aligned 30 off-trajectory cells, kept ([0-9]+) \\[Xs\\]$", "\\1", lines[5]) + expect_match(kept, "^[0-9]+$", perl = TRUE) + n_pt <- 81L + as.integer(kept) + expect_identical(lines[5:6], c( + sprintf("Aligned 30 off-trajectory cells, kept %s [Xs]", kept), + sprintf( + "Trajectory finished [Xs]: added cell metadata column 'trajectory' (%d cells with pseudotime)", + n_pt + ) + )) + expect_identical(sum(!is.na(.restore_project_cell_metadata(proj)$trajectory)), n_pt) + expect_false(any(grepl("HNSW", lines))) + + lines <- .strip_log(capture_messages(run(embedding = "UMAP", verbose = TRUE))) + expect_identical(lines[1], "Trajectory: 3 groups (C1 -> C2 -> C3), 90 cells on 'UMAP' (2 dims)") + + fine <- paste0("G", ceiling(rank(f$latent, ties.method = "first") / 20)) + proj <- add_cell_metadata_col(f$proj, stats::setNames(fine, names(f$latent)), "fine") + lines <- .strip_log(capture_messages( + run(proj, trajectory = paste0("G", 1:6), group_by = "fine", verbose = TRUE) + )) + expect_identical( + lines[1], "Trajectory: 6 groups (G1 -> ... -> G6), 120 cells on 'IterativeLSI' (5 dims)" + ) + + expect_no_message(run(verbose = FALSE)) + expect_no_message(run()) +}) + test_that(".get_trajectory_group_matrix sums features per bin via streaming multiply", { f <- create_test_trajectory_project() proj <- f$proj @@ -152,6 +199,50 @@ test_that("get_trajectory populates colData label via trajectory_label", { expect_true(all(SummarizedExperiment::colData(se)$label %in% c("C1","C2","C3"))) }) +test_that("get_trajectory drops empty bins silently and warns on negative values or a missing label", { + skip_if_not_installed("SummarizedExperiment") + f <- create_test_trajectory_project() + proj <- add_trajectory(f$proj, trajectory = c("C1", "C2", "C3"), dof = 20L) + proj <- add_matrix(proj, proj[["GeneScoreMatrix"]] - 5, mat_name = "NegMatrix", + dataset_name = "dataset_1", prefix_cells = FALSE) + + expect_no_warning(se <- get_trajectory(proj)) + expect_identical(S4Vectors::metadata(se)$Params$dropped_empty_bins, 19L) + expect_identical(ncol(se), 81L) + expect_warning( + get_trajectory(proj, assay_name = "NegMatrix", group_every = 10L, log2_norm = FALSE), + "Negative values present; skipping CPM scaling.", fixed = TRUE + ) + expect_warning( + get_trajectory(proj, assay_name = "NegMatrix", group_every = 10L, scale_to = NULL), + "Negative values present; skipping log2 normalization.", fixed = TRUE + ) + expect_warning( + get_trajectory(proj, group_every = 10L, trajectory_label = "nope"), + "trajectory_label 'nope' not found in metadata; skipping labels.", fixed = TRUE + ) +}) + +test_that("get_trajectory and the trajectory plots muffle BPCells notices", { + skip_if_not_installed("SummarizedExperiment") + withr::local_options(rlib_message_verbosity = "verbose") + f <- create_test_trajectory_project() + proj <- add_trajectory(f$proj, trajectory = c("C1", "C2", "C3"), dof = 20L) + expect_no_message(get_trajectory(proj, group_every = 10L)) + expect_no_message(plot_trajectory(proj, embedding = "UMAP", color_by = "GeneScoreMatrix", + col_name = "gene_1", add_arrow = FALSE)) + expect_no_message(plot_trajectory_profile(proj, color_by = "GeneScoreMatrix", col_name = "gene_1")) +}) + +test_that("plot_trajectory stays silent when MarchR.verbose is TRUE", { + f <- create_test_trajectory_project() + proj <- add_trajectory(f$proj, trajectory = c("C1", "C2", "C3"), dof = 20L) + withr::local_options(MarchR.verbose = TRUE) + expect_no_message(plot_trajectory(proj, add_arrow = FALSE)) + expect_no_message(plot_trajectory(proj, color_by = "GeneScoreMatrix", col_name = "gene_1", + add_arrow = FALSE)) +}) + test_that("plot_trajectory_heatmap returns a Heatmap and orders rows by peak", { skip_if_not_installed("SummarizedExperiment") skip_if_not_installed("ComplexHeatmap") From 7aa7f6356671c7d539114807e95169c673775b48 Mon Sep 17 00:00:00 2001 From: erliuu Date: Fri, 23 Oct 2026 02:13:06 -0700 Subject: [PATCH 12/12] feat([html] tutorials): Regenerate tutorials with updated logging across all modules --- vignettes/marchr_chrombpnet.Rmd | 11 +- vignettes/marchr_chrombpnet.html | 154 +++++++-------- vignettes/marchr_hematopoiesis.html | 94 ++++----- vignettes/marchr_multiome.Rmd | 2 +- vignettes/marchr_multiome.html | 293 +++++++--------------------- vignettes/marchr_scE2G.Rmd | 8 +- vignettes/marchr_scE2G.html | 8 +- 7 files changed, 199 insertions(+), 371 deletions(-) diff --git a/vignettes/marchr_chrombpnet.Rmd b/vignettes/marchr_chrombpnet.Rmd index af49ea8..cd36e83 100644 --- a/vignettes/marchr_chrombpnet.Rmd +++ b/vignettes/marchr_chrombpnet.Rmd @@ -144,14 +144,15 @@ ChromBPNet arguments. ```{r} -proj <- add_group_coverages(proj, group_by = "atac_clusters") +proj <- add_group_coverages(proj, group_by = "atac_clusters", verbose = TRUE) proj <- add_reproducible_peak_set( proj, group_by = "atac_clusters", additional_params = paste( "--call-summits --keep-dup all --shift -75 --extsize 150 --nomodel --nolambda", "-p 0.01" - ) + ), + verbose = TRUE ) ``` @@ -169,7 +170,7 @@ Fragments are pooled across the three datasets and pass through the same blackli filters as peak calling, so the exported fragments and peaks cover the same regions. ```{r} -pb <- pseudobulk_fragments(proj, group_by = "atac_clusters") +pb <- pseudobulk_fragments(proj, group_by = "atac_clusters", verbose = TRUE) pb ``` @@ -185,7 +186,7 @@ ChromBPNet does not publish a minimum depth, so pick the floor for your own data These are the `-ifrag` inputs. ```{r} -pb <- write_pseudobulk_fragments(pb, export_dir) +pb <- write_pseudobulk_fragments(pb, export_dir, verbose = TRUE) ``` ```{r} @@ -210,7 +211,7 @@ One difference is that MarchR has already removed fragments in blacklisted regio `union.narrowPeak`. ```{r} -pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group") +pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group", verbose = TRUE) read.delim(pb$manifest$peaks_path[[1]], header = FALSE, nrows = 5) ``` diff --git a/vignettes/marchr_chrombpnet.html b/vignettes/marchr_chrombpnet.html index 2733947..01d62b4 100644 --- a/vignettes/marchr_chrombpnet.html +++ b/vignettes/marchr_chrombpnet.html @@ -1638,70 +1638,56 @@

Setup

Calling Peaks per Cluster

ChromBPNet trains each cluster’s model on that cluster’s own peaks. add_group_coverages() builds pseudobulk replicates for each cluster, and add_reproducible_peak_set() calls peaks on them with MACS3. It stores the merged peak set in proj$peak_set and each cluster’s reproducible peaks in proj$group_peak_sets, which is what gets exported below.

ChromBPNet recommends relaxed peak calls (“MACS2 with p-value parameter threshold set to 0.01”), so -p 0.01 is appended to the default MACS arguments.

-
proj <- add_group_coverages(proj, group_by = "atac_clusters")
+
proj <- add_group_coverages(proj, group_by = "atac_clusters", verbose = TRUE)
proj <- add_reproducible_peak_set(
   proj,
   group_by = "atac_clusters",
   additional_params = paste(
     "--call-summits --keep-dup all --shift -75 --extsize 150 --nomodel --nolambda",
     "-p 0.01"
-  )
+  ),
+  verbose = TRUE
 )
-
Output
## ###########
-## 2026-10-18 21:19:42 Creating pseudobulk replicates for 11 groups, 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:19:42   Group 'C8': 2546 cells -> 2 replicates (500, 500 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C4': 434 cells -> 2 replicates (255, 173 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C2': 1352 cells -> 2 replicates (500, 67 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C6': 378 cells -> 2 replicates (189, 189 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C5': 322 cells -> 2 replicates (168, 145 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C10': 1188 cells -> 2 replicates (500, 343 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C1': 862 cells -> 2 replicates (500, 279 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C9': 876 cells -> 2 replicates (500, 201 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C3': 574 cells -> 2 replicates (500, 48 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C7': 446 cells -> 2 replicates (358, 88 cells each), 0.000 mins elapsed.
-## 2026-10-18 21:19:42   Group 'C11': 1293 cells -> 2 replicates (500, 143 cells each), 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:19:42 Calling peaks per replicate, 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:19:42   C8_Rep1: 500 cells, 0.000 mins elapsed.
-## 2026-10-18 21:20:06   C8_Rep2: 500 cells, 0.408 mins elapsed.
-## 2026-10-18 21:20:27   C4_Rep1: 255 cells, 0.758 mins elapsed.
-## 2026-10-18 21:21:17   C4_Rep2: 173 cells, 1.598 mins elapsed.
-## 2026-10-18 21:22:08   C2_Rep1: 500 cells, 2.436 mins elapsed.
-## 2026-10-18 21:23:24   C2_Rep2: 67 cells, 3.714 mins elapsed.
-## 2026-10-18 21:23:47   C6_Rep1: 189 cells, 4.083 mins elapsed.
-## 2026-10-18 21:24:37   C6_Rep2: 189 cells, 4.918 mins elapsed.
-## 2026-10-18 21:25:28   C5_Rep1: 168 cells, 5.772 mins elapsed.
-## 2026-10-18 21:26:23   C5_Rep2: 145 cells, 6.696 mins elapsed.
-## 2026-10-18 21:26:56   C10_Rep1: 500 cells, 7.235 mins elapsed.
-## 2026-10-18 21:27:23   C10_Rep2: 343 cells, 7.695 mins elapsed.
-## 2026-10-18 21:27:56   C1_Rep1: 500 cells, 8.237 mins elapsed.
-## 2026-10-18 21:28:26   C1_Rep2: 279 cells, 8.744 mins elapsed.
-## 2026-10-18 21:29:17   C9_Rep1: 500 cells, 9.595 mins elapsed.
-## 2026-10-18 21:29:43   C9_Rep2: 201 cells, 10.017 mins elapsed.
-## 2026-10-18 21:30:39   C3_Rep1: 500 cells, 10.954 mins elapsed.
-## 2026-10-18 21:31:02   C3_Rep2: 48 cells, 11.342 mins elapsed.
-## 2026-10-18 21:31:17   C7_Rep1: 358 cells, 11.594 mins elapsed.
-## 2026-10-18 21:32:32   C7_Rep2: 88 cells, 12.847 mins elapsed.
-## 2026-10-18 21:32:53   C11_Rep1: 500 cells, 13.198 mins elapsed.
-## 2026-10-18 21:33:17   C11_Rep2: 143 cells, 13.589 mins elapsed.
-## 2026-10-18 21:34:00 Filtering for reproducible peaks, 14.302 mins elapsed.
-## 2026-10-18 21:34:12   Group 'C8': 72869 reproducible peaks (from 2 replicates), 14.506 mins elapsed.
-## 2026-10-18 21:35:35   Group 'C4': 86125 reproducible peaks (from 2 replicates), 15.885 mins elapsed.
-## 2026-10-18 21:36:58   Group 'C2': 57013 reproducible peaks (from 2 replicates), 17.277 mins elapsed.
-## 2026-10-18 21:38:29   Group 'C6': 95956 reproducible peaks (from 2 replicates), 18.789 mins elapsed.
-## 2026-10-18 21:39:41   Group 'C5': 95402 reproducible peaks (from 2 replicates), 19.990 mins elapsed.
-## 2026-10-18 21:40:06   Group 'C10': 99365 reproducible peaks (from 2 replicates), 20.405 mins elapsed.
-## 2026-10-18 21:41:03   Group 'C1': 77834 reproducible peaks (from 2 replicates), 21.358 mins elapsed.
-## 2026-10-18 21:42:10   Group 'C9': 91391 reproducible peaks (from 2 replicates), 22.477 mins elapsed.
-## 2026-10-18 21:42:22   Group 'C3': 38690 reproducible peaks (from 2 replicates), 22.668 mins elapsed.
-## 2026-10-18 21:44:02   Group 'C7': 70884 reproducible peaks (from 2 replicates), 24.342 mins elapsed.
-## 2026-10-18 21:44:30   Group 'C11': 70714 reproducible peaks (from 2 replicates), 24.803 mins elapsed.
-## 2026-10-18 21:44:38 Final peak set: 306316 peaks, 24.934 mins elapsed.
-## 2026-10-18 21:44:38   Distal: 114959, 24.934 mins elapsed.
-## 2026-10-18 21:44:38   Intronic: 164432, 24.934 mins elapsed.
-## 2026-10-18 21:44:38   Promoter: 26925, 24.934 mins elapsed.
+
Output
## 2026-10-23 00:49:26 Group coverages: 10,271 cells in 11 groups by 'atac_clusters', 3 samples
+## Split 11 groups into 22 replicates (48-500 cells each) [0.0s]
+## 2026-10-23 00:49:26 Group coverages finished [0.0s]: added group coverages 'atac_clusters' (11 groups, 22 replicates)
+## 2026-10-23 00:49:26 Peak calling: 22 replicates in 11 groups (6,646 cells), macs3, reproducibility 2
+## C8_Rep1: called 178,033 summits from 500 cells [24.0s]
+## C8_Rep2: called 149,597 summits from 500 cells [21.1s]
+## C4_Rep1: called 524,841 summits from 255 cells [49.2s]
+## C4_Rep2: called 505,807 summits from 173 cells [47.3s]
+## C2_Rep1: called 772,402 summits from 500 cells [73.5s]
+## C2_Rep2: called 225,696 summits from 67 cells [21.1s]
+## C6_Rep1: called 492,310 summits from 189 cells [47.2s]
+## C6_Rep2: called 530,878 summits from 189 cells [52.1s]
+## C5_Rep1: called 562,721 summits from 168 cells [53.0s]
+## C5_Rep2: called 311,965 summits from 145 cells [31.7s]
+## C10_Rep1: called 198,509 summits from 500 cells [26.4s]
+## C10_Rep2: called 245,096 summits from 343 cells [31.1s]
+## C1_Rep1: called 195,083 summits from 500 cells [30.2s]
+## C1_Rep2: called 527,671 summits from 279 cells [50.9s]
+## C9_Rep1: called 187,243 summits from 500 cells [25.2s]
+## C9_Rep2: called 621,225 summits from 201 cells [58.0s]
+## C3_Rep1: called 156,732 summits from 500 cells [24.3s]
+## C3_Rep2: called 154,818 summits from 48 cells [14.7s]
+## C7_Rep1: called 770,095 summits from 358 cells [77.1s]
+## C7_Rep2: called 232,441 summits from 88 cells [22.2s]
+## C11_Rep1: called 175,068 summits from 500 cells [24.3s]
+## C11_Rep2: called 340,654 summits from 143 cells [32.3s]
+## C8: kept 72,869 reproducible peaks (2 replicates) [12.6s]
+## C4: kept 86,125 reproducible peaks (2 replicates) [81.4s]
+## C2: kept 57,013 reproducible peaks (2 replicates) [84.3s]
+## C6: kept 95,956 reproducible peaks (2 replicates) [88.3s]
+## C5: kept 95,402 reproducible peaks (2 replicates) [70.4s]
+## C10: kept 99,365 reproducible peaks (2 replicates) [23.6s]
+## C1: kept 77,834 reproducible peaks (2 replicates) [54.9s]
+## C9: kept 91,391 reproducible peaks (2 replicates) [65.0s]
+## C3: kept 38,690 reproducible peaks (2 replicates) [11.7s]
+## C7: kept 70,884 reproducible peaks (2 replicates) [105.5s]
+## C11: kept 70,714 reproducible peaks (2 replicates) [28.5s]
+## Merged 856,243 group peaks into 306,316 peaks [5.2s]
+## Annotated 306,316 peaks: 114,959 Distal, 164,432 Intronic, 26,925 Promoter [4.9s]
+## 2026-10-23 01:13:10 Peak calling finished [1486.0s]: added peak set (306,316 peaks) and 11 group peak sets
 
@@ -1710,9 +1696,11 @@

Grouping Fragments by Cluster

plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters")

pseudobulk_fragments() groups cells by a metadata column and returns one lazy fragment set per group. Fragments are pooled across the three datasets and pass through the same blacklist and chromosome filters as peak calling, so the exported fragments and peaks cover the same regions.

-
pb <- pseudobulk_fragments(proj, group_by = "atac_clusters")
-pb
-
Output
## MarchRPseudobulk: 11 groups (by atac_clusters)
+
pb <- pseudobulk_fragments(proj, group_by = "atac_clusters", verbose = TRUE)
+
pb
+
Output
## 2026-10-23 01:13:11 Pseudobulk: 10,271 cells in 11 groups by 'atac_clusters', 3 datasets
+## 2026-10-23 01:13:11 Pseudobulk finished [0.0s]: 11 fragment sets (37,183,949 fragments)
+## MarchRPseudobulk: 11 groups (by atac_clusters)
 ## # A tibble: 11 × 5
 ##    group n_cells n_fragments median_tss_enrichment passed_depth_gate
 ##    <chr>   <int>       <dbl>                 <dbl> <lgl>            
@@ -1733,20 +1721,20 @@ 

Grouping Fragments by Cluster

Writing Fragment Files

write_pseudobulk_fragments() writes one gzipped, 10x-style fragment file per cluster to export_dir/fragments/. These are the -ifrag inputs.

-
pb <- write_pseudobulk_fragments(pb, export_dir)
-
Output
## ###########
-## 2026-10-18 21:44:39   Writing fragments for group 'C8', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:44:43   Writing fragments for group 'C4', 0.072 mins elapsed.
-## 2026-10-18 21:44:44   Writing fragments for group 'C2', 0.092 mins elapsed.
-## 2026-10-18 21:44:46   Writing fragments for group 'C6', 0.127 mins elapsed.
-## 2026-10-18 21:44:47   Writing fragments for group 'C5', 0.146 mins elapsed.
-## 2026-10-18 21:44:48   Writing fragments for group 'C10', 0.165 mins elapsed.
-## 2026-10-18 21:44:52   Writing fragments for group 'C1', 0.218 mins elapsed.
-## 2026-10-18 21:44:54   Writing fragments for group 'C9', 0.263 mins elapsed.
-## 2026-10-18 21:44:56   Writing fragments for group 'C3', 0.298 mins elapsed.
-## 2026-10-18 21:44:58   Writing fragments for group 'C7', 0.329 mins elapsed.
-## 2026-10-18 21:45:00   Writing fragments for group 'C11', 0.350 mins elapsed.
+
pb <- write_pseudobulk_fragments(pb, export_dir, verbose = TRUE)
+
Output
## 2026-10-23 01:13:11 Fragment export: 11 groups to '/home/eric1126/.cache/marchr_hematopoiesis/chrombpnet_tutorial'
+## C8: wrote fragments for 2,546 cells [5.0s]
+## C4: wrote fragments for 434 cells [1.3s]
+## C2: wrote fragments for 1,352 cells [2.1s]
+## C6: wrote fragments for 378 cells [1.2s]
+## C5: wrote fragments for 322 cells [1.2s]
+## C10: wrote fragments for 1,188 cells [3.2s]
+## C1: wrote fragments for 862 cells [2.7s]
+## C9: wrote fragments for 876 cells [2.1s]
+## C3: wrote fragments for 574 cells [1.9s]
+## C7: wrote fragments for 446 cells [1.3s]
+## C11: wrote fragments for 1,293 cells [2.8s]
+## 2026-10-23 01:13:35 Fragment export finished [24.8s]: added manifest column 'fragments_path' (11 files)
 
read.delim(pb$manifest$fragments_path[[1]], header = FALSE, nrows = 5)
Output
##     V1     V2     V3                                V4
@@ -1762,21 +1750,11 @@ 

Writing Fragment Files

Writing Peaks

write_pseudobulk_peaks() writes each cluster’s peaks to export_dir/peaks/. scope = "group" skips the merged peak set; the default, "both", also writes it as union.narrowPeak.

-
pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group")
+
pb <- write_pseudobulk_peaks(pb, export_dir, scope = "group", verbose = TRUE)
read.delim(pb$manifest$peaks_path[[1]], header = FALSE, nrows = 5)
-
Output
## ###########
-## 2026-10-18 21:45:02   Writing peaks for group 'C8', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:45:03   Writing peaks for group 'C4', 0.003 mins elapsed.
-## 2026-10-18 21:45:03   Writing peaks for group 'C2', 0.007 mins elapsed.
-## 2026-10-18 21:45:03   Writing peaks for group 'C6', 0.010 mins elapsed.
-## 2026-10-18 21:45:03   Writing peaks for group 'C5', 0.014 mins elapsed.
-## 2026-10-18 21:45:03   Writing peaks for group 'C10', 0.018 mins elapsed.
-## 2026-10-18 21:45:04   Writing peaks for group 'C1', 0.023 mins elapsed.
-## 2026-10-18 21:45:04   Writing peaks for group 'C9', 0.027 mins elapsed.
-## 2026-10-18 21:45:04   Writing peaks for group 'C3', 0.031 mins elapsed.
-## 2026-10-18 21:45:04   Writing peaks for group 'C7', 0.033 mins elapsed.
-## 2026-10-18 21:45:05   Writing peaks for group 'C11', 0.036 mins elapsed.
+
Output
## 2026-10-23 01:13:35 Peak export: 11 groups to '/home/eric1126/.cache/marchr_hematopoiesis/chrombpnet_tutorial'
+## Wrote 11 group peak files (38,690-99,365 peaks) [2.4s]
+## 2026-10-23 01:13:37 Peak export finished [2.4s]: added manifest column 'peaks_path' (11 files)
 ##      V1        V2        V3   V4   V5 V6      V7      V8 V9 V10
 ## 1 chr14  77234591  77235092 C8_1 1000  . 314.012 314.012 -1 250
 ## 2  chr2  64977998  64978499 C8_2 1000  . 211.867 211.867 -1 250
diff --git a/vignettes/marchr_hematopoiesis.html b/vignettes/marchr_hematopoiesis.html
index 1c9e69c..126c242 100644
--- a/vignettes/marchr_hematopoiesis.html
+++ b/vignettes/marchr_hematopoiesis.html
@@ -1577,7 +1577,7 @@ 

Initialize a MarchRProject

} proj
Output
## MarchRProject Object
-## Directory: /tmp/RtmpdQmqNu/marchr_project
+## Directory: /tmp/RtmprU04Ui/marchr_project
 ## 3 Datasets:
 ##   scATAC_BMMC_R1:
 ##     5000 cells: scATAC_BMMC_R1#TAGGAGGGTTAACCGT-1, scATAC_BMMC_R1#CCTTGGTAGTTCTCCC-1, scATAC_BMMC_R1#GCCAGCAGTTCTGAGT-1, scATAC_BMMC_R1#TAGCATGGTGACCAGA-1 ... scATAC_BMMC_R1#CTGCTCAAGTGTCGGA-1
@@ -1669,58 +1669,58 @@ 

Doublet Scoring and Filtering

assay_name = "TileMatrix", verbose = TRUE )
-
Output
## 2026-10-20 13:57:15 Doublet scoring: 3 datasets, 10,681 cells, 4 threads
+
Output
## 2026-10-23 00:07:23 Doublet scoring: 3 datasets, 10,681 cells, 4 threads
 ## [scATAC_BMMC_R1]
-##   Transposed TileMatrix storage order [5.1s]
+##   Transposed TileMatrix storage order [5.3s]
 ##   Simulated 20,000 doublets (1,000 x 20 trials)
 ##   Iterative LSI: 4,939 cells, 2 iterations, 30 dims, 4 threads
 ##     [Iteration 1/2]
-##       Selected 25,000 features (top accessible) [2.7s]
-##       Fit LSI on 4,939 cells [1.3s]
+##       Selected 25,000 features (top accessible) [2.6s]
+##       Fit LSI on 4,939 cells [1.2s]
 ## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
-##       Found 15 clusters, merged to 6 [0.7s]
+##       Found 15 clusters, merged to 6 [0.6s]
 ##       Pseudobulked 6 clusters [0.7s]
-##       Iteration finished [5.4s]
+##       Iteration finished [5.2s]
 ##     [Iteration 2/2]
 ##       Selected 25,000 variable features [0.2s]
 ##       Fit LSI on 4,939 cells [1.5s]
 ##       Iteration finished [1.7s]
-##   Iterative LSI finished [8.2s]: 4,939 x 30 embedding
-##   Projected 20,000 doublets into LSI [6.6s]
-##   Fit UMAP, re-projection R^2 = 0.984 [4.9s]
-##   Projected 20,000 doublets into UMAP [1.3s]
+##   Iterative LSI finished [8.1s]: 4,939 x 30 embedding
+##   Projected 20,000 doublets into LSI [6.4s]
+##   Fit UMAP, re-projection R^2 = 0.984 [4.8s]
+##   Projected 20,000 doublets into UMAP [1.2s]
 ##   Scored 4,939 cells by doublet neighbors in UMAP [0.7s]
-##   Dataset finished [26.9s]
+##   Dataset finished [26.4s]
 ## [scATAC_CD34_BMMC_R1]
-##   Transposed TileMatrix storage order [5.2s]
+##   Transposed TileMatrix storage order [6.1s]
 ##   Simulated 15,000 doublets (1,000 x 15 trials)
 ##   Iterative LSI: 3,280 cells, 2 iterations, 30 dims, 4 threads
 ##     [Iteration 1/2]
 ##       Selected 25,000 features (top accessible) [1.1s]
-##       Fit LSI on 3,280 cells [0.9s]
+##       Fit LSI on 3,280 cells [1.0s]
 ## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 16 datapoints. Try higher ef value
 ##       Found 13 clusters, merged to 6 [0.4s]
 ##       Pseudobulked 6 clusters [0.6s]
-##       Iteration finished [3.1s]
+##       Iteration finished [3.2s]
 ##     [Iteration 2/2]
 ##       Selected 25,000 variable features [0.2s]
 ##       Fit LSI on 3,280 cells [0.8s]
 ##       Iteration finished [1.1s]
-##   Iterative LSI finished [5.3s]: 3,280 x 30 embedding
-##   Projected 15,000 doublets into LSI [4.9s]
+##   Iterative LSI finished [5.5s]: 3,280 x 30 embedding
+##   Projected 15,000 doublets into LSI [5.0s]
 ##   Fit UMAP, re-projection R^2 = 0.994 [4.2s]
 ##   Projected 15,000 doublets into UMAP [0.7s]
 ##   Scored 3,280 cells by doublet neighbors in UMAP [0.5s]
-##   Dataset finished [20.9s]
+##   Dataset finished [22.0s]
 ## [scATAC_PBMC_R1]
-##   Transposed TileMatrix storage order [4.5s]
+##   Transposed TileMatrix storage order [5.7s]
 ##   Simulated 10,000 doublets (1,000 x 10 trials)
 ##   Iterative LSI: 2,462 cells, 2 iterations, 30 dims, 4 threads
 ##     [Iteration 1/2]
 ##       Selected 25,000 features (top accessible) [1.1s]
-##       Fit LSI on 2,462 cells [1.0s]
+##       Fit LSI on 2,462 cells [0.9s]
 ## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 19 datapoints. Try higher ef value
 ##       Found 12 clusters, merged to 6 [0.3s]
@@ -1730,13 +1730,13 @@ 

Doublet Scoring and Filtering

## Selected 25,000 variable features [0.5s] ## Fit LSI on 2,462 cells [1.1s] ## Iteration finished [1.6s] -## Iterative LSI finished [5.4s]: 2,462 x 30 embedding +## Iterative LSI finished [5.3s]: 2,462 x 30 embedding ## Projected 10,000 doublets into LSI [4.0s] ## Fit UMAP, re-projection R^2 = 0.951 [4.0s] ## Projected 10,000 doublets into UMAP [0.5s] ## Scored 2,462 cells by doublet neighbors in UMAP [0.3s] -## Dataset finished [18.8s] -## 2026-10-20 13:58:18 Doublet scoring finished [66.6s]: added doublet scores to 3 datasets (10,681 cells) +## Dataset finished [20.0s] +## 2026-10-23 00:08:29 Doublet scoring finished [68.5s]: added doublet scores to 3 datasets (10,681 cells)
for (sample_name in names(input_files)) {
   print(plot_doublet_scores(proj, dataset_name = sample_name))
@@ -1744,11 +1744,11 @@ 

Doublet Scoring and Filtering

filter_doublets() removes the highest-enrichment predicted doublets from every dataset in the project.

proj <- filter_doublets(proj, verbose = TRUE)
-
Output
## 2026-10-20 13:58:22 Doublet filtering: 3 datasets, 10,681 cells (enrichment >= 1, filter ratio 1)
+
Output
## 2026-10-23 00:08:33 Doublet filtering: 3 datasets, 10,681 cells (enrichment >= 1, filter ratio 1)
 ## scATAC_BMMC_R1: removed 243 of 4,939 cells (4.9%) [0.0s]
 ## scATAC_CD34_BMMC_R1: removed 107 of 3,280 cells (3.3%) [0.0s]
 ## scATAC_PBMC_R1: removed 60 of 2,462 cells (2.4%) [0.0s]
-## 2026-10-20 13:58:22 Doublet filtering finished [0.0s]: removed 410 of 10,681 cells (3.8%), cleared doublet data
+## 2026-10-23 00:08:33 Doublet filtering finished [0.0s]: removed 410 of 10,681 cells (3.8%), cleared doublet data
 
@@ -1764,20 +1764,20 @@

Iterative LSI

max_clusters = 25, verbose = TRUE )
-
Output
## 2026-10-20 13:58:25 Iterative LSI: 10,271 cells, 2 iterations, 30 dims, 4 threads
+
Output
## 2026-10-23 00:08:37 Iterative LSI: 10,271 cells, 2 iterations, 30 dims, 4 threads
 ## [Iteration 1/2]
-##   Selected 25,000 features (top accessible) [1.5s]
+##   Selected 25,000 features (top accessible) [2.0s]
 ##   Fit LSI on 9,596 cells, projected 404 depth outliers [9.8s]
 ##   Dropped LSI component 1 (r = 0.80 with log10(nFrags))
 ##   Found 8 clusters [1.4s]
-##   Pseudobulked 8 clusters [3.4s]
-##   Iteration finished [16.3s]
+##   Pseudobulked 8 clusters [3.5s]
+##   Iteration finished [16.9s]
 ## [Iteration 2/2]
 ##   Selected 25,000 variable features [0.2s]
-##   Fit LSI on 9,859 cells, projected 412 depth outliers [8.3s]
+##   Fit LSI on 9,859 cells, projected 412 depth outliers [8.5s]
 ##   Dropped LSI component 1 (r = 0.77 with log10(nFrags))
-##   Iteration finished [8.6s]
-## 2026-10-20 13:58:51 Iterative LSI finished [27.9s]: added dim reduction 'IterativeLSI' (10,271 x 29)
+##   Iteration finished [8.9s]
+## 2026-10-23 00:09:06 Iterative LSI finished [29.1s]: added dim reduction 'IterativeLSI' (10,271 x 29)
 
@@ -1791,9 +1791,9 @@

Clustering

cluster_graph_method = cluster_graph_leiden(resolution = 0.8), knn_method = knn_hnsw(k = 20L) )
-
Output
## 2026-10-20 13:58:54 Clustering: 10,271 cells on 'IterativeLSI' (29 dims)
-## Found 11 clusters [1.7s]
-## 2026-10-20 13:58:55 Clustering finished [1.8s]: added cell metadata column 'atac_clusters' (11 clusters)
+
Output
## 2026-10-23 00:09:08 Clustering: 10,271 cells on 'IterativeLSI' (29 dims)
+## Found 11 clusters [1.8s]
+## 2026-10-23 00:09:09 Clustering finished [1.8s]: added cell metadata column 'atac_clusters' (11 clusters)
 
@@ -1806,10 +1806,10 @@

UMAP Embedding

min_dist = 0.5, verbose = TRUE )
-
Output
## 2026-10-20 13:58:55 UMAP: 10,271 cells on 'IterativeLSI' (29 dims), 4 threads
-## Fit 2D UMAP (30 neighbors, min_dist 0.5, cosine) [5.6s]
+
Output
## 2026-10-23 00:09:09 UMAP: 10,271 cells on 'IterativeLSI' (29 dims), 4 threads
+## Fit 2D UMAP (30 neighbors, min_dist 0.5, cosine) [6.1s]
 ## Saved UMAP model [0.2s]
-## 2026-10-20 13:59:01 UMAP finished [5.8s]: added cell metadata columns 'UMAP_1', 'UMAP_2', embedding model 'UMAP'
+## 2026-10-23 00:09:16 UMAP finished [6.3s]: added cell metadata columns 'UMAP_1', 'UMAP_2', embedding model 'UMAP'
 

We can visualize the attributes of our cells, using the plot_embedding() function, specifying the coloration via the col_name parameter.

plot_embedding(proj, col_name = "atac_clusters", title = "UMAP - Clusters") +
@@ -1835,15 +1835,12 @@ 

Assigning Clusters with Gene Scores

patchwork = TRUE )

-
Output
## Warning: Converting to a dense matrix may use excessive memory
-## This message is displayed once every 8 hours.
-

Raw gene scores can be noisy at the single-cell level. add_impute_weights() computes MAGIC diffusion weights from the LSI embedding.

proj <- add_impute_weights(proj, embedding_name = "IterativeLSI", verbose = TRUE)
-
Output
## 2026-10-20 13:59:10 Impute weights: 10,271 cells on 'IterativeLSI' (29 dims), 2 replicates x 2 blocks (~5,136 cells), td = 3, ka = 4
-## Replicate 1/2: built 2 diffusion graphs [2.9s]
-## Replicate 2/2: built 2 diffusion graphs [2.7s]
-## 2026-10-20 13:59:16 Impute weights finished [5.6s]: added impute weights (2 replicates x 2 blocks)
+
Output
## 2026-10-23 00:09:25 Impute weights: 10,271 cells on 'IterativeLSI' (29 dims), 2 replicates x 2 blocks (~5,136 cells), td = 3, ka = 4
+## Replicate 1/2: built 2 diffusion graphs [2.8s]
+## Replicate 2/2: built 2 diffusion graphs [2.5s]
+## 2026-10-23 00:09:30 Impute weights finished [5.4s]: added impute weights (2 replicates x 2 blocks)
 
plot_gene_scores(
   proj,
@@ -1854,9 +1851,6 @@ 

Assigning Clusters with Gene Scores

patchwork = TRUE )

-
Output
## 2026-10-20 13:59:18 Imputing gene scores with MAGIC weights
-## 2026-10-20 13:59:19 Finished [3.1s]
-

Genome Browser Tracks

@@ -1885,10 +1879,6 @@

Project Saving

save_project() writes a self-contained copy of the MarchRProject so you can run load_project() and load your project into a fresh R session.

saved_project_dir <- file.path(cache_dir, "saved_project")
 proj <- save_project(proj, path = saved_project_dir, overwrite = TRUE)
-
Output
## Warning: Matrix compression performs poorly with non-integers.
-## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
-## This message is displayed once every 8 hours.
-

When you are ready to load the saved project, simply provide the cached project directory,

proj <- load_project(saved_project_dir)
 proj
diff --git a/vignettes/marchr_multiome.Rmd b/vignettes/marchr_multiome.Rmd index ee23895..a66f3af 100644 --- a/vignettes/marchr_multiome.Rmd +++ b/vignettes/marchr_multiome.Rmd @@ -203,7 +203,7 @@ assay **in the existing ATAC dataset**, keeping only barcodes shared by both mod Rows are Ensembl IDs, with gene symbols stored in the feature metadata. ```{r} -proj <- import_feature_matrix_10x(proj, input = rna_h5) +proj <- import_feature_matrix_10x(proj, input = rna_h5, verbose = TRUE) proj <- align_cells(proj) head(get_feature_metadata(proj, assay_names = "GeneExpressionMatrix")) ``` diff --git a/vignettes/marchr_multiome.html b/vignettes/marchr_multiome.html index 3906a41..71a1bea 100644 --- a/vignettes/marchr_multiome.html +++ b/vignettes/marchr_multiome.html @@ -1574,7 +1574,7 @@

Initialize a MarchRProject

proj <- add_fragments(proj, frags, frags_name = "ATAC", dataset_name = sample_name) proj
Output
## MarchRProject Object
-## Directory: /tmp/RtmpKpXPaN/marchr_project
+## Directory: /tmp/RtmpLETOrO/marchr_project
 ## 1 Dataset:
 ##   PBMC_10k:
 ##     671397 cells: PBMC_10k#GTAGGTGCATAACGGG-1, PBMC_10k#CCAACCCGTGGAAGGC-1, PBMC_10k#ACGGGAAGTTTACGTC-1, PBMC_10k#TAGGTTGGTTTGTGGA-1 ... PBMC_10k#GTTTCCTCACCTACGG-1
@@ -1614,104 +1614,44 @@ 

Doublet Scoring and Filtering

add_doublet_scores() simulates synthetic doublets and scores each real cell by its local doublet enrichment; filter_doublets() removes the highest-enrichment predicted doublets.

proj <- add_doublet_scores(proj, assay_name = "TileMatrix", verbose = TRUE)
proj <- filter_doublets(proj, verbose = TRUE)
-
Output
## ###########
-## 2026-10-18 21:47:18 Processing dataset 1 of 1: PBMC_10k, 0.003 mins elapsed.
-## ###########
-## 2026-10-18 21:47:33 Simulating 65000 synthetic doublets (1000 doublets x 65 trials), 0.254 mins elapsed.
-## 2026-10-18 21:47:33 Running Iterative LSI on input matrix, 0.254 mins elapsed.
-## 2026-10-18 21:47:35 Starting Iterative LSI, 0.295 mins elapsed.
-## 2026-10-18 21:47:35 Starting Iterative LSI iteration 1 of 2, 0.295 mins elapsed.
-## 2026-10-18 21:47:35 Selecting features, 0.295 mins elapsed.
-## 2026-10-18 21:47:38 Running LSI, 0.334 mins elapsed.
-## 2026-10-18 21:47:38 Starting LSI, 0.336 mins elapsed.
-## 2026-10-18 21:47:39 Normalizing matrix, 0.360 mins elapsed.
-## Warning: Matrix compression performs poorly with non-integers.
-## • Consider calling convert_matrix_type if a compressed integer matrix is intended.
-## 2026-10-18 21:47:42 Calculating SVD, 0.397 mins elapsed.
-## 
-## 2026-10-18 21:47:48 Clustering LSI results, 0.512 mins elapsed.
-## 
-## 21:47:48 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 
-## 21:47:49 Finished building index
-## 
-## 21:47:49 Searching HNSW index with ef = 100 and 1 threads
-## 
-## 21:47:50 Finished searching
-## 
-## This message is displayed once every 8 hours.
-## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
+
Output
## 2026-10-23 00:12:40 Doublet scoring: 1 dataset, 13,164 cells, 4 threads
+## [PBMC_10k]
+##   Transposed TileMatrix storage order [16.5s]
+##   Simulated 65,000 doublets (1,000 x 65 trials)
+##   Iterative LSI: 13,164 cells, 2 iterations, 30 dims, 4 threads
+##     [Iteration 1/2]
+##       Selected 25,000 features (top accessible) [2.4s]
+##       Fit LSI on 10,000 cells [10.8s]
+## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 371 datapoints. Try higher ef value
-## 2026-10-18 21:47:50 Merging 29 clusters down to 6 via hierarchical clustering, 0.539 mins elapsed.
-## 2026-10-18 21:47:50 Pseudobulking matrix, 0.539 mins elapsed.
-## 2026-10-18 21:47:52 Starting Iterative LSI iteration 2 of 2, 0.565 mins elapsed.
-## 2026-10-18 21:47:52 Selecting features, 0.565 mins elapsed.
-## 2026-10-18 21:47:53 Running LSI, 0.586 mins elapsed.
-## 2026-10-18 21:47:53 Starting LSI, 0.586 mins elapsed.
-## 2026-10-18 21:47:54 Normalizing matrix, 0.607 mins elapsed.
-## 2026-10-18 21:47:57 Calculating SVD, 0.647 mins elapsed.
-## 2026-10-18 21:48:04 Finished running Iterative LSI, 0.766 mins elapsed.
-## 2026-10-18 21:48:04 Projecting simulated doublets on LSI space, 0.766 mins elapsed.
-## 2026-10-18 21:48:54 Running UMAP fitting on LSI matrix, 1.602 mins elapsed.
-## 21:48:54 Using HNSW for nearest neighbor search
-## 21:48:54 UMAP embedding parameters a = 0.7669 b = 1.223
-## 21:48:54 Setting random seed 1
-## 21:48:54 Read 13164 rows and found 30 numeric columns
-## 21:48:54 Building HNSW index with metric 'l2' ef = 200 M = 16 using 1 threads
-## 21:48:54 Finished building index
-## 21:48:54 Searching HNSW index with ef = 40 and 4 threads
-## 21:48:55 Finished searching
-## 21:48:56 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:48:57 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:48:57 Range-scaling initial input columns to 0-10
-## 21:48:57 Commencing optimization for 500 epochs, with 946616 positive edges using 4 threads
-## 21:48:57 Using rng type: pcg
-## 21:49:00 Optimization finished
-## 2026-10-18 21:49:00 Validating re-projection Pearson correlation, 1.705 mins elapsed.
-## 21:49:00 Setting model random seed 1
-## 21:49:00 Read 13164 rows and found 30 numeric columns
-## 21:49:00 Processing block 1 of 1
-## 21:49:00 Searching HNSW index with ef = 40 and 4 threads
-## 21:49:00 Finished searching
-## 21:49:00 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:49:00 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:49:00 Commencing optimization for 167 epochs, with 526560 positive edges using 4 threads
-## 21:49:01 Finished
-## 2026-10-18 21:49:01 UMAP Re-projection Correlation: R^2 = 0.902, 1.716 mins elapsed.
-## 2026-10-18 21:49:01 Projecting simulated doublets on UMAP space, 1.716 mins elapsed.
-## 21:49:01 Setting model random seed 1
-## 21:49:01 Read 65000 rows and found 30 numeric columns
-## 21:49:01 Processing block 1 of 1
-## 21:49:01 Searching HNSW index with ef = 40 and 4 threads
-## 21:49:01 Finished searching
-## 21:49:01 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:49:01 Initializing by weighted average of neighbor coordinates using 4 threads
-## 21:49:02 Commencing optimization for 167 epochs, with 2600000 positive edges using 4 threads
-## 21:49:04 Finished
-## 2026-10-18 21:49:04 Compute doublet scores and enrichments from UMAP, 1.771 mins elapsed.
-## 21:49:04 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:49:04 Finished building index
-## 21:49:04 Searching HNSW index with ef = 200 and 1 threads
-## 21:49:06 Finished searching
-## ###########
-## 2026-10-18 21:49:07 Filtering doublets in 1 dataset(s): PBMC_10k, 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:49:07 filtering dataset: PBMC_10k, 0.000 mins elapsed.
-## 2026-10-18 21:49:07 Filtering 1732 doublets from 13164 cells (13.2%), 0.000 mins elapsed.
-## 2026-10-18 21:49:07 Dataset successfully filtered, 0.000 mins elapsed.
-## 2026-10-18 21:49:07 Removing stale doublet data, 0.000 mins elapsed.
-## 2026-10-18 21:49:07 doublet filtering complete, 0.000 mins elapsed.
+##       Found 29 clusters, merged to 6 [1.6s]
+##       Pseudobulked 6 clusters [2.1s]
+##       Iteration finished [17.0s]
+##     [Iteration 2/2]
+##       Selected 25,000 variable features [1.3s]
+##       Fit LSI on 13,164 cells [11.2s]
+##       Iteration finished [12.5s]
+##   Iterative LSI finished [32.1s]: 13,164 x 30 embedding
+##   Projected 65,000 doublets into LSI [54.4s]
+##   Fit UMAP, re-projection R^2 = 0.902 [7.6s]
+##   Projected 65,000 doublets into UMAP [3.3s]
+##   Scored 13,164 cells by doublet neighbors in UMAP [3.2s]
+##   Dataset finished [117.3s]
+## 2026-10-23 00:14:32 Doublet scoring finished [117.3s]: added doublet scores to 1 dataset (13,164 cells)
+## 2026-10-23 00:14:32 Doublet filtering: 1 dataset, 13,164 cells (enrichment >= 1, filter ratio 1)
+## PBMC_10k: removed 1,732 of 13,164 cells (13.2%) [0.0s]
+## 2026-10-23 00:14:32 Doublet filtering finished [0.0s]: removed 1,732 of 13,164 cells (13.2%), cleared doublet data
 

Import RNA

import_feature_matrix_10x() adds the Gene Expression features as a GeneExpressionMatrix assay in the existing ATAC dataset, keeping only barcodes shared by both modalities. Rows are Ensembl IDs, with gene symbols stored in the feature metadata.

-
proj <- import_feature_matrix_10x(proj, input = rna_h5)
+
proj <- import_feature_matrix_10x(proj, input = rna_h5, verbose = TRUE)
proj <- align_cells(proj)
 head(get_feature_metadata(proj, assay_names = "GeneExpressionMatrix"))
-
Output
## ###########
-## 2026-10-18 21:49:07 Barcode intersection: 10010 shared, 1422 ATAC-only dropped, 2002 RNA-only dropped, 0.005 mins elapsed.
-## ###########
+
Output
## 2026-10-23 00:14:32 Feature import: 'pbmc_10k_filtered_feature_bc_matrix.h5' (Gene Expression) into 'PBMC_10k'
+## Matched 10,010 barcodes, dropped 1,422 ATAC-only and 2,002 RNA-only cells
+## 2026-10-23 00:14:32 Feature import finished [0.3s]: added assay 'GeneExpressionMatrix' (36,601 features x 10,010 cells), feature metadata 'gene_symbol'
 ##                 gene_symbol           assay_name
 ## ENSG00000243485 MIR1302-2HG GeneExpressionMatrix
 ## ENSG00000237613     FAM138A GeneExpressionMatrix
@@ -1741,64 +1681,34 @@ 

Iterative LSI

feature_selection_method = select_features_variance(num_feats = 2500L), verbose = TRUE )
-
Output
## ###########
-## 2026-10-18 21:49:16 Starting Iterative LSI, 0.149 mins elapsed.
-## ###########
-## 2026-10-18 21:49:16 Starting Iterative LSI iteration 1 of 2, 0.149 mins elapsed.
-## 2026-10-18 21:49:16 Selecting features, 0.149 mins elapsed.
-## 2026-10-18 21:49:19 Running LSI, 0.196 mins elapsed.
-## 2026-10-18 21:49:19 Starting LSI, 0.204 mins elapsed.
-## 2026-10-18 21:49:24 Filtering 401 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.278 mins elapsed.
-## 2026-10-18 21:49:27 Normalizing matrix, 0.340 mins elapsed.
-## 2026-10-18 21:49:36 Calculating SVD, 0.483 mins elapsed.
-## 2026-10-18 21:49:48 Dropping PCs 1 due to high correlation with sequencing depth, 0.685 mins elapsed.
-## 2026-10-18 21:49:48 Re-projecting outlier cells into LSI space, 0.685 mins elapsed.
-## 2026-10-18 21:49:57 Clustering LSI results, 0.837 mins elapsed.
-## 21:49:57 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:49:58 Finished building index
-## 21:49:58 Searching HNSW index with ef = 100 and 1 threads
-## 21:49:58 Finished searching
-## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
+
Output
## 2026-10-23 00:14:32 Iterative LSI: 10,010 cells, 2 iterations, 30 dims, 4 threads
+## [Iteration 1/2]
+##   Selected 25,000 features (top accessible) [2.6s]
+##   Fit LSI on 9,599 cells, projected 401 depth outliers [39.3s]
+##   Dropped LSI component 1 (r = 0.95 with log10(nFrags))
+## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 1 datapoints. Try higher ef value
-## 2026-10-18 21:49:58 Merging 22 clusters down to 6 via hierarchical clustering, 0.859 mins elapsed.
-## 2026-10-18 21:49:58 Pseudobulking matrix, 0.859 mins elapsed.
-## 2026-10-18 21:50:05 Starting Iterative LSI iteration 2 of 2, 0.967 mins elapsed.
-## 2026-10-18 21:50:05 Selecting features, 0.967 mins elapsed.
-## 2026-10-18 21:50:06 Running LSI, 0.977 mins elapsed.
-## 2026-10-18 21:50:06 Starting LSI, 0.977 mins elapsed.
-## 2026-10-18 21:50:09 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD, 1.039 mins elapsed.
-## 2026-10-18 21:50:13 Normalizing matrix, 1.106 mins elapsed.
-## 2026-10-18 21:50:21 Calculating SVD, 1.235 mins elapsed.
-## 2026-10-18 21:50:28 Dropping PCs 1 due to high correlation with sequencing depth, 1.358 mins elapsed.
-## 2026-10-18 21:50:28 Re-projecting outlier cells into LSI space, 1.358 mins elapsed.
-## 2026-10-18 21:50:37 Finished running Iterative LSI, 1.495 mins elapsed.
-## ###########
-## 2026-10-18 21:51:01 Starting Iterative LSI, 0.405 mins elapsed.
-## ###########
-## 2026-10-18 21:51:01 Starting Iterative LSI iteration 1 of 2, 0.405 mins elapsed.
-## 2026-10-18 21:51:01 Selecting features, 0.405 mins elapsed.
-## 2026-10-18 21:51:24 Running LSI, 0.796 mins elapsed.
-## 2026-10-18 21:51:24 Starting LSI, 0.796 mins elapsed.
-## 2026-10-18 21:51:28 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD, 0.848 mins elapsed.
-## 2026-10-18 21:51:31 Normalizing matrix, 0.899 mins elapsed.
-## 2026-10-18 21:51:36 Calculating SVD, 0.990 mins elapsed.
-## 2026-10-18 21:51:37 Re-projecting outlier cells into LSI space, 1.008 mins elapsed.
-## 2026-10-18 21:51:40 Clustering LSI results, 1.048 mins elapsed.
-## 21:51:40 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:51:40 Finished building index
-## 21:51:40 Searching HNSW index with ef = 100 and 1 threads
-## 21:51:41 Finished searching
-## 2026-10-18 21:51:41 Merging 27 clusters down to 6 via hierarchical clustering, 1.068 mins elapsed.
-## 2026-10-18 21:51:41 Pseudobulking matrix, 1.068 mins elapsed.
-## 2026-10-18 21:51:44 Starting Iterative LSI iteration 2 of 2, 1.119 mins elapsed.
-## 2026-10-18 21:51:44 Selecting features, 1.119 mins elapsed.
-## 2026-10-18 21:51:44 Running LSI, 1.119 mins elapsed.
-## 2026-10-18 21:51:44 Starting LSI, 1.119 mins elapsed.
-## 2026-10-18 21:52:06 Filtering 402 outlier cells (colSum quantiles 0.02-0.98) before SVD, 1.496 mins elapsed.
-## 2026-10-18 21:52:29 Normalizing matrix, 1.868 mins elapsed.
-## 2026-10-18 21:53:13 Calculating SVD, 2.598 mins elapsed.
-## 2026-10-18 21:53:14 Re-projecting outlier cells into LSI space, 2.614 mins elapsed.
-## 2026-10-18 21:53:16 Finished running Iterative LSI, 2.663 mins elapsed.
+##   Found 22 clusters, merged to 6 [1.4s]
+##   Pseudobulked 6 clusters [6.6s]
+##   Iteration finished [50.0s]
+## [Iteration 2/2]
+##   Selected 25,000 variable features [0.6s]
+##   Fit LSI on 9,608 cells, projected 402 depth outliers [31.7s]
+##   Dropped LSI component 1 (r = 0.96 with log10(nFrags))
+##   Iteration finished [32.4s]
+## 2026-10-23 00:15:59 Iterative LSI finished [91.0s]: added dim reduction 'LSI_ATAC' (10,010 x 29)
+## 2026-10-23 00:16:00 Iterative LSI: 10,010 cells, 2 iterations, 30 dims, 4 threads
+## [Iteration 1/2]
+##   Selected 2,500 variable features [24.3s]
+##   Fit LSI on 9,598 cells, projected 402 depth outliers [16.0s]
+##   Found 27 clusters, merged to 6 [1.3s]
+##   Pseudobulked 6 clusters [3.1s]
+##   Iteration finished [44.8s]
+## [Iteration 2/2]
+##   Selected 2,500 variable features [0.0s]
+##   Fit LSI on 9,608 cells, projected 402 depth outliers [96.3s]
+##   Iteration finished [96.4s]
+## 2026-10-23 00:18:39 Iterative LSI finished [166.0s]: added dim reduction 'LSI_RNA' (10,010 x 30)
 
@@ -1809,9 +1719,6 @@

Combining Modalities

embedding_names = c("LSI_ATAC", "LSI_RNA"), output_name = "LSI_Combined" )
-
Output
## Warning: Converting to a dense matrix may use excessive memory
-## This message is displayed once every 8 hours.
-

Clustering

@@ -1823,18 +1730,11 @@

Clustering

verbose = TRUE )
table(get_cell_metadata(proj)$clusters)
-
Output
## ###########
-## 2026-10-18 21:53:17 Extracting embedding 'LSI_Combined', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:53:17 Clustering 10010 cells with 59 dimensions, 0.000 mins elapsed.
-## 21:53:17 Building HNSW index with metric 'euclidean' ef = 200 M = 16 using 1 threads
-## 21:53:17 Finished building index
-## 21:53:17 Searching HNSW index with ef = 100 and 1 threads
-## 21:53:18 Finished searching
-## Warning in .fn(threads = 1L, verbose = TRUE, k = 20L, metric = "euclidean", :
+
Output
## 2026-10-23 00:18:39 Clustering: 10,010 cells on 'LSI_Combined' (59 dims)
+## Warning in .fn(threads = 1L, verbose = FALSE, k = 20L, metric = "euclidean", :
 ## KNN search didn't find self-neighbor for 2 datapoints. Try higher ef value
-## 2026-10-18 21:53:18 Found 16 clusters, 0.028 mins elapsed.
-## 2026-10-18 21:53:18 Added 16 clusters as 'clusters' in cell metadata, 0.029 mins elapsed.
+## Found 16 clusters [2.0s]
+## 2026-10-23 00:18:41 Clustering finished [2.0s]: added cell metadata column 'clusters' (16 clusters)
 ## 
 ##   C1  C10  C11  C12  C13  C14  C15  C16   C2   C3   C4   C5   C6   C7   C8   C9 
 ##  228 2852  477   98   34  338  364  401 1092 1143 1128  343  657  124  567  164
@@ -1852,63 +1752,18 @@ 

UMAP Embedding

verbose = TRUE ) }
-
Output
## ###########
-## 2026-10-18 21:53:18 Extracting embedding 'LSI_ATAC', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:53:18 Computing UMAP on 10010 cells with 29 dimensions, 0.000 mins elapsed.
-## 21:53:18 Using HNSW for nearest neighbor search
-## 21:53:18 UMAP embedding parameters a = 0.2321 b = 1.681
-## 21:53:18 Setting random seed 1
-## 21:53:18 Read 10010 rows and found 29 numeric columns
-## 21:53:18 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 21:53:19 Finished building index
-## 21:53:19 Searching HNSW index with ef = 40 and 4 threads
-## 21:53:19 Finished searching
-## 21:53:20 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:53:21 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:53:21 Range-scaling initial input columns to 0-10
-## 21:53:21 Commencing optimization for 500 epochs, with 586026 positive edges using 4 threads
-## 21:53:21 Using rng type: pcg
-## 21:53:24 Optimization finished
-## 2026-10-18 21:53:24 Added UMAP embedding as 'UMAP_ATAC' (2 components), 0.096 mins elapsed.
-## ###########
-## 2026-10-18 21:53:24 Extracting embedding 'LSI_RNA', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:53:24 Computing UMAP on 10010 cells with 30 dimensions, 0.000 mins elapsed.
-## 21:53:24 Using HNSW for nearest neighbor search
-## 21:53:24 UMAP embedding parameters a = 0.2321 b = 1.681
-## 21:53:24 Setting random seed 1
-## 21:53:24 Read 10010 rows and found 30 numeric columns
-## 21:53:24 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 21:53:25 Finished building index
-## 21:53:25 Searching HNSW index with ef = 40 and 4 threads
-## 21:53:25 Finished searching
-## 21:53:26 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:53:27 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:53:27 Range-scaling initial input columns to 0-10
-## 21:53:27 Commencing optimization for 500 epochs, with 573228 positive edges using 4 threads
-## 21:53:27 Using rng type: pcg
-## 21:53:30 Optimization finished
-## 2026-10-18 21:53:30 Added UMAP embedding as 'UMAP_RNA' (2 components), 0.095 mins elapsed.
-## ###########
-## 2026-10-18 21:53:30 Extracting embedding 'LSI_Combined', 0.000 mins elapsed.
-## ###########
-## 2026-10-18 21:53:30 Computing UMAP on 10010 cells with 59 dimensions, 0.000 mins elapsed.
-## 21:53:30 Using HNSW for nearest neighbor search
-## 21:53:30 UMAP embedding parameters a = 0.2321 b = 1.681
-## 21:53:30 Setting random seed 1
-## 21:53:30 Read 10010 rows and found 59 numeric columns
-## 21:53:30 Building HNSW index with metric 'cosine' ef = 200 M = 16 using 1 threads
-## 21:53:31 Finished building index
-## 21:53:31 Searching HNSW index with ef = 40 and 4 threads
-## 21:53:31 Finished searching
-## 21:53:32 Commencing smooth kNN distance calibration using 4 threads with target n_neighbors = 40
-## 21:53:33 Initializing from normalized Laplacian + noise (using RSpectra)
-## 21:53:33 Range-scaling initial input columns to 0-10
-## 21:53:33 Commencing optimization for 500 epochs, with 587204 positive edges using 4 threads
-## 21:53:33 Using rng type: pcg
-## 21:53:35 Optimization finished
-## 2026-10-18 21:53:36 Added UMAP embedding as 'UMAP_Combined' (2 components), 0.097 mins elapsed.
+
Output
## 2026-10-23 00:18:41 UMAP: 10,010 cells on 'LSI_ATAC' (29 dims), 4 threads
+## Fit 2D UMAP (40 neighbors, min_dist 0.8, cosine) [5.4s]
+## Saved UMAP model [0.2s]
+## 2026-10-23 00:18:47 UMAP finished [5.6s]: added cell metadata columns 'UMAP_ATAC_1', 'UMAP_ATAC_2', embedding model 'UMAP_ATAC'
+## 2026-10-23 00:18:47 UMAP: 10,010 cells on 'LSI_RNA' (30 dims), 4 threads
+## Fit 2D UMAP (40 neighbors, min_dist 0.8, cosine) [5.1s]
+## Saved UMAP model [0.2s]
+## 2026-10-23 00:18:52 UMAP finished [5.3s]: added cell metadata columns 'UMAP_RNA_1', 'UMAP_RNA_2', embedding model 'UMAP_RNA'
+## 2026-10-23 00:18:52 UMAP: 10,010 cells on 'LSI_Combined' (59 dims), 4 threads
+## Fit 2D UMAP (40 neighbors, min_dist 0.8, cosine) [5.3s]
+## Saved UMAP model [0.2s]
+## 2026-10-23 00:18:56 UMAP finished [5.5s]: added cell metadata columns 'UMAP_Combined_1', 'UMAP_Combined_2', embedding model 'UMAP_Combined'
 

All three embeddings, colored by the joint clusters:

plot_embedding(proj, embedding = "UMAP_ATAC", title = "ATAC") +
diff --git a/vignettes/marchr_scE2G.Rmd b/vignettes/marchr_scE2G.Rmd
index bfa822e..a8615de 100644
--- a/vignettes/marchr_scE2G.Rmd
+++ b/vignettes/marchr_scE2G.Rmd
@@ -63,7 +63,8 @@ pb <- pseudobulk_fragments(
   # Keep blacklisted regions. scE2G removes blacklisted candidate regions itself and then adds
   # gene promoters back, so fragments filtered out here would leave any promoter inside a
   # blacklisted region with no signal.
-  blacklist = FALSE
+  blacklist = FALSE,
+  verbose = TRUE
 )
 pb
 ```
@@ -76,7 +77,7 @@ warns when that applies.
 
 ```{r}
 input_dir <- file.path(cache_dir, "scE2G_inputs")
-pb <- write_sce2g_inputs(pb, dir = input_dir)
+pb <- write_sce2g_inputs(pb, dir = input_dir, verbose = TRUE)
 ```
 
 This writes:
@@ -112,7 +113,8 @@ model, which adds RNA-accessibility correlation features.
 pb <- write_sce2g_inputs(
   pb,
   dir = input_dir,
-  rna = proj[["RNA", by_dataset = FALSE]]  # raw RNA counts assay
+  rna = proj[["RNA", by_dataset = FALSE]],  # raw RNA counts assay
+  verbose = TRUE
 )
 ```
 
diff --git a/vignettes/marchr_scE2G.html b/vignettes/marchr_scE2G.html
index 7235b78..ed7371b 100644
--- a/vignettes/marchr_scE2G.html
+++ b/vignettes/marchr_scE2G.html
@@ -1532,7 +1532,8 @@ 

Group Fragments by Cluster

# Keep blacklisted regions. scE2G removes blacklisted candidate regions itself and then adds # gene promoters back, so fragments filtered out here would leave any promoter inside a # blacklisted region with no signal. - blacklist = FALSE + blacklist = FALSE, + verbose = TRUE ) pb

Each group becomes one scE2G cell cluster. For multiome data, scE2G computes its RNA-accessibility correlation on a random sample of 20,000 cells from any larger cluster, and write_sce2g_inputs() warns when that applies.

@@ -1540,7 +1541,7 @@

Group Fragments by Cluster

Write scE2G Inputs

input_dir <- file.path(cache_dir, "scE2G_inputs")
-pb <- write_sce2g_inputs(pb, dir = input_dir)
+pb <- write_sce2g_inputs(pb, dir = input_dir, verbose = TRUE)

This writes:

  • fragments/<cluster>.tsv.gz: one fragment file per cluster, compressed with bgzip and indexed with tabix (a .tbi file alongside).
  • @@ -1560,7 +1561,8 @@

    Multiome Data

    pb <- write_sce2g_inputs(
       pb,
       dir = input_dir,
    -  rna = proj[["RNA", by_dataset = FALSE]]  # raw RNA counts assay
    +  rna = proj[["RNA", by_dataset = FALSE]],  # raw RNA counts assay
    +  verbose = TRUE
     )

    RNA is written per cluster as rna/<cluster>.h5ad: