Distributing a disk-backed Seurat object in a data package

This vignette is for dataset authors: people who want to ship a Seurat v5 object whose counts live in 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 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

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.

library(SeuratObject)
#> Loading required package: sp
#> 'SeuratObject' was built under R 4.6.0 but the current version is
#> 4.6.2; it is recomended that you reinstall 'SeuratObject' as the ABI
#> for R may have changed
#> 'SeuratObject' was built with package 'Matrix' 1.7.5 but the current
#> version is 1.7.6; it is recomended that you reinstall 'SeuratObject' as
#> the ABI for 'Matrix' may have changed
#> 
#> Attaching package: 'SeuratObject'
#> The following objects are masked from 'package:base':
#> 
#>     intersect, t
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:

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 = '[email protected]', 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.

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"))
#> [1] "RenameDims"
#> attr(,"package")
#> [1] "BPCells"

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:

seu <- Seurat::NormalizeData(seu, verbose = FALSE)
Layers(seu[["RNA"]])
#> [1] "counts" "data"
seurat_storage_report(seu)
#>  assay  layer representation operations    backing
#>    RNA counts        BPCells          0 rna_counts
#>    RNA   data   Lazy BPCells          2 rna_counts
#>    ADT counts        BPCells          0 adt_counts
#> 
#>       store files  bytes               layers
#>  rna_counts     8 139141 RNA/counts, RNA/data
#>  adt_counts     8   4594           ADT/counts
#> 
#> Logical layers: 3
#> Physical backing stores: 2
#> (files and bytes are measured file sizes of the store directories, not matrix dimensions)

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

res <- save_seurat_object(seu, name = "demo_seurat", package_dir = pkg)
#> Warning: Converting to a dense matrix may use excessive memory
#> Saved Seurat object 'demo_seurat':
#>   inst/extdata/demo_seurat/ (2 backing directories, 143,735 bytes, each copied once)
#>   data/demo_seurat.rda (placeholder)
#>   inst/projectData/manifest.dcf (added)
#> 
#> No documentation topic for 'demo_seurat' found in R/. Add a roxygen2 block ending in "demo_seurat" (usually in R/data.R) and run devtools::document().
#> 
#> This message is displayed once every 8 hours.

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:

res$layers
#>   assay  layer    kind     stores n_stores values_compared
#> 1   RNA counts bpcells RNA_counts        1        complete
#> 2   RNA   data bpcells RNA_counts        1        complete
#> 3   ADT counts bpcells ADT_counts        1        complete
res$backing[, c("id", "path", "files", "bytes", "layers")]
#>           id               path files  bytes               layers
#> 1 RNA_counts bpcells/RNA_counts     8 139141 RNA/counts, RNA/data
#> 2 ADT_counts bpcells/ADT_counts     8   4594           ADT/counts
res$manifest_status
#> [1] "added"

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

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):

files <- list.files(pkg, recursive = TRUE, all.files = TRUE)
unique(sub("(bpcells/[^/]+)/.*", "\\1/", files))
#> [1] "data/demo_seurat.rda"                        
#> [2] "DESCRIPTION"                                 
#> [3] "inst/extdata/demo_seurat/backing.dcf"        
#> [4] "inst/extdata/demo_seurat/bpcells/ADT_counts/"
#> [5] "inst/extdata/demo_seurat/bpcells/RNA_counts/"
#> [6] "inst/extdata/demo_seurat/object.rds"         
#> [7] "inst/projectData/manifest.dcf"               
#> [8] "LICENSE"                                     
#> [9] "NAMESPACE"
  • 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/<id>/ 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:

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")
#>                                                                           dataset 
#>                                                                     "demo_seurat" 
#>                                                                           package 
#>                                                                   "myDataPackage" 
#>                                                                            status 
#>                     "This object is a placeholder, not the actual Seurat object." 
#>                                                                           storage 
#> "The real dataset is stored separately as a disk-backed (BPCells) Seurat object." 
#>                                                                            step_1 
#>            "Remove this placeholder from the global environment: rm(demo_seurat)" 
#>                                                                            step_2 
#>            "Attach the data package: projectData::data_attach(\"myDataPackage\")" 
#>                                                                            step_3 
#>                                               "Use the real dataset: demo_seurat" 
#>                                                                              note 
#> "data() does not print the real object, and loading it can mask an attached one." 
#>                                                                          requires 
#>       "Required packages: projectData, projectData.Seurat, SeuratObject, BPCells" 
#>                                                                           install 
#>   "Install if missing: remotes::install_github(\"blaserlab/projectData.Seurat\")" 
#> attr(,"class")
#> [1] "projectData_Seurat_placeholder"
#> attr(,"object_name")
#> [1] "demo_seurat"
#> attr(,"package")
#> [1] "myDataPackage"
#> [1] ".GlobalEnv"        "package:stats"     "package:graphics" 
#> [4] "package:grDevices" "package:utils"     "package:datasets" 
#> [7] "package:methods"   "Autoloads"         "package:base"

