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
66 changes: 47 additions & 19 deletions R/dimensionality_reduction.R
Original file line number Diff line number Diff line change
Expand Up @@ -798,10 +798,13 @@ LSI.default <- function(
if (verbose) {
log_progress("Starting LSI")
}
original_x <- if (!is.null(outlier_quantiles)) x else NULL

mat_stats <- matrix_stats(x, row_stats = "mean", col_stats = "mean")
read_depth <- mat_stats$col_stats["mean", ] * nrow(x)
cell_depth <- mat_stats$col_stats["mean", ] * nrow(x)
read_depth <- cell_depth
# Cells removed below are subtracted from these totals instead of re-reading x
kept <- seq_along(cell_depth)
feature_nonzero <- mat_stats$row_stats["nonzero", ]
feature_sums <- .feature_sums(mat_stats$row_stats, ncol(x), x)

# Filter outlier cells before SVD
zero_cells <- which(read_depth == 0)
Expand All @@ -812,9 +815,8 @@ LSI.default <- function(
length(zero_cells), ncol(x)
))
x <- x[, -zero_cells]
if (!is.null(original_x)) original_x <- x
mat_stats <- matrix_stats(x, row_stats = "mean", col_stats = "mean")
read_depth <- mat_stats$col_stats["mean", ] * nrow(x)
kept <- kept[-zero_cells]
read_depth <- cell_depth[kept]
} else {
read_depth[zero_cells] <- 1
}
Expand All @@ -833,25 +835,29 @@ LSI.default <- function(
))
}
outlier_cells <- colnames(x)[outlier_idx]
all_cells <- colnames(x)
outlier_x <- x[, outlier_idx]
outlier_stats <- matrix_stats(outlier_x, row_stats = "mean")$row_stats
feature_nonzero <- feature_nonzero - outlier_stats["nonzero", ]
feature_sums <- feature_sums - .feature_sums(outlier_stats, length(outlier_idx), x)
x <- x[, -outlier_idx]
mat_stats <- matrix_stats(x, row_stats = "mean", col_stats = "mean")
read_depth <- mat_stats$col_stats["mean", ] * nrow(x)
kept <- kept[-outlier_idx]
read_depth <- cell_depth[kept]
}
}

zero_feats <- mat_stats$row_stats["mean", ] == 0
if (any(zero_feats)) {
x <- x[!zero_feats, ]
mat_stats$row_stats <- mat_stats$row_stats[, !zero_feats, drop = FALSE]
}
zero_feats <- feature_nonzero == 0
if (any(zero_feats)) x <- x[!zero_feats, ]
feature_means <- feature_sums[!zero_feats] / ncol(x)

