---
title: "A quick start guide to the scider package"
author: "Mengbo Li, Ning Liu, Quoc Hoang Nguyen and Yunshun Chen"
date: "`r Sys.Date()`"
output: 
  html_document:
    toc: true
    number_sections: true
    theme: cosmo
    highlight: tango
    code_folding: show
vignette: >
  %\VignetteIndexEntry{scider_introduction}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<style type="text/css">
  body{
  font-size: 12pt;
}
</style>

```{r message=FALSE, warning=FALSE, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, dpi = 72)
suppressWarnings(library(ggplot2))
suppressMessages(library(scider))
suppressMessages(library(SpatialExperiment))

setClassUnion("ExpData", c("matrix", "SummarizedExperiment"))
```

scider is an user-friendly R package providing functions to model 
the global density of cells in a slide of spatial transcriptomics 
data. All functions in the package are built based on the 
SpatialExperiment object, allowing integration into various 
spatial transcriptomics-related packages from Bioconductor. 
After modelling density, the package allows for serveral 
downstream analysis, including colocalization analysis, 
boundary detection analysis and differential density analysis.

# Installation

```{r eval=FALSE}
if (!require("BiocManager", quietly = TRUE)) {
    install.packages("BiocManager")
}

BiocManager::install("scider")
```

The development version of `scider` can be installed from GitHub:

```{r eval=FALSE}
devtools::install_github("ChenLaboratory/scider")
```

# Quick start

```{r}
library(scider)
library(SpatialExperiment)
```


# Load data

In this vignette, we will use a subset of a Xenium Breast Cancer dataset.

```{r}
data("xenium_bc_spe")
```

In the data, we have quantification of 541 genes from 10000 cells.

```{r}
spe
```

We also have cell-type annotations of these cells, there are 4 cell types.

```{r}
table(colData(spe)$cell_type)
```

We can use the function `plotSpatial` to visualise the cell position and 
color the cells by cell types.

```{r, fig.width=5, fig.height=4}
plotSpatial(spe, group.by = "cell_type", pt.alpha = 0.8)
```


# Grid-based analysis

`scider` can conduct grid-based density analysis for spatial transcriptomics 
data.

## Density calculation

We can perform density calculation for each cell type using function `gridDensity`.
The calculated density and grid information are saved in the metadata of the 
SpatialExperimnet object.
```{r}
spe <- gridDensity(spe)
names(metadata(spe))
```
```{r}
metadata(spe)$grid_density
```

We can visualise the overall cell density of the whole tissue using function `plotDensity`.
```{r, fig.width=5, fig.height=4}
plotDensity(spe)
```

We can also visualise the density of individual cell type, e.g., fibroblast cells.
```{r, fig.width=5, fig.height=4}
plotDensity(spe, coi = "Fibroblasts")
```


## Find Regions-of-interest (ROIs)

After obtaining grid-based density for each COI, we can then detect 
regions-of-interest (ROIs) based on density or select by user.

### Detected by algorithm

To detect ROIs automatically, we can use the function `findROI`.

The detected ROIs are saved in the metadata of the SpatialExperiment object.

Here we identify ROIs based on the fibroblasts cell density.
```{r}
spe <- findROI(spe, coi = "Fibroblasts")
metadata(spe)$fibroblasts_roi
```

We can visualise the ROIs with function `plotROI`.
```{r, fig.width=5, fig.height=5}
plotROI(spe, roi = "Fibroblasts")
```

### Select ROI by user

Alternatively, users can select ROIs based on their own 
research interest (drawn by hand).
This can be done using function `selectRegion`.
This function will open an interactive window with an interactive plot for 
users to zoom-in/-out and select ROI using either a rectangular or lasso 
selection tool. Users can also press the `Export selected points` button to 
save the ROIs as object in the R environment.

```{r, eval=FALSE}
selectRegion(metadata(spe)$grid_density, x.col = "x_grid", y.col = "y_grid")
```

After closing the interactive window, the selected ROI has been saved as 
a data.frame object named `sel_region` in the R environment.

```{r, eval=FALSE}
sel_region
```

We can then use the `postSelRegion` to save the ROI in the metadata of 
the SpatialExperiment object.

```{r, eval=FALSE}
spe1 <- postSelRegion(spe, sel_region = sel_region)
metadata(spe1)$roi
```

Similarly, we can plot visualise the user-defined ROI with function `plotROI`.

```{r, eval=FALSE}
plotROI(spe1)
```

## Testing relationship between cell types

After defining ROIs, we can then test the relationship between any two 
cell types within each ROI or overall but account for ROI variation using 
a cubic spline or a linear fit. This can be done with function `corrDensity`.

```{r}
results <- corDensity(spe, roi = "Fibroblasts")
```

We can see the correlation between each pair of cell types in each fibroblasts ROI.

```{r}
results$ROI
```

Or the correlation between each pair of cell types across all fibroblasts ROI:

```{r}
results$overall
```


We can also visualise the fitting using function `plotDensCor`.

```{r, fig.width=8, fig.height=6}
plotDensCor(spe, celltype1 = "Breast cancer", celltype2 = "Fibroblasts")
```

Or, we can visualise the statistics between each pair of cell types using 
function `plotCorHeatmap` in the ROIs: 


```{r, fig.width=7, fig.height=4}
plotCorHeatmap(results$ROI)
```

Or the correlation between cell type pairs across the whole slide:

```{r, fig.width=7, fig.height=4}
plotCorHeatmap(results$overall)
```


# Cell-based analysis

Based on the grid density, we can ask many biological question about the data. 
For example, we would like to know if a certain cell type that are located in 
high density of fibroblast cells are different to the same cell type from 
a different level of fibroblast region.

## cell annotation based on grid density

To address this question, we first need to divide cells into different 
levels of grid density. This can be done using a contour identification 
strategy with function `getContour`.


```{r}
spe <- getContour(spe, coi = "Fibroblasts", equal.cell = TRUE)
```

Different level of contour can be visualised with cells using `plotContour`.

```{r, fig.width=5, fig.height=4}
plotContour(spe, coi = "Fibroblasts")
```


We can then annotate cells by their locations within each contour 
using function `allocateCells`.


```{r}
spe <- allocateCells(spe)
```


```{r, fig.width=6, fig.height=4}
plotSpatial(spe, group.by = "fibroblasts_contour", pt.alpha = 0.5)
```

We can visualise cell type composition per level.

```{r, fig.width=6, fig.height=4}
plotCellCompo(spe, contour = "Fibroblasts")
```


```{r, fig.width=7, fig.height=5}
plotCellCompo(spe, contour = "Fibroblasts", roi = "Fibroblasts")
```


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

