---
author: "Åsa Björklund & Paulo Czarnewski"
date: '`r format(Sys.Date(), "%B %d, %Y")`'
output:
html_document:
self_contained: true
highlight: tango
df_print: paged
toc: yes
toc_float:
collapsed: false
smooth_scroll: true
toc_depth: 3
keep_md: yes
fig_caption: true
html_notebook:
self_contained: true
highlight: tango
df_print: paged
toc: yes
toc_float:
collapsed: false
smooth_scroll: true
toc_depth: 3
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(message=FALSE, warning=FALSE, result='hold',fig.width=12,tidy=TRUE)
knitr::opts_knit$set(progress=TRUE,verbose=TRUE)
```
# Clustering
In this tutorial we will continue the analysis of the integrated dataset. We will use the integrated PCA to perform the clustering. First we will construct a $k$-nearest neighbour graph in order to perform a clustering on the graph. We will also show how to perform hierarchical clustering and k-means clustering on PCA space.
Let's first load all necessary libraries and also the integrated dataset from the previous step.
```{r, message='hide',warning='hide',results='hold'}
suppressPackageStartupMessages({
library(scater)
library(scran)
library(cowplot)
library(ggplot2)
library(rafalib)
library(pheatmap)
library(igraph)
})
sce <- readRDS("data/results/covid_qc_dr_int.rds")
```
## Graph clustering
***
The procedure of clustering on a Graph can be generalized as 3 main steps:
1) Build a kNN graph from the data
2) Prune spurious connections from kNN graph (optional step). This is a SNN graph.
3) Find groups of cells that maximizes the connections within the group compared other groups.
### Building kNN / SNN graph
The first step into graph clustering is to construct a k-nn graph, in case you don't have one. For this, we will use the PCA space. Thus, as done for dimensionality reduction, we will use ony the top *N* PCA dimensions for this purpose (the same used for computing UMAP / tSNE).
```{r, message='hide',warning='hide',results='hold'}
#These 2 lines are for demonstration purposes only
g <- buildKNNGraph(sce,k=30,use.dimred="MNN")
reducedDim(sce,"KNN") <- igraph::as_adjacency_matrix(g)
#These 2 lines are the most recommended
g <- buildSNNGraph(sce,k=30,use.dimred="MNN")
reducedDim(sce,"SNN") <- as_adjacency_matrix(g, attr = "weight")
```
We can take a look at the kNN graph. It is a matrix where every connection between cells is represented as $1$s. This is called a **unweighted** graph (default in Seurat). Some cell connections can however have more importance than others, in that case the scale of the graph from $0$ to a maximum distance. Usually, the smaller the distance, the closer two points are, and stronger is their connection. This is called a **weighted** graph. Both weighted and unweighted graphs are suitable for clustering, but clustering on unweighted graphs is faster for large datasets (> 100k cells).
```{r, message='hide',warning='hide',results='hold',fig.asp=1,fig.width=4}
#plot the KNN graph
pheatmap(reducedDim(sce,"KNN")[1:200,1:200],
col=c("white","black"),border_color = "grey90",
legend = F,cluster_rows = F,cluster_cols = F,fontsize = 2)
#or the SNN graph
pheatmap(reducedDim(sce,"SNN")[1:200,1:200],
col = colorRampPalette(c("white","yellow","red","black"))(20),
border_color = "grey90",
legend = T,cluster_rows = F,cluster_cols = F,fontsize = 2)
```
As you can see, the way Scran computes the SNN graph is different to Seurat. It gives edges to all cells that shares a neighbor, but weights the edges by how similar the neighbors are. Hence, the SNN graph has more edges than the KNN graph.
### Clustering on a graph
Once the graph is built, we can now perform graph clustering. The clustering is done respective to a resolution which can be interpreted as how coarse you want your cluster to be. Higher resolution means higher number of clusters.
```{r,results='hide',block.title=TRUE,fig.height=2.8,fig.width=10}
g <- buildSNNGraph(sce,k=5,use.dimred="MNN")
sce$louvain_SNNk5 <- factor( cluster_louvain(g)$membership )
g <- buildSNNGraph(sce,k=10,use.dimred="MNN")
sce$louvain_SNNk10 <- factor( cluster_louvain(g)$membership )
g <- buildSNNGraph(sce,k=15,use.dimred="MNN")
sce$louvain_SNNk15 <- factor( cluster_louvain(g)$membership )
plot_grid(ncol = 3,
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "louvain_SNNk5")+
ggplot2::ggtitle(label ="louvain_SNNk5"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "louvain_SNNk10")+
ggplot2::ggtitle(label ="louvain_SNNk10"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "louvain_SNNk15")+
ggplot2::ggtitle(label ="louvain_SNNk15")
)
```
We can now use the `clustree` package to visualize how cells are distributed between clusters depending on resolution.
```{r}
suppressPackageStartupMessages(library(clustree))
clustree(sce, prefix = "louvain_SNNk")
```
## K-means clustering
***
K-means is a generic clustering algorithm that has been used in many application areas. In R, it can be applied via the kmeans function. Typically, it is applied to a reduced dimension representation of the expression data (most often PCA, because of the interpretability of the low-dimensional distances). We need to define the number of clusters in advance. Since the results depend on the initialization of the cluster centers, it is typically recommended to run K-means with multiple starting configurations (via the nstart argument).
```{r,results='hide',block.title=TRUE,fig.height=2.9}
sce$kmeans_5 <- factor( kmeans(x = reducedDim(sce,"MNN"),centers = 5)$cluster )
sce$kmeans_10 <- factor(kmeans(x = reducedDim(sce,"MNN"),centers = 10)$cluster)
sce$kmeans_15 <- factor(kmeans(x = reducedDim(sce,"MNN"),centers = 15)$cluster)
plot_grid(ncol = 3,
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "kmeans_5")+
ggplot2::ggtitle(label ="KMeans5"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "kmeans_10")+
ggplot2::ggtitle(label ="KMeans10"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "kmeans_15")+
ggplot2::ggtitle(label ="KMeans15")
)
```
```{r}
clustree(sce, prefix = "kmeans_")
```
## Hierarchical clustering
***
### Defining distance between cells
The base R `stats` package already contains a function `dist` that calculates distances between all pairs of samples. Since we want to compute distances between samples, rather than among genes, we need to transpose the data before applying it to the `dist` function. This can be done by simply adding the transpose function `t()` to the data. The distance methods available in `dist` are: "euclidean", "maximum", "manhattan", "canberra", "binary" or "minkowski".
```{r,results='hide',block.title=TRUE,fig.height=5}
d <- dist( reducedDim(sce,"MNN"), method="euclidean")
```
As you might have realized, correlation is not a method implemented in the `dist` function. However, we can create our own distances and transform them to a distance object. We can first compute sample correlations using the `cor` function.
As you already know, correlation range from -1 to 1, where 1 indicates that two samples are closest, -1 indicates that two samples are the furthest and 0 is somewhat in between. This, however, creates a problem in defining distances because a distance of 0 indicates that two samples are closest, 1 indicates that two samples are the furthest and distance of -1 is not meaningful. We thus need to transform the correlations to a positive scale (a.k.a. **adjacency**):
\[adj = \frac{1- cor}{2}\]
Once we transformed the correlations to a 0-1 scale, we can simply convert it to a distance object using `as.dist` function. The transformation does not need to have a maximum of 1, but it is more intuitive to have it at 1, rather than at any other number.
```{r,results='hide',block.title=TRUE,fig.height=5,fig.width=5}
#Compute sample correlations
sample_cor <- cor( Matrix::t(reducedDim(sce,"MNN")) )
#Transform the scale from correlations
sample_cor <- (1 - sample_cor) / 2
#Convert it to a distance object
d2 <- as.dist(sample_cor)
```
### Clustering cells
After having calculated the distances between samples calculated, we can now proceed with the hierarchical clustering per-se. We will use the function `hclust` for this purpose, in which we can simply run it with the distance objects created above. The methods available are: "ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median" or "centroid". It is possible to plot the dendrogram for all cells, but this is very time consuming and we will omit for this tutorial.
```{r,results='hide',block.title=TRUE,fig.height=5,fig.width=10}
#euclidean
h_euclidean <- hclust(d, method="ward.D2")
#correlation
h_correlation <- hclust(d2, method="ward.D2")
```
Once your dendrogram is created, the next step is to define which samples belong to a particular cluster. After identifying the dendrogram, we can now literally cut the tree at a fixed threshold (with `cutree`) at different levels to define the clusters. We can either define the number of clusters or decide on a height. We can simply try different clustering levels.
```{r,results='hide',block.title=TRUE,fig.height=6}
#euclidean distance
sce$hc_euclidean_5 <- factor( cutree(h_euclidean,k = 5) )
sce$hc_euclidean_10 <- factor( cutree(h_euclidean,k = 10) )
sce$hc_euclidean_15 <- factor( cutree(h_euclidean,k = 15) )
#correlation distance
sce$hc_corelation_5 <- factor( cutree(h_correlation,k = 5) )
sce$hc_corelation_10 <- factor( cutree(h_correlation,k = 10) )
sce$hc_corelation_15 <- factor( cutree(h_correlation,k = 15) )
plot_grid(ncol = 3,
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "hc_euclidean_5")+
ggplot2::ggtitle(label ="HC_euclidean_5"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "hc_euclidean_10")+
ggplot2::ggtitle(label ="HC_euclidean_10"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "hc_euclidean_15")+
ggplot2::ggtitle(label ="HC_euclidean_15"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "hc_corelation_5")+
ggplot2::ggtitle(label ="HC_correlation_5"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "hc_corelation_10")+
ggplot2::ggtitle(label ="HC_correlation_10"),
plotReducedDim(sce,dimred = "UMAP_on_MNN",colour_by = "hc_corelation_15")+
ggplot2::ggtitle(label ="HC_correlation_15")
)
```
Finally, lets save the integrated data for further analysis.
```{r}
saveRDS(sce,"data/results/covid_qc_dr_int_cl.rds")
```
**Your turn**
By now you should know how to plot different features onto your data. Take the QC metrics that were calculated in the first exercise, that should be stored in your data object, and plot it as violin plots per cluster using the clustering method of your choice. For example, plot number of UMIS, detected genes, percent mitochondrial reads.
Then, check carefully if there is any bias in how your data is separated due to quality metrics. Could it be explained biologically, or could you have technical bias there?

### Session Info
***
```{r}
sessionInfo()
```