---
title: "Advanced Spatial Analysis"
author:
- name: Marc Elosua & Paula Nieto
  affiliation: 
  - Centro Nacional de AnĂ¡lisis GenĂ³mico (CNAG)
  email: marc.elosua@cnag.crg.eu & paula.nieto@cnag.crg.eu
date: '`r format(Sys.Date(), "%d/%m/%Y")`'
output: 
  html_document:
    includes:
      in_header: banner.html
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
```



# Analysis of Spatial Data

We are going to analyze an invasive ductal carcinoma breast tissue section from [10x Genomicsis](https://www.10xgenomics.com/) Visium Gene Expression platform.

For the analysis we will mainly use the R package [Seurat](https://satijalab.org/seurat/index.html).

## Download Data

You can download the data from [this website](https://www.10xgenomics.com/resources/datasets/human-breast-cancer-block-a-section-1-1-standard-1-1-0) or using `curl`, as shown below. We do not need to do it because it is already in the `data` folder.

```{bash, eval = FALSE}
# download files
curl -O https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Breast_Cancer_Block_A_Section_1/V1_Breast_Cancer_Block_A_Section_1_filtered_feature_bc_matrix.h5
curl -O https://cf.10xgenomics.com/samples/spatial-exp/1.1.0/V1_Breast_Cancer_Block_A_Section_1/V1_Breast_Cancer_Block_A_Section_1_spatial.tar.gz
```

## Libraries

These are the libraries we are going to use:

```{r libraries}
library(tidyverse)
library(Seurat)
library(patchwork)
```


```{r seed}
# set seed for reproducibility purposes
set.seed(1243)
# create palette for the cell types from the pals package
cell_type_palette <- c(
  "#5A5156", "#E4E1E3", "#F6222E", "#FE00FA",
  "#16FF32", "#3283FE", "#FEAF16", "#B00068",
  "#1CFFCE", "#90AD1C", "#2ED9FF", "#DEA0FD",
  "#AA0DFE", "#F8A19F", "#325A9B", "#C4451C",
  "#1C8356", "#85660D", "#B10DA1", "#FBE426",
  "#1CBE4F", "#FA0087", "#FC1CBF", "#F7E1A0",
  "#C075A6", "#782AB6", "#AAF400", "#BDCDFF",
  "#822E1C", "#B5EFB5", "#7ED7D1", "#1C7F93",
  "#D85FF7", "#683B79", "#66B0FF", "#3B00FB")
```

## Load data with Seurat
We start by loading the data Visium data. Note that here we start by already 
loading the filtered expression data. This means that we are only keeping those 
spots that overlap with the tissue as determined by `spaceranger`. 

If we expect there to be overpermabilization of the tissue or want to get a more
general look we can load the raw HDF5 file instead. The raw file contains the
matrix for all 5.000 spots comprising the capture area.
```{r load-spatial}
sp_obj <- Load10X_Spatial(
  data.dir = "data", # Directory where these data is stored
  filename = "filtered_feature_bc_matrix.h5", # Name of H5 file containing the feature barcode matrix
  assay = "Spatial", # Name of assay
  slice = "slice1",   # Name of the image
  filter.matrix = TRUE # Only keep spots that have been determined to be over tissue
  )
