Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.Rhistory
.RData
.Ruserdata
.Rlib
Rplots.pdf
*.Rproj
.vscode
Expand Down
217 changes: 159 additions & 58 deletions R/deviations.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,80 @@
)
}

.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)
}

# 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
Expand All @@ -38,22 +112,44 @@
#' @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.
#'
#' @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)`. 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()`.
#'
#' **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. 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
#' 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
Expand All @@ -71,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)) {
Expand All @@ -88,7 +189,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
Expand All @@ -105,6 +207,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"]]
Expand All @@ -130,71 +234,68 @@ 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)))
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...")
peak_mat <- BPCells::transpose_storage_order(
peak_mat, outdir = file.path(scratch, "PeakMatrix"), tmpdir = scratch
)
}
# 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)
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)))
}
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)
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)))
}
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])
}
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)
}

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'",
dev_name, z_name, ds))
}
unlink(scratch, recursive = TRUE, expand = FALSE)
}
proj
}
Expand Down
Loading
Loading