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
16 changes: 16 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
# MarchR (development version)

## New features

* `save_project(copy = FALSE)` saves a lightweight checkpoint that points at stored data instead of copying it. Cell or feature subsets, fragment operations and lazy tile matrices are saved as recipes, and `load_project()` reports when it loads one.
* `add_tile_matrix(materialize = FALSE)` keeps the tile matrix lazy: nothing is written, and every read recomputes it from fragments.
* Printing a project marks assays that are computed when read.

## Behavior changes

* `add_gene_score_matrix()` stores gene scores under the project directory instead of reading a temporary file.
* `save_project(copy = FALSE)` keeps the project's working directory, never deletes data when saving over a checkpoint, and still copies data stored in R's temporary directory, including UMAP models and linkage matrices.
* `load_project()` errors when data referenced by a checkpoint no longer matches what was saved.
* `add_tile_matrix()` errors on arguments it does not use instead of ignoring them.
* The hematopoiesis and multiome tutorials keep the project under `cache_dir` instead of R's temporary directory.

# MarchR 0.3.0

## New features
Expand Down
93 changes: 70 additions & 23 deletions R/fragment_ops.R
Original file line number Diff line number Diff line change
Expand Up @@ -138,15 +138,19 @@ 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 materialize (logical) If \code{TRUE}, compute the tile matrix once and store it on disk;
#' if \code{FALSE}, keep it lazy and recompute it from fragments on every read. Default: \code{TRUE}.
#' @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 the tile matrix assay stored on disk, or the lazy
#' \code{IterableMatrix} if \code{return_matrix = TRUE}.
#' \code{IterableMatrix} computed from fragments, without adding it to the object.
#' @param ... Must be empty; other arguments are an error.
#' @return Modified object with the tile matrix assay, 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. 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.
#' With \code{materialize = FALSE}, IterativeLSI runs slower and its results can differ
#' from those on a stored matrix.
#' @name add_tile_matrix
NULL

Expand All @@ -161,6 +165,7 @@ add_tile_matrix <- function(
tile_size = 500,
mode = c("insertions", "fragments"),
binarize = FALSE,
materialize = TRUE,
return_matrix = FALSE,
...
) {
Expand Down Expand Up @@ -193,9 +198,12 @@ add_tile_matrix.MarchRDataset <- function(
mode = c("insertions", "fragments"),
overwrite = TRUE,
binarize = FALSE,
materialize = TRUE,
return_matrix = FALSE,
...
) {
rlang::check_dots_empty()
assert_for(materialize, "logical")
if (length(frags_name) == 0) {
frags_name <- select_fragment_name(proj, frags_name = frags_name)
}
Expand Down Expand Up @@ -238,14 +246,19 @@ add_tile_matrix.MarchRDataset <- function(
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, "_")))
if (materialize) {
tile_matrix <- .write_tile_matrix(tile_matrix, tempfile(paste0(output_assay_name, "_")))
}
proj <- add_matrix(
proj,
tile_matrix,
mat_name = output_assay_name,
overwrite = overwrite
)
proj$feature_totals[[output_assay_name]] <- .compute_feature_totals(tile_matrix, tempdir())
# NULL for a lazy matrix drops stale totals; IterativeLSI counts them on first use.
proj$feature_totals[[output_assay_name]] <- if (materialize) {
.compute_feature_totals(tile_matrix, tempdir())
}
return(proj)
}