```

The visium data from 10x consists is stored in a Seurat object. This object has 
a very similar structure to the scRNAseq object:

* A spot x gene expression matrix (similar to the cell x gene matrix)

```{r}
sp_obj[["Spatial"]][1:5, 1:5]
```

* H&E Image of the tissue slice (obtained from staining during sample processing in the lab)

It adds one slot which contains the images of the Visium experiments as seen below:

```{r}
sp_obj@images
```

We can visualize the image as follows (we will also store this for later):

```{r fig.width=5, fig.height=5}
(img <- SpatialPlot(
  sp_obj, # Name of the Seurat Object
  pt.size = 0, # Point size to see spots on the tissue
  crop = FALSE # Wether to crop to see only tissue section
  ) + 
  NoLegend()
)
```

* Scaling factors that relate the original high resolution image to the lower
resolution image used here for visualization.

```{r}
sp_obj@images$slice1@scale.factors
```

## Quality control

The goal of this step is to remove poor quality spots and lowly captured genes.
To do so we will go over some basic QC steps. Furthermore, due to the nature of 
the assay during library preparation there can be some lateral diffusion of
transcripts. If there are spots not overlapping with the tissue we also need to
remove them since these are artifacts of the experiment.

As with single-cell objects, we have some important features that we can use to 
filter out bad quality spots.

* *nCount_Spatial*: number of UMIs per spot

```{r fig.width=18, fig.height=6}
umi_vln_plt <- VlnPlot(
  sp_obj, 
  features = "nCount_Spatial", 
  pt.size = 0.1) + 
  NoLegend()
umi_sp_plt <- SpatialFeaturePlot(
  sp_obj, 
  features = "nCount_Spatial")
umi_vln_plt | umi_sp_plt | img
```

The variability in the distribution of UMIs is related to the tissue
architecture, i.e. tumoral regions have a higher cell density than fibrotic
regions and thus overlapping spots contain higher counts.

* *nFeature_Spatial*: number of genes per spot

```{r fig.width=18, fig.height=6}
feat_vln_plt <- VlnPlot(
  sp_obj, 
  features = "nFeature_Spatial", 
  pt.size = 0.1) + 
  NoLegend()
feat_sp_plt <- SpatialFeaturePlot(
  sp_obj, 
  features = "nFeature_Spatial")
feat_vln_plt | feat_sp_plt | img
```

Again, here we can see how the number of genes per spot correlates with the
structure of the tissue.

* *mt.content* and *rb.content*: mitochondrial and ribosomal content per spot, respectively

We have to compute this two values by calculating the percentage of reads per
spot that belong to mitochondrial/ribosomal genes.

```{r}
# Mitochondrial content
sp_obj[["mt.content"]] <- PercentageFeatureSet(
  object = sp_obj,
  pattern = "^MT-")
summary(sp_obj[["mt.content"]])
```

```{r fig.width=10}
# Ral contentibosomal
sp_obj[["rb.content"]] <- PercentageFeatureSet(
  object = sp_obj,
  pattern = "^RPL|^RPS")
summary(sp_obj[["rb.content"]])
```

```{r fig.width=12, fig.height=6}
SpatialFeaturePlot(
  sp_obj, 
  features = c("mt.content", "rb.content"))
```

In the case of spatial data, high mitochondrial content is not necessarily 
an indicator of bad quality spots. Therefore, on its own it is not sufficient to
determine which spots to filter out. In this case, they are not pointing towards
low quality regions but seem to be reflecting the biological structure of the
tissue.

### Gene filtering

Before filtering:

```{r}
sp_obj
```

We are going to filter out genes that have no expression in the tissue.

```{r}
table(rowSums(as.matrix(sp_obj@assays$Spatial@counts)) == 0)
keep_genes <- rowSums(as.matrix(sp_obj@assays$Spatial@counts)) != 0
sp_obj <- sp_obj[keep_genes, ]
```

We see how we remove 11.678 genes while keeping 24.923.

### Spot filtering

Furthermore, we set a threshold to filter out spots with very low number of
counts (< 500) before proceeding with the downstream analysis. As we can see 
there are no spots with <500 UMIs so we will not remove any of them.


```{r}
table(colSums(as.matrix(sp_obj@assays$Spatial@counts)) < 500)
sp_obj <- subset(
  sp_obj,
  subset = nCount_Spatial > 500)
```

After filtering:

```{r}
sp_obj
```

## Preprocessing

Similar to single-cell datasets, preprocessing for spatial data requires 
normalization, identification of variable features and scaling the counts. 
To carry out these steps we will use SCTransform which takes into account that
different spot complexities observed. Spots overlapping more cell-dense regions
will have more UMIs. If we use standard Log Normalization we are removing this
biological signal from the dataset.

```{r sct}
sp_obj <- SCTransform(
  sp_obj,
  assay = "Spatial", # assay to pull the count data from
  ncells = ncol(sp_obj), # Number of subsampling Spots used to build NB regression, in this case use all
  variable.features.n = 3000,  # variable features to use after ranking by residual variance
  verbose = FALSE
  )
