/
adv-single-cell-01.Rmd
258 lines (186 loc) · 8.06 KB
/
adv-single-cell-01.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
---
title: "Large-scale clustering in Bioconductor"
description: >
Learn how to do unsupervised clustering in R/Bioconductor for large-scale data.
author: "Stephanie Hicks"
output:
rmarkdown::html_document:
highlight: pygments
toc: true
toc_depth: 3
fig_width: 5
vignette: >
%\VignetteIndexEntry{Large-scale clustering in Bioconductor}
%\VignetteEncoding[ut8]{inputenc}
%\VignetteEngine{knitr::rmarkdown}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
```
# Overview
## Key resources
- Workshop material: [pkgdown website](https://stephaniehicks.com/cshlgsd2022)
- Code: [GitHub](https://github.com/stephaniehicks/cshlgsd2022)
# Part 1
## Learning objectives
1. Understand why feature selection is important
2. Recognize basic strategies for identifying highly variable genes.
3. Be able to describe what is dimensionality reduction and name at least three types of methods.
4. Be able to describe what does clustering give us and name at least three types of approaches to clustering.
5. Be able to explain why the question "What are the 'true' number of clusters?" is not a great question and be able to reframe the question to e.g. "how well do the clusters approximate the cell types or states of interest?"
## Materials
We will go through these slides on "More Single-Cell Data Science":
- https://docs.google.com/presentation/d/19EIrGrbZoQUyYQggy8Zxzo5RiwM7fEsiP3DSAsnCOgE/edit?usp=sharing
# Part 2
## Learning objectives
1. Be able to load a `SingleCellExperiment` object in a `.HDF5` file format for large-scale single-cell data.
2. Be able to apply standard scRNA-seq workflow, but to a "large" dataset.
## Overview
This tutorial gives a demo of large-scale clustering in the Bioconductor using the *DelayedArray* framework.
*DelayedArray* is like an ordinary array in R, but allows for the data to be in-memory, on-disk in a file, or even hosted on a remote server.
We will showcase an end-to-end clustering pipeline, starting from the count data matrix stored in HDF5 (similar to what one would download from the HCA data portal) all the way to visualization and interpretation of the clustering results.
1. `scran` normalization + PCA
2. `glmpca` with `scry`
Using these reduced dimensions, we present two types of clustering:
1. SNN + Louvain clustering
2. mini-batch _k_-means (`mbkmeans`)
While we use a small-ish dataset for this demo for convenience, the code is computationally efficient even for (very) large datasets.
```{r packages}
suppressMessages({
library(SingleCellExperiment)
library(TENxPBMCData)
library(scater)
library(scran)
library(scry)
library(mbkmeans)
})
```
## Getting the data
```{r data}
sce <- TENxPBMCData("pbmc4k")
sce
counts(sce)
seed(counts(sce))
```
In this tutorial, we use a small dataset for the sake of running all the code in a short amount of time. However, this workflow is designed for large data and it will run just fine with any sized dataset. For instance, we have analyzed 1.3 million cells on a machine with a moderately sized RAM (e.g., 64GB).
By running the code below, you will run the workflow on the [10X Genomics 1.3 million cells dataset. (Warning: it takes some time!) Alternatively, you can substitute the code below with your own data in `SingleCellExperiment` format.
```{r million, eval=FALSE}
library(TENxBrainData)
sce <- TENxBrainData()
sce
```
## Filtering and normalization
### Removing low-quality cells
First, we use the `scater` package to compute a set of
QC measures and filter out the low-quality samples.
Here, we exclude those cells that have a too high percentage of mitochondrial genes or for which we detect too few genes.
```{r filter}
sce <- addPerCellQC(sce,
subsets = list(Mito = grep("^MT-", rowData(sce)$Symbol_TENx)))
high_mito <- isOutlier(sce$subsets_Mito_percent,
nmads = 3, type="higher")
low_detection <- (sce$detected < 1000)
high_counts <- sce$sum > 45000
sce <- sce[,!high_mito & !low_detection & !high_counts]
sce
```
### Removing lowly expressed genes
Next, we remove the lowly expressed genes. Here,
we keep only those genes that have at least 1 UMI
in at least 5% of the data. These threshold are
dataset-specific and may need to be taylored to
specific applications.
```{r qc-gene-filter}
num_reads <- 1
num_cells <- 0.01*ncol(sce)
keep <- which(DelayedArray::rowSums(counts(sce) >= num_reads ) >= num_cells)
sce <- sce[keep,]
sce
```
These leaves us with `length(keep)` genes.
### Normalization
Here, we apply `mbkmeans` (`k=10` and batch size of 500) as a preliminary step to `scran` normalization.
```{r mbkmeans_full}
set.seed(19)
mbk <- mbkmeans(sce, whichAssay = "counts", reduceMethod = NA,
clusters=10, batch_size = 500)
sce$mbk10 <- paste0("mbk", mbk$Clusters)
table(mbk$Clusters)
```
We then compute the normalization factors and normalize the data.
```{r scran}
sce <- computeSumFactors(sce, cluster=mbk$Clusters, min.mean = 0.1)
sce <- logNormCounts(sce)
sce
```
## Dimensionality reduction
### PCA on normalized values
Here, we compute the first 50 principal components using the top variable genes.
```{r pca}
sce <- scater::runPCA(sce, ncomponents = 50,
ntop = 1000,
scale = TRUE,
BSPARAM = BiocSingular::RandomParam())
plotPCA(sce, colour_by = "mbk10")
```
### GLM-PCA
An alternative to PCA on normalized data is to use the GLM-PCA approach, implemented in the `scry` Bioconductor package. Here, we use the faster, approximate approach that computes the null residuals and runs PCA on them.
Other approaches implemented in Bioconductor for dimensionality reduction include correspondence analysis (in the `corral` package) and ZINB-WaVE (in the `zinbwave` and `NewWave` packages).
```{r glmpca}
sce <- nullResiduals(sce, assay="counts", type="deviance")
sce <- scater::runPCA(sce, ncomponents = 50,
ntop = 1000,
exprs_values = "binomial_deviance_residuals",
scale = TRUE, name = "GLM-PCA",
BSPARAM = BiocSingular::RandomParam())
plotReducedDim(sce, dimred = "GLM-PCA", colour_by = "mbk10")
```
## Clustering
Here, we use the GLM-PCA results to obtain the final cluster labels. We use two alternative approaches: Louvain and mini-batch _k_-means.
### Louvain
```{r louvain}
g <- buildSNNGraph(sce, k=10, use.dimred = "GLM-PCA")
lou <- igraph::cluster_louvain(g)
sce$louvain <- paste0("Louvain", lou$membership)
table(sce$louvain)
```
If you want more control on the resolution of the clustering, you can use the Louvain implementation available in the `resolution` package. Alternatively, the `leiden` package implements the Leiden algorithm.
### Mini-batch k-means
Mini-batch $k$-means is a faster version of $k$-means that uses only a random "mini-batch" of data at each iteration. The algorithm is fast enough to cluster the 1.3 million cell data in the space of the top 50 PC in under 30 seconds.
Here, we run it multiple times to select the value of $k$ with the elbow method.
```{r select_k}
k_list <- seq(5, 20)
km_res <- lapply(k_list, function(k) {
mbkmeans(sce, clusters = k,
batch_size = 500,
reduceMethod = "GLM-PCA",
calc_wcss = TRUE)
})
wcss <- sapply(km_res, function(x) sum(x$WCSS_per_cluster))
plot(k_list, wcss, type = "b")
```
```{r minibatch}
sce$kmeans <- paste0("mbk", km_res[[which(k_list==12)]]$Clusters)
table(sce$kmeans)
table(sce$kmeans, sce$louvain)
```
## Cluster visualization
We can use UMAP or t-SNE to visualize the clusters.
```{r umap}
sce <- scater::runUMAP(sce, dimred = "GLM-PCA",
external_neighbors = TRUE,
BNPARAM = BiocNeighbors::AnnoyParam())
plotUMAP(sce, colour_by = "louvain")
plotUMAP(sce, colour_by = "kmeans")
```
```{r tsne}
sce <- scater::runTSNE(sce, dimred = "GLM-PCA",
external_neighbors = TRUE,
BNPARAM = BiocNeighbors::AnnoyParam())
plotTSNE(sce, colour_by = "louvain")
plotTSNE(sce, colour_by = "kmeans")
```
## Session info
```{r}
sessionInfo()
```