---
title: "Using disk-backed Monocle 3 data from a data package"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Using disk-backed Monocle 3 data from a data package}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
have_stack <- all(vapply(
c("projectData", "monocle3", "BPCells", "SingleCellExperiment",
"SummarizedExperiment", "Matrix"),
requireNamespace, logical(1), quietly = TRUE
))
knitr::opts_chunk$set(eval = have_stack)
```
This vignette is for **researchers who use** a data package that ships Monocle 3
`cell_data_set` (CDS) objects through `projectData.monocle3`. If you are creating
such a package, read
`vignette("authoring-monocle3-data", package = "projectData.monocle3")`. How the
files are stored and restored is in
`vignette("storage", package = "projectData.monocle3")`. For the general
projectData workflow (install, attach, use, conflicts) see
`vignette("projectData", package = "projectData")`; this vignette covers only what
is specific to Monocle 3 objects. What projectData does and what this adapter does
are kept apart below.
## What you need
* The **data package** (installed like any package) and **projectData**.
* **projectData.monocle3**, installed. You never call `library()` on it: the data
package's manifest names it and projectData loads its namespace when needed.
* **monocle3** and **BPCells** to *open* an object. Registering, listing and
validating a data package work without them; opening needs them (see
[Troubleshooting](#troubleshooting)). Neither is on CRAN:
```{r install, eval = FALSE}
install.packages("pak")
pak::pak(c("projectData", "bnprks/BPCells/r", "cole-trapnell-lab/monocle3",
"blaserlab/projectData.monocle3"))
```
You will want `library(monocle3)` for your own analysis. The adapter attaches
monocle3 only for the duration of the restoration and restores the search path
afterwards, so it does not do that for you.
## A demonstration package
To keep this vignette self-contained it builds two throwaway data packages in a
temporary library, using the authoring tools described in the other vignette.
Skip this chunk in real use, and omit `lib.loc` below.
```{r fixtures, message = FALSE}
library(monocle3)
library(projectData)
source(system.file("examples", "demo-package.R", package = "projectData.monocle3"))
work <- file.path(tempdir(), "using-demo")
dir.create(work)
lib <- file.path(work, "library")
dir.create(lib)
invisible(demo_data_package(work, lib, name = "demoMonocleData"))
invisible(demo_data_package(work, lib, name = "otherMonocleData"))
```
## Discover and attach
```{r attach}
data_config(messages = FALSE)
data_attach("demoMonocleData", lib.loc = lib)
as.data.frame(data_catalog())[, c("resource", "origin", "state", "storage", "loader_status")]
```
projectData reads the package's manifest and records the resource. The manifest
names the adapter (`AdapterPackage: projectData.monocle3`), so projectData knows
which loader will open it, and `origin` is `manifest`. Nothing was opened: the
state is `unopened`, the object is not in memory, and the loader has not yet been
resolved (`storage` is `unknown` and `loader_status` `unresolved` until the
adapter has been loaded, which happens on first access). You do not need to call
`data_loader_adapter()` when the manifest names the adapter.
## When is the CDS actually loaded?
On first access, and only then. This is projectData behavior (deferred access):
```{r first-access}
cds <- demo_cds
class(cds)
dim(cds)
as.data.frame(data_catalog())[, c("resource", "state", "storage", "loader_status")]
```
Now the resource is `ready`, `storage` is `disk-backed` and the loader is
`registered`. The restore itself is done by **projectData.monocle3**: it first
validates the installed directory without reading matrix values, then calls
Monocle's `load_monocle_objects()`, which rebuilds the CDS and copies the BPCells
matrix into a working directory allocated by projectData (see
`vignette("storage", package = "projectData.monocle3")`). Access again returns the same
cached object:
```{r cached}
identical(demo_cds, cds)
```
To open objects without attaching, or in scripts and functions, prefer
`data_get()`:
```{r data-get}
identical(data_get("demo_cds", collection = "demoMonocleData"), cds)
```
The restored object is an ordinary `cell_data_set` whose `counts` assay is a
BPCells matrix:
```{r counts}
class(SummarizedExperiment::assay(cds, "counts"))
SummarizedExperiment::assayNames(cds)
```
(`counts_row_order` is a second copy of the counts with a different storage order,
which Monocle maintains; it is not a separate dataset.)
## The placeholder is not the CDS
A data package that uses this adapter also contains a small `.rda` placeholder
for each CDS, so that `data()` and the help system work conventionally.
`data()` loads only that placeholder:
```{r placeholder}
e <- new.env()
data_package <- "demoMonocleData"
data("demo_cds", package = data_package, lib.loc = lib, envir = e)
class(e$demo_cds)
e$demo_cds[c("status", "step_1")]
```
If you load it into the global environment it can mask the real object: remove it
with `rm(demo_cds)` and use `data_attach()` or `data_get()`. Resolution does not
depend on it: because the manifest names the loader, projectData resolves
`demo_cds` through the manifest (`origin` is `manifest` above) even though a
placeholder of the same name exists in `data/`. Without a manifest entry,
projectData would fall back to the `.rda` and offer only the placeholder.
## How names are resolved
Each saved dataset is one resource that provides **exactly one object, with the
same name**. After `data_attach()` the name is bound on the search path;
`data_get(name, collection =)` and `data_get(name, package =)` reach it without
that. Several data packages can be used at once, and two of them may define the
same name. This is handled by projectData, not by the adapter, and it never
picks a winner by attachment order:
```{r conflict, error = TRUE}
data_attach("otherMonocleData", lib.loc = lib, id = "other")
demo_cds
```
Resolve it in any of the ways described in the "Conflicts" section of
`vignette("projectData", package = "projectData")`. The most robust for scripts is
to say which collection you mean:
```{r qualified}
other <- data_get("demo_cds", collection = "other")
dim(other)
```
(Use `data_prefer()` or `data_primary()` to decide once for a whole session.)
## What happens after `data_detach()`
```{r detach}
data_detach()
dim(cds)
sum(colSums(SummarizedExperiment::assay(cds, "counts")))
nrow(data_collections())
```
`data_detach()` forgets the collections and their cached objects. It does not
delete any files and does not invalidate objects you hold, so `cds` still works:
its counts live in the working directory that projectData allocated, which stays
until the R session ends. Attaching again opens the resource afresh, and you get a
second restored object with its own copy of the counts. Two cautions, both
explained in `vignette("storage", package = "projectData.monocle3")`: the copy
occupies temporary disk space for the rest of the session, and the UMAP index of
the CDS, if it has one, is read from the installed package, so do not reinstall
or remove the data package while you use the object.
## Troubleshooting
### A resource is missing or damaged
The loader validates the installed directory before every uncached opening,
checking the structure without reading data. If a file has been deleted, projectData
marks the resource `failed` and keeps it failed until you call `data_retry()`, even
after you restore the file. Simulating this on a copy of the library:
```{r damage, error = TRUE}
lib2 <- file.path(work, "library2")
dir.create(lib2)
invisible(file.copy(file.path(lib, "demoMonocleData"), lib2, recursive = TRUE))
victim <- file.path(lib2, "demoMonocleData", "extdata", "demo_cds", "bpcells_matrix_dir", "val")
backup <- file.path(work, "val.backup")
invisible(file.copy(victim, backup))
data_attach("demoMonocleData", lib.loc = lib2, id = "damaged")
invisible(file.remove(victim))
data_get("demo_cds", collection = "damaged")
```
The catalog says so, and a second attempt fails the same way without trying again:
```{r failed, error = TRUE}
as.data.frame(data_catalog())[, c("collection", "resource", "state")]
data_get("demo_cds", collection = "damaged")
```
Restore the files (here, put the file back; in practice reinstall the data
package), then retry:
```{r retry}
invisible(file.copy(backup, victim))
data_retry("damaged")
dim(data_get("demo_cds", collection = "damaged"))
```
If the damage already exists when you attach, a session in which the adapter is
already registered fails at `data_attach()` with the same message and registers
nothing; restore the files and attach again. A failed `data_get(package = )` can
leave the collection registered but not attached, so retry it with `package =`.
### Common messages
| Symptom | Cause | What to do |
|---|---|---|
| Catalog shows `unavailable-loader`, or "adapter package 'projectData.monocle3' is not installed" | The adapter is not installed. Other objects in the data package are unaffected | Install projectData.monocle3, then `data_retry()` |
| Error naming `monocle3` or `BPCells` at open | An optional dependency is not installed | Install it (see above), then `data_retry("")` |
| Validation error mentioning in-memory counts, HDF5, `file_index.rds`, or a symbolic link | The resource was not written by `save_monocle_cds()`, or the installation is damaged | Reinstall the data package; if it persists, ask its author to re-save with `save_monocle_cds()` |
| "required file(s) missing" | A damaged installation | Reinstall the data package, then attach again (or `data_retry()` if already attached) |
| Access returns a character vector that prints instructions | The `.rda` placeholder masks the real object | `rm()`, then `data_attach("")` |
| "ambiguous: it is provided by collections ..." | Two attached packages define the same name | `data_get(name, collection =)`, `data_prefer()` or `data_primary()` |
| An opening failed once and keeps failing | projectData caches failures | Fix the cause, then `data_retry("")` |
| Opening fails with a disk-space or permission error | The restored matrix is copied into the session temporary directory | Free space there, or start R with `TMPDIR` pointing at a larger, writable location |
```{r cleanup, include = FALSE}
try(data_detach(), silent = TRUE)
unlink(work, recursive = TRUE)
```