```

Prior to clustering, we perform dimensionality reduction via PCA. We then look 
at the elbow plot to assess the right number of principal components (PC) to
use for downstream analysis.

```{r}
sp_obj <- RunPCA(
  sp_obj, 
  npcs = 50
  )
ElbowPlot(
  sp_obj, 
  ndims = 50
  )
```

We see an elbow at 15 PC, after that the standard deviations are pretty much
flat indicating that they aren't contributing much information. To reduce
computational resources and noise we proceed with the first 15 PCs and add
another 10 for a total of 25 PCs to make sure we are not loosing biological
signal while reducing the noise.

```{r umap}
sp_obj <- RunUMAP(
  sp_obj,
  reduction = "pca",
  dims = 1:25
  )
```

## Clustering and visualization

Next we compute the K nearest neighbors and find an optimal number of clusters
using shared nearest neighbor Louvain modularity based clustering.
```{r clustering}
sp_obj <- FindNeighbors(
  sp_obj, 
  reduction = "pca", 
  dims = 1:20
  )
sp_obj <- FindClusters(
  sp_obj,
  resolution = 0.3
  )
```

Look at the clustering in the UMAP space and on the tissue:
```{r fig.width=12, fig.height=6}
umap_plt <- DimPlot(
  sp_obj, 
  label = TRUE
  )
sp_plt <- SpatialDimPlot(
  sp_obj
  ) +
  NoLegend()
umap_plt + sp_plt
```

## Gene expression and annotation

ESR1 and ERBB2 (HER2) are the two of the most common mutations in breast cancer, so one
way of annotating the tissue is by looking at ESR1 and ERBB2 positive/negative 
regions.

```{r fig.width=18, fig.height=6}
SpatialFeaturePlot(
  sp_obj, 
  features = c("ESR1", "ERBB2"), 
  alpha = c(0.1, 1)
  ) + 
  (SpatialDimPlot(
    sp_obj,
    label = TRUE
    ) +
  NoLegend())
```

From the expression of the two genes above we can do a high-level annotation.

```{r annotation}
sp_obj@meta.data <- sp_obj@meta.data %>%
  mutate(annotation = case_when(
    SCT_snn_res.0.3 == 0 ~ "Fibrotic",
    SCT_snn_res.0.3 == 1 ~ "Fibrotic",
    SCT_snn_res.0.3 == 2 ~ "HER2-/ESR1-",
    SCT_snn_res.0.3 == 3 ~ "HER2-/ESR1+",
    SCT_snn_res.0.3 == 4 ~ "HER2+/ESR1+",
    SCT_snn_res.0.3 == 5 ~ "HER2+/ESR1-",
    SCT_snn_res.0.3 == 6 ~ "HER2-/ESR1-",
    SCT_snn_res.0.3 == 7 ~ "HER2-/ESR1-",
    SCT_snn_res.0.3 == 8 ~ "HER2-/ESR1-")
    )
```

Look at the annotation
```{r fig.width=6, fig.height=6}
# We will define a palette (this is optional)
annot_pal <- c("#E41A1C", "#FF7F00", "#984EA3", "#4DAF4A", "#377EB8")
names(annot_pal) <- c("Fibrotic", "HER2-/ESR1-", "HER2-/ESR1+", "HER2+/ESR1-", "HER2+/ESR1+")
SpatialDimPlot(
  sp_obj,
  group.by = "annotation",
  cols = annot_pal
  )
