-
Notifications
You must be signed in to change notification settings - Fork 0
/
metacell_contruct.Rmd
198 lines (187 loc) · 8.66 KB
/
metacell_contruct.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
---
title: "Preprocessing of single-cell RNA samples from livers of healthy donors"
subtitle: "Data of MacParland et al. https://doi.org/10.1038/s41467-018-06318-7"
author: "Aram Safrastyan"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
toc: TRUE
code_folding: hide
number_sections: TRUE
---
<style type="text/css">
.main-container {
max-width: 1500px;
margin-left: auto;
margin-right: auto;
}
</style>
```{r global_options, echo = F}
knitr::opts_chunk$set(fig.path='markdown_results/')
```
# load libraries
***
```{r, message=F, warning=F}
#library(scWGCNA)
library(cowplot)
library(ggplot2)
library(dplyr)
library(Seurat)
library(DT)
library(tibble)
library(tidyr)
library(BiocParallel)
```
# Download the data (GSE115469)
***
```{bash download, message=F, warning=F}
#download the scRNA count matrix
mkdir -p ./scrna/data/raw/
wget -q -O - https://ftp.ncbi.nlm.nih.gov/geo/series/GSE115nnn/GSE115469/suppl/GSE115469_Data.csv.gz | gunzip -c > ./scrna/data/raw/scrna_countm.csv
#download the metadata
wget -q -O - https://ftp.ncbi.nlm.nih.gov/geo/series/GSE115nnn/GSE115469/suppl/GSE115469_CellClusterType.txt.gz | gunzip -c > ./scrna/data/raw/scrna_metadata_init.txt
```
# Data cleanup; normalization
***
```{r, message=F, warning=F, fig.width= 15, fig.height=8}
#set seed for reproducible UMAP calculations
set.seed(1)
#load data into Seurat
ref <- read.csv("./scrna/data/raw/scrna_countm.csv")
ref.txt <- read.delim("./scrna/data/raw/scrna_metadata_init.txt")
#merge cell subtypes
ref.txt$CellType<-ifelse(grepl("Hepatocyte",ref.txt$CellType),"Hepatocyte",ref.txt$CellType)
ref.txt$CellType<-ifelse(grepl("T_Cells",ref.txt$CellType),"T_Cells",ref.txt$CellType)
ref.txt$CellType<-ifelse(grepl("LSECs",ref.txt$CellType),"LSECs",ref.txt$CellType)
ref.txt$CellType<-ifelse(grepl("Macrophage",ref.txt$CellType),"Macrophage",ref.txt$CellType)
ref<-ref %>% column_to_rownames(., var = "X")
sobject <- CreateSeuratObject(ref)
sobject$cell_type<-ref.txt$CellType
#normalize and visualize the data
sobject <- NormalizeData(sobject)
sobject <- FindVariableFeatures(sobject)
sobject <- ScaleData(sobject)
sobject <- RunPCA(sobject, features = VariableFeatures(object = sobject))
sobject <- FindNeighbors(sobject)
sobject <- FindClusters(sobject)
sobject <- RunUMAP(sobject, features = VariableFeatures(object = sobject))
[email protected]$cell_type <-recode([email protected]$cell_type, Hepatocyte="Hepatocytes", T_Cells = "T cells", Macrophage="Macrophages", 'NK-like_Cells'="NK-like cells", Erythroid_Cells="Erythroid cells", Mature_B_Cells="Mature B cells", Plasma_Cells="Plasma cells", Portal_endothelial_Cells="Portal endothelial cells", Hepatic_Stellate_Cells="Hepatic stellate cells")
options(ggrepel.max.overlaps = Inf)
raw_sc_plot<-DimPlot(sobject, reduction = "umap", label = TRUE, repel = TRUE, label.size = 10, group.by = "cell_type", combine = TRUE) +
labs(title=paste0("UMAP plot of healthy liver single-cell dataset before metacell transformation", "\n", "(MacParland et al.)")) +
theme_classic(base_size = 24) +
theme(plot.title = element_text(color="black", size=26, face="bold", hjust = 0.5), legend.text=element_text(size=20)) +
guides(fill="none", colour = guide_legend(override.aes = list(size=10))) +
NoLegend()
plot(raw_sc_plot)
```
# Construct metacells
***
```{r, message=T, warning=T, fig.width= 15, fig.height=8}
[email protected] %>% dplyr::count(cell_type)
sobject$metacell_group <- as.character(sobject$cell_type)
#use predefined genes for cell cycle scoring
s.genes <- cc.genes.updated.2019$s.genes
g2m.genes <- cc.genes.updated.2019$g2m.genes
sobject <- CellCycleScoring(sobject, s.features = s.genes, g2m.features = g2m.genes, set.ident = TRUE)
[email protected] %>% dplyr::count(cell_type, Phase)
DimPlot(sobject, reduction = "umap", label = TRUE, repel = TRUE, group.by = c("cell_type", "Phase"))
#remove hepatic stellate cells due to low number
sobject<-subset(x = sobject, subset = cell_type!="Hepatic stellate cells")
#define the function from the package "scWGCNA"/"hdWGCNA"
construct_metacells <- function (seurat_obj, name = "agg", k = 50, reduction = "umap",
assay = "RNA", slot = "data")
{
reduced_coordinates <- as.data.frame(seurat_obj@reductions[[reduction]]@cell.embeddings)
nn_map <- FNN::knn.index(reduced_coordinates, k = (k - 1))
row.names(nn_map) <- row.names(reduced_coordinates)
nn_map <- cbind(nn_map, seq_len(nrow(nn_map)))
good_choices <- seq_len(nrow(nn_map))
choice <- sample(seq_len(length(good_choices)), size = 1,
replace = FALSE)
chosen <- good_choices[choice]
good_choices <- good_choices[good_choices != good_choices[choice]]
it <- 0
k2 <- k * 2
get_shared <- function(other, this_choice) {
k2 - length(union(cell_sample[other, ], this_choice))
}
while (length(good_choices) > 0 & it < 5000) {
it <- it + 1
choice <- sample(seq_len(length(good_choices)), size = 1,
replace = FALSE)
new_chosen <- c(chosen, good_choices[choice])
good_choices <- good_choices[good_choices != good_choices[choice]]
cell_sample <- nn_map[new_chosen, ]
others <- seq_len(nrow(cell_sample) - 1)
this_choice <- cell_sample[nrow(cell_sample), ]
shared <- sapply(others, get_shared, this_choice = this_choice)
if (max(shared) < 0.9 * k) {
chosen <- new_chosen
}
}
cell_sample <- nn_map[chosen, ]
combs <- combn(nrow(cell_sample), 2)
shared <- apply(combs, 2, function(x) {
k2 - length(unique(as.vector(cell_sample[x, ])))
})
message(paste0("Overlap QC metrics:\nCells per bin: ", k,
"\nMaximum shared cells bin-bin: ", max(shared), "\nMean shared cells bin-bin: ",
mean(shared), "\nMedian shared cells bin-bin: ", median(shared)))
if (mean(shared)/k > 0.1)
warning("On average, more than 10% of cells are shared between paired bins.")
exprs_old <- GetAssayData(seurat_obj, assay = assay, slot = slot)
mask <- sapply(seq_len(nrow(cell_sample)), function(x) seq_len(ncol(exprs_old)) %in%
cell_sample[x, , drop = FALSE])
mask <- Matrix::Matrix(mask)
new_exprs <- (exprs_old %*% mask)/k
colnames(new_exprs) <- paste0(name, "_", 1:ncol(new_exprs))
rownames(cell_sample) <- paste0(name, "_", 1:ncol(new_exprs))
colnames(cell_sample) <- paste0("knn_", 1:ncol(cell_sample))
seurat_aggr <- CreateSeuratObject(counts = new_exprs)
seurat_aggr
}
#construct metacells
seurat_list <- list()
for(group in unique(sobject$cell_type)){
print(group)
cur_seurat <- subset(sobject, cell_type == group)
#cur_seurat <- cur_seurat[genes.keep,]
k<-ifelse(ncol(cur_seurat@assays$RNA) <300, 8, 20)
cur_metacell_seurat <- construct_metacells(
cur_seurat, name=group,
k=k, reduction='umap',
assay='RNA', slot='data'
)
cur_metacell_seurat$cell_type <- as.character(unique(cur_seurat$cell_type))
seurat_list[[group]] <- cur_metacell_seurat
}
# merge all of the metacells objects
metacell_seurat <- merge(seurat_list[[1]], seurat_list[2:length(seurat_list)])
#size of metacell seurat file
dim(metacell_seurat)
#normalize and visualize the new data
metacell_seurat <- NormalizeData(metacell_seurat)
all.genes <- rownames(metacell_seurat)
metacell_seurat <- ScaleData(metacell_seurat, features = all.genes)
metacell_seurat <- FindVariableFeatures(metacell_seurat)
metacell_seurat <- RunPCA(metacell_seurat, features = VariableFeatures(object = metacell_seurat))
metacell_seurat <- FindNeighbors(metacell_seurat)
metacell_seurat <- FindClusters(metacell_seurat)
metacell_seurat <- RunUMAP(metacell_seurat, features = VariableFeatures(object = metacell_seurat))
options(ggrepel.max.overlaps = Inf)
[email protected]$cell_type<-recode([email protected]$cell_type, Hepatocyte="Hepatocytes", T_Cells = "T cells", Macrophage="Macrophages", 'NK-like_Cells'="NK-like cells", Erythroid_Cells="Erythroid cells", Mature_B_Cells="Mature B cells", Plasma_Cells="Plasma cells", Portal_endothelial_Cells="Portal endothelial cells")
metacell_plot<-DimPlot(metacell_seurat, reduction = "umap", label = TRUE, repel = TRUE, label.size = 10, group.by = "cell_type", combine = TRUE) +
labs(title=paste0("UMAP plot of healthy liver single-cell dataset after metacell transformation", "\n", "(MacParland et al.)")) +
theme_classic(base_size = 18) +
theme(plot.title = element_text(color="black", size=20, face="bold", hjust = 0.5), legend.text=element_text(size=20)) +
guides(fill="none", colour = guide_legend(override.aes = list(size=10))) +
NoLegend()
plot(metacell_plot)
dir.create("./scrna/data/input/")
save(raw_sc_plot, metacell_plot, file="./scrna/data/input/sc_plots.RData")
save(metacell_seurat, file="./scrna/data/input/sc_data.RData")
```
```{r}
sessionInfo()
```