From f47741cdb224ead138c7b7b0aa8572955e3d4dd2 Mon Sep 17 00:00:00 2001 From: erliuu Date: Tue, 1 Dec 2026 23:01:45 -0800 Subject: [PATCH 1/3] feat([r] save_load): Add copy = FALSE for save_project checkpointing and lazy tile matrices --- NEWS.md | 16 ++ R/fragment_ops.R | 93 +++++-- R/project_class.R | 13 +- R/save_load.R | 379 ++++++++++++++++++++++++----- man/add_gene_score_matrix.Rd | 4 +- man/add_tile_matrix.Rd | 15 +- man/load_project.Rd | 6 +- man/plot_browser_track.Rd | 2 +- man/save_project.Rd | 19 +- tests/testthat/test-fragment_ops.R | 27 ++ tests/testthat/test-gene_scores.R | 55 ++++- tests/testthat/test-project-io.R | 190 ++++++++++++++- 12 files changed, 720 insertions(+), 99 deletions(-) diff --git a/NEWS.md b/NEWS.md index b9cf4ea..329f050 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 diff --git a/R/fragment_ops.R b/R/fragment_ops.R index 62ebe7f..208d4db 100644 --- a/R/fragment_ops.R +++ b/R/fragment_ops.R @@ -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 @@ -161,6 +165,7 @@ add_tile_matrix <- function( tile_size = 500, mode = c("insertions", "fragments"), binarize = FALSE, + materialize = TRUE, return_matrix = FALSE, ... ) { @@ -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) } @@ -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) } @@ -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) } @@ -310,11 +326,13 @@ 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, @@ -322,9 +340,12 @@ add_tile_matrix.MarchRProject <- function( 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) @@ -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. @@ -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}} @@ -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) { @@ -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)) @@ -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) { @@ -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( @@ -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)) { @@ -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, @@ -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") } diff --git a/R/project_class.R b/R/project_class.R index b823eee..460eb3a 100644 --- a/R/project_class.R +++ b/R/project_class.R @@ -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) @@ -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 ) diff --git a/R/save_load.R b/R/save_load.R index ce90cd4..d83ba26 100644 --- a/R/save_load.R +++ b/R/save_load.R @@ -2,10 +2,12 @@ # Project save / load: save_project() / load_project() ######################################################################## -# Placeholder in .rds for BPCells IterableMatrix/IterableFragments -new_ondisk_ref <- function(kind, path, relative) { +# Placeholder for a BPCells object in project.rds. A plain ref points at one stored directory; +# composite refs (path = NA) hold `subset_of` plus `rows`/`cols`, a fragments `recipe`, or a +# `tile_recipe` whose tile names are rebuilt at load (`named` marks those layers). +new_ondisk_ref <- function(kind, path, relative, ...) { structure( - list(kind = kind, path = path, relative = relative), + list(kind = kind, path = path, relative = relative, ...), class = "marchr_ondisk_ref" ) } @@ -19,47 +21,187 @@ new_ondisk_ref <- function(kind, path, relative) { if (startsWith(path, prefix)) substring(path, nchar(prefix) + 1L) else NULL } +.saved_path <- function(path, root) { + .path_relative_to(path, root) %||% normalizePath(path, mustWork = FALSE) +} + +.ref_to <- function(kind, dir, root, ...) { + rel <- .path_relative_to(dir, root) + if (is.null(rel)) { + new_ondisk_ref(kind, normalizePath(dir, mustWork = FALSE), FALSE, ...) + } else { + new_ondisk_ref(kind, rel, TRUE, ...) + } +} + +.session_temp_dir <- function() normalizePath(tempdir(), mustWork = FALSE) + +.in_session_temp <- function(paths) { + paths <- normalizePath(paths, mustWork = FALSE) + temp <- .session_temp_dir() + paths == temp | startsWith(paths, paste0(temp, .Platform$file.sep)) +} + +# R deletes its session temp dir on exit, so a save outside it must copy data stored there. +.needs_own_copy <- function(paths, root) !.in_session_temp(root) & .in_session_temp(paths) + +# Apply `f` to each leaf fragments object under `frags`, keeping the layers above it. +.map_fragment_leaves <- function(frags, f) { + if (methods::.hasSlot(frags, "fragments")) { + frags@fragments <- .map_fragment_leaves(frags@fragments, f) + } else if (methods::.hasSlot(frags, "fragments_list")) { + frags@fragments_list <- lapply(frags@fragments_list, .map_fragment_leaves, f = f) + } else { + frags <- f(frags) + } + frags +} + +.fragment_leaves <- function(frags) { + leaves <- list() + .map_fragment_leaves(frags, function(leaf) { + leaves[[length(leaves) + 1L]] <<- leaf + leaf + }) + leaves +} + +# Names selecting `obj` from `leaf`, per subset axis; NULL if that axis lacks unique names. +.subset_selection <- function(obj, leaf) { + sel <- list() + for (axis in 1:2) { + leaf_names <- dimnames(leaf)[[axis]] + if (!is.null(leaf_names) && identical(dimnames(obj)[[axis]], leaf_names)) next + if (is.null(leaf_names) || anyDuplicated(leaf_names) > 0) return(NULL) + sel[[c("rows", "cols")[axis]]] <- dimnames(obj)[[axis]] + } + sel +} + +# Layers from `obj` down to its TileMatrix if each has one matrix input; else NULL. +.tile_layers <- function(obj) { + layers <- list(obj) + while (!is(obj, "TileMatrix") && methods::.hasSlot(obj, "matrix")) { + obj <- obj@matrix + layers[[length(layers) + 1L]] <- obj + } + if (is(obj, "TileMatrix")) layers +} + +# Rebuild `obj` with `f(layer, depth)` applied to each layer, TileMatrix first. +.map_tile_layers <- function(obj, f, depth = 1L) { + if (!is(obj, "TileMatrix")) obj@matrix <- .map_tile_layers(obj@matrix, f, depth + 1L) + f(obj, depth) +} + +# Tile names, cached in `acc` so datasets sharing a tiling build them once. +.tile_names <- function(tiles, acc) { + key <- rlang::hash(list(tiles@chr_levels, tiles@chr_id, tiles@start, tiles@end, tiles@tile_width)) + if (is.null(acc$tile_names[[key]])) { + ranges <- data.frame( + chr = tiles@chr_levels[tiles@chr_id + 1L], start = tiles@start, end = tiles@end, + tile_width = tiles@tile_width + ) + acc$tile_names[[key]] <- rownames( + BPCells::tile_matrix(tiles@fragments, ranges, mode = tiles@mode, explicit_tile_names = TRUE) + ) + } + acc$tile_names[[key]] +} + +# For copy = FALSE: a ref to `obj`'s stored data, or a string saying why it must be written. +.reference_in_place <- function(obj, kind, root) { + tiles <- if (kind == "matrix") .tile_layers(obj) + if (!is.null(tiles)) { + tile_names <- tiles[[length(tiles)]]@dimnames[[1]] + named <- !vapply(tiles, function(layer) is.null(layer@dimnames[[1]]), logical(1)) + if (!all(vapply(tiles[named], function(layer) identical(layer@dimnames[[1]], tile_names), + logical(1)))) { + return("its row names differ from the tiles it is computed from") + } + leaves <- .fragment_leaves(tiles[[length(tiles)]]@fragments) + } else if (kind == "matrix") { + subset <- is(obj, "MatrixSubset") + leaf <- if (subset) obj@matrix else obj + sel <- if (is(leaf, "MatrixDir")) { + if (subset) .subset_selection(obj, leaf) else list() + } + if (is.null(sel)) return("it is not stored on disk as a matrix or a cell/feature subset of one") + leaves <- list(leaf) + } else { + leaves <- .fragment_leaves(obj) + } + if ((kind == "fragments" || !is.null(tiles)) && + !all(vapply(leaves, is, logical(1), class2 = "FragmentsDir"))) { + return("its fragments are not stored in BPCells fragment directories") + } + dirs <- vapply(leaves, function(leaf) leaf@dir, character(1)) + if (any(.needs_own_copy(dirs, root))) { + return("it is stored in R's temporary directory, which is deleted when R exits") + } + + saved_leaf <- function(leaf) { + leaf@dir <- .saved_path(leaf@dir, root) + leaf + } + # path = NA makes older loaders fail on a missing directory instead of opening the full matrix. + ref <- if (!is.null(tiles)) { + # Tile names are rebuilt at load, so the save stays small. + recipe <- .map_tile_layers(obj, function(layer, depth) { + if (is(layer, "TileMatrix")) { + layer@fragments <- .map_fragment_leaves(layer@fragments, saved_leaf) + } + if (named[[depth]]) layer@dimnames[1] <- list(NULL) + layer + }) + new_ondisk_ref("matrix", NA_character_, NA, tile_recipe = recipe, named = named) + } else if (kind == "fragments" && !is(obj, "FragmentsDir")) { + new_ondisk_ref("fragments", NA_character_, NA, recipe = .map_fragment_leaves(obj, saved_leaf)) + } else if (kind == "matrix" && length(sel) > 0) { + new_ondisk_ref( + "matrix", NA_character_, NA, + subset_of = .ref_to("matrix", dirs, root, dim = dim(leaf)), + rows = sel$rows, cols = sel$cols + ) + } else { + .ref_to(kind, dirs, root, dim = if (kind == "matrix") dim(obj)) + } + dirs <- normalizePath(dirs, mustWork = FALSE) + inside <- !vapply(lapply(dirs, .path_relative_to, root = root), is.null, logical(1)) + list(ref = ref, kept = dirs[inside], external = dirs[!inside]) +} + # Detect any BPCells iterable left in the shell .has_iterable <- function(x) { + if (is(x, "marchr_ondisk_ref")) return(FALSE) if (is(x, "IterableMatrix") || is(x, "IterableFragments")) return(TRUE) if (is.list(x)) return(any(vapply(unclass(x), .has_iterable, logical(1)))) FALSE } -# Persist one iterable to `target_dir`. Returns list(ref, handle): a -# marchr_ondisk_ref for the shell and a live BPCells handle for the project. +# Persist one iterable. Returns list(ref, handle, kept, external): ref for the shell, live handle, +# and the directories under / outside `root` that the ref reads. .persist_iterable <- function(obj, kind, target_dir, root, copy, overwrite) { + if (!copy) { + placed <- .reference_in_place(obj, kind, root) + if (!is.character(placed)) return(c(placed, list(handle = obj))) + rlang::inform(sprintf("Writing '%s' into the saved project: %s.", target_dir, placed)) + } leaf_class <- if (kind == "matrix") "MatrixDir" else "FragmentsDir" - writer <- if (kind == "matrix") write_matrix_dir else write_fragments_dir + target_norm <- normalizePath(target_dir, mustWork = FALSE) - already_leaf <- is(obj, leaf_class) - target_norm <- normalizePath(target_dir, mustWork = FALSE) - current_dir <- if (already_leaf) normalizePath(obj@dir, mustWork = FALSE) else NA_character_ - - if (already_leaf && identical(current_dir, target_norm)) { - handle <- obj - ref_path <- target_norm - } else if (already_leaf && !copy) { + if (is(obj, leaf_class) && identical(normalizePath(obj@dir, mustWork = FALSE), target_norm)) { handle <- obj - ref_path <- current_dir } else { - if (!copy && !already_leaf) { - rlang::inform(sprintf( - "Writing '%s' into the project directory: it was not already stored on disk.", - target_dir - )) - } + writer <- if (kind == "matrix") write_matrix_dir else write_fragments_dir + dir.create(dirname(target_dir), showWarnings = FALSE, recursive = TRUE) handle <- rlang::with_options( writer(obj, target_dir, overwrite = overwrite), rlib_message_verbosity = "quiet" ) - ref_path <- target_norm } - - rel <- .path_relative_to(ref_path, root) - ref <- if (is.null(rel)) new_ondisk_ref(kind, ref_path, FALSE) - else new_ondisk_ref(kind, rel, TRUE) - list(ref = ref, handle = handle) + ref <- .ref_to(kind, target_norm, root, dim = if (kind == "matrix") dim(handle)) + list(ref = ref, handle = handle, kept = target_norm, external = character(0)) } # Remove matrix/fragment directories under /datasets that the current @@ -90,10 +232,9 @@ new_ondisk_ref <- function(kind, path, relative) { if (is(x, "marchr_ondisk_ref")) return(x) if (is(x, "IterableMatrix") || is(x, "IterableFragments")) { kind <- if (is(x, "IterableMatrix")) "matrix" else "fragments" - target <- file.path(root, "extra", name) - dir.create(dirname(target), showWarnings = FALSE, recursive = TRUE) - res <- .persist_iterable(x, kind, target, root, copy, overwrite) - acc$kept <- c(acc$kept, normalizePath(target, mustWork = FALSE)) + res <- .persist_iterable(x, kind, file.path(root, "extra", name), root, copy, overwrite) + acc$kept <- c(acc$kept, res$kept) + acc$external <- c(acc$external, res$external) return(res$ref) } if (is.list(x)) { @@ -112,14 +253,69 @@ new_ondisk_ref <- function(kind, path, relative) { x } -# Recursively reopen every marchr_ondisk_ref in `x` into a live BPCells handle, -# collecting any missing directories in `acc$missing`. -.reopen_refs <- function(x, root, acc) { - if (is(x, "marchr_ondisk_ref")) { - dir <- if (isTRUE(x$relative)) file.path(root, x$path) else x$path - if (!dir.exists(dir)) { acc$missing <- c(acc$missing, dir); return(x) } - return(if (identical(x$kind, "matrix")) open_matrix_dir(dir) else open_fragments_dir(dir)) +.reopen_fragment_leaf <- function(leaf, root, acc) { + dir <- if (.is_absolute_path(leaf@dir)) leaf@dir else file.path(root, leaf@dir) + if (.is_absolute_path(leaf@dir)) acc$external <- c(acc$external, dir) + if (!dir.exists(dir)) { + acc$missing <- c(acc$missing, dir) + return(leaf) + } + reopened <- open_fragments_dir(dir) + if (!identical(cellNames(reopened), cellNames(leaf)) || + !identical(chrNames(reopened), chrNames(leaf))) { + acc$changed <- c(acc$changed, dir) + } + reopened +} + +.reopen_tile_recipe <- function(ref, root, acc) { + tile_names <- NULL + .map_tile_layers(ref$tile_recipe, function(layer, depth) { + if (is(layer, "TileMatrix")) { + layer@fragments <- .map_fragment_leaves( + layer@fragments, function(leaf) .reopen_fragment_leaf(leaf, root, acc) + ) + if (any(ref$named)) tile_names <<- .tile_names(layer, acc) + } + if (ref$named[[depth]]) layer@dimnames[[1]] <- tile_names + layer + }) +} + +.reopen_ref <- function(ref, root, acc) { + if (!is.null(ref$tile_recipe) || !is.null(ref$recipe) || !is.null(ref$subset_of)) { + acc$recipes <- acc$recipes + 1L + } + if (!is.null(ref$tile_recipe)) return(.reopen_tile_recipe(ref, root, acc)) + if (!is.null(ref$recipe)) { + return(.map_fragment_leaves(ref$recipe, function(leaf) .reopen_fragment_leaf(leaf, root, acc))) + } + if (!is.null(ref$subset_of)) { + mat <- .reopen_ref(ref$subset_of, root, acc) + if (!is(mat, "IterableMatrix")) return(ref) + if (!all(ref$rows %in% rownames(mat)) || !all(ref$cols %in% colnames(mat))) { + acc$changed <- c(acc$changed, mat@dir) + return(ref) + } + if (!is.null(ref$rows)) mat <- mat[ref$rows, ] + if (!is.null(ref$cols)) mat <- mat[, ref$cols] + return(mat) + } + dir <- if (isTRUE(ref$relative)) file.path(root, ref$path) else ref$path + if (!isTRUE(ref$relative)) acc$external <- c(acc$external, dir) + if (!dir.exists(dir)) { + acc$missing <- c(acc$missing, dir) + return(ref) } + if (identical(ref$kind, "fragments")) return(open_fragments_dir(dir)) + mat <- open_matrix_dir(dir) + if (!is.null(ref$dim) && !all(dim(mat) == ref$dim)) acc$changed <- c(acc$changed, dir) + mat +} + +# Reopen every ref in `x`; record missing dirs in `acc$missing` and mismatches in `acc$changed`. +.reopen_refs <- function(x, root, acc) { + if (is(x, "marchr_ondisk_ref")) return(.reopen_ref(x, root, acc)) if (is.list(x)) { attrs <- attributes(x) y <- unclass(x) @@ -166,7 +362,7 @@ new_ondisk_ref <- function(kind, path, relative) { src <- normalizePath(src, mustWork = TRUE) rel_target <- file.path("embeddings", embedding_name, "uwot-model.tar") target <- normalizePath(file.path(root, rel_target), mustWork = FALSE) - if (copy) { + if (copy || .needs_own_copy(src, root)) { if (!identical(src, target)) { dir.create(dirname(target), recursive = TRUE, showWarnings = FALSE) if (file.exists(target)) { @@ -182,7 +378,7 @@ new_ondisk_ref <- function(kind, path, relative) { rlang::abort(sprintf("Failed to copy embedding model to '%s'.", target)) } } - project$embeddings[[embedding_name]]$model_path <- target + if (copy) project$embeddings[[embedding_name]]$model_path <- target shell$embeddings[[embedding_name]]$model_path <- rel_target kept <- c(kept, dirname(target)) } else { @@ -237,7 +433,7 @@ new_ondisk_ref <- function(kind, path, relative) { } src_norm <- normalizePath(src, mustWork = FALSE) target_norm <- normalizePath(file.path(root, rel_subdir), mustWork = FALSE) - if (!copy) { + if (!copy && !.needs_own_copy(src_norm, root)) { rel <- .path_relative_to(src_norm, root) if (is.null(rel)) return(list(path = src_norm, kept = NULL, external = src_norm)) return(list(path = rel, kept = src_norm, external = NULL)) @@ -298,15 +494,23 @@ new_ondisk_ref <- function(kind, path, relative) { structure(shell, class = shell_class) } -#' Save a MarchRProject to a self-contained directory +#' Save a MarchRProject to a directory #' #' @param project (MarchRProject) Project to save. #' @param path (character) Destination directory to write the project into. -#' @param copy (logical) Copy matrices/fragments that live outside \code{path} into it -#' so the directory is self-contained; otherwise reference them in place. Default: \code{TRUE}. +#' @param copy (logical) If \code{TRUE}, write a self-contained copy: stored data is copied and +#' queued operations (cell subsets, cell name prefixes, lazy matrices) are computed and stored. +#' If \code{FALSE}, write a checkpoint that points at stored data and keeps queued operations as +#' recipes. Default: \code{TRUE}. #' @param overwrite (logical) Allow overwriting into a directory that already holds a saved project. Default: \code{FALSE}. #' @param ... Additional arguments passed to methods. -#' @return (invisibly) The input \code{MarchRProject} with its \code{dir} field set to \code{path}. +#' @return (invisibly) The input \code{MarchRProject}. With \code{copy = TRUE}, its \code{dir} is +#' set to \code{path} and its matrices and fragments read from the copies. +#' @details +#' A checkpoint (\code{copy = FALSE}) reads stored data where it lives, so rerunning a step that +#' overwrites that data changes what the checkpoint loads; \code{load_project()} errors if the +#' dimensions or cell names no longer match. Data it cannot reference, such as data in R's +#' temporary directory, is written into \code{path}. #' @export save_project <- function(project, ...) UseMethod("save_project") @@ -330,6 +534,13 @@ save_project.MarchRProject <- function(project, path, copy = TRUE, } dir.create(path, showWarnings = FALSE, recursive = TRUE) root <- normalizePath(path, mustWork = FALSE) + if (!copy && !is.null(project$dir) && .needs_own_copy(project$dir, root)) { + rlang::inform(paste( + "The project's working directory is in R's temporary directory, which R deletes when it", + "exits, so this checkpoint keeps its own copy of the data stored there. Create the project", + "with a durable `dir` to keep checkpoints small." + )) + } shell <- project external <- character(0) @@ -349,15 +560,12 @@ save_project.MarchRProject <- function(project, path, copy = TRUE, kind <- if (slot == "matrices") "matrix" else "fragments" for (name in names(project_dataset[[slot]])) { target <- file.path(root, "datasets", ds_name, slot, name) - dir.create(dirname(target), showWarnings = FALSE, recursive = TRUE) res <- .persist_iterable(project_dataset[[slot]][[name]], kind, target, root, copy, overwrite) project_dataset[[slot]][[name]] <- res$handle shell_dataset[[slot]][[name]] <- res$ref - if (!res$ref$relative) external <- c(external, res$ref$path) - if (res$ref$relative) { - kept <- c(kept, normalizePath(file.path(root, res$ref$path), mustWork = FALSE)) - } + kept <- c(kept, res$kept) + external <- c(external, res$external) } } project$datasets[[ds_name]] <- structure(project_dataset, class = "MarchRDataset") @@ -366,15 +574,19 @@ save_project.MarchRProject <- function(project, path, copy = TRUE, extra_acc <- new.env(parent = emptyenv()) extra_acc$kept <- character(0) + extra_acc$external <- character(0) shell <- .persist_extra_iterables(shell, "x", root, copy, overwrite, extra_acc) + external <- c(external, extra_acc$external) agg_res <- .persist_linkage_aggregates(shell, root, copy, external) shell <- agg_res$shell - external <- agg_res$external + external <- unique(agg_res$external) extra_acc$kept <- c(extra_acc$kept, agg_res$kept) - if (had_prior_save) .prune_children(file.path(root, "extra"), extra_acc$kept) - if (had_prior_save) .prune_children(file.path(root, "embeddings"), embedding_res$kept) + # Data under a copy = FALSE save may be read by other saves, so only copy = TRUE prunes. + prune <- had_prior_save && copy + if (prune) .prune_children(file.path(root, "extra"), extra_acc$kept) + if (prune) .prune_children(file.path(root, "embeddings"), embedding_res$kept) if (.has_iterable(shell)) { rlang::abort(paste( @@ -391,20 +603,26 @@ save_project.MarchRProject <- function(project, path, copy = TRUE, )) } - if (had_prior_save) .prune_orphans(root, kept) + if (prune) .prune_orphans(root, kept) shell$dir <- root + if (!copy && !is.null(project$dir)) { + attr(shell, "working_dir") <- normalizePath(project$dir, mustWork = FALSE) + } + attr(shell, "copy") <- copy saveRDS(shell, file.path(root, "project.rds")) - project$dir <- root + if (copy) project$dir <- root invisible(project) } #' Load a MarchRProject saved by save_project() #' #' @param path (character) A project directory previously written by \code{\link{save_project}}. -#' @return The reconstructed \code{MarchRProject} with lazy, disk-backed matrices -#' and fragments re-opened from \code{path}. +#' @return The reconstructed \code{MarchRProject} with lazy, disk-backed matrices and fragments +#' re-opened from where they were saved. A project saved with \code{copy = FALSE} gets back the +#' working \code{dir} it had when saved, if that directory still exists; otherwise \code{dir} +#' is \code{path}. #' @export load_project <- function(path) { assert_for(path, "character") @@ -429,12 +647,23 @@ load_project <- function(path) { # iterables under /extra) reopen_acc <- new.env(parent = emptyenv()) reopen_acc$missing <- character(0) + reopen_acc$changed <- character(0) + reopen_acc$external <- character(0) + reopen_acc$recipes <- 0L + reopen_acc$tile_names <- list() shell <- .reopen_refs(shell, root, reopen_acc) if (length(reopen_acc$missing) > 0) { rlang::abort(c( "Cannot load project; referenced data directories are missing:", - reopen_acc$missing + unique(reopen_acc$missing) + )) + } + if (length(reopen_acc$changed) > 0) { + rlang::abort(c( + "Cannot load project; referenced data no longer matches what was saved:", + unique(reopen_acc$changed), + i = "A step that rewrites this data ran after the project was saved with copy = FALSE." )) } @@ -452,6 +681,40 @@ load_project <- function(path) { )) } + working_dir <- attr(shell, "working_dir") + saved_copy <- attr(shell, "copy") + attr(shell, "working_dir") <- NULL + attr(shell, "copy") <- NULL shell$dir <- root + if (!is.null(working_dir)) { + if (dir.exists(working_dir)) { + shell$dir <- working_dir + } else { + rlang::inform(sprintf( + "The project's working directory '%s' no longer exists; new on-disk results go to '%s'.", + working_dir, root + )) + } + } + if (isFALSE(saved_copy)) .inform_checkpoint(reopen_acc, working_dir) validate_MarchRProject(shell) } + +# Load notice for a copy = FALSE save: how many objects are recipes and where its data lives. +.inform_checkpoint <- function(acc, working_dir) { + sources <- unique(acc$external) + if (!is.null(working_dir)) { + inside <- startsWith(sources, paste0(working_dir, .Platform$file.sep)) + sources <- c(if (any(inside)) working_dir, sources[!inside]) + } + rlang::inform(c( + "Loaded a checkpoint (saved with copy = FALSE).", + i = if (acc$recipes > 0) sprintf( + "%d of its matrices and fragment sets are recipes, recomputed each time they are read.", + acc$recipes + ), + i = if (length(sources) > 0) { + sprintf("It reads stored data from: %s", pretty_print_vector(sources, max_len = 3)) + } + )) +} diff --git a/man/add_gene_score_matrix.Rd b/man/add_gene_score_matrix.Rd index e72a0db..6fcc2dd 100644 --- a/man/add_gene_score_matrix.Rd +++ b/man/add_gene_score_matrix.Rd @@ -88,12 +88,12 @@ Default: \code{FALSE}. See \code{BPCells::gene_score_weights_archr()}.} Defaults to all datasets with fragments.} } \value{ -Modified object with gene score assay, or an \code{IterableMatrix} +Modified object with gene score assay, or a lazy \code{IterableMatrix} (or named list for MarchRProject) if \code{return_matrix = TRUE}. } \description{ 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. } \seealso{ diff --git a/man/add_tile_matrix.Rd b/man/add_tile_matrix.Rd index 3edbdd2..f119101 100644 --- a/man/add_tile_matrix.Rd +++ b/man/add_tile_matrix.Rd @@ -19,6 +19,7 @@ mode = c("insertions", "fragments"), overwrite = TRUE, binarize = FALSE, + materialize = TRUE, return_matrix = FALSE, ... ) @@ -36,6 +37,7 @@ mode = c("insertions", "fragments"), overwrite = TRUE, binarize = FALSE, + materialize = TRUE, return_matrix = FALSE, ... ) @@ -76,17 +78,20 @@ the same name. Default: \code{TRUE}.} \item{binarize}{(logical) If \code{TRUE}, binarize the tile matrix to 0/1. Default: \code{FALSE}.} +\item{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}.} + \item{return_matrix}{(logical) If \code{TRUE}, returns the lazy -\code{IterableMatrix} computed from fragments, without writing it.} +\code{IterableMatrix} computed from fragments, without adding it to the object.} -\item{...}{Additional arguments passed to \code{BPCells::tile_matrix()}.} +\item{...}{Must be empty; other arguments are an error.} \item{dataset_names}{(character) Datasets to process. Defaults to all datasets with fragments.} } \value{ -Modified object with the tile matrix assay stored on disk, or the lazy -\code{IterableMatrix} if \code{return_matrix = TRUE}. +Modified object with the tile matrix assay, or the lazy \code{IterableMatrix} if +\code{return_matrix = TRUE}. } \description{ Add a tile matrix from fragment data @@ -96,4 +101,6 @@ 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. } diff --git a/man/load_project.Rd b/man/load_project.Rd index 9739089..50c2ab6 100644 --- a/man/load_project.Rd +++ b/man/load_project.Rd @@ -10,8 +10,10 @@ load_project(path) \item{path}{(character) A project directory previously written by \code{\link{save_project}}.} } \value{ -The reconstructed \code{MarchRProject} with lazy, disk-backed matrices -and fragments re-opened from \code{path}. +The reconstructed \code{MarchRProject} with lazy, disk-backed matrices and fragments +re-opened from where they were saved. A project saved with \code{copy = FALSE} gets back the +working \code{dir} it had when saved, if that directory still exists; otherwise \code{dir} +is \code{path}. } \description{ Load a MarchRProject saved by save_project() diff --git a/man/plot_browser_track.Rd b/man/plot_browser_track.Rd index 23465c5..d09b272 100644 --- a/man/plot_browser_track.Rd +++ b/man/plot_browser_track.Rd @@ -73,7 +73,7 @@ Ignored when \code{tile_size} is set.} \code{"nFrags"} (default) normalizes by total fragments per cell. \code{"ReadsInTSS"} normalizes by TSS-overlapping reads. \code{"nCells"} normalizes by number of cells per group (no per-cell -scaling — pass a vector of ones).} +scaling - pass a vector of ones).} \item{norm_style}{(character) Coverage scaling formula. \code{"rpkm"} (default, BPCells) scales by \code{1e9 / (group_reads * bin_width)} diff --git a/man/save_project.Rd b/man/save_project.Rd index 58f199e..6ab4795 100644 --- a/man/save_project.Rd +++ b/man/save_project.Rd @@ -3,7 +3,7 @@ \name{save_project} \alias{save_project} \alias{save_project.MarchRProject} -\title{Save a MarchRProject to a self-contained directory} +\title{Save a MarchRProject to a directory} \usage{ save_project(project, ...) @@ -16,14 +16,23 @@ save_project(project, ...) \item{path}{(character) Destination directory to write the project into.} -\item{copy}{(logical) Copy matrices/fragments that live outside \code{path} into it -so the directory is self-contained; otherwise reference them in place. Default: \code{TRUE}.} +\item{copy}{(logical) If \code{TRUE}, write a self-contained copy: stored data is copied and +queued operations (cell subsets, cell name prefixes, lazy matrices) are computed and stored. +If \code{FALSE}, write a checkpoint that points at stored data and keeps queued operations as +recipes. Default: \code{TRUE}.} \item{overwrite}{(logical) Allow overwriting into a directory that already holds a saved project. Default: \code{FALSE}.} } \value{ -(invisibly) The input \code{MarchRProject} with its \code{dir} field set to \code{path}. +(invisibly) The input \code{MarchRProject}. With \code{copy = TRUE}, its \code{dir} is +set to \code{path} and its matrices and fragments read from the copies. } \description{ -Save a MarchRProject to a self-contained directory +Save a MarchRProject to a directory +} +\details{ +A checkpoint (\code{copy = FALSE}) reads stored data where it lives, so rerunning a step that +overwrites that data changes what the checkpoint loads; \code{load_project()} errors if the +dimensions or cell names no longer match. Data it cannot reference, such as data in R's +temporary directory, is written into \code{path}. } diff --git a/tests/testthat/test-fragment_ops.R b/tests/testthat/test-fragment_ops.R index 4c8defb..694ccf6 100644 --- a/tests/testthat/test-fragment_ops.R +++ b/tests/testthat/test-fragment_ops.R @@ -54,3 +54,30 @@ test_that("a saved TileMatrix stays column-major, in place or copied", { save_project(proj, path = copy_dir) expect_equal(storage_order(load_project(copy_dir)$datasets$d1$matrices$TileMatrix), "col") }) + +test_that("add_tile_matrix with materialize = FALSE keeps a lazy matrix and writes nothing", { + stored <- .add_test_tiles(.tile_test_project(), frags_name = "ATAC")$datasets$d1$matrices$TileMatrix + proj <- .add_test_tiles(.tile_test_project(), frags_name = "ATAC", materialize = FALSE) + lazy <- proj$datasets$d1$matrices$TileMatrix + + expect_s4_class(lazy, "TileMatrix") + expect_false(dir.exists(file.path(proj$dir, "datasets"))) + expect_null(proj$datasets$d1$feature_totals$TileMatrix) + expect_identical(as(lazy, "dgCMatrix"), as(stored, "dgCMatrix")) +}) + +test_that("add_tile_matrix rejects arguments it does not use", { + expect_error( + .add_test_tiles(.tile_test_project(), frags_name = "ATAC", tile_width = 20), "must be empty" + ) +}) + +test_that("print marks a lazy TileMatrix as computed when read", { + lazy <- .add_test_tiles(.tile_test_project(), frags_name = "ATAC", materialize = FALSE) + stored <- .add_test_tiles(.tile_test_project(), frags_name = "ATAC") + + expect_match( + capture.output(print(lazy)), "TileMatrix (computed when read)", fixed = TRUE, all = FALSE + ) + expect_false(any(grepl("computed when read", capture.output(print(stored)), fixed = TRUE))) +}) diff --git a/tests/testthat/test-gene_scores.R b/tests/testthat/test-gene_scores.R index c619de4..36de65c 100644 --- a/tests/testthat/test-gene_scores.R +++ b/tests/testthat/test-gene_scores.R @@ -229,7 +229,7 @@ test_that("add_gene_score_matrix respects tile_width parameter", { test_data <- create_gene_score_test_project() proj <- test_data$proj - # Compare with different tile widths — both should work + # Compare with different tile widths. Both should work proj_500 <- add_gene_score_matrix( proj, genes = test_data$genes, @@ -382,3 +382,56 @@ test_that("add_gene_score_matrix works with multi-dataset project", { length(all_cells) - half ) }) + +######################################################################## +# Gene score storage +######################################################################## + +test_that("add_gene_score_matrix.MarchRProject writes gene scores under proj$dir", { + test_data <- create_gene_score_test_project() + proj <- test_data$proj + proj$dir <- withr::local_tempdir("gs_proj_") + args <- list(genes = test_data$genes, chrom_sizes = test_data$chrom_sizes, blacklist = FALSE) + lazy <- do.call(add_gene_score_matrix, c(list(proj, return_matrix = TRUE), args))[["demo"]] + + proj <- do.call(add_gene_score_matrix, c(list(proj), args)) + + gs <- proj$datasets[["demo"]]$matrices[["GeneScoreMatrix"]] + matrices_dir <- file.path(proj$dir, "datasets", "demo", "matrices") + expect_s4_class(gs, "MatrixDir") + expect_equal(gs@dir, normalizePath(file.path(matrices_dir, "GeneScoreMatrix"))) + expect_identical(as(gs, "dgCMatrix"), as(lazy, "dgCMatrix")) + expect_identical(list.files(matrices_dir), "GeneScoreMatrix") +}) + +test_that("add_gene_score_matrix with overwrite = FALSE leaves stored gene scores untouched", { + test_data <- create_gene_score_test_project() + proj <- test_data$proj + proj$dir <- withr::local_tempdir("gs_proj_") + proj <- add_gene_score_matrix( + proj, genes = test_data$genes, chrom_sizes = test_data$chrom_sizes, blacklist = FALSE + ) + before <- as(proj$datasets[["demo"]]$matrices[["GeneScoreMatrix"]], "dgCMatrix") + + expect_error( + add_gene_score_matrix( + proj, genes = test_data$genes[1:2, ], chrom_sizes = test_data$chrom_sizes, blacklist = FALSE + ), + "already exists" + ) + expect_identical(as(proj$datasets[["demo"]]$matrices[["GeneScoreMatrix"]], "dgCMatrix"), before) +}) + +test_that("add_gene_score_matrix.MarchRDataset stores a written matrix", { + test_data <- create_gene_score_test_project() + genome <- Genome() + genome$chromosome_size <- test_data$chrom_sizes + + dataset <- add_gene_score_matrix( + test_data$proj$datasets[["demo"]], + genome = genome, genes = test_data$genes, chrom_sizes = test_data$chrom_sizes, + blacklist = FALSE + ) + + expect_s4_class(dataset$matrices[["GeneScoreMatrix"]], "MatrixDir") +}) diff --git a/tests/testthat/test-project-io.R b/tests/testthat/test-project-io.R index f0c253f..727c40e 100644 --- a/tests/testthat/test-project-io.R +++ b/tests/testthat/test-project-io.R @@ -128,7 +128,7 @@ test_that("copy = FALSE references external data with an absolute pointer and wa expect_false(ref$relative) expect_equal(normalizePath(ref$path), normalizePath(ext)) - expect_no_error(load_project(path)) + expect_no_error(suppressMessages(load_project(path))) }) test_that("re-saving to the same path is idempotent and reloadable", { @@ -253,9 +253,195 @@ test_that("save_project muffles BPCells write notices and keeps its own notices" ) msgs <- capture_messages(save_project(proj, path = tempfile("saveproj"), copy = FALSE)) expect_match( - msgs[-length(msgs)], "^Writing '.*' into the project directory: it was not already stored on disk" + msgs[-length(msgs)], + "^Writing '.*' into the saved project: it is not stored on disk as a matrix or a cell/feature" ) expect_match( msgs[length(msgs)], "^Saved project references data outside its directory \\(not self-contained\\):" ) }) + +######################################################################## +# copy = FALSE checkpoints +######################################################################## + +test_that(".fragment_leaves finds every stored input under lazy fragment operations", { + dataset <- create_test_project(include_fragments = TRUE, cells = 6)$datasets[["dataset_1"]] + frags <- dataset$fragments[["fragments"]] + a <- write_fragments_dir(frags, tempfile("frags_a")) + b <- write_fragments_dir(frags, tempfile("frags_b")) + merged <- c(prefix_cell_names(a, "a#"), prefix_cell_names(b, "b#")) + + leaves <- .fragment_leaves(select_cells(merged, cellNames(merged)[c(1, 8)])) + + expect_equal(vapply(leaves, function(leaf) leaf@dir, character(1)), c(a@dir, b@dir)) +}) + +# One-dataset project stored under `data_dir`, with prefixed cell names and a cell subset on top. +stored_project <- function(data_dir) { + base <- create_test_project(include_fragments = TRUE, cells = 6)$datasets[["dataset_1"]] + proj <- MarchRProject(dir = data_dir) + frags <- write_fragments_dir(base$fragments[["fragments"]], file.path(data_dir, "fragments")) + proj <- add_fragments(proj, frags, frags_name = "fragments", dataset_name = "d1") + rna <- write_matrix_dir( + .prefix_cell_names_matrix(base$matrices[["RNA"]], "d1"), file.path(data_dir, "RNA"), + compress = FALSE + ) + proj <- add_matrix(proj, rna, dataset_name = "d1", mat_name = "RNA") + subset_cells(proj, paste0("d1#cell_1_", 2:5), by_dataset = FALSE) +} + +rna_values <- function(proj) as(proj$datasets[["d1"]]$matrices[["RNA"]], "dgCMatrix") +frag_values <- function(proj) as(proj$datasets[["d1"]]$fragments[["fragments"]], "data.frame") + +test_that("copy = FALSE references stored data and its lazy cell subsets without copying them", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + path <- withr::local_tempdir("checkpoint_") + + expect_message(save_project(proj, path = path, copy = FALSE), "not self-contained") + + expect_false(dir.exists(file.path(path, "datasets"))) + loaded <- suppressMessages(load_project(path)) + stored <- all_matrix_inputs(loaded$datasets[["d1"]]$matrices[["RNA"]]) + expect_equal(stored[[1]]@dir, normalizePath(file.path(data_dir, "RNA"))) + expect_identical(rna_values(loaded), rna_values(proj)) + expect_identical(frag_values(loaded), frag_values(proj)) + + suppressMessages(save_project(loaded, path = path, copy = FALSE, overwrite = TRUE)) + expect_identical(rna_values(suppressMessages(load_project(path))), rna_values(proj)) +}) + +test_that("a copy = FALSE save inside the data directory survives moving that directory", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + before <- list(rna = rna_values(proj), frags = frag_values(proj)) + suppressMessages(save_project(proj, path = data_dir, copy = FALSE)) + moved <- paste0(data_dir, "-moved") + file.rename(data_dir, moved) + withr::defer(unlink(moved, recursive = TRUE)) + + loaded <- suppressMessages(load_project(moved)) + + expect_identical(rna_values(loaded), before$rna) + expect_identical(frag_values(loaded), before$frags) +}) + +test_that("copy = FALSE writes data stored in R's temporary directory into the saved project", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + before <- list(rna = rna_values(proj), frags = frag_values(proj)) + local_mocked_bindings(.session_temp_dir = function() normalizePath(data_dir)) + path <- withr::local_tempdir("checkpoint_") + + msgs <- capture_messages(save_project(proj, path = path, copy = FALSE)) + + expect_match(msgs, "temporary directory", all = FALSE) + unlink(data_dir, recursive = TRUE) + loaded <- suppressMessages(load_project(path)) + expect_identical(rna_values(loaded), before$rna) + expect_identical(frag_values(loaded), before$frags) +}) + +test_that("load_project reports copy = FALSE data that was rewritten or removed after saving", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + path <- withr::local_tempdir("checkpoint_") + suppressMessages(save_project(proj, path = path, copy = FALSE)) + + rna_dir <- file.path(data_dir, "RNA") + write_matrix_dir(open_matrix_dir(rna_dir)[1:2, ], rna_dir, overwrite = TRUE) + expect_error(load_project(path), "no longer matches") + + unlink(file.path(data_dir, "fragments"), recursive = TRUE) + expect_error(load_project(path), "missing") +}) + +test_that("copy = FALSE keeps the working dir and load_project restores it while it exists", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + proj$dir <- withr::local_tempdir("work_") + path <- withr::local_tempdir("checkpoint_") + + saved <- suppressMessages(save_project(proj, path = path, copy = FALSE)) + + expect_equal(saved$dir, proj$dir) + expect_equal(suppressMessages(load_project(path))$dir, normalizePath(proj$dir)) + unlink(proj$dir, recursive = TRUE) + msgs <- capture_messages(loaded <- load_project(path)) + expect_match(msgs, "no longer exists", all = FALSE) + expect_equal(loaded$dir, normalizePath(path)) +}) + +test_that("saving over a copy = FALSE save never prunes directories", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + path <- withr::local_tempdir("checkpoint_") + suppressMessages(save_project(proj, path = path, copy = FALSE)) + shared <- file.path(path, "datasets", "other", "matrices", "RNA") + dir.create(shared, recursive = TRUE) + + suppressMessages(save_project(proj, path = path, copy = FALSE, overwrite = TRUE)) + + expect_true(dir.exists(shared)) +}) + +test_that("copy = FALSE saves a lazy tile matrix as a recipe without its tile names", { + proj <- stored_project(withr::local_tempdir("stored_")) |> + add_tile_matrix( + frags_name = "fragments", ranges = .tile_ranges, blacklist = FALSE, binarize = TRUE, + materialize = FALSE + ) |> + subset_cells(paste0("d1#cell_1_", 3:5), by_dataset = FALSE) + tiles <- proj$datasets$d1$matrices$TileMatrix + path <- withr::local_tempdir("checkpoint_") + + suppressMessages(save_project(proj, path = path, copy = FALSE)) + + ref <- readRDS(file.path(path, "project.rds"))$datasets$d1$matrices$TileMatrix + expect_false(dir.exists(file.path(path, "datasets"))) + expect_null(ref$tile_recipe@dimnames[[1]]) + loaded <- suppressMessages(load_project(path))$datasets$d1$matrices$TileMatrix + expect_identical(dimnames(loaded), dimnames(tiles)) + expect_identical(as(loaded, "dgCMatrix"), as(tiles, "dgCMatrix")) +}) + +test_that("load_project says when it loads a checkpoint and what it reads", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + checkpoint <- withr::local_tempdir("checkpoint_") + copy <- withr::local_tempdir("copy_") + suppressMessages(save_project(proj, path = checkpoint, copy = FALSE)) + suppressMessages(save_project(proj, path = copy)) + + msgs <- capture_messages(load_project(checkpoint)) + + expect_match(msgs, "Loaded a checkpoint", all = FALSE) + expect_match(msgs, "2 of its matrices and fragment sets are recipes", all = FALSE) + expect_match(msgs, normalizePath(data_dir), fixed = TRUE, all = FALSE) + expect_silent(load_project(copy)) +}) + +test_that("copy = FALSE copies UMAP models and linkage matrices stored in R's temporary directory", { + data_dir <- withr::local_tempdir("stored_") + proj <- stored_project(data_dir) + model <- file.path(data_dir, "embeddings", "UMAP", "uwot-model.tar") + dir.create(dirname(model), recursive = TRUE) + writeLines("model", model) + proj$embeddings$UMAP <- list(model_path = model) + links <- file.path(data_dir, "coaccessibility_peaks") + dir.create(links) + writeLines("links", file.path(links, "version")) + proj$co_accessibility <- structure(data.frame(score = 1), agg_path = links) + local_mocked_bindings(.session_temp_dir = function() normalizePath(data_dir)) + path <- withr::local_tempdir("checkpoint_") + + msgs <- capture_messages(save_project(proj, path = path, copy = FALSE)) + + shell <- readRDS(file.path(path, "project.rds")) + expect_match(msgs, "working directory is in R's temporary directory", all = FALSE) + expect_equal(shell$embeddings$UMAP$model_path, file.path("embeddings", "UMAP", "uwot-model.tar")) + expect_true(file.exists(file.path(path, shell$embeddings$UMAP$model_path))) + expect_equal(attr(shell$co_accessibility, "agg_path"), file.path("extra", "linkage-coaccessibility")) + expect_true(file.exists(file.path(path, "extra", "linkage-coaccessibility", "version"))) +}) From 5d54a9165f35968cc18fefa8a2217a1606cd2344 Mon Sep 17 00:00:00 2001 From: erliuu Date: Tue, 1 Dec 2026 23:02:23 -0800 Subject: [PATCH 2/3] docs([rmd] tutorials): Update tutorials to keep projects in cache_dir for persistence --- vignettes/marchr_hematopoiesis.Rmd | 10 +++++----- vignettes/marchr_multiome.Rmd | 9 +++++---- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/vignettes/marchr_hematopoiesis.Rmd b/vignettes/marchr_hematopoiesis.Rmd index da0c962..29d2191 100644 --- a/vignettes/marchr_hematopoiesis.Rmd +++ b/vignettes/marchr_hematopoiesis.Rmd @@ -103,15 +103,15 @@ library(MarchR) set_threads(4) ``` -Downloads and references are cached in `cache_dir` so they are reused -across runs; the project itself is written to a temporary directory. -MarchR creates each directory as needed. +Downloads, references and the project are kept in `cache_dir`, so they persist +across sessions and runs. To keep the project in R's temporary directory instead, set +`project_dir <- file.path(tempdir(), "marchr_project")`. MarchR creates each directory as needed. ```{r} cache_dir <- path.expand("~/.cache/marchr_hematopoiesis") data_dir <- file.path(cache_dir, "data") ref_dir <- file.path(cache_dir, "references") -project_dir <- file.path(tempdir(), "marchr_project") +project_dir <- file.path(cache_dir, "project") ``` ## Download Fragments @@ -134,7 +134,7 @@ by the same on-disk project directory. proj <- MarchRProject(dir = project_dir) for (sample_name in names(input_files)) { frags <- open_fragments_10x(input_files[[sample_name]]) %>% - write_fragments_dir(file.path(project_dir, "fragments", sample_name)) + write_fragments_dir(file.path(project_dir, "fragments", sample_name), overwrite = TRUE) proj <- add_fragments( proj, frags, diff --git a/vignettes/marchr_multiome.Rmd b/vignettes/marchr_multiome.Rmd index a66f3af..86aa635 100644 --- a/vignettes/marchr_multiome.Rmd +++ b/vignettes/marchr_multiome.Rmd @@ -106,15 +106,16 @@ library(MarchR) set_threads(4) ``` -Downloads and references are cached in `cache_dir` so they are reused -across runs; the project itself is written to a temporary directory. +Downloads, references and the project are kept in `cache_dir`, so they persist +across sessions and runs. To keep the project in R's temporary directory instead, set +`project_dir <- file.path(tempdir(), "marchr_project")`. ```{r} sample_name <- "PBMC_10k" cache_dir <- path.expand("~/.cache/marchr_multiome") data_dir <- file.path(cache_dir, "data") ref_dir <- file.path(cache_dir, "references") -project_dir <- file.path(tempdir(), "marchr_project") +project_dir <- file.path(cache_dir, "project") ``` ## Download Data @@ -145,7 +146,7 @@ dataset later. ```{r} proj <- MarchRProject(dir = project_dir) frags <- open_fragments_10x(atac_gz) %>% - write_fragments_dir(file.path(project_dir, "fragments", sample_name)) + write_fragments_dir(file.path(project_dir, "fragments", sample_name), overwrite = TRUE) proj <- add_fragments(proj, frags, frags_name = "ATAC", dataset_name = sample_name) proj ``` From 130259e41c1aaf76ac5bf52517b5b51cb1ad8a57 Mon Sep 17 00:00:00 2001 From: erliuu Date: Tue, 1 Dec 2026 23:03:01 -0800 Subject: [PATCH 3/3] chore([r] comments): Replace dash characters --- R/group_coverages.R | 10 +++++----- R/markers.R | 2 +- R/track_plotting.R | 4 ++-- tests/testthat/test-doublet.R | 4 ++-- tests/testthat/test-group_coverages.R | 4 ++-- tests/testthat/test-peaks.R | 6 +++--- tests/testthat/test-scale_dims_cor_cutoff.R | 2 +- 7 files changed, 16 insertions(+), 16 deletions(-) diff --git a/R/group_coverages.R b/R/group_coverages.R index 0bb6543..2dc7503 100644 --- a/R/group_coverages.R +++ b/R/group_coverages.R @@ -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( @@ -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( @@ -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, @@ -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, @@ -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 diff --git a/R/markers.R b/R/markers.R index 7c36705..8f00901 100644 --- a/R/markers.R +++ b/R/markers.R @@ -594,7 +594,7 @@ add_marker_features.MarchRProject <- function( } ######################################################################## -# get_marker_features() — retrieval +# get_marker_features() - retrieval ######################################################################## #' Retrieve stored marker feature results diff --git a/R/track_plotting.R b/R/track_plotting.R index c6e4fb0..dd19817 100644 --- a/R/track_plotting.R +++ b/R/track_plotting.R @@ -107,7 +107,7 @@ gene_region <- function(transcripts, gene_symbol, #' \code{"nFrags"} (default) normalizes by total fragments per cell. #' \code{"ReadsInTSS"} normalizes by TSS-overlapping reads. #' \code{"nCells"} normalizes by number of cells per group (no per-cell -#' scaling — pass a vector of ones). +#' scaling - pass a vector of ones). #' @param norm_style (character) Coverage scaling formula. \code{"rpkm"} #' (default, BPCells) scales by \code{1e9 / (group_reads * bin_width)} #' (insertions per kilobase per normalized read). \code{"archr"} reproduces @@ -526,7 +526,7 @@ plot_browser_track <- function( proj, dataset_names, frags_name, norm_method, cell_names_ordered ) { if (norm_method == "nCells") { - # Uniform weighting — all cells contribute equally + # Uniform weighting. All cells contribute equally counts <- rep(1, length(cell_names_ordered)) names(counts) <- cell_names_ordered return(counts) diff --git a/tests/testthat/test-doublet.R b/tests/testthat/test-doublet.R index 23890e5..ebf7dc3 100644 --- a/tests/testthat/test-doublet.R +++ b/tests/testthat/test-doublet.R @@ -1,5 +1,5 @@ ######################################################################## -# Tests for simulate_doublets() — the streaming BPCells rewrite. +# Tests for simulate_doublets() - the streaming BPCells rewrite. ######################################################################## # Larger-than-default fixture so downsampling has something to act on. @@ -211,7 +211,7 @@ test_that("simulate_doublets sample_ratio = 1 produces no downsampling", { # Reconstruct the expected idx1/idx2 draws from the same seed sequence # the implementation uses. This is a deliberate coupling between the - # test and the draw order — if the draw order changes, this test must + # test and the draw order. If the draw order changes, this test must # be updated in the same PR. set.seed(11L) idx1 <- sample.int(ncol(.doublet_test_mat), n_doublets * n_trials, diff --git a/tests/testthat/test-group_coverages.R b/tests/testthat/test-group_coverages.R index 6dd7870..3e8b9a0 100644 --- a/tests/testthat/test-group_coverages.R +++ b/tests/testthat/test-group_coverages.R @@ -24,7 +24,7 @@ test_that(".assign_by_labels splits cells by sample label", { test_that(".assign_by_labels redistributes when no sample meets min_cells", { cells <- paste0("cell_", 1:60) - # 6 samples with 10 cells each — none meet min_cells = 20 + # 6 samples with 10 cells each. None meet min_cells = 20 labels <- rep(paste0("S", 1:6), each = 10) names(labels) <- cells @@ -181,7 +181,7 @@ test_that("add_group_coverages.default without labels", { }) test_that("add_group_coverages.default handles few-cell groups", { - # Only 10 cells — should trigger with-replacement strategy + # Only 10 cells. Should trigger with-replacement strategy groups <- setNames( rep("tiny", 10), paste0("cell_", 1:10) diff --git a/tests/testthat/test-peaks.R b/tests/testthat/test-peaks.R index 59447b0..66d42ef 100644 --- a/tests/testthat/test-peaks.R +++ b/tests/testthat/test-peaks.R @@ -649,7 +649,7 @@ test_that("get_peak_set errors on empty peak set", { ######################################################################## -# add_reproducible_peak_set() — integration tests (require MACS) +# add_reproducible_peak_set() - integration tests (require MACS) ######################################################################## test_that("add_reproducible_peak_set respects exclude_chr", { @@ -826,7 +826,7 @@ test_that("add_reproducible_peak_set annotates peaks when genes available", { ######################################################################## -# add_reproducible_peak_set() — parameter validation +# add_reproducible_peak_set() - parameter validation ######################################################################## test_that("add_reproducible_peak_set errors without group coverages", { @@ -859,7 +859,7 @@ test_that("add_reproducible_peak_set auto-selects single group coverage", { ######################################################################## -# add_reproducible_peak_set() — MACS method (skip if unavailable) +# add_reproducible_peak_set() - MACS method (skip if unavailable) ######################################################################## test_that("add_reproducible_peak_set works with MACS method", { diff --git a/tests/testthat/test-scale_dims_cor_cutoff.R b/tests/testthat/test-scale_dims_cor_cutoff.R index 5f83644..934a349 100644 --- a/tests/testthat/test-scale_dims_cor_cutoff.R +++ b/tests/testthat/test-scale_dims_cor_cutoff.R @@ -44,7 +44,7 @@ test_that(".scale_dims handles zero-variance rows", { result <- MarchR:::.scale_dims(mat) - # First row has zero variance — should be all zeros (not NaN) + # First row has zero variance. Should be all zeros (not NaN) expect_equal(result[1, ], rep(0, 5)) # Second row should be properly z-scored expect_equal(mean(result[2, ]), 0, tolerance = 1e-10)