Repository navigation
Expand file tree
/
Copy pathtutorialScRNAseqAnalysis.Rmd
More file actions
500 lines (325 loc) · 10.3 KB
/
Copy pathtutorialScRNAseqAnalysis.Rmd
File metadata and controls
500 lines (325 loc) · 10.3 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
---
title: "Single-Cell RNA-seq Analysis of Human PBMCs with Bioconductor"
author: "Adrien Jolly"
---
# Overview
In this practical, we will analyze a human PBMC dataset generated using the platform developed by 10x Genomics.
The following steps will be performed sequencially:
- Load raw count data
- Identify and remove empty droplets
- Perform quality control filtering
- Normalize counts
- Eliminate doublets
- Model gene variance and perform feature selection
- Perform PCA, UMAP and clustering and cluster annotation
- Annotate cells using SingleR
For the second day the students will be more independent in their analysis.
the script covers specific approaches which the students will incorporate in their own code
- data integration (scaling)
- batch correction with fast MNN
- pseudobulking and differential gene expression analysis with DEseq2.
All analysis is performed using Bioconductor and the SingleCellExperiment framework (see https://bioconductor.org/books/release/OSCA/).
---
# Package Installation (Run Once)
If you are using the provided Docker image, you can skip this section.
Otherwise, run this chunk to install all required packages.
```{r install_packages, eval=TRUE}
# Check if BiocManager is installed
if (!requireNamespace("BiocManager", quietly = TRUE)) {
install.packages("BiocManager")
}
# Install Bioconductor packages (only if missing)
bioc_pkgs <- c(
"DropletUtils",
"SingleCellExperiment",
"scater",
"scran",
"bluster",
"batchelor",
"SingleR",
"celldex",
"DESeq2",
"edgeR",
"scDblFinder",
"EnhancedVolcano"
)
for (pkg in bioc_pkgs) {
if (!requireNamespace(pkg, quietly = TRUE)) {
BiocManager::install(pkg, ask = FALSE, update = FALSE)
}
}
# Install CRAN packages (only if missing)
cran_pkgs <- c("ggplot2", "patchwork")
for (pkg in cran_pkgs) {
if (!requireNamespace(pkg, quietly = TRUE)) {
install.packages(pkg)
}
}
```
---
# Load Required Packages
```{r setup, message=FALSE, warning=FALSE}
library(DropletUtils)
library(AnnotationHub)
library(SingleCellExperiment)
library(scater)
library(scran)
library(bluster)
library(batchelor)
library(ggplot2)
library(patchwork)
library(SingleR)
library(celldex)
library(DESeq2)
library(edgeR)
library(scDblFinder)
```
---
# Load 10x Data
The matrix contains UMI counts (not expression values).
```{r}
sce <- read10xCounts("sample_raw_feature_bc_matrix_1")
sce
```
Inspect:
- Rows = genes
- Columns = barcoded droplets
- Counts = UMI-collapsed molecule counts
---
# Identify Empty Droplets
Empty droplets contain ambient RNA.
We use the knee/elbow plot to determine a lower UMI cutoff.
```{r}
barcodeRanks <- barcodeRanks(counts(sce))
plot(barcodeRanks$rank,
barcodeRanks$total,
log="xy",
xlab="Rank",
ylab="Total UMI count",
main="Barcode Rank Plot (Knee/Elbow)")
abline(h=metadata(barcodeRanks)$knee, col="red")
abline(h=metadata(barcodeRanks)$inflection, col="blue")
```
- Where is the elbow?
- What UMI threshold would you choose?
```{r}
# set your own threshold
umi_threshold <- ##
#how many cells do you have left?
sce[, colSums(counts(sce)) > umi_threshold]
# Elbow method can be too restrictive,we'll use emptyDrops, established statistical method to remove empty droplets based on distance to ambient rnas
# compare elbow method result and to result from emptydrops
e.out <- emptyDrops(counts(sce))
sce[,which(e.out$FDR <= 0.001)]
sce<- sce[,which(e.out$FDR <= 0.001)]
```
---
# Per-Cell Quality Control
We compute QC metrics.
first we calculate the percentage of mito high cells, due to mitochondrial degradation, apoptotic cells are expected to have a high % of mitochondrial RNA, we want to exclude these cells
```{r}
rownames(sce) <- uniquifyFeatureNames(
rowData(sce)$ID, rowData(sce)$Symbol)
is.mito <-grepl("^MT-", rownames(sce))
table(is.mito) #check number of mito genes
sce <- addPerCellQC(sce, subsets=list(Mito=is.mito))
library(scuttle)
df <- perCellQCMetrics(sce, subsets=list(Mito=is.mito))
summary(df$sum)
reasons <- perCellQCFilters(df,sub.fields="subsets_Mito_percent")
summary(reasons$discard)
sce$discard <- reasons$discard
```
# Violin Plots for QC
```{r}
library(scater)
gridExtra::grid.arrange(
plotColData(sce, y="sum", colour_by="discard") + scale_y_log10() + ggtitle("Total count"),
plotColData(sce, y="detected", colour_by="discard")
+scale_y_log10() + ggtitle("Detected features"),
plotColData(sce, y="subsets_Mito_percent", colour_by="discard")
+ ggtitle("High Mito"),
ncol=3
)
```
### are we happy with the proposed discarded cells?
```{r}
#if yes, let's remove them
sce <- sce[,!reasons$discard]
```
---
# Normalization
Counts depend on sequencing depth.
We estimate size factors estimation by deconvolution and perform log transformation + library size
```{r}
sce <- computeSumFactors(sce)
sce <- logNormCounts(sce)
```
Check size factors:
```{r}
summary(sizeFactors(sce))
```
---
# Variance Modeling and Feature Selection
We expect most of the variation in gene expression between cells to be technical, driven in particular by sampling noise. Given the effect of sampling noise, we expect a relation between variance and mean, we model the trend to identify genes with bona fide biological variation
```{r}
dec <- modelGeneVar(sce)
fit.default <- metadata(dec)
plot(dec$mean,
dec$total,
pch=16,
cex=0.5,
xlab="Mean expression",
ylab="Total variance",
main="Mean-Variance Plot")
curve(fit.default$trend(x), col="dodgerblue", add=TRUE, lwd=2)
```
Select highly variable genes:
```{r}
hvg <- getTopHVGs(dec, n=2000)
```
# Doublet identification
a single droplet may erroneously capture more than one cell; these are called _doublets_. There are some statistical methods that can be used
To try and detect the doublets, we can use statistical algorithms, many of which are implemented in the `scDblFinder` package. We will focus on one technique that uses simulations to identify droplets that are likely to contain more than one cell.
```{r}
dbl.dens <- computeDoubletDensity(sce, subset.row=hvg,
d=ncol(reducedDim(sce)))
sce$DoubletScore <- dbl.dens
summary(dbl.dens)
```
The function `computeDoubletDensity` identifies potential doublet cells based on the local density of simulated doublet expression profiles.
```{r}
#quickly run UMAP to identify doublets (not the "final" UMAP)
sce <- runUMAP(sce)
plotUMAP(sce, colour_by="DoubletScore")
```
We can define a threshold to identify putative doublets.
```{r}
dbl.calls <- doubletThresholding(data.frame(score=dbl.dens),
method="griffiths", returnType="call")
summary(dbl.calls)
```
And finally eliminate them from the dataset before continuing the analysis.
```{r}
sce <- sce[, dbl.calls == "singlet"]
sce
```
---
# PCA
Dimensionality reduction on selected features.
```{r}
sce <- runPCA(sce, subset_row=hvg)
```
For further analysis, we want to select a number of components which are informative and discard non informative PCs
```{r}
var_explained <- attr(reducedDim(sce, "PCA"), "percentVar")
plot(var_explained,
type="b",
xlab="PC",
ylab="Percent variance explained",
main="Elbow Plot")
```
# Decide:
How many PCs should we retain?
```{r}
n_pcs <- # FILL
set.seed(1001010)
sce <- runUMAP(sce, dimred="PCA", ncomponents= "fill", n_dimred=n_pcs)
```
# Clustering and marker detection
We cluster with Louvain clustering
```{r}
clusters <- clusterRows(reducedDim(sce, "PCA"), NNGraphParam(cluster.fun="louvain",cluster.args=list(resolution=0.2)))
sce$cluster <- factor(clusters)
```
Visualize:
```{r}
plotUMAP(sce, colour_by="cluster")
```
```{r}
markers <- findMarkers(sce, sce$cluster)
head(markers[[1]])
```
We can for instance extract the top 15 genes from each comparison to use as cluster-specific markers.
```{r}
mm <- unique(unlist(lapply(markers, function(x) rownames(x)[1:15])))
plotGroupedHeatmap(sce, features=mm, group="cluster", center=TRUE)
```
#### at this point you extract top 20 marker genes per cluster and check for pathway enrichment using online tools such as EnrichR or Chatgpt. try out multiple cluster
# Cell Type Annotation with SingleR
We use reference PBMC data.
```{r}
ref <- HumanPrimaryCellAtlasData()
pred <- SingleR(test=sce,
ref=ref,
labels=ref$label.main)
sce$celltype <- pred$labels
```
Plot annotation:
```{r}
plotUMAP(sce, colour_by="celltype")
```
save R object
```{r}
saveRDS(sce,"sceD1.rds")
```
#end of Day 1
On the second day, the students will first make their own .rmd scripts to analyse 2 other samples then the 3 samples will be combined and further analysis will be performed on the combined dataset.
# data integration
once you have generated multiple sce, you want to integrate the data of the 3 samples
```{r}
# keep only common genes
common_genes <- Reduce(intersect,list(rownames(sce1),rownames(sce2),rownames(sce3)))
sce1 <- sce1[common_genes, ]
sce2 <- sce2[common_genes, ]
sce3 <- sce3[common_genes, ]
# rescale each sample to make the 3 comparable
sce.list <- multiBatchNorm(sce1, sce2, sce3)
sce.list[[1]]$donor <- "D1"
sce.list[[2]]$donor <- "D2"
sce.list[[3]]$donor <- "D3"
sce.combined <- do.call(cbind, sce.list)
table(sce.combined$donor)
```
# batch correction:
in order to perform a single coherent clustering we may need to create a corrected dimensional reduction which eliminate the sample effect.
```{r}
sce.mnn <- fastMNN(sce.list)
reducedDim(sce.mnn, "corrected")
reducedDim(sce.combined, "MNN") <- reducedDim(sce.mnn, "corrected")
# we perform a UMAP using the corrected dimentionality reduction and check whether the donor effect is corrected.
sce.combined <- runUMAP(
sce.combined,
dimred = "MNN"
)
plotUMAP(sce.combined, colour_by = "donor")
```
# Create Pseudobulk Counts
cells are not biological replicates, statistical tools to study differential gene expression between populations
```{r}
table(sce$donor)
```
Aggregate by donor and cell type:
```{r}
pseudo <- aggregateAcrossCells(
sce,
ids=DataFrame(donor=sce$donor,
celltype=sce$celltype)
)
```
---
#. Differential Expression with DESeq2
We compare two conditions (fill appropriately).
```{r}
dds <- DESeqDataSetFromMatrix(
countData=assay(pseudo, "counts"),
colData=colData(pseudo),
design=~ condition
)
dds <- DESeq(dds)
res <- results(dds)
```
Inspect:
```{r}
head(res[order(res$padj), ])
```