```

## Deconvolution

We are going to use [SPOTlight](https://academic.oup.com/nar/article/49/9/e50/6129341?login=true) in conjunction with a subset of the [Tumor Immune Cell Atlas](https://genome.cshlp.org/content/31/10/1913) to deconvolute our spots and map immune populations to our tumor section.

```{r spotlight}
# load library
library(SPOTlight)
library(NMF)
```

Load downsampled version of the Tumor Immune Cell Atlas and explore the metadata
we have. We are going to use annotation level 1 for the deconvolution 
(`lv1_annot`). Moreover, since the origin of these cells is from different
organs and papers we want to minize batch effect. To do so we will only select
cells coming from one cancer type which has enough cells for all cell types.

```{r load-sc}
atlas <- readRDS("R_obj/TICAtlas_downsample.rds")
head(atlas@meta.data)
table(atlas@meta.data$lv1_annot)
```

### Marker genes
First of all we need to compute the markers for the cell types using Seurat's
function `FindAllMarkers`. 

```{r marker-genes, eval = FALSE}
Idents(atlas) <- "lv1_annot"
  
sc_markers <- FindAllMarkers(
  object = atlas,
  assay = "RNA",
  slot = "data",
  only.pos = TRUE
  )

saveRDS(sc_markers, "R_obj/filtered_atlas_markers.rds")
```

```{r}
sc_markers <- readRDS("R_obj/filtered_atlas_markers.rds")
sc_markers %>%
  group_by(cluster) %>% 
  top_n(5, wt = avg_log2FC) %>% 
  DT::datatable()
```

### Run Deconvolution
Run the deconvolution using the scRNAseq atlas and the spatial transcriptomics data.

```{r deconvolution, eval = FALSE}
decon_mtrx_ls <- spotlight_deconvolution(
  se_sc = atlas, # Single-cell dataset
  counts_spatial = sp_obj@assays$Spatial@counts,
  clust_vr = "lv1_annot", # Label to use for the deconvolution (cell types)
  cluster_markers = sc_markers, # Cell type markers
  hvg = 3000, # Number of HVGs to use on top of the markers
  min_cont = 0, # minimum expected contribution per cell type and spot
  assay = "RNA",
  slot = "counts"
  )

saveRDS(decon_mtrx_ls, "R_obj/deconvolution_ls.rds")
```

```{r}
decon_mtrx_ls <- readRDS("R_obj/deconvolution_ls.rds")
```

### Deconvolution assesment
Before even looking at the decomposed spots we can gain insight on how well the model performed by looking at the topic profiles for the cell types.

```{r}
nmf_mod <- decon_mtrx_ls[[1]]
decon_mtrx <- decon_mtrx_ls[[2]]
rownames(decon_mtrx) <- colnames(sp_obj)
# info on the NMF model
nmf_mod[[1]]
# deconvolution matrix
head(decon_mtrx)
```

Look at how specific the topic profiles are for each cell type. Ideally we want
to see how each cell type has its own unique topic profile. This means the model
has learnt a unique gene signature for that cell type.

```{r fig.height=10, fig.width=10}
h <- NMF::coef(nmf_mod[[1]])
rownames(h) <- paste("Topic", 1:nrow(h), sep = "_")
topic_profile_plts <- SPOTlight::dot_plot_profiles_fun(
  h = h,
  train_cell_clust = nmf_mod[[2]])
topic_profile_plts[[2]]
```

We also want to take a look at the topic profiles of the individual cells. 
We want to see how all the cells from the same cell type share the same topic
profiles to make sure the learned signature is robust. In this plot each facet 
shows all the cells from the same cell type.

```{r fig.width=25, fig.height=25}
topic_profile_plts[[1]] +
  theme(axis.text.x = element_blank())
