-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path02_Clustering_Annotation.rmd
More file actions
380 lines (305 loc) · 13.2 KB
/
02_Clustering_Annotation.rmd
File metadata and controls
380 lines (305 loc) · 13.2 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
---
title: "Visium post-QC clustering and cell type annotation"
author: "Harvard Chan Bioinformatics Core"
date: "`r Sys.Date()`"
output:
html_document:
code_folding: hide
df_print: paged
highlights: pygments
number_sections: false
self_contained: true
theme: default
toc: true
toc_float:
collapsed: true
smooth_scroll: true
params:
project_file: ./information.R
results_dir: ./results
visium_postQCF: "01_qc.RDS"
scrna_refF: "allen_scRNAseq_ref_subset.qs"
---
This code is in this  revision.
```{r versioncheck, cache = FALSE, message = FALSE, warning=FALSE}
library(rstudioapi)
setwd(fs::path_dir(getSourceEditorContext()$path))
stopifnot(R.version$major>= 4) # requires R4
if (compareVersion(R.version$minor,"3.1")<0) warning("We recommend >= R4.3.1")
stopifnot(compareVersion(as.character(BiocManager::version()), "3.18")>=0)
stopifnot(compareVersion(as.character(packageVersion("Seurat")), "5.1")>=0)
```
```{r load_libraries, cache = FALSE, message = FALSE, warning=FALSE, echo=FALSE,}
library(bcbioR)
library(knitr)
# analysis-specific package
library(Seurat)
library(SeuratWrappers)
library(Banksy)
library(quadprog)
library(spacexr)
# General data-wrangling
library(glue)
library(qs)
library(tidyverse)
# Plotting
library(patchwork)
library(ggprism)
import::from(magrittr,set_colnames,set_rownames,"%<>%")
invisible(list2env(params,environment()))
source(project_file)
ggplot2::theme_set(theme_prism(base_size = 12))
# https://grafify-vignettes.netlify.app/colour_palettes.html
# NOTE change colors here if you wish
scale_colour_discrete <- function(...)
scale_colour_manual(...,
values = as.vector(grafify:::graf_palettes[["kelly"]]))
scale_fill_discrete <- function(...)
scale_fill_manual(...,
values = as.vector(grafify:::graf_palettes[["kelly"]]))
opts_chunk[["set"]](
cache = F,
cache.lazy = FALSE,
dev = c("png", "pdf"),
error = TRUE,
highlight = TRUE,
message = FALSE,
prompt = FALSE,
tidy = FALSE,
warning = FALSE,
echo = T,
fig.height = 4)
# set seed for reproducibility
set.seed(1234567890L)
options(future.globals.maxSize= 2000000000)
inputRead <- function(f){
if(R.utils::isUrl(f)){f <- url(f)}
if(sum(endsWith(f,c("rds","RDS")))>0){
return(readRDS(f))
}else if(sum(endsWith(f,c("qs","QS")))>0){
return(qread(f))
}else{
print("Check file extension and choose appropriate functions!")
}
}
```
## Project details
- Project: `r project`
- PI: `r PI`
- Analyst: `r analyst`
- Experiment: `r experiment`
- Aim: `r aim`
In this template, we assume you have already run QC on your visium data:
- Remove genes that are contamination/poor quality-related (e.g. mitochondria or hemoglobin);
- Keep only cells that have all QC metrics passing the chosen thresholds
Now, we will move to the analysis of Visium data, we will perform:
- Normalization
- Unsupervised sketch clustering
- scRNA-seq data project
# Normalize Data
Normalization is important in order to make expression counts comparable across genes and/or sample. We note that the best normalization methods for spatial data are still being developed and evaluated. Here we use a standard log-normalization.
```{r normalize}
visiumHD_postQCobj <- inputRead(visium_postQCF)
assaytouse <- DefaultAssay(visiumHD_postQCobj)
message("Default assay: [",assaytouse,
"] used, please change it if another assay is of interest.")
object_filt <- NormalizeData(visiumHD_postQCobj, assay = assaytouse)
```
# Unsupervised Clustering
The authors of the `Seurat` package recommend the `Seurat` v5 **[sketch clustering](https://satijalab.org/seurat/articles/seurat5_sketch_analysis)** workflow because it exhibits improved performance, especially for identifying rare and spatially restricted groups.
Sketch-based analyses aim to "subsample" large datasets in a way that preserves rare populations. Here, we sketch the Visium HD dataset, perform clustering on the subsampled cells, and then project the cluster labels back to the full dataset.
```{r create sketch assay}
object_filt <- FindVariableFeatures(object_filt)
# we select 10,000 cells and create a new 'sketch' assay
object_filt <- SketchData(
object = object_filt,
assay = assaytouse,
ncells = 10000,
method = "LeverageScore",
sketched.assay = "sketch"
)
```
```{r perform sketched clustering}
# switch analysis to sketched cells
DefaultAssay(object_filt) <- "sketch"
# perform clustering workflow
object_filt <- FindVariableFeatures(object_filt)
object_filt <- ScaleData(object_filt)
object_filt <- RunPCA(object_filt, assay = "sketch", reduction.name = "pca.sketch")
# default first 50 PCs are used
object_filt <- FindNeighbors(object_filt, assay = "sketch",
reduction = "pca.sketch",
dims = 1:50)
# you may want to tweak resolution parameter in your own data
object_filt <- FindClusters(object_filt, cluster.name = "seurat_cluster.sketched",
resolution = .65)
# Use the same dimension of PCs for both FindNeighbors and run UMAP
object_filt <- RunUMAP(object_filt, reduction = "pca.sketch",
reduction.name = "umap.sketch", return.model = T,
dims = 1:50)
```
```{r project clusters}
object_filt <- ProjectData(
object = object_filt,
assay = assaytouse,
full.reduction = "full.pca.sketch",
sketched.assay = "sketch",
sketched.reduction = "pca.sketch",
umap.model = "umap.sketch",
dims = 1:50,
refdata = list(seurat_cluster.projected = "seurat_cluster.sketched")
)
```
```{r visualize clusters,fig.height = 5,fig.width = 10}
object_filt$seurat_cluster.projected <- object_filt$seurat_cluster.projected %>%
as.numeric %>% as.factor()
DefaultAssay(object_filt) <- "sketch"
Idents(object_filt) <- "seurat_cluster.sketched"
p1 <- DimPlot(object_filt, reduction = "umap.sketch", label = F, cols = 'polychrome') +
ggtitle("Sketched clustering") +
theme(legend.position = "bottom")+
guides(color = guide_legend(override.aes = list(size=4), ncol=5) )
# switch to full dataset
DefaultAssay(object_filt) <- assaytouse
Idents(object_filt) <- "seurat_cluster.projected"
p2 <- DimPlot(object_filt, reduction = "full.umap.sketch", label = F, raster = F,
cols = 'polychrome') +
ggtitle("Projected clustering") +
theme(legend.position = "bottom")+
guides(color = guide_legend(override.aes = list(size=4), ncol=5) )
p1 | p2
```
```{r visualize clusters on image}
color_pal = Seurat::DiscretePalette(n = length(unique(object_filt$seurat_cluster.projected)),
palette = "polychrome")
names(color_pal) <- sort(unique(object_filt$seurat_cluster.projected))
image_seurat_clusters <- SpatialDimPlot(object_filt,
group.by = 'seurat_cluster.projected',
pt.size.factor = 8, cols = color_pal) +
theme(legend.position = "bottom",legend.title=element_blank())+
guides(fill = guide_legend(override.aes = list(size=4,name=""), ncol=5) )
image_seurat_clusters
```
# Spatially-informed Clustering
BANKSY is another method for performing clustering.
Unlike Seurat, BANKSY takes into account not only an individual spot’s expression pattern but also the mean and the gradient of gene expression levels in a spot’s broader neighborhood. This makes it valuable for identifying and segmenting spatial tissue domains.
```{r run banksy}
# lambda: (numeric between 0-1) Spatial weight parameter
# k_geom: (integer) kNN parameter - number of neighbors to use, default is 15
# Please consider tweaking those two parameters based on your understanding of your data
object_filt <- RunBanksy(object_filt, lambda = 0.8, verbose = T,
assay = assaytouse, slot = 'data', k_geom = 50)
object_filt <- RunPCA(object_filt, assay = "BANKSY",
reduction.name = "pca.banksy",
features = rownames(object_filt),
npcs = 30)
object_filt <- FindNeighbors(object_filt,
reduction = "pca.banksy",
dims = 1:30)
# again, do not forget to try different resolutions
object_filt <- FindClusters(object_filt, cluster.name = "banksy_cluster",
resolution = 0.5)
```
```{r}
color_pal = Seurat::DiscretePalette(n = length(unique(object_filt$banksy_cluster)),
palette = "polychrome")
names(color_pal) <- sort(unique(object_filt$banksy_cluster))
image_banksy_clusters <- SpatialDimPlot(object_filt,
group.by = "banksy_cluster",
pt.size.factor = 7,
cols = color_pal)+
theme(legend.position = "bottom",legend.title=element_blank())+
guides(fill = guide_legend(override.aes = list(size=4,name=""), ncol=5) )
image_seurat_clusters | image_banksy_clusters
```
# Cell Type Annotation
Perhaps we are particularly interested in understanding the organization of cell types in the cortical region of the brain.
We first subset our Seurat object to this region of interest.
```{r}
# change the list of clusters to your interest regions based on previous clustering results
ROI <- subset(object_filt, seurat_cluster.projected %in% c(18, 19, 7, 2, 4))
color_pal = Seurat::DiscretePalette(n = length(unique(object_filt$seurat_cluster.projected)),
palette = "polychrome")
names(color_pal) <- sort(unique(object_filt$seurat_cluster.projected))
SpatialDimPlot(ROI, group.by = 'seurat_cluster.projected',
pt.size.factor = 8, cols = color_pal)+
theme(legend.position = "bottom",legend.title=element_blank())+
guides(fill = guide_legend(override.aes = list(size=4,name=""), ncol=5) )
```
To perform accurate annotation of cell types, we must also take into consideration that our 16 um spots may contain one or more cells each. The method Robust Cell Type Deconvolution (**RCTD**) has been shown to accurately annotate spatial data from a variety of technologies while taking into consideration that a single spot may exhibit multiple cell type profiles.
RCTD takes an scRNA-seq dataset as a reference and a spatial dataset as a query. For a reference, we use a subsampled version of the mouse scRNA-seq dataset from the Allen Brain Atlas. We use our cortex Seurat object as the spatial query. For computational efficiency, we sketch the spatial query dataset, apply RCTD to deconvolute the ‘sketched’ cortical cells and annotate them, and then project these annotations to the full cortical dataset.
```{r sketch cortex}
DefaultAssay(ROI) <- assaytouse
ROI <- FindVariableFeatures(ROI)
ROI <- SketchData(
object = ROI,
ncells = 3000,
method = "LeverageScore",
sketched.assay = "sketch"
)
DefaultAssay(ROI) <- "sketch"
ROI <- ScaleData(ROI)
ROI <- RunPCA(ROI, assay = "sketch", reduction.name = "pca.ROI.sketch", verbose = T)
ROI <- FindNeighbors(ROI, reduction = "pca.ROI.sketch", dims = 1:50)
ROI <- RunUMAP(ROI, reduction = "pca.ROI.sketch", reduction.name = "umap.ROI.sketch", return.model = T, dims = 1:50, verbose = T)
counts_hd <- ROI[["sketch"]]$counts
ROI_cells_hd <- colnames(ROI[["sketch"]])
coords <- GetTissueCoordinates(ROI)[ROI_cells_hd, 1:2]
# create the RCTD query object
query <- SpatialRNA(coords, counts_hd, colSums(counts_hd))
```
# Reference projection
```{r load ref, prep for RCTD}
ref_subset <- inputRead(scrna_refF)
# Check the label column you want to use from the scRNA-seq obs data
Idents(ref_subset) <- "subclass_label"
counts <- ref_subset[["RNA"]]$counts
cluster <- as.factor(ref_subset$subclass_label)
nUMI <- ref_subset$nCount_RNA
levels(cluster) <- gsub("/", "-", levels(cluster))
cluster <- droplevels(cluster)
# create the RCTD reference object
reference <- Reference(counts, cluster, nUMI)
```
```{r run RCTD}
RCTD <- create.RCTD(query, reference, max_cores = 6)
RCTD <- run.RCTD(RCTD, doublet_mode = "doublet") # this command takes ~15 mins to run
# add results back to Seurat object
ROI <- AddMetaData(ROI, metadata = RCTD@results$results_df)
```
```{r project to all cortical cells}
ROI$first_type <- as.character(ROI$first_type)
ROI$first_type[is.na(ROI$first_type)] <- "Unknown"
ROI <- ProjectData(
object = ROI,
assay = assaytouse,
full.reduction = "pca.ROI",
sketched.assay = "sketch",
sketched.reduction = "pca.ROI.sketch",
umap.model = "umap.ROI.sketch",
dims = 1:50,
refdata = list(full_first_type = "first_type")
)
```
We can see that the excitatory neurons are located in layers at varying cortical depths, as expected
```{r visualize labels}
Idents(ROI) <- "full_first_type"
cells <- CellsByIdentities(ROI)
# Layered (starts with L), excitatory neurons in the ROI
excitatory_names <- sort(grep("^L.* CTX", names(cells), value = TRUE))
SpatialDimPlot(ROI, cells.highlight = cells[excitatory_names],
cols.highlight = c("#FFFF00", "grey50"), facet.highlight = T,
combine = T, ncol = 4, pt.size.factor = 8)
```
## Methods
### Citation
```{r citations}
citation("Seurat")
citation("Banksy")
citation("quadprog")
citation("spacexr")
```
### Session Information
```{r}
sessionInfo()
```