--- title: "Storage, lazy operations, and what is supported" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Storage, lazy operations, and what is supported} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") have_stack <- all(vapply( c("projectData", "SeuratObject", "BPCells", "Seurat", "Matrix"), requireNamespace, logical(1), quietly = TRUE )) knitr::opts_chunk$set(eval = have_stack) ``` `projectData.Seurat` preserves how a Seurat object *stores* its data. This vignette explains what that means, why the package does not use Seurat's own persistence functions, and which representations it accepts. It does not change how Seurat computes anything. ## Three ideas that are easy to confuse **Logical layers.** A Seurat v5 assay contains named layers such as `counts`, `data` and `scale.data`. Each is a matrix with its own name, and `Layers(object)` lists them. **Physical backing.** With BPCells, matrix data live in *directories* of files on disk. A BPCells directory is the physical store. **Lazy transformations.** A BPCells matrix can be a *recipe*: a directory plus a queue of operations (scale, `log1p`, row selection, ...) that is evaluated when values are read. Seurat's `NormalizeData()` and `ScaleData()` on a BPCells counts layer produce such recipes. The consequence is that **several logical layers do not imply several physical matrices**. Build a small object (the helper is in `inst/examples` and is only used by the vignettes): ```{r object} library(SeuratObject) library(projectData.Seurat) source(system.file("examples", "demo-package.R", package = "projectData.Seurat")) work <- file.path(tempdir(), "storage-demo") dir.create(work) seu <- demo_object(work) Layers(seu[["RNA"]]) seurat_storage_report(seu) ``` `RNA` has two logical layers but one physical store. The queued operations of `data` can be inspected without computing anything (directory paths removed): ```{r ops} operations <- function(m) { lines <- capture.output(print(m)) sub("(directory) .*$", "\\1", grep("^[0-9]+\\. ", lines, value = TRUE)) } operations(LayerData(seu, "data")) ``` Step 1 reads the directory shared with `counts`; the rest are the normalization. Nothing was computed to display this. ### What it saves If the normalized layer were materialized and written to a directory of its own, it would be a second physical matrix. This compares the size of the one store the lazy layer needs with what a materialized copy would add (here both are uncompressed, so the copy is as large as the original): ```{r cost} bytes <- function(d) sum(file.size(list.files(d, full.names = TRUE))) materialized <- BPCells::write_matrix_dir(LayerData(seu, "data"), file.path(work, "materialized"), compress = FALSE) c(shared_store = bytes(file.path(work, "rna_counts")), extra_if_materialized = bytes(file.path(work, "materialized"))) ``` These are measured file sizes. The matrix dimensions (200 x 60) are the same for every layer; they say nothing about storage. The saved resource keeps the lazy layer lazy, so only the counts store is copied: ```{r saved} pkg <- file.path(work, "pkg") dir.create(pkg) writeLines(c("Package: sizeDemo", "Version: 0.1.0"), file.path(pkg, "DESCRIPTION")) res <- suppressMessages(save_seurat_object(seu, "demo", pkg)) res$backing[, c("id", "files", "bytes", "layers")] ``` ## What laziness does not give you * **Repeated computation.** A lazy layer is recomputed each time values are read; the saving in storage is paid for in computation. This is a trade-off, not a free gain. * **Disk-backed is not RAM-free.** Cell and feature metadata, reductions, graphs, in-memory layers, and anything an analysis function pulls out of a layer are ordinary R objects in memory. Reading a block of a layer produces an in-memory result. The package says the *underlying matrix storage* stays on disk, nothing more. * **Some Seurat operations materialize intermediate results.** Whether a given function stays lazy depends on the function and the Seurat and BPCells versions. The adapter does not change that and does not optimize Seurat's algorithms; it preserves whatever representation the object had when you saved it, and restores it. * **The installed files must stay.** A restored object reads from the installed data package, so it cannot be moved or reinstalled underneath a running session (see the user vignette). Verifying that the representation is preserved is exactly what `seurat_storage_report()` is for: run it on the object before saving and on the restored object afterwards. ## Why not `SaveSeuratRds()`? SeuratObject provides `SaveSeuratRds()` and `LoadSeuratRds()`, which are the right tools for many objects. This package does not use them for authoring because of one specific, reproducible failure with lazy layers. Observed with **SeuratObject 5.4.0, Seurat 6.0.0 and BPCells 0.3.0** (R 4.5.2, Linux): for a `counts` layer on a BPCells directory and a `data` layer made by `NormalizeData()` over it, `SaveSeuratRds()` records, for each layer, the directory it reads and a function to reopen it as a plain matrix. For the lazy `data` layer that directory is the one of `counts`. `LoadSeuratRds()` then reopens it, and the restored `data` layer holds **the raw counts**, with no warning from the load: ```{r native, eval = have_stack && packageVersion("SeuratObject") == "5.4.0" && packageVersion("BPCells") == "0.3.0"} native <- file.path(work, "native") dir.create(native) suppressWarnings(SaveSeuratRds(seu, file.path(native, "seu.rds"), move = TRUE, relative = FALSE)) back <- LoadSeuratRds(file.path(native, "seu.rds")) as_dense <- function(x) suppressWarnings(as.matrix(x)) # the restored `data` is not the normalized data ... isTRUE(all.equal(as_dense(LayerData(back, "data")), as_dense(LayerData(seu, "data")))) # ... it is the counts isTRUE(all.equal(unname(as_dense(LayerData(back, "data"))), unname(as_dense(LayerData(back, "counts"))))) ``` On the macOS GitHub Actions runner (arm64, R 4.6.2, SeuratObject 5.4.0, BPCells 0.3.1) the restored `data` layer was instead **empty** ("Layer 'data' is empty"); the cause was not investigated. Both outcomes are wrong, and the package's test asserts only that the lazy values are not restored. If your versions differ, this chunk is not run, and you should not assume the same behavior (or its absence) without trying it. Other observations from the same versions, made while developing the package: a second layer sharing a directory with another got a wrong relative path when saved with `relative = TRUE`; with `relative = TRUE` the paths are resolved against the working directory at load time, and from another directory the load only warned and returned an object without its disk layers; and a missing layer yielded a partial object even with `options(Seurat.io.rds.strict = TRUE)`. None of this means `SaveSeuratRds()` is unreliable in general. It is a statement about lazy BPCells layers that share a directory, in a data package that has to be relocatable and read-only. `projectData.Seurat` instead finds the physical directories through BPCells' own operation graph, copies each once, and rewrites the leaves of each layer's graph (see `?save_seurat_object`), then verifies the result before committing it. ## What is supported "Supported" means tested in the saved-and-restored round trip described in the README, not merely serializable with `saveRDS()`. | Representation | Handling | |---|---| | BPCells directory-backed counts (`MatrixDir`) | Supported | | Lazy BPCells transformations over a directory (`NormalizeData()`, `ScaleData()` on BPCells) | Supported: the operation graph is kept, nothing is computed | | Several layers sharing one physical directory | Supported: each directory is copied once and sharing is preserved | | Several assays | Supported where validated (RNA + ADT, each on its own directory) | | Ordinary in-memory secondary layers (`dgCMatrix`, `matrix`) | Stored inside `object.rds` as they are; they count against memory when the object is opened | | Cell and feature metadata, reductions, graphs, neighbors, identities, variable features | Preserved | | Compressed BPCells directories | Expected to work (copied byte for byte); not tested separately | | BPCells HDF5-backed or anndata-backed matrices | **Refused** | | BPCells in-memory matrix classes (`PackedMatrixMem_*`, wrappers of R matrices) | **Refused** | | `DelayedArray` / `HDF5Array`-backed assays | **Refused** | | BPCells matrices in a v3/v4 `Assay`, `SCTAssay` | **Refused** | | Spatial image-backed objects | **Refused** | | BPCells or `DelayedArray` matrices hidden in `misc`, `tools`, `commands` or list columns of `meta.data` | **Refused** (they would keep the author's paths) | | Symbolic links or nested directories inside a BPCells directory | **Refused** | | A fully in-memory Seurat object | Not this package's job: use an ordinary `.rda` dataset | "Refused" means `save_seurat_object()` stops with an error of class `projectData.Seurat_unsupported_storage` that lists every offending assay and layer, **before writing anything**. Nothing is silently materialized and no reference is silently left dangling. The package never converts in-memory matrices to BPCells for you. ### Further limitations * File paths stored as plain text anywhere in an object (for example in `commands`) cannot be told from other strings, and are neither examined nor rewritten. * Layers of up to 1e6 entries are compared completely against the original before saving; larger layers are compared on four columns spread across the matrix (`res$layers$values_compared` says which). A sample is not a proof about the other columns. * File checksums are not computed. * Only Linux has been tested (see the README for the Seurat, SeuratObject, BPCells and R versions). Windows and macOS are not verified. * Saving is staged and rolled back on failure, but it is not a filesystem transaction (see `?save_seurat_object`). ### Ordinary `.rda`, or this package? | Situation | Use | |---|---| | The object, counts included, is comfortable in memory and you want one file | An ordinary `.rda` data package; no adapter is needed | | The counts are large and should stay on disk, with lazy normalization intact | `projectData.Seurat` | | The object depends on HDF5, `DelayedArray` or spatial images | Neither works directly; convert the object to BPCells directory storage first, if that suits the analysis | ```{r cleanup, include = FALSE} unlink(work, recursive = TRUE) ```