6. The manifest

save_seurat_object() has already created or updated inst/projectData/manifest.dcf:

cat(readLines(res$manifest), sep = "\n")
#> ManifestVersion: 1
#> 
#> Resource: demo_seurat
#> Loader: projectData.Seurat::seurat
#> Source: extdata/demo_seurat
#> Objects: demo_seurat
#> HelpTopic: demo_seurat
#> RecordedClass: Seurat
#> AdapterPackage: projectData.Seurat

Source is the installed path (extdata/<name>, 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:

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.

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:

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/<name>.rda must be part of the package source. If your .gitignore excludes *.rda, add !data/<name>.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:

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"))
#> [1] "backing.dcf" "bpcells"     "object.rds"

The installed resource is read-only data: nothing below writes to it.

9. Load it through projectData

library(projectData)
data_config(messages = FALSE)
restored <- data_get("demo_seurat", package = "myDataPackage", lib.loc = lib)
class(restored)
#> [1] "Seurat"
#> attr(,"package")
#> [1] "SeuratObject"
dim(restored)
#> [1] 200  60

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:

seurat_storage_report(restored)
#>  assay  layer representation operations    backing
#>    RNA counts        BPCells          0 RNA_counts
#>    RNA   data   Lazy BPCells          2 RNA_counts
#>    ADT counts        BPCells          0 ADT_counts
#> 
#>       store files  bytes               layers
#>  RNA_counts     8 139141 RNA/counts, RNA/data
#>  ADT_counts     8   4594           ADT/counts
#> 
#> Logical layers: 3
#> Physical backing stores: 2
#> (files and bytes are measured file sizes of the store directories, not matrix dimensions)

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:

a <- suppressWarnings(as.matrix(LayerData(seu, "data")))
b <- suppressWarnings(as.matrix(LayerData(restored, "data")))
all.equal(a, b)
#> [1] TRUE

The restored object does not depend on your original directories:

dirs <- BPCells::all_matrix_inputs(restored[["RNA"]]@layers$data)
startsWith(normalizePath(vapply(dirs, function(d) d@dir, "")), normalizePath(lib))
#> [1] TRUE

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.

res2 <- save_seurat_object(seu, "demo_seurat", pkg, overwrite = TRUE)
#> Replaced Seurat object 'demo_seurat':
#>   inst/extdata/demo_seurat/ (2 backing directories, 143,735 bytes, each copied once)
#>   data/demo_seurat.rda (placeholder)
#>   inst/projectData/manifest.dcf (unchanged)
res2$replaced
#> [1] TRUE

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:

in_memory <- CreateSeuratObject(Matrix::Matrix(counts, sparse = TRUE))
save_seurat_object(in_memory, "plain", pkg)
#> Error in `save_seurat_object()`:
#> ! Cannot save Seurat object 'plain':
#>   - no layer is backed by a BPCells directory (MatrixDir); nothing in the object is disk-backed
#> 
#> The storage model of an object is never changed silently: unsupported representations are refused, not converted. Nothing was written.
#> To fix: keep BPCells directory matrices (see BPCells::write_matrix_dir()) and ordinary R matrices, and remove spatial images, HDF5 or DelayedArray matrices and BPCells matrices stored in `misc`, `tools` or `commands`. A fully in-memory object needs no adapter: ship it as an ordinary .rda dataset. See the troubleshooting table in the projectData.Seurat README.

The full list of what is supported is in vignette("storage", package = "projectData.Seurat").