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
4 changes: 4 additions & 0 deletions R/RcppExports.R
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ rcpp_hello_world <- function() {
.Call(`_MarchR_rcpp_hello_world`)
}

steady_clock_seconds_rcpp <- function() {
.Call(`_MarchR_steady_clock_seconds_rcpp`)
}

get_subset_from_logical_selection_rcpp <- function(selection, dimension_sums) {
.Call(`_MarchR_get_subset_from_logical_selection_rcpp`, selection, dimension_sums)
}
Expand Down
144 changes: 106 additions & 38 deletions R/bulk_projection.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,22 @@
)
}

# Overlap bulk ATAC peaks onto the reduction's feature ranges and return a sparse
# (reduction features x bulk samples) count matrix in reduction feature order.
# @noRd
.match_bulk_features <- function(se_atac, feature_gr, assay_name = "counts",
force = FALSE, verbose = TRUE) {
assert_has_package(c("SummarizedExperiment", "GenomicRanges", "S4Vectors"))

.assert_bulk_se <- function(se_atac) {
if (!methods::is(se_atac, "RangedSummarizedExperiment")) {
rlang::abort(paste0(
"`se_atac` must be a RangedSummarizedExperiment carrying rowRanges. ",
"Build one with SummarizedExperiment(assays = ..., rowRanges = <GRanges>)."
))
}
}

# Overlap bulk ATAC peaks onto the reduction's feature ranges and return a sparse
# (reduction features x bulk samples) count matrix in reduction feature order.
# @noRd
.match_bulk_features <- function(se_atac, feature_gr, assay_name = "counts",
force = FALSE, verbose) {
assert_has_package(c("SummarizedExperiment", "GenomicRanges", "S4Vectors"))
.assert_bulk_se(se_atac)
available <- SummarizedExperiment::assayNames(se_atac)
if (!assay_name %in% available) {
rlang::abort(sprintf(
Expand Down Expand Up @@ -84,9 +87,9 @@
}
}
if (verbose) {
log_progress(sprintf(
"Matched %d of %d reduction features to bulk peaks (%.1f%%)",
length(covered), length(feature_gr), 100 * overlap_ratio
.log_step(sprintf(
"Matched %s of %s reduction features to bulk peaks (%.1f%%)",
.log_count(length(covered)), .log_count(length(feature_gr)), 100 * overlap_ratio
))
}

Expand Down Expand Up @@ -180,15 +183,10 @@
# Simulate every bulk sample and bind into one (features x pseudo-cells) matrix.
# @noRd
.simulate_all_bulk_samples <- function(mapped_counts, feature_names, depth_n, n,
seed, verbose = TRUE) {
seed, verbose) {
t0 <- steady_clock_seconds_rcpp()
sample_names <- colnames(mapped_counts)
sims <- lapply(seq_along(sample_names), function(s) {
if (verbose) {
log_progress(sprintf(
"Simulating pseudo-cells for sample %d of %d (%s)",
s, length(sample_names), sample_names[s]
))
}
one <- .simulate_bulk_pseudocells(
feature_counts = mapped_counts[, s],
n_features = nrow(mapped_counts),
Expand All @@ -201,6 +199,12 @@
})
combined <- do.call(cbind, sims)
rownames(combined) <- feature_names
if (verbose) {
.log_step(sprintf(
"Simulated %s from %s (%s each, mean depth %s)", .log_plural(ncol(combined), "pseudo-cell"),
.log_plural(length(sample_names), "sample"), .log_count(ncol(sims[[1]])), .log_count(depth_n)
), since = t0)
}
combined
}

Expand Down Expand Up @@ -236,7 +240,7 @@
#' @param seed (numeric) Random seed. Default: 1.
#' @param threads (integer) Threads for the UMAP transform in the MarchRProject method. Default
#' `get_threads()`. The DimReduction method projects single-threaded (default NULL).
#' @param verbose (logical) Print progress. Default: \code{TRUE}.
#' @param verbose (logical) Print progress messages. Default \code{getOption("MarchR.verbose", FALSE)}.
#' @param ... Passed to methods.
#'
#' @return A list with \code{simulated_reduced_dims}, \code{overlap_ratio} and
Expand Down Expand Up @@ -278,10 +282,13 @@ project_bulk_atac.DimReduction <- function(
force = FALSE,
seed = 1L,
threads = NULL,
verbose = TRUE,
verbose = getOption("MarchR.verbose", FALSE),
...
) {
.start_log_clock()
assert_for(verbose, "logical")
assert_has_package(c("SummarizedExperiment", "GenomicRanges", "IRanges", "S4Vectors"))
.assert_bulk_se(se_atac)
assert_is_wholenumber(n)
assert_greater_than_zero(n)
.resolve_threads(threads, default = 1L, warn_as = "project_bulk_atac() on a DimReduction")
Expand All @@ -293,24 +300,38 @@ project_bulk_atac.DimReduction <- function(

selected <- .reduction_selected_features(x, iteration)
feature_gr <- .feature_keys_to_granges(selected)
iterative <- !is.null(x$fitted_params$iter_info)
if (verbose) {
run <- .log_start("Bulk projection", sprintf(
"%s into %s (%s%s)", .log_plural(ncol(se_atac), "sample"), class(x)[1],
if (iterative) sprintf("iteration %d, ", iteration) else "",
.log_plural(length(selected), "feature")
))
}
matched <- .match_bulk_features(
se_atac, feature_gr, assay_name = assay_name, force = force, verbose = verbose
)
depth_n <- .reduction_depth(x, iteration)
if (verbose) {
log_progress(sprintf("Simulating pseudo-cells at a mean depth of %d counts", depth_n))
}

sim <- .simulate_all_bulk_samples(
matched$counts, selected, depth_n = depth_n, n = n,
seed = seed, verbose = verbose
)
if (verbose) log_progress("Projecting simulated pseudo-cells into the fitted space")
t0 <- steady_clock_seconds_rcpp()
project_args <- list(x, as(sim, "IterableMatrix"))
if (!is.null(x$fitted_params$iter_info)) {
if (iterative) {
project_args$iteration <- iteration
}
simulated_reduced_dims <- as.matrix(do.call(project, project_args))
if (verbose) {
.log_step(sprintf(
"Projected %s into %s", .log_plural(nrow(simulated_reduced_dims), "pseudo-cell"),
sub("^Iterative", "", class(x)[1])
), since = t0)
.log_finish(run, sprintf(
"%s x %d reduced dims", .log_count(nrow(simulated_reduced_dims)), ncol(simulated_reduced_dims)
))
}

list(
simulated_reduced_dims = simulated_reduced_dims,
Expand Down Expand Up @@ -354,7 +375,9 @@ project_bulk_atac.DimReduction <- function(
"Assay '%s' not found in dataset '%s'.", assay_name, dset
))
}
as.matrix(x$datasets[[dset]]$matrices[[assay_name]])
rlang::with_options(
as.matrix(x$datasets[[dset]]$matrices[[assay_name]]), rlib_message_verbosity = "quiet"
)
})
if (is.null(feature_names)) feature_names <- rownames(mats[[1]])
if (is.null(feature_names)) {
Expand Down Expand Up @@ -393,34 +416,63 @@ project_bulk_atac.MarchRProject <- function(
force = FALSE,
seed = 1L,
threads = get_threads(),
verbose = TRUE,
verbose = getOption("MarchR.verbose", FALSE),
...
) {
.start_log_clock()
assert_for(verbose, "logical")
assert_for(x, "MarchRProject")
threads <- .resolve_threads(threads)
dim_reduction_name <- select_embedding_name(x, dim_reduction_name)
dataset_names <- select_dataset_names(x, dataset_names)
dim_reduction <- get_dim_reduction(x, dim_reduction_name)
# The cell-embedding assay usually shares the reduction's name. IterativeLSI() sets output_assay_name.
if (is.null(reduced_dims_assay)) reduced_dims_assay <- dim_reduction_name
.assert_bulk_se(se_atac)
if (is.null(iteration)) {
iteration <- dim_reduction$fitted_params$iterations %||% 1L
}
assert_is_wholenumber(iteration)
assert_is_wholenumber(n)
assert_greater_than_zero(n)

if (!is.null(embedding_name)) {
available_assays <- unique(unlist(get_assay_names(x)))
if (!reduced_dims_assay %in% available_assays) {
rlang::abort(sprintf(
"Assay '%s' not found. Pass `reduced_dims_assay` naming the cell embeddings. Available: %s",
reduced_dims_assay, paste(available_assays, collapse = ", ")
))
}
}
if (verbose) {
n_cells <- sum(purrr::map_int(
x$datasets[dataset_names], ~ ncol(.x$matrices[[reduced_dims_assay]]) %||% 0L
))
run <- .log_start("Bulk projection", sprintf(
"%s into '%s' (%s%s)%s", .log_plural(ncol(se_atac), "sample"), dim_reduction_name,
if (is.null(dim_reduction$fitted_params$iter_info)) "" else sprintf("iteration %d, ", iteration),
.log_plural(length(.reduction_selected_features(dim_reduction, iteration)), "feature"),
if (is.null(embedding_name)) "" else paste0(", ", .log_plural(n_cells, "cell"))
))
}

res <- project_bulk_atac(
dim_reduction, se_atac,
embedding_name = NULL, assay_name = assay_name, n = n, iteration = iteration,
force = force, seed = seed, verbose = verbose
)
if (verbose) {
sim_summary <- sprintf(
"%s from %s in %s", .log_plural(nrow(res$simulated_reduced_dims), "pseudo-cell"),
.log_plural(ncol(se_atac), "sample"), sub("^Iterative", "", class(dim_reduction)[1])
)
}
if (is.null(embedding_name)) {
if (verbose) .log_finish(run, sim_summary)
return(res)
}

available_assays <- unique(unlist(get_assay_names(x)))
if (!reduced_dims_assay %in% available_assays) {
rlang::abort(sprintf(
"Assay '%s' not found. Pass `reduced_dims_assay` naming the cell embeddings. Available: %s",
reduced_dims_assay, paste(available_assays, collapse = ", ")
))
}

embedding_record <- x$embeddings[[embedding_name]] %||% NULL
if (!is.null(embedding_record)) {
if (!identical(embedding_record$method, "umap")) {
Expand Down Expand Up @@ -476,22 +528,25 @@ project_bulk_atac.MarchRProject <- function(
"Stored UMAP model archive is missing: %s", model_path
))
}
if (verbose) log_progress("Loading the fitted UMAP transform model")
t0 <- steady_clock_seconds_rcpp()
model <- uwot::load_uwot(model_path)
on.exit(uwot::unload_uwot(model), add = TRUE)
if (verbose) .log_step(sprintf("Loaded UMAP model '%s'", embedding_name), since = t0)
} else {
rlang::warn(paste0(
"No project-level UMAP transform model is stored for '", embedding_name,
"'. Reconstructing a legacy pinned model; re-run add_umap() for exact projection."
))
if (verbose) log_progress("Reconstructing the legacy fitted UMAP model")
t0 <- steady_clock_seconds_rcpp()
model <- .pinned_umap_model(
reduced_dims, umap_coords, umap_params = umap_params,
threads = threads, verbose = FALSE
)
on.exit(uwot::unload_uwot(model), add = TRUE)
if (verbose) .log_step("Rebuilt legacy UMAP model from stored coordinates", since = t0)
}

t0 <- steady_clock_seconds_rcpp()
set.seed(seed)
check_idx <- sort(sample(
nrow(reduced_dims), min(nrow(reduced_dims), n_check_cells)
Expand All @@ -504,7 +559,14 @@ project_bulk_atac.MarchRProject <- function(
dim1 = stats::cor(reprojected[, 1], umap_coords[check_idx, 1]),
dim2 = stats::cor(reprojected[, 2], umap_coords[check_idx, 2])
)
if (min(projection_corr) < min_corr) {
below <- min(projection_corr) < min_corr
if (verbose) {
.log_step(sprintf(
"Re-projected %s to check UMAP, r = %.3f%s", .log_plural(length(check_idx), "cell"),
min(projection_corr), if (below) sprintf(" (below %.2f)", min_corr) else ""
), since = t0)
}
if (below) {
rlang::warn(sprintf(
paste0(
"UMAP reprojection correlation is %.4f, below the %.2f threshold. ",
Expand All @@ -514,11 +576,17 @@ project_bulk_atac.MarchRProject <- function(
))
}

if (verbose) log_progress("Projecting bulk samples into the UMAP embedding")
t0 <- steady_clock_seconds_rcpp()
simulated_umap <- uwot::umap_transform(
res$simulated_reduced_dims, model, n_threads = threads,
n_sgd_threads = .umap_sgd_threads(model), verbose = FALSE
)
if (verbose) {
.log_step(
sprintf("Projected %s into UMAP", .log_plural(nrow(simulated_umap), "pseudo-cell")), since = t0
)
.log_finish(run, paste(sim_summary, "and UMAP"))
}
sim_names <- rownames(res$simulated_reduced_dims)

list(
Expand Down
Loading
Loading