Expand All @@ -266,9 +279,12 @@ add_tile_matrix.MarchRProject <- function(
mode = c("insertions", "fragments"),
overwrite = TRUE,
binarize = FALSE,
materialize = TRUE,
return_matrix = FALSE,
...
) {
rlang::check_dots_empty()
assert_for(materialize, "logical")
if (length(frags_name) == 0) {
frags_name <- select_fragment_name(proj, frags_name = frags_name)
}
Expand Down Expand Up @@ -310,21 +326,26 @@ add_tile_matrix.MarchRProject <- function(
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)
)
# Prefixed before writing, so a stored directory already holds the final cell names.
tile_matrix <- .prefix_cell_names_matrix(tile_matrix, dataset_name)
if (materialize) {
tile_matrix <- .write_tile_matrix(
tile_matrix, 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)
)
# NULL for a lazy matrix drops stale totals; IterativeLSI counts them on first use.
proj$datasets[[dataset_name]]$feature_totals[[output_assay_name]] <- if (materialize) {
.compute_feature_totals(
tile_matrix, file.path(proj$dir, "datasets", dataset_name, "feature_totals", output_assay_name)
)
}
}
if (return_matrix) {
return(return_mats)
Expand All @@ -345,7 +366,7 @@ add_tile_matrix.MarchRProject <- function(
#' Add a gene score matrix from fragment data
#'
#' Computes gene activity scores using ArchR's distance-weighted model.
#' Wraps \code{BPCells::gene_score_archr()} — see that function for
#' Wraps \code{BPCells::gene_score_archr()}. See that function for
#' algorithmic details.
#'
#' @param proj (MarchRProject or MarchRDataset) Object containing fragments.
Expand All @@ -372,7 +393,7 @@ add_tile_matrix.MarchRProject <- function(
#' @param overwrite (logical) Overwrite existing assay. Default: \code{FALSE}.
#' @param return_matrix (logical) If \code{TRUE}, returns the matrix directly.
#'
#' @return Modified object with gene score assay, or an \code{IterableMatrix}
#' @return Modified object with gene score assay, or a lazy \code{IterableMatrix}
#' (or named list for MarchRProject) if \code{return_matrix = TRUE}.
#'
#' @seealso \code{\link{add_tile_matrix}} \code{\link{set_gene_annotations}}
Expand Down Expand Up @@ -457,7 +478,8 @@ add_gene_score_matrix.MarchRDataset <- function(
tile_width = tile_width,
tile_max_count = tile_max_count,
scale_factor = scale_factor,
addArchRBug = addArchRBug
addArchRBug = addArchRBug,
out_dir = if (!return_matrix) tempfile(paste0(output_assay_name, "_"))
)

if (return_matrix) {
Expand Down Expand Up @@ -525,7 +547,13 @@ add_gene_score_matrix.MarchRProject <- function(
if (!frags_name %in% get_fragment_names(proj, dataset_name)) {
next
}
frags <- get_fragments(proj, dataset_name = dataset_name, frags_name)
if (!return_matrix && !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.
frags <- get_fragments(proj, dataset_name = dataset_name, frags_name) %>%
.prefix_cell_names_fragments(dataset_name)
# Keep fragments on the same chromosomes used to define gene regions.
frags <- select_chromosomes(frags, as.character(chrom_sizes$chr))

Expand All @@ -535,7 +563,10 @@ add_gene_score_matrix.MarchRProject <- function(
tile_width = tile_width,
tile_max_count = tile_max_count,
scale_factor = scale_factor,
addArchRBug = addArchRBug
addArchRBug = addArchRBug,
out_dir = if (!return_matrix) {
file.path(proj$dir, "datasets", dataset_name, "matrices", output_assay_name)
}
)

if (return_matrix) {
Expand Down Expand Up @@ -568,7 +599,9 @@ add_gene_score_matrix.MarchRProject <- function(
#' @param tile_max_count Per-tile count ceiling.
#' @param scale_factor Depth normalization factor.
#' @param addArchRBug Replicate ArchR nested gene bug.
#' @return An IterableMatrix of gene scores.
#' @param out_dir Directory to write the scores into, or NULL to return them lazily.
#' @return An IterableMatrix of gene scores: a MatrixDir at `out_dir`, or a lazy matrix that
#' reads an intermediate tile matrix under tempdir() when `out_dir` is NULL.
#' @keywords internal
#' @noRd
.compute_gene_scores <- function(
Expand All @@ -577,7 +610,8 @@ add_gene_score_matrix.MarchRProject <- function(
tile_width = 500,
tile_max_count = 4,
scale_factor = 10000,
addArchRBug = FALSE
addArchRBug = FALSE,
out_dir = NULL
) {
# Deduplicate genes by name (e.g., PAR genes on chrX/chrY)
if (!is.null(gene_name_column) && gene_name_column %in% colnames(genes)) {
Expand All @@ -588,7 +622,14 @@ add_gene_score_matrix.MarchRProject <- function(
valid_chrs <- intersect(unique(chrom_sizes$chr), chrNames(frags))
genes <- genes[genes$chr %in% valid_chrs, ]

gene_score_archr(
if (is.null(out_dir)) {
tile_dir <- tempfile("gene_score_tile_mat")
} else {
dir.create(dirname(out_dir), recursive = TRUE, showWarnings = FALSE)
tile_dir <- tempfile("gene_score_tiles_", tmpdir = dirname(out_dir))
on.exit(unlink(tile_dir, recursive = TRUE), add = TRUE)
}
scores <- gene_score_archr(
fragments = frags,
genes = genes,
chromosome_sizes = chrom_sizes,
Expand All @@ -597,6 +638,12 @@ add_gene_score_matrix.MarchRProject <- function(
gene_name_column = gene_name_column,
tile_max_count = tile_max_count,
scale_factor = scale_factor,
addArchRBug = addArchRBug
addArchRBug = addArchRBug,
tile_matrix_path = tile_dir
)
if (is.null(out_dir)) {
return(scores)
}
unlink(out_dir, recursive = TRUE, expand = FALSE)
rlang::with_options(write_matrix_dir(scores, out_dir), rlib_message_verbosity = "quiet")
}
10 changes: 5 additions & 5 deletions R/group_coverages.R
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ add_group_coverages.MarchRProject <- function(
# 1. A column name (character length 1) to pull from cell metadata
# 2. A named vector of group labels (names = cell names)
if (is.character(group_by) && length(group_by) == 1 && is.null(names(group_by))) {
# Column name — extract from metadata
# Column name - extract from metadata
group_by_name <- group_by
extra_cells <- character(0)
all_cell_names <- unlist(
Expand All @@ -204,7 +204,7 @@ add_group_coverages.MarchRProject <- function(
}
)

# Every cell must have a group assignment — no gaps allowed
# Every cell must have a group assignment. No gaps allowed
missing <- setdiff(all_cell_names, names(groups))
if (length(missing) > 0) {
rlang::abort(sprintf(
Expand Down Expand Up @@ -454,7 +454,7 @@ get_group_coverages <- function(proj, group_by = character(0)) {
) {
n_cells <- length(cell_names)

# Strategy 1: Enough cells to split by sample — each large sample becomes its own replicate
# Strategy 1: Enough cells to split by sample. Each large sample becomes its own replicate
if (n_cells >= min_cells * min_replicates && !is.null(sample_labels)) {
reps <- .assign_by_labels(
cell_names = cell_names,
Expand All @@ -471,7 +471,7 @@ get_group_coverages <- function(proj, group_by = character(0)) {
replace = FALSE
)
} else {
# Strategy 3: Very few cells — must sample with replacement to reach min_cells per replicate
# Strategy 3: Very few cells. Must sample with replacement to reach min_cells per replicate
reps <- .least_overlap_cells(
cell_names = cell_names,
n = min_replicates,
Expand Down Expand Up @@ -578,7 +578,7 @@ get_group_coverages <- function(proj, group_by = character(0)) {
assignment[idx, j] <- 1L
}

# Euclidean distance between columns measures overlap — maximize to minimize shared cells
# Euclidean distance between columns measures overlap. Maximize to minimize shared cells
d <- sum(stats::dist(t(assignment))^2)
if (d > best_dist) {
best_dist <- d
Expand Down
2 changes: 1 addition & 1 deletion R/markers.R
Original file line number Diff line number Diff line change
Expand Up @@ -594,7 +594,7 @@ add_marker_features.MarchRProject <- function(
}

########################################################################
# get_marker_features() — retrieval
# get_marker_features() - retrieval
########################################################################

#' Retrieve stored marker feature results
Expand Down
13 changes: 12 additions & 1 deletion R/project_class.R
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,14 @@ get_assay_feature_info <- function(x, assay_name) {
))
}

# TRUE if reading `mat` computes values; subsets and renames of stored data count as stored.
.computed_on_read <- function(mat) {
while (is(mat, "MatrixSubset") || is(mat, "RenameDims")) mat <- mat@matrix
leaves <- all_matrix_inputs(mat)
is(mat, "TileMatrix") || is(mat, "PeakMatrix") ||
length(leaves) != 1L || !identical(leaves[[1]], mat)
}

# Helper function to print a single assay
print_assay_info <- function(x, assay_name) {
assay_info <- get_assay_feature_info(x, assay_name)
Expand All @@ -554,9 +562,12 @@ print_assay_info <- function(x, assay_name) {
)
}

mats <- Filter(Negate(is.null), lapply(x$datasets, function(ds) ds$matrices[[assay_name]]))
read_tag <- if (length(mats) > 0 && .computed_on_read(mats[[1]])) " (computed when read)" else ""
assay_line <- sprintf(
" %s: %s\n %s\n",
" %s%s: %s\n %s\n",
assay_name,
read_tag,
missing_dataset_str,
assay_info$feature_info
)
Expand Down
Loading
Loading