---
title: Save/load spatial omics data to/from file
author: Aaron Lun
package: alabaster.spatial 
date: "Revised: December 29, 2023"
output:
  BiocStyle::html_document
vignette: >
  %\VignetteIndexEntry{Saving spatial experiments}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, echo=FALSE}
knitr::opts_chunk$set(error=FALSE, warning=FALSE, message=FALSE)
library(BiocStyle)
self <- Biocpkg("alabaster.spatial")
```

# Overview

The `SpatialExperiment` class (from the `r Biocpkg("SpatialExperiment")` package) provides a representation of spatial transcriptomics data that is compatible with Bioconductor's `SummarizedExperiment` ecosystem.
The `r self` package contains methods to save and load `SpatialExperiment` objects into and out of file. 
Check out the `r Biocpkg("alabaster.base")` for more details on the motivation and concepts of the **alabaster** framework.

# Quick start

To demonstrate, we'll use the example dataset provided in the `r Biocpkg("SpatialExperiment")` package:

```{r}
library(SpatialExperiment)

# Copying the example from ?read10xVisium.
dir <- system.file("extdata", "10xVisium", package = "SpatialExperiment")
sample_ids <- c("section1", "section2")
samples <- file.path(dir, sample_ids, "outs")
spe <- read10xVisium(
   samples,
   sample_ids,
   type = "sparse",
   data = "raw",
   images = "lowres", 
   load = FALSE
)
colnames(spe) <- make.unique(colnames(spe)) # Making the column names unique.

spe
```

We call the usual `saveObject()` function to save its contents to file:

```{r}
library(alabaster.spatial)
tmp <- tempfile()
saveObject(spe, tmp)
list.files(tmp, recursive=TRUE)
```

This goes through the usual saving process for `SingleCellExperiment`s, with an additional saving step for the spatial data (see the `coordinates/` and `images/` subdirectories).
We can then load it back in using the `readObject()` function:

```{r}
roundtrip <- readObject(tmp)
plot(imgRaster(getImg(roundtrip, "section1")))
```

More details on the metadata and on-disk layout are provided in the [schema](https://artifactdb.github.io/BiocObjectSchemas/html/spatial_experiment/v1.html).

# Session info {-}

```{r}
sessionInfo()
```