# Normalization
if (verbose) {
log_progress("Normalizing matrix")
}
mat <- normalize_tfidf(
x = x,
feature_means = mat_stats$row_stats["mean", ],
feature_means = feature_means,
read_depth = cell_depth[kept],
scale_factor = scale_factor,
lsi_method = lsi_method
)
Expand Down Expand Up @@ -897,7 +903,7 @@ LSI.default <- function(
fitted_params <- list(
scale_factor = scale_factor,
lsi_method = lsi_method,
feature_means = mat_stats$row_stats["mean", ],
feature_means = feature_means,
pcs_to_keep = pca_feats_to_keep,
feature_loadings = svd_attr$u,
n_dimensions = ncol(pca_res),
Expand All @@ -912,9 +918,7 @@ LSI.default <- function(
# Re-project outlier cells that were excluded from SVD
if (length(outlier_cells) > 0) {
if (verbose) log_progress("Re-projecting outlier cells into LSI space")
outlier_proj <- project.LSI(dim_reduction, original_x[, outlier_cells],
drop_zero_cells = drop_zero_cells)
all_cells <- colnames(original_x)
outlier_proj <- project.LSI(dim_reduction, outlier_x, drop_zero_cells = drop_zero_cells)
assertthat::assert_that(
!anyNA(match(all_cells, c(rownames(pca_res), rownames(outlier_proj)))),
msg = "Outlier re-projection lost cells - all original cells must be present"
Expand All @@ -935,6 +939,13 @@ LSI.default <- function(
))
}

# Per-feature sums from matrix_stats() row means. Integer matrices have integer sums, so rounding
# removes the floating-point error of mean * n and keeps the subtractions in LSI.default() exact.
.feature_sums <- function(row_stats, n_cells, mat) {
sums <- row_stats["mean", ] * n_cells
if (is(mat, "IterableMatrix") && matrix_type(mat) == "uint32_t") round(sums) else sums
}


#' @inheritParams apply_to_assay.MarchRProject
#' @param dim_reduction_name (character) Name to store the DimReduction result. Defaults to "LSI".
Expand Down Expand Up @@ -1149,6 +1160,9 @@ project_test <- function(mat, ...) {
#' uses uniform sampling. Default NULL.
#' @param seed (numeric) Seed for the subsample draw (only for this subsample). Default 1.
#' @param drop_zero_cells (logical) Passed to `LSI()`; drop 0-count cells before LSI. Default TRUE.
#' @param feature_means (numeric or NULL) For `IterativeLSI.default()`: per-feature means of `x` after
#' binarization (when `binarize = TRUE`), named like `rownames(x)`. NULL computes them with a full
#' pass over `x`. the MarchRProject method supplies them from stored per-feature totals. Default NULL.
#' @param threads (integer) Per-call override of `set_threads()`. Default NULL threads each SVD with
#' `get_threads()` and clusters single-threaded. Note that an explicit value also threads the clustering
#' KNN, which makes results non-deterministic.
Expand Down Expand Up @@ -1326,11 +1340,16 @@ IterativeLSI.default <- function(
sample_group = NULL,
seed = 1,
drop_zero_cells = TRUE,
feature_means = NULL,
threads = NULL,
verbose = FALSE
) {
assert_has_package("RcppHNSW")
assert_is_mat(x)
if (!is.null(feature_means)) {
assert_is_numeric(feature_means)
assert_len(feature_means, nrow(x))
}
assert_greater_than_zero(n_iterations)
assert_is_wholenumber(n_iterations)
knn_threads <- .resolve_threads(threads, default = 1L)
Expand Down Expand Up @@ -1382,7 +1401,7 @@ IterativeLSI.default <- function(
total_features = total_features,
filter_top_features = filter_top_features,
pseudobulk_format = pseudobulk_format,
feature_means = matrix_stats(x, row_stats = "mean")$row_stats["mean", ],
feature_means = feature_means %||% matrix_stats(x, row_stats = "mean")$row_stats["mean", ],
iterations = n_iterations,
iter_info = tibble::tibble(
iteration = integer(),
Expand Down Expand Up @@ -1769,6 +1788,14 @@ IterativeLSI.MarchRProject <- function(
# Get matrices from all specified datasets
input_mat <- x[[assay_name, dataset_names]]

# Stored per-feature totals stand in for the full pass that computes feature means
feature_means <- NULL
if (binarize) {
stored <- .stored_feature_means(x, assay_name, dataset_names)
x <- stored$proj
feature_means <- stats::setNames(stored$means, rownames(input_mat))
}

# Stratify pre-iteration subsampling by dataset of origin when not supplied
if (is.null(sample_group)) {
cell_dataset <- unlist(lapply(dataset_names, function(dname) {
Expand Down Expand Up @@ -1804,6 +1831,7 @@ IterativeLSI.MarchRProject <- function(
sample_group = sample_group,
seed = seed,
drop_zero_cells = drop_zero_cells,
feature_means = feature_means,
threads = threads,
verbose = verbose
)
Expand Down
11 changes: 11 additions & 0 deletions R/doublet.R
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,15 @@ add_doublet_scores.MarchRDataset <- function(
assay_name <- select_assay_name(x, assay_name)
input_mat <- x[[assay_name]]

# Stored per-feature totals stand in for the doublet LSI's own pass over the matrix
totals <- x$feature_totals[[assay_name]]
if (binarize && !isFALSE(lsi_params$binarize) && is.null(lsi_params$feature_means) &&
.feature_totals_valid(totals, input_mat)) {
lsi_params$feature_means <- stats::setNames(
.read_feature_counts(totals) / ncol(input_mat), rownames(input_mat)
)
}

scoring_method <- match.arg(scoring_method)
assert_that(is.function(knn_method))

Expand Down Expand Up @@ -873,10 +882,12 @@ filter_doublets.MarchRDataset <- function(
))
}
# Remove doublet cells from the primary assay, then propagate via align_cells to all assays/fragments
before <- proj
assay_name <- get_assay_names(proj)[1]
mat <- proj$matrices[[assay_name]]
proj$matrices[[assay_name]] <- mat[, !colnames(mat) %in% remove_cells, drop = FALSE]
proj <- align_cells(proj, how = "intersect")
proj <- .update_feature_totals(proj, before)

# Metadata must be synced separately since align_cells only handles matrices and fragments
proj$cell_metadata <- proj$cell_metadata[
Expand Down
86 changes: 86 additions & 0 deletions R/feature_totals.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
########################################################################
# Stored per-feature totals
########################################################################

# A dataset's `feature_totals[[assay]]` holds the number of cells with a nonzero
# value in each feature, written to disk as a features x 1 matrix, plus fingerprints of the cells
# and features it was counted on. IterativeLSI and doublet scoring read it in place of a full pass
# over the matrix, but only while both fingerprints match the matrix they are about to use.

.cells_key <- function(mat) rlang::hash(sort(colnames(mat), method = "radix"))

.features_key <- function(mat) rlang::hash(rownames(mat))

# Dimnames are dropped so the pass does not load the stored feature names.
.count_nonzero_cells <- function(mat) {
dimnames(mat) <- list(NULL, NULL)
matrix_stats(mat, row_stats = "nonzero")$row_stats["nonzero", ]
}

# Always writes a new directory under `parent_dir`: other objects may still point at the old one.
.write_feature_totals <- function(counts, cells_key, features_key, parent_dir) {
dir.create(parent_dir, recursive = TRUE, showWarnings = FALSE)
counts_mat <- as(Matrix::Matrix(counts, ncol = 1, sparse = TRUE), "IterableMatrix") %>%
convert_matrix_type("uint32_t")
list(
counts = write_matrix_dir(counts_mat, tempfile("feature_totals_", tmpdir = parent_dir)),
cells = cells_key,
features = features_key
)
}

.compute_feature_totals <- function(mat, parent_dir) {
.write_feature_totals(.count_nonzero_cells(mat), .cells_key(mat), .features_key(mat), parent_dir)
}

.read_feature_counts <- function(entry) as.numeric(as(entry$counts, "dgCMatrix")[, 1])

.feature_totals_valid <- function(entry, mat, features_key = .features_key(mat)) {
!is.null(entry) && nrow(entry$counts) == nrow(mat) &&
identical(entry$cells, .cells_key(mat)) && identical(entry$features, features_key)
}

# After cells were removed from `old_ds` to give `new_ds`, rewrites each still-valid entry for the
# remaining cells, subtracting the removed cells or recounting the kept ones, whichever is fewer.
.update_feature_totals <- function(new_ds, old_ds) {
for (assay in names(old_ds$feature_totals)) {
entry <- old_ds$feature_totals[[assay]]
old_mat <- old_ds$matrices[[assay]]
new_mat <- new_ds$matrices[[assay]]
if (is.null(new_mat) || !.feature_totals_valid(entry, old_mat)) next
removed <- setdiff(colnames(old_mat), colnames(new_mat))
if (length(removed) == 0 || !all(colnames(new_mat) %in% colnames(old_mat))) next
counts <- if (length(removed) <= ncol(new_mat)) {
.read_feature_counts(entry) - .count_nonzero_cells(old_mat[, removed, drop = FALSE])
} else {
.count_nonzero_cells(new_mat)
}
new_ds$feature_totals[[assay]] <- .write_feature_totals(
counts, .cells_key(new_mat), entry$features, dirname(entry$counts@dir)
)
}
new_ds
}

# Feature means of `assay_name` across `dataset_names`, as IterativeLSI computes them after
# binarization. Datasets without valid stored totals are counted now, and their totals stored.
.stored_feature_means <- function(proj, assay_name, dataset_names) {
features_key <- NULL
counts <- 0
n_cells <- 0
for (ds in dataset_names) {
mat <- proj$datasets[[ds]]$matrices[[assay_name]]
features_key <- features_key %||% .features_key(mat)
entry <- proj$datasets[[ds]]$feature_totals[[assay_name]]
if (!.feature_totals_valid(entry, mat, features_key)) {
entry <- .write_feature_totals(
.count_nonzero_cells(mat), .cells_key(mat), features_key,
file.path(proj$dir, "datasets", ds, "feature_totals", assay_name)
)
proj$datasets[[ds]]$feature_totals[[assay_name]] <- entry
}
counts <- counts + .read_feature_counts(entry)
n_cells <- n_cells + ncol(mat)
}
list(proj = proj, means = counts / n_cells)
}
35 changes: 29 additions & 6 deletions R/fragment_ops.R
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,15 @@ resolve_chrom_sizes <- function(source, chrom_sizes, exclude_chr = character(0))
#' \code{c("chrM", "chrY")}.
#' @param tile_size (numeric) Tile width in base pairs. Default: 500.
#' @param mode (character) One of \code{"insertions"} or \code{"fragments"}.
#' @param return_matrix (logical) If \code{TRUE}, returns the \code{IterableMatrix}
#' instead of adding it to the object.
#' @param return_matrix (logical) If \code{TRUE}, returns the lazy
#' \code{IterableMatrix} computed from fragments, without writing it.
#' @param ... Additional arguments passed to \code{BPCells::tile_matrix()}.
#' @return Modified object with tile matrix assay, or an \code{IterableMatrix}
#' if \code{return_matrix = TRUE}.
#' @return Modified object with the tile matrix assay stored on disk, or the lazy
#' \code{IterableMatrix} if \code{return_matrix = TRUE}.
#' @details Wraps \code{BPCells::tile_matrix()} to produce a tiles x cells
#' count matrix from fragment data.
#' count matrix from fragment data. The matrix is written column-major (each
#' cell stored contiguously) with \code{BPCells::transpose_storage_order()}.
#' Writing needs temporary disk space next to the output, about the size of the matrix.
#' @name add_tile_matrix
NULL

Expand Down Expand Up @@ -233,13 +235,17 @@ add_tile_matrix.MarchRDataset <- function(
if (return_matrix) {
return(tile_matrix)
}
if (!overwrite && output_assay_name %in% names(proj$matrices)) {
rlang::abort(sprintf("matrix with name %s already exists in dataset", output_assay_name))
}
tile_matrix <- .write_tile_matrix(tile_matrix, tempfile(paste0(output_assay_name, "_")))
proj <- add_matrix(
proj,
tile_matrix,
assay_name = output_assay_name,
mat_name = output_assay_name,
overwrite = overwrite
)
proj$feature_totals[[output_assay_name]] <- .compute_feature_totals(tile_matrix, tempdir())
return(proj)
}

Expand Down Expand Up @@ -301,20 +307,37 @@ add_tile_matrix.MarchRProject <- function(
return_mats[[dataset_name]] <- tile_matrix
next
}
if (!overwrite && output_assay_name %in% names(proj$datasets[[dataset_name]]$matrices)) {
rlang::abort(sprintf("matrix with name %s already exists in dataset", output_assay_name))
}
# Prefixed before writing, so the stored directory already holds the final cell names.
tile_matrix <- .write_tile_matrix(
.prefix_cell_names_matrix(tile_matrix, dataset_name),
file.path(proj$dir, "datasets", dataset_name, "matrices", output_assay_name)
)
proj <- add_matrix(
proj,
tile_matrix,
dataset_name = dataset_name,
mat_name = output_assay_name,
overwrite = overwrite
)
proj$datasets[[dataset_name]]$feature_totals[[output_assay_name]] <- .compute_feature_totals(
tile_matrix, file.path(proj$dir, "datasets", dataset_name, "feature_totals", output_assay_name)
)
}
if (return_matrix) {
return(return_mats)
}
return(proj)
}

# Column-major optimization
.write_tile_matrix <- function(tile_matrix, out_dir) {
unlink(out_dir, recursive = TRUE, expand = FALSE)
BPCells::transpose_storage_order(tile_matrix, outdir = out_dir, tmpdir = dirname(out_dir))
}

########################################################################
# add_gene_score_matrix() method definition
########################################################################
Expand Down
Loading
Loading