```

Lastly we can take a look at which genes the model learned for each topic.
Higher values indicate that the gene is more relevant for that topic. 
In the below table we can see how the top genes for topic 1 are characteristic
for B cells (i.e. *CD79A*, *CD79B*, *MS4A1*, *IGHD*...).

```{r basis-dt}
sign <- basis(nmf_mod[[1]])
colnames(sign) <- paste0("Topic", seq_len(ncol(sign)))
# This can be dynamically visualized with DT as shown below
DT::datatable(sign, filter = "top")
```

### Deconvolution visualization

Let's now visualize how the deconvoluted spots on the the Seurat object.

```{r}
# We will only add the deconvolution matrix
decon_mtrx <- decon_mtrx_ls[[2]]
decon_mtrx <- decon_mtrx[, colnames(decon_mtrx) != "res_ss"]
decon_mtrx <- decon_mtrx[, !is.na(colnames(decon_mtrx))]
# Set as 0 those cell types that contribute <2% to the spot
decon_mtrx[decon_mtrx < 0.02] <- 0
```

```{r eval = FALSE}
# Add deconvolution results to Seurat object
sp_obj@meta.data <- cbind(sp_obj@meta.data, decon_mtrx)
saveRDS(sp_obj, "R_obj/breast_slide_deconvoluted.rds")
```

We have an object with the deconvolution information already added:

```{r}
sp_obj <- readRDS("R_obj/breast_slide_deconvoluted.rds")
```

The first thing we can do is look at the spatial scatterpie. This plot 
represents each spot as an individual piechart where the proportion of each 
cell type within that spot is represented.
```{r}
ct <- colnames(decon_mtrx)
scatterpie_plot(
    se_obj = sp_obj,
    cell_types_all = ct,
    pie_scale = 0.3) +
  coord_fixed(ratio = 1) +
  scale_fill_manual(values = cell_type_palette)
```

As we can see when we look at all the cell types at the same time we are not 
able to discern clear patterns. To improve the visualization we will remove 
those cell types that are found in >80% of the spot and keep those that aren't
ubiquitouslyy expressed.

```{r}
# keep only cell types that are present in less than 80% of the spots
keep_0.8 <- colSums(sp_obj@meta.data[, ct] > 0) < 0.8 * ncol(sp_obj)
# but not those that were not found on the tissue
keep_g0 <- colSums(sp_obj@meta.data[, ct] > 0) > 0
# select cell types fullfiling the conditions
ct_var <- colnames(sp_obj@meta.data[, ct])[keep_0.8 & keep_g0]
ct_var
```

Plot the spatial scatterpie only with the cell types of interest
```{r}
scatterpie_plot(
  se_obj = sp_obj,
  cell_types_all = ct_var,
  pie_scale = 0.3) +
  coord_fixed(ratio = 1) +
  scale_fill_manual(values = cell_type_palette)
```

Next, we can visualize the individual cell type proportions on the spatial slide.

```{r fig.width=25, fig.height=32}
scaleFUN <- function(x) sprintf("%.2f", x)
SpatialPlot(
  object = sp_obj,
  features = ct,
  alpha = c(0, 1),
  ncol = 4, image.alpha = 0) &
  scale_fill_gradientn(
    colors = grDevices::heat.colors(10, rev = TRUE),
    # 2 decimals in the legend
    labels = scaleFUN,
    n.breaks = 4)
```

Lets now see the frequencies of selected cell types across the regions in the tissue. 
We will focus on pre-exhausted T cells and macrophages as they can give an idea of how 
infiltrated the tumor can be. 

```{r fig.height=10, fig.width=9}
VlnPlot(
  sp_obj,
  features = c("Monocytes", "TAMs.C1QC", "TAMs.proinflamatory", "CD8.terminally.exhausted", "CD8.pre.exhausted"),
  group.by = "annotation",
  cols = annot_pal,
  pt.size = 0.2
  )
```

```{r}
plt_annot <- SpatialDimPlot(
  sp_obj, 
  group.by = "annotation",
  cols = annot_pal
  )
img | plt_annot
```

We can see that in the HER2+/ESR1- (dark red) region we have an abundance of pre-exhausted CD8 
T cells as well as pro-inflamatory macrophages. The presence of both subtypes at the 
same time in a tumor region, can be indicative of the presence of a highly infiltrated
tumor, often referred to as a "hot" tumor.

This type of tumors often have a better response to treatment, opposite to cold regions,
where little to no immune cells are able to infiltrate the tumor, conforming a immune
excluded section, often linked to worse treatment response.

*** 

<a href="#top">Back to top</a>

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