--- title: "Distributing a disk-backed Seurat object in a data package" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Distributing a disk-backed Seurat object in a data package} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") # The worked example needs Seurat and BPCells (BPCells is not on CRAN). Where # they are missing the code is shown but not run. have_stack <- all(vapply( c("projectData", "SeuratObject", "BPCells", "Seurat", "Matrix"), requireNamespace, logical(1), quietly = TRUE )) knitr::opts_chunk$set(eval = have_stack) ``` This vignette is for **dataset authors**: people who want to ship a Seurat v5 object whose counts live in [BPCells](https://github.com/bnprks/BPCells) directories as part of an ordinary R package. People who only *use* such a package should read `vignette("using-seurat-data", package = "projectData.Seurat")`. How the lazy layers and shared directories work is explained in `vignette("storage", package = "projectData.Seurat")`. ## The problem, and who does what A Seurat object with BPCells storage holds *references* to directories on the author's disk. `saveRDS()` or `save()` store those paths, not the data, so the object is useless on any other machine. `projectData.Seurat` copies the directories into the package, rewrites the references to be relative to the package, and lets [projectData](https://github.com/blaserlab/projectData) restore the object on first access. | projectData (core) | projectData.Seurat (this adapter) | |---|---| | Registers installed data packages, builds the catalog from metadata | Declares the loader `projectData.Seurat::seurat` | | Resolves names, handles conflicts, caches and retries | Validates a saved resource, restores the object (`open`) | | Opens a resource lazily, on first access | Provides `save_seurat_object()` and `write_seurat_manifest()` for authors | The general adapter mechanism is described in `vignette("adapters", package = "projectData")`. ## Prerequisites ```{r install, eval = FALSE} install.packages(c("projectData", "SeuratObject", "Seurat")) # BPCells is not on CRAN remotes::install_github("bnprks/BPCells/r") remotes::install_github("blaserlab/projectData.Seurat") ``` Everything below runs in temporary directories and writes nothing else. The object is tiny and synthetic (200 genes, 60 cells), so no download is needed. ```{r libs} library(SeuratObject) library(BPCells) library(projectData.Seurat) work <- file.path(tempdir(), "authoring-demo") dir.create(work) ``` ## 1. Prepare an ordinary R package A data package is an R package whose source directory has a `DESCRIPTION`. Create it as you would any other (for example `usethis::create_package()`). The only requirement for this adapter is that `DESCRIPTION` has a `Package` field, because `save_seurat_object()` refuses to write anywhere else: ```{r skeleton} pkg <- file.path(work, "myDataPackage") dir.create(file.path(pkg, "R"), recursive = TRUE) writeLines(c( "Package: myDataPackage", "Title: Example Seurat Data", "Version: 0.1.0", "Authors@R: person('Ada', 'Author', email = 'ada@example.com', role = c('aut', 'cre'))", "Description: A tiny synthetic data package that ships a disk-backed Seurat object.", "License: MIT + file LICENSE", "Suggests: projectData.Seurat", "Encoding: UTF-8" ), file.path(pkg, "DESCRIPTION")) writeLines(c("YEAR: 2026", "COPYRIGHT HOLDER: Ada Author"), file.path(pkg, "LICENSE")) writeLines(character(), file.path(pkg, "NAMESPACE")) ``` `projectData.Seurat` is listed under `Suggests`: your users need it only to open the object, and projectData loads it (without attaching it) from the manifest. ## 2. Create a Seurat object with BPCells-backed counts The counts are written to a BPCells directory, and the Seurat object points at it. Here this directory is the author's *original*; it is read, never modified, moved or deleted by anything below. ```{r object} set.seed(7403) counts <- matrix(rpois(200 * 60, 3), 200, 60, dimnames = list(paste0("gene", 1:200), paste0("cell", 1:60))) adt <- matrix(rpois(5 * 60, 20), 5, 60, dimnames = list(paste0("adt", 1:5), colnames(counts))) originals <- file.path(work, "originals") dir.create(originals) rna_dir <- write_matrix_dir(Matrix::Matrix(counts, sparse = TRUE), file.path(originals, "rna_counts"), compress = FALSE) adt_dir <- write_matrix_dir(Matrix::Matrix(adt, sparse = TRUE), file.path(originals, "adt_counts"), compress = FALSE) seu <- CreateSeuratObject(CreateAssay5Object(counts = rna_dir)) seu[["ADT"]] <- CreateAssay5Object(counts = adt_dir) DefaultAssay(seu) <- "RNA" class(LayerData(seu, "counts")) ``` ## 3. Normalize lazily On a BPCells counts layer, `NormalizeData()` does not compute a normalized matrix. It queues the operations on the counts, so `data` is *the same directory* seen through a chain of transformations: ```{r normalize} seu <- Seurat::NormalizeData(seu, verbose = FALSE) Layers(seu[["RNA"]]) seurat_storage_report(seu) ``` Two logical layers in `RNA` (`counts`, `data`), but one physical directory: `data` is `Lazy BPCells` with queued operations. This is what the adapter preserves. (`seurat_storage_report()` only reads the structure; it computes no values. Its file sizes are measured sizes on disk, not matrix dimensions.) ## 4. Save the object into the package ```{r save} res <- save_seurat_object(seu, name = "demo_seurat", package_dir = pkg) ``` The `name` must be a syntactically valid R name that does not start with a dot. It becomes the resource directory, the placeholder, the manifest entry **and** the name users will type. (Avoid names that already exist in base packages: a dataset called `example` would mask `utils::example`.) (BPCells may print a one-time notice about converting to a dense matrix: the verification step compares values of the staged copy with the original.) The call stages everything in a hidden directory inside the package, verifies it (see `?save_seurat_object`), and only then moves it into place. It returns invisibly a list describing what was done: ```{r result} res$layers res$backing[, c("id", "path", "files", "bytes", "layers")] res$manifest_status ``` Each physical directory was copied once, however many layers use it. Your object `seu` and the original directories are unchanged. ## 5. The generated package layout ```text myDataPackage/ ├── DESCRIPTION ├── R/ │ └── data.R (you write this; step 7) ├── data/ │ └── demo_seurat.rda placeholder └── inst/ ├── extdata/ │ └── demo_seurat/ │ ├── object.rds │ ├── backing.dcf │ └── bpcells/ │ ├── RNA_counts/ │ └── ADT_counts/ └── projectData/ └── manifest.dcf ``` This is what is actually on disk (the files inside each BPCells directory are collapsed): ```{r layout} files <- list.files(pkg, recursive = TRUE, all.files = TRUE) unique(sub("(bpcells/[^/]+)/.*", "\\1/", files)) ``` * `inst/extdata/demo_seurat/object.rds` is the Seurat object, saved with `saveRDS()`. Every BPCells reference in it is a path *relative to the resource*, for example `bpcells/RNA_counts`. * `backing.dcf` lists the BPCells directories the resource owns. * `bpcells//` holds one directory per distinct physical matrix. ### The placeholder is not the Seurat object `data/demo_seurat.rda` exists so that `data()`, `R CMD check` and roxygen2 treat the dataset in the conventional way. It is a small character vector, not a Seurat object. `data("demo_seurat")` returns **the placeholder**, and can mask the real object if you attach the data package afterwards. The real object is reached through projectData (step 9). The placeholder explains itself with base R alone. Here it is printed in a fresh R process in which neither projectData nor this package is attached: ```{r placeholder} rda <- file.path(pkg, "data", "demo_seurat.rda") script <- sprintf("load('%s'); print(demo_seurat); print(search())", rda) out <- system2(file.path(R.home("bin"), "Rscript"), c("--vanilla", "-e", shQuote(script)), stdout = TRUE) cat(out, sep = "\n") ``` ## 6. The manifest `save_seurat_object()` has already created or updated `inst/projectData/manifest.dcf`: ```{r manifest} cat(readLines(res$manifest), sep = "\n") ``` `Source` is the *installed* path (`extdata/`, never `inst/extdata/...`). The `Loader` is the identifier projectData uses to find the adapter, and `AdapterPackage` tells projectData which package to load it from. You do not normally need `write_seurat_manifest()` after a save. Use it to **reconcile** the manifest with what is on disk, for example after copying a resource directory and its placeholder in from another checkout, or after deleting one: ```{r reconcile} write_seurat_manifest(package_dir = pkg) ``` It is idempotent: when nothing changed it prints nothing and does not rewrite the file. Only manifest entries owned by this loader are ever added, updated or removed; entries of other adapters are preserved, and it never deletes a resource directory or a placeholder. See `?write_seurat_manifest`. ## 7. Document the dataset Like any dataset, document it in `R/data.R`. `save_seurat_object()` never edits this file; it only tells you when a topic is missing. ```{r document} writeLines(c( "#' Demonstration Seurat object", "#'", "#' A synthetic 200-gene, 60-cell object with BPCells-backed RNA and ADT counts", "#' and a lazily normalized `data` layer.", "#'", "#' @format A Seurat object with two assays (`RNA`, `ADT`).", "#' @details Do not use `data()` to get the object (that returns a placeholder).", "#' Use `projectData::data_attach()` or `projectData::data_get()`.", "#' @source Simulated.", "\"demo_seurat\"" ), file.path(pkg, "R", "data.R")) ``` Then run `devtools::document()` (roxygen2) to create `man/demo_seurat.Rd`. In this vignette the equivalent help page is written directly, to avoid a dependency on roxygen2: ```{r rd} dir.create(file.path(pkg, "man")) writeLines(c( "\\name{demo_seurat}", "\\alias{demo_seurat}", "\\docType{data}", "\\title{Demonstration Seurat object}", "\\format{A Seurat object with two assays (RNA, ADT).}", "\\description{A synthetic object with BPCells-backed counts.}", "\\details{Use \\code{projectData::data_attach()} or \\code{projectData::data_get()}.}", "\\keyword{datasets}" ), file.path(pkg, "man", "demo_seurat.Rd")) ``` Practical notes for the real package: * The placeholder `data/.rda` must be **part of the package source**. If your `.gitignore` excludes `*.rda`, add `!data/.rda`, or the placeholder (and with it the manifest entry) will be missing from fresh checkouts. * The backing directories count towards the size of the package. * Check the size limits of wherever you distribute the package; CRAN, for example, expects much smaller packages than a typical single-cell dataset. ## 8. Install the data package Installation is ordinary. Here it goes into a temporary library: ```{r install-pkg} lib <- file.path(work, "library") dir.create(lib) install.packages(pkg, lib = lib, repos = NULL, type = "source", quiet = TRUE) list.files(file.path(lib, "myDataPackage", "extdata", "demo_seurat")) ``` The installed resource is read-only data: nothing below writes to it. ## 9. Load it through projectData ```{r load} library(projectData) data_config(messages = FALSE) restored <- data_get("demo_seurat", package = "myDataPackage", lib.loc = lib) class(restored) dim(restored) ``` `data_get()` registered the package and opened the resource on this first access. `data_attach("myDataPackage")` would register it and let you use the bare name `demo_seurat`; see the user vignette. ## 10. Verify that the storage is still lazy The restored object reads from the installed copy, and its layers have the same structure as the original: ```{r verify} seurat_storage_report(restored) ``` Same two stores, same `Lazy BPCells` `data` layer sharing the `RNA` counts directory. The values agree with the original, which can be checked here because the object is small: ```{r values} a <- suppressWarnings(as.matrix(LayerData(seu, "data"))) b <- suppressWarnings(as.matrix(LayerData(restored, "data"))) all.equal(a, b) ``` The restored object does not depend on your original directories: ```{r independent} dirs <- BPCells::all_matrix_inputs(restored[["RNA"]]@layers$data) startsWith(normalizePath(vapply(dirs, function(d) d@dir, "")), normalizePath(lib)) ``` ## Replacing a dataset Saving the same `name` again is refused unless you say `overwrite = TRUE`, and even then only for a resource and placeholder that this package can show it wrote (a directory that merely contains an `object.rds` is refused). A failed save restores the previous files. See `?save_seurat_object`. ```{r overwrite} res2 <- save_seurat_object(seu, "demo_seurat", pkg, overwrite = TRUE) res2$replaced ``` ## What is refused Unsupported storage is refused *before anything is written*, never silently materialized or converted. For example, an object whose counts are an ordinary in-memory matrix has nothing disk-backed to ship: ```{r refused, error = TRUE} in_memory <- CreateSeuratObject(Matrix::Matrix(counts, sparse = TRUE)) save_seurat_object(in_memory, "plain", pkg) ``` The full list of what is supported is in `vignette("storage", package = "projectData.Seurat")`. ```{r cleanup, include = FALSE} unlink(work, recursive = TRUE) ```