---
title: "A quick start guide to the scider package"
author: "Ning Liu, Mengbo Li, 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))
```

scider is a 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, color = cell_type, alpha = 0.8)
```


# Grid-based analysis

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

## Density calculation

Before calculating density, we need to define cell type-of-interest (COI).
In this case, all cell types are COIs.

```{r}
coi <- unique(colData(spe)$cell_type)
coi
```

We can perform density calculation for each COI using function `gridDensity`.
The calculated density and grid information are saved in the metadata of the 
SpatialExperimnet object.

```{r}
spe <- gridDensity(spe, coi = coi)

names(metadata(spe))
```

```{r}
metadata(spe)$grid_density
```

We can visualise the density of each COI using function `plotDensity`.

```{r, fig.width=5, fig.height=4}
plotDensity(spe, coi = coi[1])
```



## 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.

```{r}
spe <- findROI(spe, coi = coi)

metadata(spe)$roi
```

We can visualise the ROIs with function `plotROI`.

```{r, fig.width=5, fig.height=5}
plotROI(spe)
```

### 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`, by setting the `celltype1` and 
`celltype2` parameters, the modelling results are saved in the metadata 
of the SpatialExperiment object.


```{r}
model_result <- corDensity(spe)
```

We can see the correlation between breast cancer and fibroblasts in each ROI.

```{r}
model_result
```

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 cell types using 
function `plotModStat` with a heatmap.


```{r, fig.width=7, fig.height=4}
plotCorHeatmap(model_result)
```



```{r, fig.width=5, fig.height=4}
model_result2 <- corDensity(spe, by.roi = FALSE)

plotCorHeatmap(model_result2)
```


# 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 breast cancer cells are different to the same cell type from 
a different level of breast cancer 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 = "Breast cancer")
```

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

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


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, color = breast_cancer_contour, alpha = 0.5)
```

We can visualise cell type composition per level.

```{r, fig.width=6, fig.height=4}
plotCellCompo(spe, coi = "Breast cancer")
```


```{r, fig.width=7, fig.height=5}
plotCellCompo(spe, coi = "Breast cancer", by.roi = TRUE)
```





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

















