From 6d4212ebd77ae77ba96ff5307f8f3445e33430bc Mon Sep 17 00:00:00 2001 From: erliuu Date: Thu, 15 Oct 2026 14:54:39 -0700 Subject: [PATCH 1/2] feat([r] betterChromVAR): Reimplement betterChromVAR with BPCells streaming compatibility within add_background_peaks() --- .gitignore | 1 + R/deviations.R | 197 ++++++--- R/enrichment.R | 243 +++++++++-- R/project_class.R | 28 +- man/MarchRProject.Rd | 3 +- man/add_background_peaks.Rd | 70 +++- man/add_deviations_matrix.Rd | 38 +- man/get_background_peaks.Rd | 7 +- tests/testthat/test-background-reference.R | 234 +++++++++++ tests/testthat/test-deviations.R | 450 +++++++++++++++++++++ tests/testthat/test-enrichment.R | 85 ++++ 11 files changed, 1233 insertions(+), 123 deletions(-) diff --git a/.gitignore b/.gitignore index 2ec6b6e..a2cc3fc 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ .Rhistory .RData .Ruserdata +.Rlib Rplots.pdf *.Rproj .vscode diff --git a/R/deviations.R b/R/deviations.R index 8b568b0..75702c7 100644 --- a/R/deviations.R +++ b/R/deviations.R @@ -24,6 +24,52 @@ ) } +# ponytail: E and V are dense bins x cells; chunk over cells if that exceeds RAM. +.bin_background_moments <- function(bins, peak_mat, row_map) { + bin_membership <- Matrix::sparseMatrix( + i = bins$peak2bin[row_map], j = seq_along(row_map), + 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)) + + e_bin <- as.matrix(bins$bin_probs %*% bin_counts) + v_bin <- as.matrix(bins$bin_probs %*% bin_sumsq) - e_bin^2 + v_bin[v_bin < 0] <- 0 + + dimnames(e_bin) <- list(NULL, colnames(peak_mat)) + dimnames(v_bin) <- dimnames(e_bin) + list(e = e_bin, v = v_bin) +} + +# Variances add across a motif's peaks because each peak's background draw is independent. +.deviations_analytic <- function(bins, matches_aligned, peak_mat, row_map, + expectation, cell_depth) { + matches_aligned <- methods::as(matches_aligned, "dgCMatrix") + moments <- .bin_background_moments(bins, peak_mat, row_map) + + # Must index bins exactly as .bin_background_moments() does. + bin_membership <- Matrix::sparseMatrix( + i = bins$peak2bin[row_map], j = seq_along(row_map), + x = rep(1, length(row_map)), + dims = c(length(bins$bin_density), length(row_map)) + ) + motif_bins <- Matrix::t(bin_membership %*% matches_aligned) + + observed <- as.matrix(BPCells::t(matches_aligned) %*% peak_mat) + bg_exp <- as.matrix(motif_bins %*% moments$e) + bg_sd <- sqrt(pmax(0, as.matrix(motif_bins %*% moments$v))) + residual <- observed - bg_exp + + global_frac <- as.numeric(BPCells::t(matches_aligned) %*% expectation) + dev <- residual / outer(global_frac, cell_depth) + z <- residual / bg_sd + + dimnames(dev) <- dimnames(z) <- list(colnames(matches_aligned), colnames(peak_mat)) + list(deviations = dev, z = z) +} + #' Compute per-cell ChromVAR-style motif deviations #' #' Builds two motif x cell BPCells matrices per dataset: raw deviations @@ -44,16 +90,34 @@ #' #' @return Modified MarchRProject. #' -#' @details Equivalent to ArchR's `addDeviationsMatrix()` -#' (MatrixDeviations.R:44). Uses BPCells streaming `%*%` for the -#' `t(matches) %*% PeakMatrix` multiplication and Welford online mean/sd -#' for the background iteration loop, bounding RAM to two motif x cell -#' dense accumulators. -#' All output datasets use the pooled peak-accessibility expectation from -#' the stored background reference, with each cell's own total counts. -#' Backgrounds must have current reference provenance and at least two -#' iterations. Regenerate legacy or stale backgrounds with -#' `add_background_peaks(overwrite = TRUE)`. +#' @details All output datasets use the pooled peak-accessibility expectation +#' from the stored background reference, with each cell's own total counts. +#' Backgrounds must have current reference provenance, and sampled +#' backgrounds at least two iterations. Regenerate legacy or stale +#' backgrounds with `add_background_peaks(overwrite = TRUE)`. A row-major +#' PeakMatrix, as written by `add_peak_matrix()`, is transposed to a +#' temporary column-major copy under `proj$dir` for the computation; the +#' stored assay is unchanged. +#' +#' **ArchR correspondence**: with a `"chromVAR"` or `"bpcells"` background, +#' this corresponds to ArchR's `addDeviationsMatrix()`. +#' +#' **betterChromVAR correspondence**: with a `"betterChromVAR"` background, +#' background moments are computed in closed form as in the betterChromVAR +#' package (Wang et al., bioRxiv 2026), so results are deterministic; see the +#' preprint for the method. Unlike `betterChromVAR::computeBackgrounds()`, the +#' variance includes the between-bin term. z-scores run slightly narrower than +#' sampled ones, whose spread includes Monte Carlo noise. Memory grows with +#' `bin_size^2` times the cells in a dataset, about 1.2 GB per 10,000 cells. +#' +#' @references +#' Schep AN, Wu B, Buenrostro JD, Greenleaf WJ (2017). chromVAR: inferring +#' transcription-factor-associated accessibility from single-cell epigenomic +#' data. *Nature Methods* 14(10), 975-978. \doi{10.1038/nmeth.4401} +#' +#' Wang J, Sonder E, Domcke S, Robinson MD, Germain P-L (2026). Addressing +#' technical variations in ATAC-seq data and improving motif accessibility +#' analyses. *bioRxiv*. \doi{10.64898/2026.08.21.746151} #' #' @name add_deviations_matrix NULL @@ -88,7 +152,8 @@ add_deviations_matrix.MarchRProject <- function( )) } reference <- .validate_background_reference(proj, bgd) - if (ncol(bgd) < 2L) { + analytic <- inherits(bgd, "MarchRBinBackground") + if (!analytic && ncol(bgd) < 2L) { rlang::abort("Deviations require at least two background iterations to estimate variance.") } if (is.null(matrix_name)) matrix_name <- peak_annotation @@ -105,6 +170,8 @@ add_deviations_matrix.MarchRProject <- function( rlang::abort("No dataset has a PeakMatrix. Run add_peak_matrix() first.") } + 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)) peak_mat <- proj$datasets[[ds]]$matrices[["PeakMatrix"]] @@ -130,46 +197,83 @@ add_deviations_matrix.MarchRProject <- function( nrow(peak_mat) expectation <- peak_sums / sum(peak_sums) - if (verbose) { - message(sprintf(" Streaming t(M) %%*%% PeakMatrix (%d motifs x %d cells)...", - ncol(matches), ncol(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." + )) } - # Observed motif x cell counts. The motif x cell result is dense and at - # tutorial scale (~1k motifs x 100k cells x float64 ~ 800 MB) it fits in RAM. - matches_aligned <- matches[row_map, , drop = FALSE] - observed <- as.matrix(BPCells::t(matches_aligned) %*% peak_mat) - motif_exp_per_peak <- as.numeric(BPCells::t(matches_aligned) %*% expectation) - expected <- outer(motif_exp_per_peak, cell_depth) - obs_dev <- (observed - expected) / expected + matches_aligned <- matches[row_map, , drop = FALSE] - if (verbose) { - message(sprintf(" Welford accumulation over %d background iterations...", - ncol(bgd))) - } - # Welford online mean/variance over background iterations bounds RAM to - # two motif x cell accumulators instead of materializing the full 3D - # iteration array. - mean_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) - m2_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) - - for (k in seq_len(ncol(bgd))) { - # 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) - 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 - - delta <- dev_k - mean_acc - mean_acc <- mean_acc + delta / k - m2_acc <- m2_acc + delta * (dev_k - mean_acc) + # 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...") + scratch <- tempfile("transpose_", tmpdir = proj$dir) + dir.create(scratch) + peak_mat <- BPCells::transpose_storage_order( + peak_mat, outdir = file.path(scratch, "PeakMatrix"), tmpdir = scratch + ) } - sd_sampled <- sqrt(m2_acc / (ncol(bgd) - 1)) - deviations <- obs_dev - mean_acc - z <- deviations / sd_sampled + if (analytic) { + if (verbose) { + message(sprintf(" Analytic background over %d bias bins (%d motifs x %d cells)...", + length(bgd$bin_density), ncol(matches), ncol(peak_mat))) + } + analytic_out <- .deviations_analytic( + bins = bgd, + matches_aligned = matches_aligned, + peak_mat = peak_mat, + row_map = row_map, + expectation = expectation, + cell_depth = cell_depth + ) + deviations <- analytic_out$deviations + z <- analytic_out$z + } else { + if (verbose) { + message(sprintf(" Streaming t(M) %%*%% PeakMatrix (%d motifs x %d cells)...", + ncol(matches), ncol(peak_mat))) + } + + # Observed motif x cell counts. The motif x cell result is dense and at + # tutorial scale (~1k motifs x 100k cells x float64 ~ 800 MB) it fits in RAM. + observed <- as.matrix(BPCells::t(matches_aligned) %*% peak_mat) + motif_exp_per_peak <- as.numeric(BPCells::t(matches_aligned) %*% expectation) + expected <- outer(motif_exp_per_peak, cell_depth) + obs_dev <- (observed - expected) / expected + + if (verbose) { + message(sprintf(" Welford accumulation over %d background iterations...", + ncol(bgd))) + } + # Welford online mean/variance over background iterations bounds RAM to + # two motif x cell accumulators instead of materializing the full 3D + # iteration array. + mean_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) + m2_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) + + for (k in seq_len(ncol(bgd))) { + # 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) + 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 + + delta <- dev_k - mean_acc + mean_acc <- mean_acc + delta / k + m2_acc <- m2_acc + delta * (dev_k - mean_acc) + } + sd_sampled <- sqrt(m2_acc / (ncol(bgd) - 1)) + + deviations <- obs_dev - mean_acc + z <- deviations / sd_sampled + } dimnames(deviations) <- list(colnames(matches), colnames(peak_mat)) dimnames(z) <- dimnames(deviations) @@ -195,6 +299,7 @@ add_deviations_matrix.MarchRProject <- function( message(sprintf(" Stored '%s' and '%s' on dataset '%s'", dev_name, z_name, ds)) } + unlink(scratch, recursive = TRUE, expand = FALSE) } proj } diff --git a/R/enrichment.R b/R/enrichment.R index 883fdcd..579df5b 100644 --- a/R/enrichment.R +++ b/R/enrichment.R @@ -3,28 +3,35 @@ # Phase 3 of the motif/ChromVAR feature suite. ######################################################################## -#' Sample bias-matched background peaks +#' Compute bias-matched background peaks #' -#' Builds a peak x n_iterations integer matrix where each row contains -#' background peak indices matched to that peak's bias profile -#' (log10(rowSums + 1), gc, length). Required upstream of -#' `peak_annotation_enrichment(background = "background_peaks")` and -#' `add_deviations_matrix()`. +#' Matches each peak to background peaks with similar accessibility +#' (log10(rowSums + 1)) and GC content; `"bpcells"` also matches peak length. +#' `"chromVAR"` and `"bpcells"` store a peak x `n_iterations` integer matrix of +#' sampled background peak indices. `"betterChromVAR"` stores the bias bins +#' those samples are drawn from, so `add_deviations_matrix()` needs no sampling. +#' Required upstream of `peak_annotation_enrichment(background = "background_peaks")` +#' and `add_deviations_matrix()`. #' #' @param proj (MarchRProject) Project with peak_set, peak_set$gc, and a #' PeakMatrix. -#' @param method (character) `"chromVAR"` (default, ArchR-faithful via -#' `chromVAR::getBackgroundPeaks`) or `"bpcells"` (dependency-free via -#' `BPCells::knn_hnsw`). -#' @param n_iterations (integer) Background peaks sampled per peak. -#' Default 50 (matches ArchR). -#' @param w (numeric) chromVAR `w` parameter. Default 0.1. -#' @param bin_size (integer) chromVAR `bs` parameter. Default 50. -#' @param seed (integer) Random seed. Default 1L. Honored by MarchR; -#' ArchR hard-codes set.seed(1). +#' @param method (character) `"chromVAR"` (default, via +#' `chromVAR::getBackgroundPeaks()`), `"bpcells"` (dependency-free, via +#' `BPCells::knn_hnsw()`), or `"betterChromVAR"` (dependency-free; +#' deterministic bias bins with closed-form deviations, see Details). +#' @param n_iterations (integer) Background peaks sampled per peak. Default 50. +#' For `"betterChromVAR"`, used only when enrichment draws peaks from the bins. +#' @param w (numeric) Gaussian bias-kernel width in whitened bias units, for +#' `"chromVAR"` and `"betterChromVAR"`. Default 0.1, suited to +#' `bin_size = 50`; raise it when `bin_size` is smaller. +#' @param bin_size (integer) Bins per bias dimension for `"chromVAR"` and +#' `"betterChromVAR"`. Default 50. +#' @param seed (integer) Random seed. Default 1L. For `"betterChromVAR"`, used +#' only when enrichment draws peaks from the bins. #' @param knn_ef (integer) `ef` parameter for `BPCells::knn_hnsw()` (only #' used when `method = "bpcells"`). -#' @param overwrite (logical) Replace existing background_peaks. Default FALSE. +#' @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 dataset_names (character or NULL) Reference datasets whose PeakMatrix #' counts are pooled for background matching and deviation expectations. @@ -32,14 +39,39 @@ #' fixes the reference population even when other datasets are added. #' @param ... Unused. #' -#' @return Modified MarchRProject with `proj$background_peaks` populated. +#' @return Modified MarchRProject with `proj$background_peaks` populated: a +#' peak x `n_iterations` integer matrix for `"chromVAR"` and `"bpcells"`, or +#' for `"betterChromVAR"` a `MarchRBinBackground` list with `bs` (grid +#' dimensions), `peak2bin` (bin of each peak), `bin_density` (peaks per bin), +#' and `bin_probs` (sparse bin x bin per-peak selection probabilities). #' #' @details -#' Equivalent to ArchR's `addBgdPeaks()` (MatrixDeviations.R:714). +#' **ArchR correspondence**: `method = "chromVAR"` corresponds to ArchR's +#' `addBgdPeaks()`, except that `seed` is honored where ArchR hard-codes +#' `set.seed(1)`. +#' +#' **betterChromVAR correspondence**: `method = "betterChromVAR"` stores the bias +#' bins of the betterChromVAR package (Wang et al., bioRxiv 2026) instead of +#' sampled peaks; see the preprint for the method. Unlike +#' `betterChromVAR::getBackgroundBins()`, bins are chosen by kernel weight alone, +#' as in `chromVAR::getBackgroundPeaks()` (Schep et al., Nat Methods 2017). +#' Enrichment functions draw `n_iterations` peaks per peak from the bins, as +#' `betterChromVAR::sampleBackgroundPeaks()` does. Building the bins needs +#' memory growing with `bin_size^4`, about 0.25 GB at the default. +#' #' Background consumers validate reference cells, peak keys, GC, and streamed #' peak totals before reuse. After these inputs change, or for backgrounds saved #' without reference provenance, rerun with `overwrite = TRUE`. #' +#' @references +#' Schep AN, Wu B, Buenrostro JD, Greenleaf WJ (2017). chromVAR: inferring +#' transcription-factor-associated accessibility from single-cell epigenomic +#' data. *Nature Methods* 14(10), 975-978. \doi{10.1038/nmeth.4401} +#' +#' Wang J, Sonder E, Domcke S, Robinson MD, Germain P-L (2026). Addressing +#' technical variations in ATAC-seq data and improving motif accessibility +#' analyses. *bioRxiv*. \doi{10.64898/2026.08.21.746151} +#' #' @name add_background_peaks NULL @@ -53,7 +85,7 @@ add_background_peaks <- function(proj, ...) { #' @export add_background_peaks.MarchRProject <- function( proj, - method = c("chromVAR", "bpcells"), + method = c("chromVAR", "bpcells", "betterChromVAR"), n_iterations = 50L, w = 0.1, bin_size = 50L, @@ -66,6 +98,12 @@ add_background_peaks.MarchRProject <- function( ) { method <- match.arg(method) assert_for(proj, "MarchRProject") + if (method == "betterChromVAR" && bin_size^2 > 1e5) { + rlang::abort(c( + "`bin_size` is too large for method = \"betterChromVAR\".", + i = "Use bin_size <= 316. Memory scales with bin_size^4." + )) + } if (is.null(proj$peak_set) || nrow(proj$peak_set) == 0) { rlang::abort("Project has no peak set. Run add_reproducible_peak_set() first.") } @@ -76,7 +114,16 @@ add_background_peaks.MarchRProject <- function( .validate_background_reference( proj, proj$background_peaks, .background_reference(proj, dataset_names) ) - if (verbose) message("background_peaks already populated. Use overwrite = TRUE to recompute.") + stored_method <- attr(proj$background_peaks, "method") %||% "unknown" + if (!identical(stored_method, method)) { + rlang::warn(sprintf( + paste("Kept the existing background (method '%s'); requested method '%s'", + "was ignored. Use overwrite = TRUE to switch."), + stored_method, method + )) + } else if (verbose) { + message("background_peaks already populated. Use overwrite = TRUE to recompute.") + } return(proj) } @@ -86,25 +133,40 @@ add_background_peaks.MarchRProject <- function( gc <- proj$peak_set$gc len <- proj$peak_set$end - proj$peak_set$start - bgd <- if (method == "chromVAR") { - .background_peaks_chromvar(row_sums, gc, proj$peak_set, - n_iterations, w, bin_size, seed) - } else { - .background_peaks_bpcells(row_sums, gc, len, n_iterations, seed, knn_ef) - } + 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), + betterChromVAR = structure( + .background_bins(row_sums, gc, bs = c(bin_size, bin_size), w = w), + class = "MarchRBinBackground" + ) + ) attr(bgd, "method") <- method attr(bgd, "seed") <- seed - attr(bgd, "n_iter") <- n_iterations attr(bgd, "rowData") <- list(rowSums = row_sums, gc = gc, length = len) - rownames(bgd) <- peak_keys + if (inherits(bgd, "MarchRBinBackground")) { + attr(bgd, "w") <- w + attr(bgd, "expand_iter") <- n_iterations + names(bgd$peak2bin) <- peak_keys + } else { + attr(bgd, "n_iter") <- n_iterations + rownames(bgd) <- peak_keys + } attr(bgd, "reference") <- reference[c("version", "scope", "dataset_names", "signature")] proj$background_peaks <- bgd if (verbose) { - message(sprintf(" Stored background_peaks: %d peaks x %d iterations (method = %s)", - nrow(bgd), ncol(bgd), method)) + 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)) + } else { + message(sprintf(" Stored background_peaks: %d peaks x %d iterations (method = %s)", + nrow(bgd), ncol(bgd), method)) + } } proj } @@ -156,6 +218,102 @@ add_background_peaks.MarchRProject <- function( }, integer(n_iter))) } +# Bin (i, j) has index i + (j - 1) * bs[1]. bin_probs[b, j] is the probability of +# one given peak of bin j, so bin_probs %*% bin_density is 1 for each occupied bin. +.background_bins <- function(row_sums, gc, bs = c(50L, 50L), w = 0.1) { + if (!is.numeric(bs) || length(bs) != 2L || !all(is.finite(bs)) || any(bs < 2L)) { + rlang::abort("`bin_size` must give at least 2 bins per bias dimension.") + } + if (any(bs != round(bs))) { + rlang::abort("`bin_size` must be a whole number of bins per bias dimension.") + } + bs <- as.integer(bs) + if (!is.numeric(w) || length(w) != 1L || !is.finite(w) || w <= 0) { + rlang::abort("`w` must be a single positive number.") + } + + bias <- cbind(log10(row_sums + 1), gc) + whitened <- t(forwardsolve(t(chol(stats::cov(bias))), t(bias))) + + mins <- c(min(whitened[, 1]), min(whitened[, 2])) + maxs <- c(max(whitened[, 1]), max(whitened[, 2])) + spans <- maxs - mins + if (any(spans <= 0)) { + rlang::abort("Bias dimensions must vary across peaks to form background bins.") + } + + grid_idx <- vapply(1:2, function(d) { + i <- round((whitened[, d] - mins[d]) / spans[d] * (bs[d] - 1L)) + 1L + pmax(1L, pmin(bs[d], as.integer(i))) + }, integer(nrow(whitened))) + + peak2bin <- grid_idx[, 1] + (grid_idx[, 2] - 1L) * bs[1] + density <- tabulate(peak2bin, nbins = prod(bs)) + + centers <- expand.grid( + seq(mins[1], maxs[1], length.out = bs[1]), + seq(mins[2], maxs[2], length.out = bs[2]) + ) + kernel <- stats::dnorm(unname(as.matrix(stats::dist(centers))), 0, w) + # Dividing by density makes bin choice depend on the kernel alone, not on peak count. + occupied <- as.numeric(density > 0) + normalizer <- as.vector(kernel %*% occupied) + normalizer[normalizer < 1e-9] <- 1 + probs <- kernel / normalizer + probs <- probs / rep(pmax(density, 1L), each = nrow(probs)) + probs[, density == 0] <- 0 + probs[probs < 1e-6] <- 0 + row_mass <- as.vector(probs %*% density) + probs <- probs / pmax(row_mass, 1e-12) + + list( + bs = bs, + peak2bin = as.integer(peak2bin), + bin_density = density, + bin_probs = methods::as(probs, "dgCMatrix") + ) +} + +.sample_background_peaks <- function(bins, n_iterations, seed = 1L) { + peak2bin <- bins$peak2bin + density <- bins$bin_density + n_bins <- length(density) + by_bin <- split(seq_along(peak2bin), peak2bin) + + out <- matrix(0L, nrow = length(peak2bin), ncol = n_iterations) + set.seed(seed) + for (key in names(by_bin)) { + b <- as.integer(key) + targets <- by_bin[[key]] + # Reaching bin j requires picking it and then a peak inside it. + probs <- as.numeric(bins$bin_probs[b, ]) * density + if (sum(probs) == 0) probs[b] <- 1 + + drawn_bins <- sample.int(n_bins, length(targets) * n_iterations, + replace = TRUE, prob = probs) + draws_per_bin <- tabulate(drawn_bins, nbins = n_bins) + drawn <- integer(length(drawn_bins)) + for (j in which(draws_per_bin > 0)) { + pool <- by_bin[[as.character(j)]] + drawn[drawn_bins == j] <- pool[sample.int(length(pool), draws_per_bin[j], replace = TRUE)] + } + out[targets, ] <- matrix(drawn, ncol = n_iterations) + } + out +} + +.background_peak_indices <- function(bgd, n_iterations = NULL) { + if (inherits(bgd, "MarchRBinBackground")) { + .sample_background_peaks( + bgd, + n_iterations %||% attr(bgd, "expand_iter") %||% 50L, + seed = attr(bgd, "seed") %||% 1L + ) + } else { + bgd + } +} + # Pool by peak identity, never by dataset position. Only O(peaks) statistics # and compact cell-identity hashes are retained, not matrices or cell vectors. .background_reference <- function(proj, dataset_names = NULL) { @@ -223,9 +381,21 @@ add_background_peaks.MarchRProject <- function( fields <- c("version", "scope", "dataset_names", "signature") if (!identical(stored[fields], reference[fields])) stale("reference inputs have changed") keys <- names(reference$row_sums) - if (!is.matrix(bgd) || !is.numeric(bgd) || nrow(bgd) != length(keys) || - !identical(rownames(bgd), keys) || !ncol(bgd) || anyNA(bgd) || - any(!is.finite(bgd)) || any(bgd != floor(bgd) | bgd < 1 | bgd > length(keys))) { + if (inherits(bgd, "MarchRBinBackground")) { + n_bins <- as.integer(prod(bgd$bs)) + if (!is.list(bgd) || length(bgd$peak2bin) != length(keys) || + !identical(names(bgd$peak2bin), keys) || + !is.integer(bgd$peak2bin) || anyNA(bgd$peak2bin) || + any(bgd$peak2bin < 1L | bgd$peak2bin > n_bins) || + length(bgd$bin_density) != n_bins || + sum(bgd$bin_density) != length(keys) || + !identical(dim(bgd$bin_probs), c(n_bins, n_bins))) { + stale("invalid bias bins or ordering") + } + } else if (!is.matrix(bgd) || !is.numeric(bgd) || nrow(bgd) != length(keys) || + !identical(rownames(bgd), keys) || !ncol(bgd) || anyNA(bgd) || + any(!is.finite(bgd)) || + any(bgd != floor(bgd) | bgd < 1 | bgd > length(keys))) { stale("invalid peak indices or ordering") } if (!isTRUE(all.equal(attr(bgd, "rowData")$rowSums, reference$row_sums, @@ -233,10 +403,11 @@ add_background_peaks.MarchRProject <- function( reference } -#' Retrieve the stored background peaks matrix +#' Retrieve the stored background peaks #' @param proj (MarchRProject) #' @param ... Unused. -#' @return Peak x n_iterations integer matrix, or NULL if not computed. +#' @return Peak x n_iterations integer matrix (`"chromVAR"`, `"bpcells"`), a +#' `MarchRBinBackground` list (`"betterChromVAR"`), or NULL if not computed. #' @name get_background_peaks NULL @@ -330,6 +501,7 @@ peak_annotation_enrichment.MarchRProject <- function( 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) { @@ -428,6 +600,7 @@ custom_enrichment.MarchRProject <- function( rlang::abort("background = 'background_peaks' requires add_background_peaks() to have been run.") } .validate_background_reference(proj, bgd) + bgd <- .background_peak_indices(bgd) unique(c(fg_idx, as.vector(bgd[fg_idx, ]))) } diff --git a/R/project_class.R b/R/project_class.R index 4edc199..aa4cb78 100644 --- a/R/project_class.R +++ b/R/project_class.R @@ -323,8 +323,9 @@ validate_MarchRProject <- function(x) { # Check background_peaks if ("background_peaks" %in% names(x) && !is.null(x$background_peaks)) { assertthat::assert_that( - is.matrix(x$background_peaks), - msg = "background_peaks must be a matrix or NULL" + is.matrix(x$background_peaks) || + inherits(x$background_peaks, "MarchRBinBackground"), + msg = "background_peaks must be a matrix, a MarchRBinBackground, or NULL" ) } @@ -382,7 +383,8 @@ validate_MarchRProject <- function(x) { #' @param group_coverages A named list of pseudobulk group coverages. #' @param peak_set A peak-set data frame or `NULL`. #' @param peak_annotations A named list of peak annotations. -#' @param background_peaks A background-peak matrix or `NULL`. +#' @param background_peaks A background-peak matrix, a `MarchRBinBackground` +#' bins list, or `NULL`. #' @param kmer_bias A named list of k-mer bias results. #' @param impute_weights Imputation weights or `NULL`. #' @param co_accessibility A co-accessibility result data frame or `NULL`. @@ -663,12 +665,20 @@ print_peak_annotations_section <- function(x) { # Helper function to print background peaks information. print_background_peaks_section <- function(x) { if (!is.null(x$background_peaks)) { - method <- attr(x$background_peaks, "method") %||% "?" - n_iter <- attr(x$background_peaks, "n_iter") %||% ncol(x$background_peaks) - cat(sprintf( - "Background Peaks: %d peaks x %d iter (method = %s)\n", - nrow(x$background_peaks), n_iter, method - )) + bgd <- x$background_peaks + method <- attr(bgd, "method") %||% "?" + if (inherits(bgd, "MarchRBinBackground")) { + cat(sprintf( + "Background Peaks: %d peaks in %d bias bins (method = %s)\n", + length(bgd$peak2bin), length(bgd$bin_density), method + )) + } else { + n_iter <- attr(bgd, "n_iter") %||% ncol(bgd) + cat(sprintf( + "Background Peaks: %d peaks x %d iter (method = %s)\n", + nrow(bgd), n_iter, method + )) + } } } diff --git a/man/MarchRProject.Rd b/man/MarchRProject.Rd index 890a08e..4ed2724 100644 --- a/man/MarchRProject.Rd +++ b/man/MarchRProject.Rd @@ -45,7 +45,8 @@ MarchRProject( \item{peak_annotations}{A named list of peak annotations.} -\item{background_peaks}{A background-peak matrix or \code{NULL}.} +\item{background_peaks}{A background-peak matrix, a \code{MarchRBinBackground} +bins list, or \code{NULL}.} \item{kmer_bias}{A named list of k-mer bias results.} diff --git a/man/add_background_peaks.Rd b/man/add_background_peaks.Rd index 91cc9a2..331c9ef 100644 --- a/man/add_background_peaks.Rd +++ b/man/add_background_peaks.Rd @@ -3,11 +3,11 @@ \name{add_background_peaks} \alias{add_background_peaks} \alias{add_background_peaks.MarchRProject} -\title{Sample bias-matched background peaks} +\title{Compute bias-matched background peaks} \usage{ \method{add_background_peaks}{MarchRProject}( proj, - method = c("chromVAR", "bpcells"), + method = c("chromVAR", "bpcells", "betterChromVAR"), n_iterations = 50L, w = 0.1, bin_size = 50L, @@ -23,24 +23,29 @@ \item{proj}{(MarchRProject) Project with peak_set, peak_set$gc, and a PeakMatrix.} -\item{method}{(character) \code{"chromVAR"} (default, ArchR-faithful via -\code{chromVAR::getBackgroundPeaks}) or \code{"bpcells"} (dependency-free via -\code{BPCells::knn_hnsw}).} +\item{method}{(character) \code{"chromVAR"} (default, via +\code{chromVAR::getBackgroundPeaks()}), \code{"bpcells"} (dependency-free, via +\code{BPCells::knn_hnsw()}), or \code{"betterChromVAR"} (dependency-free; +deterministic bias bins with closed-form deviations, see Details).} -\item{n_iterations}{(integer) Background peaks sampled per peak. -Default 50 (matches ArchR).} +\item{n_iterations}{(integer) Background peaks sampled per peak. Default 50. +For \code{"betterChromVAR"}, used only when enrichment draws peaks from the bins.} -\item{w}{(numeric) chromVAR \code{w} parameter. Default 0.1.} +\item{w}{(numeric) Gaussian bias-kernel width in whitened bias units, for +\code{"chromVAR"} and \code{"betterChromVAR"}. Default 0.1, suited to +\code{bin_size = 50}; raise it when \code{bin_size} is smaller.} -\item{bin_size}{(integer) chromVAR \code{bs} parameter. Default 50.} +\item{bin_size}{(integer) Bins per bias dimension for \code{"chromVAR"} and +\code{"betterChromVAR"}. Default 50.} -\item{seed}{(integer) Random seed. Default 1L. Honored by MarchR; -ArchR hard-codes set.seed(1).} +\item{seed}{(integer) Random seed. Default 1L. For \code{"betterChromVAR"}, used +only when enrichment draws peaks from the bins.} \item{knn_ef}{(integer) \code{ef} parameter for \code{BPCells::knn_hnsw()} (only used when \code{method = "bpcells"}).} -\item{overwrite}{(logical) Replace existing background_peaks. Default FALSE.} +\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.} @@ -52,18 +57,45 @@ fixes the reference population even when other datasets are added.} \item{...}{Unused.} } \value{ -Modified MarchRProject with \code{proj$background_peaks} populated. +Modified MarchRProject with \code{proj$background_peaks} populated: a +peak x \code{n_iterations} integer matrix for \code{"chromVAR"} and \code{"bpcells"}, or +for \code{"betterChromVAR"} a \code{MarchRBinBackground} list with \code{bs} (grid +dimensions), \code{peak2bin} (bin of each peak), \code{bin_density} (peaks per bin), +and \code{bin_probs} (sparse bin x bin per-peak selection probabilities). } \description{ -Builds a peak x n_iterations integer matrix where each row contains -background peak indices matched to that peak's bias profile -(log10(rowSums + 1), gc, length). Required upstream of -\code{peak_annotation_enrichment(background = "background_peaks")} and -\code{add_deviations_matrix()}. +Matches each peak to background peaks with similar accessibility +(log10(rowSums + 1)) and GC content; \code{"bpcells"} also matches peak length. +\code{"chromVAR"} and \code{"bpcells"} store a peak x \code{n_iterations} integer matrix of +sampled background peak indices. \code{"betterChromVAR"} stores the bias bins +those samples are drawn from, so \code{add_deviations_matrix()} needs no sampling. +Required upstream of \code{peak_annotation_enrichment(background = "background_peaks")} +and \code{add_deviations_matrix()}. } \details{ -Equivalent to ArchR's \code{addBgdPeaks()} (MatrixDeviations.R:714). +\strong{ArchR correspondence}: \code{method = "chromVAR"} corresponds to ArchR's +\code{addBgdPeaks()}, except that \code{seed} is honored where ArchR hard-codes +\code{set.seed(1)}. + +\strong{betterChromVAR correspondence}: \code{method = "betterChromVAR"} stores the bias +bins of the betterChromVAR package (Wang et al., bioRxiv 2026) instead of +sampled peaks; see the preprint for the method. Unlike +\code{betterChromVAR::getBackgroundBins()}, bins are chosen by kernel weight alone, +as in \code{chromVAR::getBackgroundPeaks()} (Schep et al., Nat Methods 2017). +Enrichment functions draw \code{n_iterations} peaks per peak from the bins, as +\code{betterChromVAR::sampleBackgroundPeaks()} does. Building the bins needs +memory growing with \code{bin_size^4}, about 0.25 GB at the default. + Background consumers validate reference cells, peak keys, GC, and streamed peak totals before reuse. After these inputs change, or for backgrounds saved without reference provenance, rerun with \code{overwrite = TRUE}. } +\references{ +Schep AN, Wu B, Buenrostro JD, Greenleaf WJ (2017). chromVAR: inferring +transcription-factor-associated accessibility from single-cell epigenomic +data. \emph{Nature Methods} 14(10), 975-978. \doi{10.1038/nmeth.4401} + +Wang J, Sonder E, Domcke S, Robinson MD, Germain P-L (2026). Addressing +technical variations in ATAC-seq data and improving motif accessibility +analyses. \emph{bioRxiv}. \doi{10.64898/2026.08.21.746151} +} diff --git a/man/add_deviations_matrix.Rd b/man/add_deviations_matrix.Rd index 35a9af6..1f7b4af 100644 --- a/man/add_deviations_matrix.Rd +++ b/man/add_deviations_matrix.Rd @@ -43,14 +43,32 @@ Builds two motif x cell BPCells matrices per dataset: raw deviations (\verb{ZScore}). } \details{ -Equivalent to ArchR's \code{addDeviationsMatrix()} -(MatrixDeviations.R:44). Uses BPCells streaming \code{\%*\%} for the -\code{t(matches) \%*\% PeakMatrix} multiplication and Welford online mean/sd -for the background iteration loop, bounding RAM to two motif x cell -dense accumulators. -All output datasets use the pooled peak-accessibility expectation from -the stored background reference, with each cell's own total counts. -Backgrounds must have current reference provenance and at least two -iterations. Regenerate legacy or stale backgrounds with -\code{add_background_peaks(overwrite = TRUE)}. +All output datasets use the pooled peak-accessibility expectation +from the stored background reference, with each cell's own total counts. +Backgrounds must have current reference provenance, and sampled +backgrounds at least two iterations. Regenerate legacy or stale +backgrounds with \code{add_background_peaks(overwrite = TRUE)}. A row-major +PeakMatrix, as written by \code{add_peak_matrix()}, is transposed to a +temporary column-major copy under \code{proj$dir} for the computation; the +stored assay is unchanged. + +\strong{ArchR correspondence}: with a \code{"chromVAR"} or \code{"bpcells"} background, +this corresponds to ArchR's \code{addDeviationsMatrix()}. + +\strong{betterChromVAR correspondence}: with a \code{"betterChromVAR"} background, +background moments are computed in closed form as in the betterChromVAR +package (Wang et al., bioRxiv 2026), so results are deterministic; see the +preprint for the method. Unlike \code{betterChromVAR::computeBackgrounds()}, the +variance includes the between-bin term. z-scores run slightly narrower than +sampled ones, whose spread includes Monte Carlo noise. Memory grows with +\code{bin_size^2} times the cells in a dataset, about 1.2 GB per 10,000 cells. +} +\references{ +Schep AN, Wu B, Buenrostro JD, Greenleaf WJ (2017). chromVAR: inferring +transcription-factor-associated accessibility from single-cell epigenomic +data. \emph{Nature Methods} 14(10), 975-978. \doi{10.1038/nmeth.4401} + +Wang J, Sonder E, Domcke S, Robinson MD, Germain P-L (2026). Addressing +technical variations in ATAC-seq data and improving motif accessibility +analyses. \emph{bioRxiv}. \doi{10.64898/2026.08.21.746151} } diff --git a/man/get_background_peaks.Rd b/man/get_background_peaks.Rd index 7c62c2f..2c90458 100644 --- a/man/get_background_peaks.Rd +++ b/man/get_background_peaks.Rd @@ -3,7 +3,7 @@ \name{get_background_peaks} \alias{get_background_peaks} \alias{get_background_peaks.MarchRProject} -\title{Retrieve the stored background peaks matrix} +\title{Retrieve the stored background peaks} \usage{ \method{get_background_peaks}{MarchRProject}(proj, ...) } @@ -13,8 +13,9 @@ \item{...}{Unused.} } \value{ -Peak x n_iterations integer matrix, or NULL if not computed. +Peak x n_iterations integer matrix (\code{"chromVAR"}, \code{"bpcells"}), a +\code{MarchRBinBackground} list (\code{"betterChromVAR"}), or NULL if not computed. } \description{ -Retrieve the stored background peaks matrix +Retrieve the stored background peaks } diff --git a/tests/testthat/test-background-reference.R b/tests/testthat/test-background-reference.R index a0072c9..c240d38 100644 --- a/tests/testthat/test-background-reference.R +++ b/tests/testthat/test-background-reference.R @@ -110,3 +110,237 @@ test_that("background remapping preserves weights, including repeated indices", expect_equal(dimnames(mapped), dimnames(M)) expect_error(MarchR:::.permute_matches(M, c(0L, 2L, 3L)), "valid peak") }) + +test_that(".background_bins produces a normalized bin-to-bin probability matrix", { + set.seed(1) + n_peaks <- 500L + row_sums <- rpois(n_peaks, lambda = 40) + 1 + gc <- runif(n_peaks, 0.3, 0.7) + + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(10L, 10L), w = 0.1) + + expect_length(bins$peak2bin, n_peaks) + expect_true(all(bins$peak2bin >= 1L & bins$peak2bin <= 100L)) + expect_length(bins$bin_density, 100L) + expect_identical(sum(bins$bin_density), n_peaks) + expect_s4_class(bins$bin_probs, "dgCMatrix") + expect_identical(dim(bins$bin_probs), c(100L, 100L)) + expect_identical(dimnames(bins$bin_probs), list(NULL, NULL)) + + occupied <- which(bins$bin_density > 0) + reachable <- as.vector(bins$bin_probs %*% bins$bin_density) + expect_equal(reachable[occupied], rep(1, length(occupied)), tolerance = 1e-10) + + expect_error(MarchR:::.background_bins(row_sums, gc, bs = c(1L, 10L)), + "at least 2 bins") + expect_error(MarchR:::.background_bins(row_sums, gc, bs = c("6", "6")), + "at least 2 bins") + expect_error(MarchR:::.background_bins(row_sums, gc, bs = c(Inf, 10)), + "at least 2 bins") + expect_error(MarchR:::.background_bins(row_sums, gc, bs = c(6.9, 6.9)), + "whole number") + expect_error(MarchR:::.background_bins(row_sums, gc, w = -1), + "positive number") +}) + +test_that(".background_bins draws bins by kernel distance alone and normalizes rows exactly", { + set.seed(4) + n_peaks <- 5000L + row_sums <- rpois(n_peaks, lambda = 40) + 1 + gc <- pmin(pmax(rnorm(n_peaks, 0.5, 0.08), 0.05), 0.95) + bs <- c(30L, 30L) + bins <- MarchR:::.background_bins(row_sums, gc, bs = bs, w = 0.1) + occupied <- which(bins$bin_density > 0) + + # Equidistant bins must be drawn equally often whatever their peak count. + grid <- expand.grid(seq_len(bs[1]), seq_len(bs[2])) + drawn <- as.matrix(bins$bin_probs %*% Matrix::Diagonal(x = bins$bin_density)) + probes <- order(bins$bin_density, decreasing = TRUE)[1:10] + spreads <- do.call(rbind, lapply(probes, function(b) { + kept <- drawn[b, ] > 0 + offset <- paste(abs(grid[[1]] - grid[[1]][b]), abs(grid[[2]] - grid[[2]][b]))[kept] + spread <- function(x) ave(x, offset, FUN = function(v) diff(range(v))) + cbind(drawn = spread(drawn[b, kept]), density = spread(bins$bin_density[kept])) + })) + expect_lt(max(spreads[, "drawn"]), 1e-6) + # Some equidistant bins must differ in peak count, or the check above is vacuous. + expect_gt(max(spreads[, "density"]), 0) + + # Truncation must not break the row totals. + expect_equal(as.vector(bins$bin_probs %*% bins$bin_density)[occupied], + rep(1, length(occupied)), tolerance = 1e-10) +}) + +test_that(".background_bins decorrelates the bias axes and honors the kernel width", { + set.seed(3) + n_peaks <- 3000L + z <- rnorm(n_peaks) + row_sums <- round(exp(4 + 0.5 * z)) + gc <- 0.5 + 0.05 * (z + 0.3 * rnorm(n_peaks)) + + # Correlated accessibility and GC must land on uncorrelated grid axes. + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(12L, 12L), w = 0.1) + cells <- arrayInd(bins$peak2bin, c(12L, 12L)) + expect_lt(abs(stats::cor(cells[, 1], cells[, 2])), 0.1) + + narrow <- MarchR:::.background_bins(row_sums, gc, bs = c(12L, 12L), w = 0.05) + wide <- MarchR:::.background_bins(row_sums, gc, bs = c(12L, 12L), w = 0.2) + expect_gt(Matrix::nnzero(wide$bin_probs), Matrix::nnzero(narrow$bin_probs)) + + expect_lt(Matrix::nnzero(bins$bin_probs), 0.05 * prod(dim(bins$bin_probs))) + expect_equal(Matrix::nnzero(bins$bin_probs[, bins$bin_density == 0]), 0L) +}) + +test_that(".sample_background_peaks draws valid, reproducible peak indices", { + set.seed(1) + n_peaks <- 400L + row_sums <- rpois(n_peaks, lambda = 30) + 1 + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(8L, 8L), w = 0.1) + + idx <- MarchR:::.sample_background_peaks(bins, n_iterations = 6L, seed = 1L) + + expect_identical(dim(idx), c(n_peaks, 6L)) + expect_true(is.integer(idx)) + expect_true(all(idx >= 1L & idx <= n_peaks)) + + again <- MarchR:::.sample_background_peaks(bins, n_iterations = 6L, seed = 1L) + expect_identical(idx, again) + differs <- MarchR:::.sample_background_peaks(bins, n_iterations = 6L, seed = 2L) + expect_false(identical(idx, differs)) +}) + +test_that(".sample_background_peaks follows the bin law and is uniform within bins", { + set.seed(1) + n_peaks <- 400L + row_sums <- rpois(n_peaks, lambda = 30) + 1 + gc <- runif(n_peaks, 0.3, 0.7) + # w = 1 spans about one bin, so draws reach sparse bins too. + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(8L, 8L), w = 1) + idx <- MarchR:::.sample_background_peaks(bins, n_iterations = 2000L, seed = 1L) + + for (b in order(bins$bin_density, decreasing = TRUE)[1:3]) { + draws <- idx[bins$peak2bin == b, ] + n <- length(draws) + expected <- as.numeric(bins$bin_probs[b, ]) * bins$bin_density + observed <- tabulate(bins$peak2bin[draws], nbins = length(expected)) / n + + # Twice the expected total variation of an exact sampler. + noise <- 0.5 * sqrt(2 / (pi * n)) * sum(sqrt(expected * (1 - expected))) + expect_lt(0.5 * sum(abs(observed - expected)), 2 * noise, + label = sprintf("total variation distance, bin %d", b)) + + # Catches sparse-bin defects that total variation averages away: exact sampling + # stays below 6, wrong single-peak draws exceed 11. Bins expecting < 5 draws are skipped. + common <- n * expected >= 5 + z <- (observed - expected)[common] / sqrt(expected[common] * (1 - expected[common]) / n) + expect_lt(max(abs(z)), 8, label = sprintf("largest per-bin z-score, bin %d", b)) + + # Peaks within a bin must be drawn uniformly; biased draws score p < 1e-100. + pool <- which(bins$peak2bin == which.max(expected)) + counts <- tabulate(draws, nbins = n_peaks)[pool] + expect_gt(stats::chisq.test(counts)$p.value, 1e-4, + label = sprintf("uniformity p-value, bin %d", b)) + } +}) + +test_that("add_background_peaks(method = 'betterChromVAR') stores a validating bin background", { + proj <- background_reference_fixture() + set.seed(1) + proj$peak_set$gc <- runif(nrow(proj$peak_set), 0.3, 0.7) + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + + proj <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE) + bgd <- get_background_peaks(proj) + + expect_s3_class(bgd, "MarchRBinBackground") + expect_identical(attr(bgd, "method"), "betterChromVAR") + expect_identical(names(bgd$peak2bin), MarchR:::.peak_set_keys(proj$peak_set)) + expect_silent(MarchR:::.validate_background_reference(proj, bgd)) + expect_error( + add_background_peaks(proj, method = "betterChromVAR", bin_size = 500L, verbose = FALSE), + "too large" + ) +}) + +test_that("bin background validation rejects a changed peak set", { + proj <- background_reference_fixture() + set.seed(1) + proj$peak_set$gc <- runif(nrow(proj$peak_set), 0.3, 0.7) + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + proj <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE) + + proj$peak_set <- proj$peak_set[-1, ] + expect_error( + MarchR:::.validate_background_reference(proj, get_background_peaks(proj)), + "stale" + ) +}) + +test_that("MarchRProject accepts and round-trips an analytic bin background", { + proj <- background_reference_fixture() + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + proj <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE) + + expect_silent(MarchR:::validate_MarchRProject(proj)) + + root <- withr::local_tempdir() + save_project(proj, path = root, overwrite = TRUE) + loaded <- load_project(root) + + bgd <- get_background_peaks(loaded) + expect_s3_class(bgd, "MarchRBinBackground") + expect_identical(attr(bgd, "method"), "betterChromVAR") + expect_identical(bgd$peak2bin, get_background_peaks(proj)$peak2bin) + expect_silent(MarchR:::.validate_background_reference(loaded, bgd)) +}) + +test_that("print() reports both background representations", { + proj <- background_reference_fixture() + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + + bins <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE) + out <- capture.output(print(bins)) + expect_true(any(grepl("Background Peaks", out))) + expect_match( + paste(out, collapse = "\n"), + "Background Peaks: 10 peaks in 36 bias bins \\(method = betterChromVAR\\)" + ) + + mat <- suppressMessages( + add_background_peaks(proj, method = "bpcells", n_iterations = 5L, verbose = FALSE) + ) + out2 <- capture.output(print(mat)) + expect_true(any(grepl("Background Peaks", out2))) + expect_match( + paste(out2, collapse = "\n"), + "Background Peaks: 10 peaks x 5 iter \\(method = bpcells\\)" + ) +}) + +test_that("add_background_peaks warns when a method switch is ignored", { + proj <- background_reference_fixture() + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + proj <- suppressMessages( + add_background_peaks(proj, method = "bpcells", n_iterations = 5L, verbose = FALSE) + ) + + expect_warning( + kept <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE), + "existing background \\(method 'bpcells'\\)" + ) + expect_identical(attr(get_background_peaks(kept), "method"), "bpcells") + + expect_no_warning( + add_background_peaks(proj, method = "bpcells", n_iterations = 5L, verbose = FALSE) + ) + + switched <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, overwrite = TRUE, verbose = FALSE) + expect_s3_class(get_background_peaks(switched), "MarchRBinBackground") +}) diff --git a/tests/testthat/test-deviations.R b/tests/testthat/test-deviations.R index f042de2..59b48b3 100644 --- a/tests/testthat/test-deviations.R +++ b/tests/testthat/test-deviations.R @@ -232,3 +232,453 @@ test_that("plot_var_deviations returns a ggplot", { p <- plot_var_deviations(var_tbl, n = 10L) expect_s3_class(p, "ggplot") }) + +test_that(".bin_background_moments matches brute-force sampling from the same bins", { + set.seed(1) + n_peaks <- 600L + counts <- matrix(rpois(n_peaks * 2L, lambda = 6), nrow = n_peaks) + rownames(counts) <- paste0("p", seq_len(n_peaks)) + colnames(counts) <- c("cellA", "cellB") + + row_sums <- rowSums(counts) + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(8L, 8L), w = 0.5) + + peak_mat <- BPCells::write_matrix_memory(as(counts, "IterableMatrix")) + moments <- MarchR:::.bin_background_moments(bins, peak_mat, seq_len(n_peaks)) + + expect_identical(dim(moments$e), c(64L, 2L)) + expect_identical(dim(moments$v), c(64L, 2L)) + expect_true(all(moments$v >= 0)) + + idx <- MarchR:::.sample_background_peaks(bins, n_iterations = 3000L, seed = 7L) + occupied <- which(bins$bin_density > 0) + probe <- occupied[which.max(bins$bin_density[occupied])] + rows <- which(bins$peak2bin == probe) + drawn <- as.vector(idx[rows, ]) + sampled <- counts[drawn, "cellA"] + + expect_equal(unname(moments$e[probe, "cellA"]), mean(sampled), tolerance = 0.05) + expect_equal(unname(moments$v[probe, "cellA"]), stats::var(sampled), tolerance = 0.10) +}) + +test_that(".bin_background_moments reproduces the exact sampling-distribution moments", { + set.seed(2) + n_peaks <- 800L + counts <- matrix(rpois(n_peaks * 2L, lambda = 5) + 1L, nrow = n_peaks) + rownames(counts) <- paste0("p", seq_len(n_peaks)) + colnames(counts) <- c("cellA", "cellB") + + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(rowSums(counts), gc, bs = c(6L, 6L), w = 0.75) + + peak_mat <- BPCells::write_matrix_memory(as(counts, "IterableMatrix")) + moments <- MarchR:::.bin_background_moments(bins, peak_mat, seq_len(n_peaks)) + + # Exact enumeration over Pr(peak p | bin b) = bin_probs[b, bin(p)]; must match to 1e-8. + occ <- which(bins$bin_density > 0) + ref <- vapply(occ, function(b) { + p <- as.numeric(bins$bin_probs[b, bins$peak2bin]) + p <- p / sum(p) + mu <- sum(p * counts[, "cellA"]) + c(mu = mu, vr = sum(p * (counts[, "cellA"] - mu)^2)) + }, numeric(2)) + + expect_equal(unname(moments$e[occ, "cellA"]), ref["mu", ], tolerance = 1e-8) + expect_equal(unname(moments$v[occ, "cellA"]), ref["vr", ], tolerance = 1e-8) +}) + +test_that(".bin_background_moments gathers bins through row_map, not by position", { + set.seed(3) + n_peaks <- 400L + counts <- matrix(rpois(n_peaks * 2L, lambda = 6), nrow = n_peaks) + rownames(counts) <- paste0("p", seq_len(n_peaks)) + colnames(counts) <- c("cellA", "cellB") + + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(rowSums(counts), gc, bs = c(8L, 8L), w = 0.5) + + ident <- MarchR:::.bin_background_moments( + bins, + BPCells::write_matrix_memory(as(counts, "IterableMatrix")), + seq_len(n_peaks) + ) + + # row_map = perm must recover the same bins, so the moments are unchanged. + perm <- sample(n_peaks) + permuted <- MarchR:::.bin_background_moments( + bins, + BPCells::write_matrix_memory(as(counts[perm, ], "IterableMatrix")), + perm + ) + + expect_equal(unname(permuted$e), unname(ident$e)) + expect_equal(unname(permuted$v), unname(ident$v)) +}) + +test_that(".deviations_analytic returns finite motif x cell deviations and z", { + set.seed(3) + n_peaks <- 400L + n_cells <- 5L + counts <- matrix(rpois(n_peaks * n_cells, lambda = 6), nrow = n_peaks) + rownames(counts) <- paste0("p", seq_len(n_peaks)) + colnames(counts) <- paste0("cell", seq_len(n_cells)) + + row_sums <- rowSums(counts) + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(8L, 8L), w = 0.5) + peak_mat <- BPCells::write_matrix_memory(as(counts, "IterableMatrix")) + + matches <- Matrix::sparseMatrix( + i = c(1:80, 150:200), j = c(rep(1L, 80), rep(2L, 51)), x = 1, + dims = c(n_peaks, 2L), + dimnames = list(rownames(counts), c("M1", "M2")) + ) + + expectation <- row_sums / sum(row_sums) + cell_depth <- colSums(counts) + out <- MarchR:::.deviations_analytic( + bins, matches, peak_mat, seq_len(n_peaks), expectation, cell_depth + ) + + expect_identical(dim(out$deviations), c(2L, n_cells)) + expect_identical(dim(out$z), c(2L, n_cells)) + expect_true(all(is.finite(out$deviations))) + expect_true(all(is.finite(out$z))) + expect_identical(rownames(out$z), c("M1", "M2")) + expect_identical(colnames(out$z), colnames(counts)) + + moments <- MarchR:::.bin_background_moments(bins, peak_mat, seq_len(n_peaks)) + bm <- Matrix::sparseMatrix( + i = bins$peak2bin, j = seq_len(n_peaks), x = rep(1, n_peaks), + dims = c(length(bins$bin_density), n_peaks) + ) + motif_bins <- Matrix::t(bm %*% methods::as(matches, "dgCMatrix")) + observed <- as.matrix(Matrix::t(matches) %*% counts) + bg_exp <- as.matrix(motif_bins %*% moments$e) + global_exp <- as.numeric(Matrix::t(matches) %*% expectation) + + expect_equal( + unname(out$deviations), + unname((observed - bg_exp) / outer(global_exp, cell_depth)) + ) + + perm <- sample(n_peaks) + permuted <- MarchR:::.deviations_analytic( + bins, + matches[perm, , drop = FALSE], + BPCells::write_matrix_memory(as(counts[perm, ], "IterableMatrix")), + perm, + expectation[perm], + cell_depth + ) + expect_equal(unname(permuted$z), unname(out$z)) + expect_equal(unname(permuted$deviations), unname(out$deviations)) +}) + +test_that("analytic z tracks the sampled z on the same bins", { + set.seed(4) + n_peaks <- 500L + n_cells <- 12L + counts <- matrix(rpois(n_peaks * n_cells, lambda = 8), nrow = n_peaks) + rownames(counts) <- paste0("p", seq_len(n_peaks)) + colnames(counts) <- paste0("cell", seq_len(n_cells)) + + row_sums <- rowSums(counts) + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(8L, 8L), w = 0.5) + peak_mat <- BPCells::write_matrix_memory(as(counts, "IterableMatrix")) + + motif_peaks <- lapply(1:4, function(k) sample(n_peaks, 60)) + matches <- Matrix::sparseMatrix( + i = unlist(motif_peaks), + j = rep(1:4, each = 60), x = 1, + dims = c(n_peaks, 4L), + dimnames = list(rownames(counts), paste0("M", 1:4)) + ) + + expectation <- row_sums / sum(row_sums) + cell_depth <- colSums(counts) + analytic <- MarchR:::.deviations_analytic( + bins, matches, peak_mat, seq_len(n_peaks), expectation, cell_depth + ) + + # Monte Carlo estimate of the same count-residual z. + idx <- MarchR:::.sample_background_peaks(bins, n_iterations = 400L, seed = 11L) + observed <- as.matrix(Matrix::t(matches) %*% counts) + sampled_z <- matrix(0, nrow = 4L, ncol = n_cells) + for (m in 1:4) { + rows <- motif_peaks[[m]] + sums <- vapply(seq_len(ncol(idx)), function(k) { + colSums(counts[idx[rows, k], , drop = FALSE]) + }, numeric(n_cells)) + sampled_z[m, ] <- (observed[m, ] - rowMeans(sums)) / + apply(sums, 1, stats::sd) + } + + # Signal-free motifs attenuate the OLS slope, hence the wide band. + expect_gt(stats::cor(as.vector(analytic$z), as.vector(sampled_z)), 0.9) + slope <- stats::coef( + stats::lm(as.vector(sampled_z) ~ 0 + as.vector(analytic$z)) + )[[1]] + expect_gt(slope, 0.8) + expect_lt(slope, 1.25) +}) + +test_that("analytic z preserves the get_var_deviations motif ranking", { + # A per-motif scale offset would reorder the variance ranking despite high correlation. + set.seed(5) + n_peaks <- 1200L + n_cells <- 24L + n_motif <- 12L + lambda <- rlnorm(n_peaks, 0.3, 1.0) + depth <- runif(n_cells, 0.6, 1.8) + + sizes <- rep(c(40L, 120L, 300L), length.out = n_motif) + motif_peaks <- lapply(sizes, function(s) sample(n_peaks, s)) + matches <- Matrix::sparseMatrix( + i = unlist(motif_peaks), j = rep(seq_len(n_motif), sizes), x = 1, + dims = c(n_peaks, n_motif), + dimnames = list(paste0("p", seq_len(n_peaks)), paste0("M", seq_len(n_motif))) + ) + + # Motifs 1-4 carry real group-specific signal; the rest are null. + grp <- rep(1:2, each = n_cells / 2) + mult <- matrix(1, n_peaks, n_cells) + for (m in 1:2) mult[motif_peaks[[m]], grp == 1] <- 2.0 + for (m in 3:4) mult[motif_peaks[[m]], grp == 2] <- 2.0 + counts <- matrix( + rpois(n_peaks * n_cells, outer(lambda, depth) * mult), + nrow = n_peaks, ncol = n_cells, + dimnames = list(rownames(matches), paste0("c", seq_len(n_cells))) + ) + + row_sums <- rowSums(counts) + 1 + gc <- pmin(pmax(rnorm(n_peaks, 0.5, 0.08), 0.05), 0.95) + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(12L, 12L), w = 0.4) + peak_mat <- BPCells::write_matrix_memory(as(counts, "IterableMatrix")) + expectation <- row_sums / sum(row_sums) + cell_depth <- colSums(counts) + + analytic <- MarchR:::.deviations_analytic( + bins, matches, peak_mat, seq_len(n_peaks), expectation, cell_depth + ) + + # Sampled ratio z. + idx <- MarchR:::.sample_background_peaks(bins, n_iterations = 200L, seed = 9L) + obs_0 <- as.matrix(Matrix::t(matches) %*% counts) + exp_0 <- outer(as.numeric(Matrix::t(matches) %*% expectation), cell_depth) + dev_0 <- (obs_0 - exp_0) / exp_0 + mean_acc <- matrix(0, n_motif, n_cells) + m2_acc <- mean_acc + for (k in seq_len(ncol(idx))) { + M_k <- Matrix::sparseMatrix( + i = idx[unlist(motif_peaks), k], j = rep(seq_len(n_motif), sizes), x = 1, + dims = c(n_peaks, n_motif) + ) + exp_k <- outer(as.numeric(Matrix::t(M_k) %*% expectation), cell_depth) + dev_k <- (as.matrix(Matrix::t(M_k) %*% counts) - exp_k) / exp_k + delta <- dev_k - mean_acc + mean_acc <- mean_acc + delta / k + m2_acc <- m2_acc + delta * (dev_k - mean_acc) + } + sampled_z <- (dev_0 - mean_acc) / sqrt(m2_acc / (ncol(idx) - 1)) + + v_anal <- apply(analytic$z, 1, stats::var) + v_samp <- apply(sampled_z, 1, stats::var) + + expect_gt(stats::cor(rank(-v_anal), rank(-v_samp), method = "spearman"), 0.9) + expect_setequal(head(order(-v_anal), 4L), 1:4) + expect_setequal(head(order(-v_samp), 4L), 1:4) +}) + +test_that("analytic z uses the background variance, not its mean", { + set.seed(6) + n_peaks <- 500L + n_cells <- 12L + # Overdispersed (var 72, mean 8): a z built from the mean would be about 3x off. + counts <- matrix(rnbinom(n_peaks * n_cells, mu = 8, size = 1), nrow = n_peaks) + rownames(counts) <- paste0("p", seq_len(n_peaks)) + colnames(counts) <- paste0("cell", seq_len(n_cells)) + + row_sums <- rowSums(counts) + 1 + gc <- runif(n_peaks, 0.3, 0.7) + bins <- MarchR:::.background_bins(row_sums, gc, bs = c(8L, 8L), w = 0.5) + peak_mat <- BPCells::write_matrix_memory(as(counts, "IterableMatrix")) + + motif_peaks <- lapply(1:4, function(k) sample(n_peaks, 60)) + matches <- Matrix::sparseMatrix( + i = unlist(motif_peaks), j = rep(1:4, each = 60), x = 1, + dims = c(n_peaks, 4L), + dimnames = list(rownames(counts), paste0("M", 1:4)) + ) + + expectation <- row_sums / sum(row_sums) + cell_depth <- colSums(counts) + analytic <- MarchR:::.deviations_analytic( + bins, matches, peak_mat, seq_len(n_peaks), expectation, cell_depth + ) + + idx <- MarchR:::.sample_background_peaks(bins, n_iterations = 400L, seed = 13L) + observed <- as.matrix(Matrix::t(matches) %*% counts) + sampled_z <- matrix(0, nrow = 4L, ncol = n_cells) + for (m in 1:4) { + rows <- motif_peaks[[m]] + sums <- vapply(seq_len(ncol(idx)), function(k) { + colSums(counts[idx[rows, k], , drop = FALSE]) + }, numeric(n_cells)) + sampled_z[m, ] <- (observed[m, ] - rowMeans(sums)) / apply(sums, 1, stats::sd) + } + + slope <- stats::coef( + stats::lm(as.vector(sampled_z) ~ 0 + as.vector(analytic$z)) + )[[1]] + expect_gt(slope, 0.8) + expect_lt(slope, 1.25) +}) + +test_that("add_deviations_matrix runs end to end on an analytic background", { + skip_if_not_installed("GenomicRanges") + proj <- create_test_project_with_peaks() + proj$dir <- withr::local_tempdir() + set.seed(1) + n_peaks <- nrow(proj$peak_set) + proj$peak_set$gc <- runif(n_peaks, 0.3, 0.7) + proj$peak_set$idx <- seq_len(n_peaks) + + n_cells <- 8L + fake_counts <- matrix(rpois(n_peaks * n_cells, lambda = 5), + nrow = n_peaks, ncol = n_cells) + rownames(fake_counts) <- MarchR:::.peak_set_keys(proj$peak_set) + colnames(fake_counts) <- paste0("cell", seq_len(n_cells)) + proj$datasets[[1]]$matrices[["PeakMatrix"]] <- + BPCells::write_matrix_memory(as(fake_counts, "IterableMatrix")) + + gr <- GenomicRanges::GRangesList( + M1 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + M2 = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)), + M3 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1001000, 1004000)) + ) + proj <- add_peak_annotations(proj, gr, name = "TestMotif", verbose = FALSE) + proj <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE) + proj <- add_deviations_matrix(proj, peak_annotation = "TestMotif", + matrix_name = "AnalyticMotif", verbose = FALSE) + + ds <- proj$datasets[[1]] + expect_true("AnalyticMotifDeviations" %in% names(ds$matrices)) + expect_true("AnalyticMotifZScore" %in% names(ds$matrices)) + expect_equal(dim(ds$matrices[["AnalyticMotifZScore"]]), c(3L, n_cells)) + expect_true(all(is.finite(as.matrix(ds$matrices[["AnalyticMotifZScore"]])))) +}) + +test_that("analytic backgrounds bypass the two-iteration requirement", { + skip_if_not_installed("GenomicRanges") + proj <- background_reference_fixture() + proj$dir <- withr::local_tempdir() + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + + gr <- GenomicRanges::GRangesList( + M1 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + M2 = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)) + ) + proj <- add_peak_annotations(proj, gr, name = "BypassMotif", verbose = FALSE) + proj <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, verbose = FALSE) + + # Bin backgrounds have no iteration axis, so the two-iteration check must not apply. + expect_no_error( + proj <- add_deviations_matrix(proj, peak_annotation = "BypassMotif", + matrix_name = "BypassMotif", verbose = FALSE) + ) + expect_true("BypassMotifZScore" %in% names(proj$datasets[[1]]$matrices)) +}) + +test_that("add_deviations_matrix rejects cells with zero peak counts", { + skip_if_not_installed("GenomicRanges") + proj <- create_test_project_with_peaks() + proj$dir <- withr::local_tempdir() + set.seed(1) + n_peaks <- nrow(proj$peak_set) + proj$peak_set$gc <- runif(n_peaks, 0.3, 0.7) + proj$peak_set$idx <- seq_len(n_peaks) + + fake_counts <- matrix(rpois(n_peaks * 8L, lambda = 5), nrow = n_peaks, ncol = 8L) + fake_counts[, 3] <- 0 + rownames(fake_counts) <- MarchR:::.peak_set_keys(proj$peak_set) + colnames(fake_counts) <- paste0("cell", seq_len(8L)) + proj$datasets[[1]]$matrices[["PeakMatrix"]] <- + BPCells::write_matrix_memory(as(fake_counts, "IterableMatrix")) + + gr <- GenomicRanges::GRangesList( + M1 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + M2 = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)) + ) + proj <- add_peak_annotations(proj, gr, name = "TestMotif", verbose = FALSE) + proj <- add_background_peaks(proj, method = "bpcells", n_iterations = 3L, + seed = 1L, verbose = FALSE) + expect_error( + add_deviations_matrix(proj, peak_annotation = "TestMotif", verbose = FALSE), + "has 1 cell with zero peak counts" + ) + + # Both paths divide by cell depth, so the guard must sit before the branch. + pa <- add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, + w = 0.75, overwrite = TRUE, verbose = FALSE) + expect_s3_class(get_background_peaks(pa), "MarchRBinBackground") + expect_error( + add_deviations_matrix(pa, peak_annotation = "TestMotif", matrix_name = "ZdAn", + verbose = FALSE), + "has 1 cell with zero peak counts" + ) +}) + +test_that("add_deviations_matrix gives the same result from a row-major PeakMatrix", { + skip_if_not_installed("GenomicRanges") + make_proj <- function(row_major) { + proj <- create_test_project_with_peaks() + proj$dir <- withr::local_tempdir(.local_envir = parent.frame()) + set.seed(1) + n_peaks <- nrow(proj$peak_set) + proj$peak_set$gc <- runif(n_peaks, 0.3, 0.7) + proj$peak_set$idx <- seq_len(n_peaks) + fake_counts <- matrix(rpois(n_peaks * 8L, lambda = 5) + 1L, nrow = n_peaks, ncol = 8L) + rownames(fake_counts) <- MarchR:::.peak_set_keys(proj$peak_set) + colnames(fake_counts) <- paste0("cell", seq_len(8L)) + mat <- if (row_major) { + t(BPCells::write_matrix_memory(as(t(fake_counts), "IterableMatrix"))) + } else { + BPCells::write_matrix_memory(as(fake_counts, "IterableMatrix")) + } + expect_identical(BPCells::storage_order(mat), if (row_major) "row" else "col") + proj$datasets[[1]]$matrices[["PeakMatrix"]] <- mat + gr <- GenomicRanges::GRangesList( + M1 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + M2 = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)) + ) + add_peak_annotations(proj, gr, name = "TestMotif", verbose = FALSE) + } + run <- function(proj, ...) { + proj <- add_background_peaks(proj, ..., verbose = FALSE) + add_deviations_matrix(proj, peak_annotation = "TestMotif", verbose = FALSE) + } + settings <- list( + list(method = "betterChromVAR", bin_size = 6L, w = 0.75), + list(method = "bpcells", n_iterations = 3L, seed = 1L) + ) + for (args in settings) { + col <- do.call(run, c(list(make_proj(FALSE)), args)) + row_proj <- make_proj(TRUE) + row <- do.call(run, c(list(row_proj), args)) + for (nm in c("TestMotifDeviations", "TestMotifZScore")) { + expect_identical( + as.matrix(row$datasets[[1]]$matrices[[nm]]), + as.matrix(col$datasets[[1]]$matrices[[nm]]) + ) + } + expect_identical( + BPCells::storage_order(row$datasets[[1]]$matrices[["PeakMatrix"]]), "row" + ) + expect_length(list.files(row$dir, pattern = "^transpose_"), 0L) + } +}) diff --git a/tests/testthat/test-enrichment.R b/tests/testthat/test-enrichment.R index 5467cec..17edc64 100644 --- a/tests/testthat/test-enrichment.R +++ b/tests/testthat/test-enrichment.R @@ -152,3 +152,88 @@ test_that("plot_enrichment_heatmap returns ComplexHeatmap when populated", { expect_true(inherits(hm, "Heatmap") || inherits(hm, "HeatmapList") || inherits(hm, "ggplot")) }) + +analytic_enrichment_fixture <- function(method = "betterChromVAR", ...) { + proj <- background_reference_fixture() + proj$peak_set$idx <- seq_len(nrow(proj$peak_set)) + gr <- GenomicRanges::GRangesList( + M1 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + M2 = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)) + ) + proj <- add_peak_annotations(proj, gr, name = "TestMotif", verbose = FALSE) + if (method == "betterChromVAR") { + add_background_peaks(proj, method = "betterChromVAR", bin_size = 6L, w = 0.75, verbose = FALSE, ...) + } else { + add_background_peaks(proj, method = method, verbose = FALSE, ...) + } +} + +test_that("custom_enrichment accepts an analytic bin background", { + skip_if_not_installed("GenomicRanges") + proj <- analytic_enrichment_fixture() + + ranges <- GenomicRanges::GRanges( + proj$peak_set$chr[1:5], + IRanges::IRanges(proj$peak_set$start[1:5], proj$peak_set$end[1:5]) + ) + res <- custom_enrichment( + proj, ranges, peak_annotation = "TestMotif", + background = "background_peaks", verbose = FALSE + ) + expect_gt(nrow(res), 0) + expect_true("mlog10_p" %in% colnames(res)) + expect_gt(length(res$mlog10_p), 0) + expect_true(all(is.finite(res$mlog10_p))) +}) + +test_that("peak_annotation_enrichment accepts an analytic bin background", { + skip_if_not_installed("GenomicRanges") + proj <- analytic_enrichment_fixture() + + peak_keys <- MarchR:::.peak_set_keys(proj$peak_set) + marker_result <- structure( + list(results = tibble::tibble( + foreground = "C1", + feature = peak_keys[c(2, 4)], + p_val_adj = c(0.01, 0.02), + log2_fc = c(1.5, 2.0) + )), + class = c("MarkerResult", "list") + ) + + res <- peak_annotation_enrichment( + proj, marker_result = marker_result, peak_annotation = "TestMotif", + cutoff = "p_val_adj <= 0.1 & log2_fc >= 0.5", + background = "background_peaks", verbose = FALSE + ) + expect_gt(nrow(res), 0) + expect_true("mlog10_p" %in% colnames(res)) + expect_gt(length(res$mlog10_p), 0) + expect_true(all(is.finite(res$mlog10_p))) +}) + +test_that("enrichment accepts a sampled matrix background unchanged", { + skip_if_not_installed("GenomicRanges") + proj <- analytic_enrichment_fixture("bpcells", n_iterations = 5L) + expect_true(is.matrix(get_background_peaks(proj))) + + ranges <- GenomicRanges::GRanges( + proj$peak_set$chr[1:5], + IRanges::IRanges(proj$peak_set$start[1:5], proj$peak_set$end[1:5]) + ) + res <- custom_enrichment( + proj, ranges, peak_annotation = "TestMotif", + background = "background_peaks" + ) + expect_gt(nrow(res), 0) + expect_true("mlog10_p" %in% colnames(res)) + expect_gt(length(res$mlog10_p), 0) + expect_true(all(is.finite(res$mlog10_p))) +}) + +test_that("analytic background expands to the requested n_iterations", { + skip_if_not_installed("GenomicRanges") + proj <- analytic_enrichment_fixture(n_iterations = 11L) + 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) +}) From 91817d699a11ac66b28f99f7275f2181eb7ccb81 Mon Sep 17 00:00:00 2001 From: erliuu Date: Thu, 15 Oct 2026 20:11:27 -0700 Subject: [PATCH 2/2] feat([r] betterChromVAR): Add fixed size output chunking (temporary disk write) to reduce memory footprint for intermediate matrices --- R/deviations.R | 146 +++++++++++++++---------------- R/enrichment.R | 22 +++-- man/add_background_peaks.Rd | 22 +++-- man/add_deviations_matrix.Rd | 18 ++-- tests/testthat/test-deviations.R | 56 +++++++++++- 5 files changed, 158 insertions(+), 106 deletions(-) diff --git a/R/deviations.R b/R/deviations.R index 75702c7..68ddaa7 100644 --- a/R/deviations.R +++ b/R/deviations.R @@ -24,7 +24,6 @@ ) } -# ponytail: E and V are dense bins x cells; chunk over cells if that exceeds RAM. .bin_background_moments <- function(bins, peak_mat, row_map) { bin_membership <- Matrix::sparseMatrix( i = bins$peak2bin[row_map], j = seq_along(row_map), @@ -70,6 +69,35 @@ list(deviations = dev, z = z) } +# 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) + motif_exp_per_peak <- as.numeric(BPCells::t(matches_aligned) %*% expectation) + expected <- outer(motif_exp_per_peak, cell_depth) + obs_dev <- (observed - expected) / expected + + mean_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) + m2_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) + for (k in seq_len(ncol(bgd))) { + # 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) + 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 + + delta <- dev_k - mean_acc + mean_acc <- mean_acc + delta / k + m2_acc <- m2_acc + delta * (dev_k - mean_acc) + } + deviations <- obs_dev - mean_acc + z <- deviations / sqrt(m2_acc / (ncol(bgd) - 1)) + dimnames(deviations) <- dimnames(z) <- list(colnames(matches), colnames(peak_mat)) + list(deviations = deviations, z = z) +} + #' Compute per-cell ChromVAR-style motif deviations #' #' Builds two motif x cell BPCells matrices per dataset: raw deviations @@ -84,6 +112,7 @@ #' @param dataset_names (character) Datasets to compute on. Default: all #' datasets that have a PeakMatrix. This selects output datasets, not the #' 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 ... Unused. @@ -94,10 +123,11 @@ #' from the stored background reference, with each cell's own total counts. #' Backgrounds must have current reference provenance, and sampled #' backgrounds at least two iterations. Regenerate legacy or stale -#' backgrounds with `add_background_peaks(overwrite = TRUE)`. A row-major -#' PeakMatrix, as written by `add_peak_matrix()`, is transposed to a -#' temporary column-major copy under `proj$dir` for the computation; the -#' stored assay is unchanged. +#' backgrounds with `add_background_peaks(overwrite = TRUE)`. Cells are +#' processed `chunk_size` at a time. Chunk results, and a column-major copy +#' of the PeakMatrix when it is stored row-major, are written to a temporary +#' directory under `proj$dir` and removed on exit, including on error. The +#' stored PeakMatrix is unchanged. #' #' **ArchR correspondence**: with a `"chromVAR"` or `"bpcells"` background, #' this corresponds to ArchR's `addDeviationsMatrix()`. @@ -107,8 +137,10 @@ #' package (Wang et al., bioRxiv 2026), so results are deterministic; see the #' preprint for the method. Unlike `betterChromVAR::computeBackgrounds()`, the #' variance includes the between-bin term. z-scores run slightly narrower than -#' sampled ones, whose spread includes Monte Carlo noise. Memory grows with -#' `bin_size^2` times the cells in a dataset, about 1.2 GB per 10,000 cells. +#' sampled ones, whose spread includes Monte Carlo noise. The bin moments are +#' dense bins x chunk matrices (`bin_size^2` bins, set in +#' `add_background_peaks()`), about 1.2 GB per 10,000 cells at +#' `bin_size = 50`; lower `chunk_size` to reduce this. #' #' @references #' Schep AN, Wu B, Buenrostro JD, Greenleaf WJ (2017). chromVAR: inferring @@ -135,11 +167,16 @@ add_deviations_matrix.MarchRProject <- function( peak_annotation, matrix_name = NULL, dataset_names = character(0), + chunk_size = 20000L, overwrite = FALSE, verbose = TRUE, ... ) { 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)) { + rlang::abort("`chunk_size` must be a single positive whole number of cells.") + } matches <- get_matches(proj, peak_annotation) bgd <- get_background_peaks(proj) if (is.null(bgd)) { @@ -208,92 +245,51 @@ add_deviations_matrix.MarchRProject <- function( 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) message(" Transposing PeakMatrix to column-major...") - scratch <- tempfile("transpose_", tmpdir = proj$dir) - dir.create(scratch) 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)) + message(sprintf(" %s (%d motifs x %d cells)...", bg, ncol(matches), ncol(peak_mat))) + } - if (analytic) { - if (verbose) { - message(sprintf(" Analytic background over %d bias bins (%d motifs x %d cells)...", - length(bgd$bin_density), ncol(matches), ncol(peak_mat))) - } - analytic_out <- .deviations_analytic( - bins = bgd, - matches_aligned = matches_aligned, - peak_mat = peak_mat, - row_map = row_map, - expectation = expectation, - cell_depth = cell_depth - ) - deviations <- analytic_out$deviations - z <- analytic_out$z - } else { - if (verbose) { - message(sprintf(" Streaming t(M) %%*%% PeakMatrix (%d motifs x %d cells)...", - ncol(matches), ncol(peak_mat))) - } - - # Observed motif x cell counts. The motif x cell result is dense and at - # tutorial scale (~1k motifs x 100k cells x float64 ~ 800 MB) it fits in RAM. - observed <- as.matrix(BPCells::t(matches_aligned) %*% peak_mat) - motif_exp_per_peak <- as.numeric(BPCells::t(matches_aligned) %*% expectation) - expected <- outer(motif_exp_per_peak, cell_depth) - obs_dev <- (observed - expected) / expected - - if (verbose) { - message(sprintf(" Welford accumulation over %d background iterations...", - ncol(bgd))) + 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)) { + cols <- chunks[[i]] + if (verbose && length(chunks) > 1L) { + message(sprintf(" Cells %d-%d of %d...", cols[1], cols[length(cols)], ncol(peak_mat))) } - # Welford online mean/variance over background iterations bounds RAM to - # two motif x cell accumulators instead of materializing the full 3D - # iteration array. - mean_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) - m2_acc <- matrix(0, nrow = ncol(matches), ncol = ncol(peak_mat)) - - for (k in seq_len(ncol(bgd))) { - # 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) - 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 - - delta <- dev_k - mean_acc - mean_acc <- mean_acc + delta / k - m2_acc <- m2_acc + delta * (dev_k - mean_acc) + out <- if (analytic) { + .deviations_analytic(bgd, matches_aligned, peak_mat[, cols], row_map, + expectation, cell_depth[cols]) + } else { + # matches are re-permuted in every chunk; cache them if that shows in profiles. + .deviations_sampled(bgd, matches, matches_aligned, peak_mat[, cols], row_map, + expectation, cell_depth[cols]) } - sd_sampled <- sqrt(m2_acc / (ncol(bgd) - 1)) - - deviations <- obs_dev - mean_acc - z <- deviations / sd_sampled + 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) + rm(out) } - dimnames(deviations) <- list(colnames(matches), colnames(peak_mat)) - dimnames(z) <- dimnames(deviations) - dev_path <- file.path(proj$dir, "datasets", ds, "matrices", dev_name) z_path <- file.path(proj$dir, "datasets", ds, "matrices", z_name) - dir.create(dirname(dev_path), recursive = TRUE, showWarnings = FALSE) if (overwrite) { unlink(dev_path, recursive = TRUE) unlink(z_path, recursive = TRUE) } - dev_iter <- BPCells::write_matrix_dir( - as(deviations, "IterableMatrix"), dev_path, compress = TRUE - ) - z_iter <- BPCells::write_matrix_dir( - as(z, "IterableMatrix"), z_path, compress = TRUE - ) - - proj$datasets[[ds]]$matrices[[dev_name]] <- dev_iter - proj$datasets[[ds]]$matrices[[z_name]] <- z_iter + 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) { message(sprintf(" Stored '%s' and '%s' on dataset '%s'", diff --git a/R/enrichment.R b/R/enrichment.R index 579df5b..bc739d2 100644 --- a/R/enrichment.R +++ b/R/enrichment.R @@ -5,20 +5,18 @@ #' Compute bias-matched background peaks #' -#' Matches each peak to background peaks with similar accessibility -#' (log10(rowSums + 1)) and GC content; `"bpcells"` also matches peak length. -#' `"chromVAR"` and `"bpcells"` store a peak x `n_iterations` integer matrix of -#' sampled background peak indices. `"betterChromVAR"` stores the bias bins -#' those samples are drawn from, so `add_deviations_matrix()` needs no sampling. -#' Required upstream of `peak_annotation_enrichment(background = "background_peaks")` -#' and `add_deviations_matrix()`. +#' Matches each peak to background peaks with similar accessibility and GC content; +#' `"bpcells"` also matches peak length. +#' `"chromVAR"` and `"bpcells"` store a peak x `n_iterations` integer matrix of sampled background peak indices. +#' `"betterChromVAR"` stores the bias bins those samples are drawn from, so `add_deviations_matrix()` needs no sampling. +#' Required upstream of `peak_annotation_enrichment(background = "background_peaks")` and `add_deviations_matrix()`. #' #' @param proj (MarchRProject) Project with peak_set, peak_set$gc, and a #' PeakMatrix. -#' @param method (character) `"chromVAR"` (default, via -#' `chromVAR::getBackgroundPeaks()`), `"bpcells"` (dependency-free, via -#' `BPCells::knn_hnsw()`), or `"betterChromVAR"` (dependency-free; -#' deterministic bias bins with closed-form deviations, see Details). +#' @param method (character) +#' `"chromVAR"` (default, via `chromVAR::getBackgroundPeaks()`), +#' `"bpcells"` (dependency-free, via `BPCells::knn_hnsw()`), +#' `"betterChromVAR"` (dependency-free; deterministic bias bins with closed-form deviations). #' @param n_iterations (integer) Background peaks sampled per peak. Default 50. #' For `"betterChromVAR"`, used only when enrichment draws peaks from the bins. #' @param w (numeric) Gaussian bias-kernel width in whitened bias units, for @@ -51,7 +49,7 @@ #' `set.seed(1)`. #' #' **betterChromVAR correspondence**: `method = "betterChromVAR"` stores the bias -#' bins of the betterChromVAR package (Wang et al., bioRxiv 2026) instead of +#' bins reintegrated from the betterChromVAR package (Wang et al., bioRxiv 2026) instead of #' sampled peaks; see the preprint for the method. Unlike #' `betterChromVAR::getBackgroundBins()`, bins are chosen by kernel weight alone, #' as in `chromVAR::getBackgroundPeaks()` (Schep et al., Nat Methods 2017). diff --git a/man/add_background_peaks.Rd b/man/add_background_peaks.Rd index 331c9ef..9a70c7b 100644 --- a/man/add_background_peaks.Rd +++ b/man/add_background_peaks.Rd @@ -23,10 +23,10 @@ \item{proj}{(MarchRProject) Project with peak_set, peak_set$gc, and a PeakMatrix.} -\item{method}{(character) \code{"chromVAR"} (default, via -\code{chromVAR::getBackgroundPeaks()}), \code{"bpcells"} (dependency-free, via -\code{BPCells::knn_hnsw()}), or \code{"betterChromVAR"} (dependency-free; -deterministic bias bins with closed-form deviations, see Details).} +\item{method}{(character) +\code{"chromVAR"} (default, via \code{chromVAR::getBackgroundPeaks()}), +\code{"bpcells"} (dependency-free, via \code{BPCells::knn_hnsw()}), +\code{"betterChromVAR"} (dependency-free; deterministic bias bins with closed-form deviations).} \item{n_iterations}{(integer) Background peaks sampled per peak. Default 50. For \code{"betterChromVAR"}, used only when enrichment draws peaks from the bins.} @@ -64,13 +64,11 @@ dimensions), \code{peak2bin} (bin of each peak), \code{bin_density} (peaks per b and \code{bin_probs} (sparse bin x bin per-peak selection probabilities). } \description{ -Matches each peak to background peaks with similar accessibility -(log10(rowSums + 1)) and GC content; \code{"bpcells"} also matches peak length. -\code{"chromVAR"} and \code{"bpcells"} store a peak x \code{n_iterations} integer matrix of -sampled background peak indices. \code{"betterChromVAR"} stores the bias bins -those samples are drawn from, so \code{add_deviations_matrix()} needs no sampling. -Required upstream of \code{peak_annotation_enrichment(background = "background_peaks")} -and \code{add_deviations_matrix()}. +Matches each peak to background peaks with similar accessibility and GC content; +\code{"bpcells"} also matches peak length. +\code{"chromVAR"} and \code{"bpcells"} store a peak x \code{n_iterations} integer matrix of sampled background peak indices. +\code{"betterChromVAR"} stores the bias bins those samples are drawn from, so \code{add_deviations_matrix()} needs no sampling. +Required upstream of \code{peak_annotation_enrichment(background = "background_peaks")} and \code{add_deviations_matrix()}. } \details{ \strong{ArchR correspondence}: \code{method = "chromVAR"} corresponds to ArchR's @@ -78,7 +76,7 @@ and \code{add_deviations_matrix()}. \code{set.seed(1)}. \strong{betterChromVAR correspondence}: \code{method = "betterChromVAR"} stores the bias -bins of the betterChromVAR package (Wang et al., bioRxiv 2026) instead of +bins reintegrated from the betterChromVAR package (Wang et al., bioRxiv 2026) instead of sampled peaks; see the preprint for the method. Unlike \code{betterChromVAR::getBackgroundBins()}, bins are chosen by kernel weight alone, as in \code{chromVAR::getBackgroundPeaks()} (Schep et al., Nat Methods 2017). diff --git a/man/add_deviations_matrix.Rd b/man/add_deviations_matrix.Rd index 1f7b4af..8724dab 100644 --- a/man/add_deviations_matrix.Rd +++ b/man/add_deviations_matrix.Rd @@ -10,6 +10,7 @@ peak_annotation, matrix_name = NULL, dataset_names = character(0), + chunk_size = 20000L, overwrite = FALSE, verbose = TRUE, ... @@ -28,6 +29,8 @@ NULL (default), uses \code{peak_annotation}.} datasets that have a PeakMatrix. This selects output datasets, not the reference population configured by \code{add_background_peaks()}.} +\item{chunk_size}{(integer) Cells per chunk; bounds dense per-chunk memory. Default 20000.} + \item{overwrite}{(logical) Replace existing matrices. Default FALSE.} \item{verbose}{(logical) Default TRUE.} @@ -47,10 +50,11 @@ All output datasets use the pooled peak-accessibility expectation from the stored background reference, with each cell's own total counts. Backgrounds must have current reference provenance, and sampled backgrounds at least two iterations. Regenerate legacy or stale -backgrounds with \code{add_background_peaks(overwrite = TRUE)}. A row-major -PeakMatrix, as written by \code{add_peak_matrix()}, is transposed to a -temporary column-major copy under \code{proj$dir} for the computation; the -stored assay is unchanged. +backgrounds with \code{add_background_peaks(overwrite = TRUE)}. Cells are +processed \code{chunk_size} at a time. Chunk results, and a column-major copy +of the PeakMatrix when it is stored row-major, are written to a temporary +directory under \code{proj$dir} and removed on exit, including on error. The +stored PeakMatrix is unchanged. \strong{ArchR correspondence}: with a \code{"chromVAR"} or \code{"bpcells"} background, this corresponds to ArchR's \code{addDeviationsMatrix()}. @@ -60,8 +64,10 @@ background moments are computed in closed form as in the betterChromVAR package (Wang et al., bioRxiv 2026), so results are deterministic; see the preprint for the method. Unlike \code{betterChromVAR::computeBackgrounds()}, the variance includes the between-bin term. z-scores run slightly narrower than -sampled ones, whose spread includes Monte Carlo noise. Memory grows with -\code{bin_size^2} times the cells in a dataset, about 1.2 GB per 10,000 cells. +sampled ones, whose spread includes Monte Carlo noise. The bin moments are +dense bins x chunk matrices (\code{bin_size^2} bins, set in +\code{add_background_peaks()}), about 1.2 GB per 10,000 cells at +\code{bin_size = 50}; lower \code{chunk_size} to reduce this. } \references{ Schep AN, Wu B, Buenrostro JD, Greenleaf WJ (2017). chromVAR: inferring diff --git a/tests/testthat/test-deviations.R b/tests/testthat/test-deviations.R index 59b48b3..812f06f 100644 --- a/tests/testthat/test-deviations.R +++ b/tests/testthat/test-deviations.R @@ -679,6 +679,60 @@ test_that("add_deviations_matrix gives the same result from a row-major PeakMatr expect_identical( BPCells::storage_order(row$datasets[[1]]$matrices[["PeakMatrix"]]), "row" ) - expect_length(list.files(row$dir, pattern = "^transpose_"), 0L) + expect_length(list.files(row$dir, pattern = "^deviations_"), 0L) + } +}) + +test_that("add_deviations_matrix gives the same result in chunks of cells", { + skip_if_not_installed("GenomicRanges") + proj <- create_test_project_with_peaks() + proj$dir <- withr::local_tempdir() + set.seed(1) + n_peaks <- nrow(proj$peak_set) + proj$peak_set$gc <- runif(n_peaks, 0.3, 0.7) + proj$peak_set$idx <- seq_len(n_peaks) + fake_counts <- matrix(rpois(n_peaks * 8L, lambda = 5) + 1L, nrow = n_peaks, ncol = 8L) + rownames(fake_counts) <- MarchR:::.peak_set_keys(proj$peak_set) + colnames(fake_counts) <- paste0("cell", seq_len(8L)) + proj$datasets[[1]]$matrices[["PeakMatrix"]] <- + BPCells::write_matrix_memory(as(fake_counts, "IterableMatrix")) + gr <- GenomicRanges::GRangesList( + M1 = GenomicRanges::GRanges("chr1", IRanges::IRanges(1000000, 1003000)), + M2 = GenomicRanges::GRanges("chr2", IRanges::IRanges(2000000, 2003000)) + ) + proj <- add_peak_annotations(proj, gr, name = "TestMotif", verbose = FALSE) + + settings <- list( + list(method = "betterChromVAR", bin_size = 6L, w = 0.75), + list(method = "bpcells", n_iterations = 3L, seed = 1L) + ) + for (args in settings) { + p <- do.call(add_background_peaks, + c(list(proj), args, list(overwrite = TRUE, verbose = FALSE))) + whole <- add_deviations_matrix(p, "TestMotif", matrix_name = "Whole", + overwrite = TRUE, verbose = FALSE) + expect_message( + add_deviations_matrix(p, "TestMotif", matrix_name = "Progress", chunk_size = 3L, + overwrite = TRUE), + "Cells 1-3 of 8" + ) + for (size in c(3L, 7L)) { + chunked <- add_deviations_matrix(p, "TestMotif", matrix_name = "Chunked", + chunk_size = size, overwrite = TRUE, verbose = FALSE) + for (out in c("Deviations", "ZScore")) { + expect_identical( + as.matrix(chunked$datasets[[1]]$matrices[[paste0("Chunked", out)]]), + as.matrix(whole$datasets[[1]]$matrices[[paste0("Whole", out)]]) + ) + } + } + expect_length(list.files(p$dir, pattern = "^deviations_"), 0L) + } +}) + +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)) { + expect_error(add_deviations_matrix(proj, "TestMotif", chunk_size = bad), "chunk_size") } })