--- title: "Get started with spiSEE" author: - name: Emile Danvin - name: Dario Righelli date: "`r Sys.Date()`" output: BiocStyle::html_document: toc_float: true vignette: > %\VignetteIndexEntry{1. Get started with spiSEE} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6, fig.height = 4.5, message = FALSE, dev = "jpeg", dev.args = list(jpeg = list(quality = 75)), dpi = 100, fig.retina = 1) ``` # Introduction `r BiocStyle::Biocpkg("spiSEE")` adds spatial panels to `r BiocStyle::Biocpkg("iSEE")` for data at cellular resolution: imaging-based (CosMx, Xenium) and sequencing-based (Visium HD, cell-segmented). The data are a standard `r BiocStyle::Biocpkg("SpatialExperiment")`. A region selected on an overview map (fields of view for CosMx, single cells for the other platforms) is applied to every panel: spatial plots, quality-control histograms, spatial statistics, spatially variable genes, cellular niches and spatial domains. Heavy analyses run only when the user presses *Compute*, on the selected region. This vignette shows how to install the package, runs it on a small CosMx example and lists every panel. The vignette *CosMx workflow: the mouse dentate gyrus* then goes through a complete analysis of a real dataset: quality control of a whole brain section, cell polygons, niches, spatial domains, statistics and the apps. ## Relation to other Bioconductor packages spiSEE is mainly an interactive front end. Several of its analyses call other Bioconductor packages, and it puts them in one `r BiocStyle::Biocpkg("iSEE")` app where a selection made in one panel is applied to all the others. ```{r relation, echo = FALSE} pk <- c("Voyager", "SpaceTrooper", "ggspavis", "imcRtools", "Banksy") rel <- data.frame( Package = vapply(pk, BiocStyle::Biocpkg, character(1)), `What it does` = c( paste("Exploratory spatial data analysis (e.g. Moran's I) on a", "`SpatialFeatureExperiment`, from R code"), paste("Quality control of imaging-based data (GLM-based QC score,", "outlier detection), loaders and polygon plots"), paste("Static `ggplot2` plots of spots, molecules, reduced", "dimensions and QC"), paste("Analysis of imaging mass cytometry and other multiplexed", "imaging data: spatial graphs, neighbourhoods, interaction", "tests"), paste("Spatial clustering of cells from their own and their", "neighbourhood expression (mean and azimuthal Gabor features)")), `How spiSEE relates to it` = c( paste("spiSEE calls it for global and local Moran's I and graph", "plots, on a graph built with SpatialFeatureExperiment, and", "shows the results in panels"), paste("spiSEE uses it to load CosMx data; its QC panels plot the", "metrics from `spatialPerCellQC()`"), paste("spiSEE draws comparable maps, but interactive and linked to", "the other panels"), paste("Different data type (protein imaging); spiSEE targets", "transcriptomics at cell resolution"), paste("spiSEE's spatial domains use a simpler mix (own PCs plus", "neighbourhood mean, Louvain); for a dedicated method, use", "Banksy and show its labels in spiSEE")), check.names = FALSE, row.names = NULL) knitr::kable(rel) ``` Spatial join counts come from `r BiocStyle::CRANpkg("spdep")` and L-functions from `r BiocStyle::Biocpkg("spatialFDA")`. Any label stored in `colData`, for example Banksy clusters, can be shown in the panels. Limits: one sample per app (choose it with `sample =`), and the panels are designed for cell-resolution data, not for spot-level Visium. # Installation ```{r install, eval = FALSE} if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("spiSEE") ``` # Quick start A small CosMx dataset ships with `r BiocStyle::Biocpkg("SpaceTrooper")`: one field of view (FOV) of a tumour sample with 905 cells, about 1,000 genes, cell polygons and a cell-type label per cell. ```{r read} library(spiSEE) library(SpaceTrooper) dir <- system.file("extdata", "CosMx_DBKero_Tiny", package = "SpaceTrooper") spe <- readCosmxSPE(dirName = dir, sampleName = "DBKero") spe <- spatialPerCellQC(spe) spe <- readAndAddPolygonsToSPE(spe) labels <- read.delim(file.path(dir, "labels_tiny.tsv")) spe$cell_type <- factor(labels$label[match(colnames(spe), labels$cell_id)]) spe <- spe[!grepl("^NegPrb", rownames(spe)), ] # Library-size normalisation (size factors centred at 1), then log2(x + 1). cn <- SingleCellExperiment::counts(spe) sf <- Matrix::colSums(cn) SingleCellExperiment::logcounts(spe) <- log2(t(t(cn) / (sf / mean(sf))) + 1) spe ``` One call opens the app: ```{r app} app <- spiSEE(spe, cache = FALSE) if (interactive()) shiny::runApp(app) ``` `spiSEE()` detects the platform from characteristic `colData` columns (here CosMx, so regions are selected as FOV tiles), picks the cell-type column, QC metrics and default genes, and builds a layout. Two layouts are predefined: `mode = "analysis"` (the default) and `mode = "qc"`, meant for unfiltered data. ```{r platform} getPlatform(spe) ``` ## How the app works * **Select a region** on the overview map: click FOV tiles (CosMx) or single cells (Xenium, Visium HD and any other `SpatialExperiment`), or drag a box, then press *Validate*. Every spatial panel follows. *Clear* goes back to the whole dataset; a second click on a selected tile or cell removes it. A selection can also be given at launch with `selection =`. * **Compute when ready**: statistics, gene rankings and niches recompute only when *Compute* is pressed, on the current region and parameters. Results computed beforehand and stored in the object (niches, domains) are shown at once. * **Combine freely**: the spatial panels work next to any iSEE panel (reduced dimensions, feature assays, tables), and *Organize panels* adds or removes panels while the app runs. # The panels ```{r panel-table, echo = FALSE} panels <- data.frame( Panel = c("`SpatialMapPanel`", "`SpatialPlotPanel`", "`SpatialQCPanel`", "`FOVZoomPanel` (CosMx)", "`FOVStatsPanel` (CosMx)", "`SpatialStatsPanel`", "`SVGPanel`", "`SpatialNichePanel`"), Shows = c( "the tissue as FOV tiles (CosMx) or cells; region selection", "cells or polygons coloured by an annotation, a QC metric or a gene", paste("histogram of a QC metric, SpaceTrooper's outlier fences and", "the number of flagged cells"), "the selected FOVs and their cells coloured by a QC metric", "boxplots of QC metrics per FOV", "spatial statistics, listed below", paste("genes ranked by Moran's I on the region; a click shows the", "gene in a linked spatial plot"), "niches, neighbourhood composition and entropy, spatial domains"), `Main parameters` = c( "—", "`ColorBy`, `UsePolygons`, `PointSize`", "`Metric`, `UseFences`", "`ColorBy`", "—", "`PlotType`, `Genes`, `LabelCol`, `K`, `Alpha`", "`TopN`, `K`, `LinkedPanel`", "`PlotType`, `LabelCol`, `K`, `NNiches`, `Lambda`"), check.names = FALSE) knitr::kable(panels) ``` The statistics panel offers: | Statistic | `PlotType` | |---|---| | Spatial neighbour graph (k-NN) | `graph_plot` | | Local Moran's I of one or more genes | `localmoran_plot` | | Moran scatter plot | `moran_plot` | | Local cluster significance (hot and cold spots) | `locclust_plot` | | Join-count statistics of the cell types | `joincount_plot` | | Cell-type co-occurrence heatmap | `joincount_heatmap_plot` | | L-function of the most frequent cell type | `lest_plot` | | L-cross function of the two most frequent cell types | `lcross_plot` | Moran's I and local clusters come from `r BiocStyle::Biocpkg("Voyager")`, the L-functions from `r BiocStyle::Biocpkg("spatialFDA")`. The niche panel shows: | Plot | `PlotType` | |---|---| | Niches on tissue | `niche_map` | | Niche × cell-type enrichment (heatmap) | `niche_heatmap` | | Niche composition (bar) | `niche_bar` | | Neighbourhood entropy on tissue | `entropy_map` | | Spatial domains on tissue | `domain_map` | | Expression clusters on tissue | `cluster_map` | | Domains vs expression clusters | `domain_vs_cluster` | # Niches and spatial domains outside the app The analyses behind the niche panel are exported, so they can be run on the whole dataset beforehand and stored with the object. The neighbour graph is built once: ```{r graph} spe <- buildSpatialGraph(spe, k = 15) spe <- computeNiches(spe, label_col = "cell_type", k = 15, n_niches = 4) table(spe$niche) ``` Each niche is named after the two cell types most over-represented in it. The composition of each cell's neighbourhood is kept as a reduced dimension: ```{r composition} comp <- reducedDim(spe, "NicheComposition") round(sort(colMeans(comp[spe$cell_type == "TAMs", ], na.rm = TRUE), decreasing = TRUE)[1:4], 2) ``` Spatial domains cluster expression smoothed over the neighbourhood (`lambda` = weight of the neighbourhood, `lambda = 0` gives plain expression clusters, also returned as `expr_cluster`). They need a PCA: ```{r domains} pca <- prcomp(t(as.matrix(logcounts(spe))), rank. = 15) reducedDim(spe, "PCA") <- pca$x spe <- computeSpatialDomains(spe, k_spatial = 15, lambda = 0.5, resolution = 0.5) table(domain = spe$spatial_domain, expression = spe$expr_cluster) ``` The niche panel opens on these stored results without recomputing, with the same `k`, number of niches and `lambda`; *Compute* on a selected region reuses the stored `resolution`. # Custom layouts Any list of panels can be passed as `initial =`, including standard iSEE panels. A non-empty `ComputeTrigger` computes a panel when the app opens: ```{r custom} panels <- list( SpatialMapPanel(), SpatialPlotPanel(ColorBy = "cell_type", UsePolygons = TRUE), SpatialQCPanel(Metric = "Area_um"), SpatialStatsPanel(PlotType = "joincount_heatmap_plot", LabelCol = "cell_type", K = 15L, ComputeTrigger = "launch"), iSEE::ReducedDimensionPlot(Type = "PCA", ColorBy = "Column data", ColorByColumnData = "niche")) app <- spiSEE(spe, initial = panels, cache = FALSE) ``` For reports, `plotSpatialCells()` draws the cells as in the spatial plot panels, with the same colours, here the niches computed above: ```{r static, fig.width = 7, fig.height = 4} #| fig.cap = paste("The niches of the example, drawn outside the app with", #| "plotSpatialCells().") plotSpatialCells(spe, "niche") ``` # Image cache Spatial plots are cached as images on disk (`spatialCacheDir()`), so a view already seen, also after a restart, opens at once. The cache keeps 1 GB and drops the least recently used images first. `cache = FALSE` keeps images in memory only; this vignette uses it so that it writes nothing to the user's folders. `clearSpatialCache()` empties the folder. # Loading other data ```{r loaders, eval = FALSE} spe <- loadCosmx("cosmx_spe.rds") # a prepared CosMx object spe <- loadXenium("path/to/xenium/outs") # 10x Xenium bundle spe <- loadVisiumHD("path/to/segmented_outputs") # Visium HD, cell-segmented ``` Any `SpatialExperiment` with spatial coordinates works; `setPlatform()` sets how regions are selected when it cannot be detected. The app shows one sample at a time: with several samples, choose one with `spiSEE(spe, sample = "...")`. Entries of `metadata(spe)` that the panels use when present (gene ranking, per-FOV tables, FOV layout) are listed in `?spiSEE`. # Session information ```{r session-info} sessionInfo() ```