-
Notifications
You must be signed in to change notification settings - Fork 2
/
scDataAnalysis_Utilities.R
2555 lines (1887 loc) · 87.8 KB
/
scDataAnalysis_Utilities.R
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## list of functions ####
library(data.table)
library(Matrix)
library(compiler)
library(magrittr)
library(Seurat)
#library(DropletUtils)
#library(cicero)
#library(cisTopic)
#library(ggpubr)
library(ggplot2)
library(RColorBrewer)
library(heatmaply)
library(DoubletFinder)
library(clusterProfiler)
library(reldist)
#library(MatrixModels)
#library(scABC)
#library(preprocessCore)
library(chromVAR)
library(motifmatchr)
library(SummarizedExperiment)
library(BiocParallel)
#library(JASPAR2016)
# for clustering and/or validation
#library(cluster)
#library(factoextra)
library(fpc)
library(mclust)
library(patchwork)
## **** note: for cluster validation, check: ***** ##
## **** http://www.sthda.com/english/wiki/wiki.php?id_contents=7952 ***##
rebin_matrix2Bin <- function(mtx, resl = 100 * 1000){
# mtx: matrix wiht rownames as chr-start-end and
# colnames as cell names
rnames = rownames(mtx)
mtx_chr = sapply(rnames, function(x) unlist(strsplit(x, '-'))[1])
chrs = unique(mtx_chr)
starts = as.numeric(sapply(rnames, function(x) unlist(strsplit(x, '-'))[2]))
ends = as.numeric(sapply(rnames, function(x) unlist(strsplit(x, '-'))[3]))
rebin_mat = NULL
for(chr0 in chrs){
mtx0 = mtx[mtx_chr == chr0, ]
mtx0 = as.data.table(mtx0)
mtx0$start = starts[mtx_chr == chr0]
mtx0$end = ends[mtx_chr == chr0]
mtx0[, 'id' := ceiling((start+ end)/resl/2)]
mtx0[, 'bin_id' := paste0(chr0, '-', id)]
mtx0[, c('start', 'end', 'id') := NULL]
rebin_mat = rbind(rebin_mat, mtx0)
}
rebin_mat = data.table(rebin_mat)
setkey(rebin_mat, bin_id)
new_mat = rebin_mat[, lapply(.SD, sum), by = bin_id]
new_mat = new_mat[complete.cases(new_mat)]
feature.names = new_mat$bin_id
new_mat[, 'bin_id' := NULL]
new_mat = as.matrix(new_mat)
new_mat = as(new_mat, "sparseMatrix")
rownames(new_mat) = feature.names
return(new_mat)
}
rebin_matrix2Bin = cmpfun(rebin_matrix2Bin)
## given a matrix list, cbind them using the union set of features
cBind_union_features <- function(mat_list){
ff = rownames(mat_list[[1]])
for(i in 2:length(mat_list)){
ff = unique(union(ff, rownames(mat_list[[i]])))
}
## make a mtx with full features
mat_union = list()
for(i in 1:length(mat_list)){
mtx0 = mat_list[[i]]
ff0 = setdiff(ff, rownames(mtx0))
if(length(ff0) > 0 ) {
tmp = as(matrix(0, length(ff0), ncol(mtx0)), "sparseMatrix")
rownames(tmp) = ff0
}
tmp_mat = rbind(mtx0, tmp)
mat_union[[i]] = tmp_mat[order(rownames(tmp_mat)), ]
}
return(do.call('cbind', mat_union))
}
cBind_union_features = cmpfun(cBind_union_features)
# filtering of atac matrix
filterMat <- function(atac.mtx, minFrac_in_cell = 0.01, min_depth = 1000,
max_depth = 100000){
depth.cell = Matrix::colSums(atac.mtx)
atac.mtx = atac.mtx[, depth.cell > min_depth & depth.cell < max_depth]
frac.in.cell = Matrix::rowSums(atac.mtx > 0)
atac.mtx = atac.mtx[frac.in.cell > minFrac_in_cell, ]
return(atac.mtx)
}
# assign gene to nearest peak and mark a gene if its tss within the peak
assignGene2Peak <- function(mtx, gene_ann, trans_dist = 1e+05){
gene_ann[, 'tss' := ifelse(strand == '+', start, end)]
peaks = tidyr::separate(data.table(x=rownames(mtx)),
col = x,
into = c('chr', 'start', 'end'))
peaks$peak_name = rownames(mtx)
class(peaks$start) = 'integer'
class(peaks$end) = 'integer'
chrs = unique(peaks$chr)
peaks_ann = NULL
for(chr0 in chrs){
peaks0 = peaks[chr == chr0]
genes0 = gene_ann[chr == chr0]
peaks0[, 'id' := which.min(abs(genes0$tss - start/2 - end/2)), by = peak_name]
peaks0[, 'gene_name' := genes0[id, gene_name]]
peaks0[, 'dist0' := min(abs(genes0$tss - start/2 -end/2)), by = peak_name]
peaks0[, 'gene_name' := ifelse(dist0 > trans_dist, '', gene_name)]
peaks0$tss_name = ''
for(i in 1:nrow(peaks0)){
tss0 = genes0[tss <= (peaks0$end[i] + 1000) & tss >= (peaks0$start[i] - 1000)]
if(nrow(tss0) > 0 ) {
if(peaks0$gene_name[i] %in% tss0$gene_name) peaks0$gene_name[i] <- ''
peaks0$tss_name[i] = paste(paste0(unique(tss0$gene_name), '-Tss'),
collapse = ',')
}
}
peaks_ann = rbind(peaks_ann, peaks0)
}
peaks_ann[, 'id':= NULL]
peaks_ann[, 'dist0':= NULL]
peaks_ann[, 'peak_new_name' := ifelse(!is.na(gene_name) & nchar(gene_name) > 1,
paste0(peak_name, ',', gene_name), peak_name)]
peaks_ann[, 'peak_new_name' := ifelse(!is.na(tss_name) & nchar(tss_name) > 1,
paste0(peak_new_name, ',', tss_name), peak_new_name)]
setkey(peaks_ann, peak_name)
rownames(mtx) = peaks_ann[rownames(mtx)]$peak_new_name
return(mtx)
}
# assign gene to nearest peak and mark a gene if its tss within the peak
# input peak_coords with chr-start-end, format
assignGene2Peak_coords <- function(peak_coords, gene_ann, trans_dist = 1e+05){
gene_ann[, 'tss' := ifelse(strand == '+', start, end)]
peaks = tidyr::separate(data.table(x = peak_coords),
col = x,
into = c('chr', 'start', 'end'))
peaks$peak_name = peak_coords
class(peaks$start) = 'integer'
class(peaks$end) = 'integer'
geneTssInPeak <- function(tss_ids, genes0){
if(!is.na(tss))
rr = genes0[tss <= end & tss >= start]$gene_name
return(paste(rr, collapse = ','))
}
chrs = unique(peaks$chr)
peaks_ann = NULL
for(chr0 in chrs){
peaks0 = peaks[chr == chr0]
genes0 = gene_ann[chr == chr0]
peaks0[, 'id' := which.min(abs(genes0$tss - start/2 - end/2)), by = 'peak_name']
peaks0[, 'gene_name' := genes0[id, gene_name]]
peaks0[, 'dist0' := min(abs(genes0$tss - start/2 -end/2)), by = peak_name]
peaks0[, 'gene_name' := ifelse(dist0 > trans_dist, '', gene_name)]
peaks0$tss_name = ''
for(i in 1:nrow(peaks0)){
tss0 = genes0[tss <= (peaks0$end[i] + 1000) & tss >= (peaks0$start[i] - 1000)]
if(nrow(tss0) > 0 ) {
if(peaks0$gene_name[i] %in% tss0$gene_name) peaks0$gene_name[i] <- ''
peaks0$tss_name[i] = paste(paste0(unique(tss0$gene_name), '-Tss'),
collapse = ',')
}
}
peaks_ann = rbind(peaks_ann, peaks0)
}
peaks_ann[, 'id':= NULL]
peaks_ann[, 'dist0':= NULL]
peaks_ann[, 'peak_new_name' := ifelse(!is.na(gene_name) & nchar(gene_name) > 1,
paste0(peak_name, ',', gene_name), peak_name)]
peaks_ann[, 'peak_new_name' := ifelse(!is.na(tss_name) & nchar(tss_name) > 1,
paste0(peak_new_name, ',', tss_name), peak_new_name)]
setkey(peaks_ann, peak_name)
return(peaks_ann[peak_coords, ]$peak_new_name)
}
regress_on_pca <- function(seurat.obj, reg.var = 'nCount_ATAC'){
pcs = seurat.obj@[email protected]
pcs.reg = pcs
for(i in 1:length(reg.var)){
reg.var0 = seurat.obj[[reg.var[i]]][[1]]
pcs.reg = apply(pcs.reg, 2, function(x) lm(x ~ reg.var0)$residual )
}
colnames(pcs.reg) = colnames(pcs)
seurat.obj@[email protected] = pcs.reg
return(seurat.obj)
}
# do normalization using log, tf-idf, or none, regress out confounds on pca or not
doBasicSeurat_atac <- function(mtx, npc = 50, top.variable = 0.2,
norm_by = c('log', 'tf-idf', 'none'),
doScale = T, doCenter = T, assay = 'ATAC',
reg.var = 'nCount_ATAC', regressOnPca = T,
project = 'scATAC'){
# top.variabl -- use top most variable features
seurat.obj = CreateSeuratObject(mtx, project = project, assay = assay,
names.delim = '-')
if(norm_by == 'log') seurat.obj@assays[[assay]]@data <- log1p(mtx) / log(2)
if(norm_by == 'tf-idf') seurat.obj@assays[[assay]]@data <- TF.IDF(mtx, verbose = F)
seurat.obj <- FindVariableFeatures(object = seurat.obj,
selection.method = 'vst',
nfeatures = floor(nrow(mtx) * top.variable))
if(regressOnPca){
reg.var0 = NULL
}else{
reg.var0 = reg.var
}
seurat.obj <- ScaleData(object = seurat.obj,
features = VariableFeatures(seurat.obj),
vars.to.regress = reg.var0, do.scale = doScale,
do.center = doCenter)
#seurat.obj <- RunPCA(object = seurat.obj,
# features = VariableFeatures(object = seurat.obj),
# verbose = FALSE, seed.use = 10, npc = npc)
seurat.obj <- RunPCA(object = seurat.obj,
features = VariableFeatures(object = seurat.obj),
verbose = FALSE, npc = npc)
if(length(reg.var) > 0 & regressOnPca) seurat.obj = regress_on_pca(seurat.obj, reg.var)
return(seurat.obj)
}
doBasicSeurat_atac = cmpfun(doBasicSeurat_atac)
# do normalization using log, tf-idf, or none, regress out confounds on pca or not
doBasicSeurat_atac_updated <- function(mtx, npc = 30, top.variable = 5000,
norm_by = c('log', 'tf-idf', 'none'),
doScale = T, doCenter = T, assay = 'ATAC',
reg.var = 'nCount_ATAC', regressOnPca = T,
project = 'scATAC', vap.min.frac = 0,
meta.data = NULL){
# top.variabl -- use top most variable features
seurat.obj = CreateSeuratObject(mtx, project = project, assay = assay,
names.delim = '-',
meta.data = meta.data)
if(norm_by == 'log') seurat.obj@assays[[assay]]@data <- log1p(mtx) / log(2)
if(norm_by == 'tf-idf') seurat.obj@assays[[assay]]@data <- TF.IDF(mtx, verbose = F)
nvap = ifelse(top.variable > 1, top.variable, floor(top.variable * ncol(mtx)))
seurat.obj <- FindVariableFeatures(object = seurat.obj,
selection.method = 'vst',
nfeatures = nvap)
vaps = VariableFeatures(seurat.obj)
peak.frac = rowMeans(mtx > 0)
excludePks.fromVAP = names(which(peak.frac < vap.min.frac))
vaps = setdiff(vaps, excludePks.fromVAP)
if(length(vaps) < 10) stop('Top few VAPs left!')
## redo normalization using vap
if(norm_by == 'tf-idf'){
mtx.norm = TF.IDF(mtx[vaps, ])
tmp <- mtx[setdiff(rownames(mtx), vaps), ]
data0 <- rbind(mtx.norm, tmp)
seurat.obj[[assay]]@data = data0[rownames(mtx), ]
rm(data0, tmp, mtx.norm)
}
if(regressOnPca){
reg.var0 = NULL
}else{
reg.var0 = reg.var
}
VariableFeatures(seurat.obj) <- vaps
seurat.obj <- ScaleData(object = seurat.obj,
features = vaps,
vars.to.regress = reg.var0, do.scale = doScale,
do.center = doCenter)
seurat.obj <- RunPCA(object = seurat.obj,
features = vaps,
verbose = FALSE, npc = npc)
if(length(reg.var) > 0 & regressOnPca) seurat.obj = regress_on_pca(seurat.obj, reg.var)
return(seurat.obj)
}
doBasicSeurat_atac_updated = cmpfun(doBasicSeurat_atac_updated)
# do normalization, pca using Seurat
doBasicSeurat_RNA <- function(mtx, npc = 50, top.variable = 0.2, pmito.upper = 0.2,
doScale = T, doCenter = T, min_nCount = 1500,
max_nCount = 15000, reg.var = 'nCount_RNA', sct=F,
mdata = NULL){
## top.variabl -- use top most variable features
# filter cells with high percentage of mitocondria genes
nCount = Matrix::colSums(mtx)
mtx = mtx[, nCount < max_nCount & nCount > min_nCount]
mito.features <- grep(pattern = "^MT-",
x = rownames(x = mtx), value = TRUE)
perc.mito = Matrix::colSums(mtx[mito.features, ])/Matrix::colSums(mtx)
mtx = mtx[, perc.mito <= pmito.upper]
perc.mito = perc.mito[perc.mito <= pmito.upper]
# create seurat object
if(!is.null(mdata)) mdata = mdata[colnames(mtx), ]
seurat.obj = CreateSeuratObject(mtx, project = 'scRNA', assay = 'RNA',
names.delim = '-', min.cells = 10, min.features = 100,
meta.data = mdata)
# add perc.mito to seurat objects
cnames = colnames(seurat.obj)
tmp.mito = data.table('perc' = perc.mito, 'cname' = names(perc.mito))
setkey(tmp.mito, cname)
[email protected][['perc.mito']] = tmp.mito[cnames]$perc
seurat.obj <- subset(x = seurat.obj, subset = (nFeature_RNA < 10000))
vegs = ifelse(top.variable > 1, top.variable, floor(nrow(mtx) * top.variable))
if(!sct){
seurat.obj <- NormalizeData(seurat.obj, normalization.method = 'LogNormalize',
scale.factor = 1e4)
seurat.obj <- FindVariableFeatures(object = seurat.obj,
selection.method = 'vst',
nfeatures = vegs)
seurat.obj <- ScaleData(object = seurat.obj,
features = VariableFeatures(seurat.obj),
vars.to.regress = reg.var,
do.scale = doScale, do.center = doCenter)
}else{
seurat.obj <- SCTransform(seurat.obj, vars.to.regress = reg.var, verbose = F,
variable.features.n = floor(nrow(mtx) * top.variable))
}
#seurat.obj <- RunPCA(object = seurat.obj,
# features = VariableFeatures(object = seurat.obj),
# verbose = FALSE, seed.use = 10, npc = npc)
seurat.obj <- RunPCA(object = seurat.obj,
features = VariableFeatures(object = seurat.obj),
verbose = FALSE, npc = npc)
return(seurat.obj)
}
doBasicSeurat_RNA = cmpfun(doBasicSeurat_RNA)
# Find doublets
FindDoublets <- function(seurat.rna, PCs = 1:50,
exp_rate = 0.02, sct = FALSE){
# sct--do SCTransform or not
## pK identification
sweep.res.list <- paramSweep_v3(seurat.rna, PCs = PCs, sct = sct)
sweep.stats <- summarizeSweep(sweep.res.list, GT = FALSE)
bcmvn <- find.pK(sweep.stats)
## Homotypic Doublet proportion Estimate
annotations <- [email protected]$seurat_clusters
homotypic.prop <- modelHomotypic(annotations) ## ex: annotations <- [email protected]$ClusteringResults
nExp_poi <- round(exp_rate * length(seurat.rna$seurat_clusters)) ## Assuming 7.5% doublet formation rate - tailor for your dataset
nExp_poi.adj <- round(nExp_poi*(1-homotypic.prop))
## Run DoubletFinder with varying classification stringencies
seurat.rna <- doubletFinder_v3(seurat.rna, PCs = PCs, pN = 0.25,
pK = 0.09, nExp = nExp_poi, reuse.pANN = FALSE,
sct = sct)
seurat.rna <- doubletFinder_v3(seurat.rna, PCs = PCs, pN = 0.25,
pK = 0.09, nExp = nExp_poi.adj,
reuse.pANN = paste0("pANN_0.25_0.09_", nExp_poi),
sct = sct)
doublet_var = paste0('DF.classifications_0.25_0.09_', nExp_poi.adj)
seurat.rna[['Doublet_Singlet']] = seurat.rna[[doublet_var]]
mnames = names([email protected])
[email protected][, grep(mnames, pattern = '0.25_0.09')] <- NULL
#seurat.rna = subset(seurat.rna, Doublet_Singlet == 'Singlet')
return(seurat.rna)
}
doSeurat_rmDoublets <- function(sampleID, exp_rate = 0.05, pmito.upper = 0.15,
min_nCount = 1500, max_nCount = 50000,
clusterOn = 'pca', npc = 50,
resolution = 0.5){
dir0 = '/mnt/isilon/tan_lab/chenc6/MLLr_Project/scRNA/CellRangerResults/June19_2019/'
sampleName = paste0('MLL_', sampleID, '_scRNA')
mtx = Read10X(paste0(dir0, sampleName, '/', sampleName, '/outs/filtered_feature_bc_matrix'))
colnames(mtx) = paste0(sampleID, '_', colnames(mtx))
# remove red blood cells
if('HBB' %in% rownames(mtx)){
hbb_exp = mtx['HBB', ]
mtx = mtx[, hbb_exp < 3]
}
##try remove doublets instead of manully filter cells with larger UMI
seurat.obj = doBasicSeurat_RNA(mtx, min_nCount = min_nCount, max_nCount = max_nCount,
npc = npc, pmito.upper = pmito.upper)
seurat.obj = FindNeighbors(seurat.obj, reduction = clusterOn, dims = 1:npc)
seurat.obj = FindClusters(seurat.obj, resolution = resolution)
seurat.obj = FindDoublets(seurat.obj, exp_rate = exp_rate)
seurat.obj = RunUMAP(seurat.obj, dims = 1:npc)
p1 <- DimPlot(seurat.obj, reduction = 'umap',
group.by = 'Doublet_Singlet') + ggtitle('With Doublets')
## remove doublets and do PCA and clustering again
seurat.obj = subset(seurat.obj, Doublet_Singlet == 'Singlet')
seurat.obj = doBasicSeurat_RNA(seurat.obj@assays$RNA@counts,
min_nCount = min_nCount, max_nCount = max_nCount)
seurat.obj = RunUMAP(seurat.obj, dims = 1:npc)
seurat.obj = RunTSNE(seurat.obj, dims = 1:npc)
seurat.obj = FindNeighbors(seurat.obj, reduction = 'pca', dims = 1:npc)
seurat.obj = FindClusters(seurat.obj, resolution = resolution)
p2 <- DimPlot(seurat.obj, reduction = 'umap', label = T) + ggtitle('Doublets Removed')
## load to viscello
inputs = prepInput4Cello(mtx = seurat.obj@assays$RNA@counts,
seurat.obj = seurat.obj,
cello.name = sampleName,
assay = 'RNA',
extraDR = T, cluster_excluded = NULL)
# save inputs for future use
celloInputDir = paste0('Input4VisCello/', sampleName)
system(paste0('mkdir -p ', celloInputDir))
saveRDS(inputs$eset, file = paste0(celloInputDir, '/eset.rds'))
saveRDS(inputs$clist, file = paste0(celloInputDir, '/clist.rds'))
ggsave(CombinePlots(plots = list(p1, p2)), device = 'eps', width = 14,
height = 6, filename = paste0('Figures/scRNA/MLL_',
sampleID, '/', sampleName, '_umap_with_doublets.eps'))
saveRDS(seurat.obj, paste0('Seurat_Objects/scRNA/seurat_', sampleName, '_doubletRemoved.rds'))
return(seurat.obj)
}
##bcPrefix can be set as sampleName or ID
doSeurat_rmDoublets_dir <- function(filtered_mtx_dir, exp_rate = 0.05, pmito.upper = 0.15,
min_nCount = 1500, max_nCount = 50000,
clusterOn = 'pca', npc = 50,
resolution = 0.5, bcPrefix = 'pbmc',
savePlot = T){
mtx = Read10X(filtered_mtx_dir)
colnames(mtx) = paste0(bcPrefix, '_', colnames(mtx))
# remove red blood cells
if('HBB' %in% rownames(mtx)){
hbb_exp = mtx['HBB', ]
mtx = mtx[, hbb_exp < 3]
}
##try remove doublets instead of manully filter cells with larger UMI
seurat.obj = doBasicSeurat_RNA(mtx, min_nCount = min_nCount, max_nCount = max_nCount,
npc = npc, pmito.upper = pmito.upper)
seurat.obj = FindNeighbors(seurat.obj, reduction = clusterOn, dims = 1:npc)
seurat.obj = FindClusters(seurat.obj, resolution = resolution)
seurat.obj = FindDoublets(seurat.obj, exp_rate = exp_rate)
seurat.obj = RunUMAP(seurat.obj, dims = 1:npc)
p1 <- DimPlot(seurat.obj, reduction = 'umap',
group.by = 'Doublet_Singlet') + ggtitle('With Doublets')
## remove doublets and do PCA and clustering again
seurat.obj = subset(seurat.obj, Doublet_Singlet == 'Singlet')
seurat.obj = doBasicSeurat_RNA(seurat.obj@assays$RNA@counts,
min_nCount = min_nCount, max_nCount = max_nCount)
seurat.obj = RunUMAP(seurat.obj, dims = 1:npc)
seurat.obj = RunTSNE(seurat.obj, dims = 1:npc)
seurat.obj = FindNeighbors(seurat.obj, reduction = 'pca', dims = 1:npc)
seurat.obj = FindClusters(seurat.obj, resolution = resolution)
p2 <- DimPlot(seurat.obj, reduction = 'umap', label = T) +
ggtitle('Doublets Removed')
if(savePlot) ggsave(CombinePlots(plots = list(p1, p2)), device = 'eps', width = 14,
height = 6, filename = paste0('Figures/scRNA/', bcPrefix, '_umap_with_doublets.eps'))
seurat.obj$sample = bcPrefix
return(seurat.obj)
}
# basic seurat plot
basicSeuratPlot <- function(org.seurat.obj){
p1 <- VizDimLoadings(object = org.seurat.obj, dims = 1:2, nfeatures = 20)
p2 <- DimHeatmap(object = org.seurat.obj, dims = 1:6, cells = 100, balanced = TRUE)
p3 <- ElbowPlot(object = org.seurat.obj, ndims = 50)
mfeatures = names([email protected])
pfeatures = mfeatures[grepl(mfeatures, pattern = 'nCount_|mito')]
p4 <- VlnPlot(org.seurat.obj, pfeatures)
return(list(p1, p2, p3, p4))
}
## map gene to atac peak
gene2peak <- function(gene_set, peaks, gene_ann){
# should include tss information in gene_list
gene_list = gene_ann[gene_name %in% gene_set, ]
chrs = unique(gene_list$chr)
gene_new = NULL
peaks[, 'midP' := start/2 + end/2]
for(chr0 in chrs){
gene0 = gene_list[chr == chr0, ]
peaks0 = peaks[chr == chr0]
gene0[, 'peak_id' := which(tss >= peaks0$start & tss <= peaks0$end), by = gene_id]
gene0[, 'peak_id' := ifelse(is.na(peak_id), which.min(abs(tss - peaks0$midP)), peak_id), by = gene_name]
gene0[, 'peak' := peaks0[peak_id]$pos]
gene_new = rbind(gene_new, gene0)
}
return(gene_new)
}
read10X_ATAC <- function(dirt){
mtx_path <- paste0(dirt, "matrix.mtx")
feature_path <- paste0(dirt, "peaks.bed")
barcode_path <- paste0(dirt, "barcodes.tsv")
features <-readr::read_tsv(feature_path, col_names = F) %>% tidyr::unite(feature, sep = '-')
barcodes <- readr::read_tsv(barcode_path, col_names = F) %>% tidyr::unite(barcode)
mtx <- Matrix::readMM(mtx_path) %>%
magrittr::set_rownames(features$feature)%>%
magrittr::set_colnames(barcodes$barcode)
return(mtx)
}
read_mtx_scATACpro <- function(mtx_path){
#mtx_path <- paste0(dirt, "matrix.mtx")
mtx.dir = dirname(mtx_path)
feature_path <- paste0(mtx.dir, "/features.txt")
barcode_path <- paste0(mtx.dir, "/barcodes.txt")
features <- fread(feature_path, header = F)
barcodes <- fread(barcode_path, header = F)
mtx <- Matrix::readMM(mtx_path) %>%
magrittr::set_rownames(features$V1)%>%
magrittr::set_colnames(barcodes$V1)
return(mtx)
}
normalize_gene_activities.corrected <- function (activity_matrices, cell_num_genes)
{
if (!is.list(activity_matrices)) {
scores <- activity_matrices
normalization_df <- data.frame(cell = colnames(activity_matrices),
cell_group = 1)
}else {
scores <- do.call(cbind, activity_matrices)
normalization_df <- do.call(rbind, lapply(seq_along(activity_matrices),
function(x) {
data.frame(cell = colnames(activity_matrices[[x]]),
cell_group = rep(x, ncol(activity_matrices[[x]])))
}))
}
scores <- scores[Matrix::rowSums(scores) != 0, Matrix::colSums(scores) !=
0]
## correct by adding following lines
cell_num_genes = cell_num_genes[normalization_df$cell %in% colnames(scores)]
normalization_df = subset(normalization_df, cell %in% colnames(scores))
##
normalization_df$cell_group <- factor(normalization_df$cell_group)
normalization_df$total_activity <- Matrix::colSums(scores)
normalization_df$total_sites <- cell_num_genes[as.character(normalization_df$cell)]
if (!is.list(activity_matrices)) {
activity_model <- stats::lm(log(total_activity) ~ log(total_sites),
data = normalization_df)
} else {
activity_model <- stats::lm(log(total_activity) ~ log(total_sites) *
cell_group, data = normalization_df)
}
normalization_df$fitted_curve <- exp(as.vector(predict(activity_model,
type = "response")))
size_factors <- log(normalization_df$fitted_curve)/mean(log(normalization_df$fitted_curve))
size_factors <- Matrix::Diagonal(x = 1/size_factors)
row.names(size_factors) <- normalization_df$cell
colnames(size_factors) <- row.names(size_factors)
scores <- Matrix::t(size_factors %*% Matrix::t(scores))
scores@x <- pmin(1e+09, exp(scores@x) - 1)
sum_activity_scores <- Matrix::colSums(scores)
scale_factors <- Matrix::Diagonal(x = 1/sum_activity_scores)
row.names(scale_factors) <- normalization_df$cell
colnames(scale_factors) <- row.names(scale_factors)
scores <- Matrix::t(scale_factors %*% Matrix::t(scores))
if (!is.list(activity_matrices)) {
rn = row.names(activity_matrices)
cn = colnames(activity_matrices)
rn = rn[rn %in% row.names(scores)]
cn = cn[cn %in% colnames(scores)]
ret <- scores[rn, cn]
}
else {
ret <- lapply(activity_matrices, function(x) {
rn = row.names(x)
cn = colnames(x)
rn = rn[rn %in% row.names(x)]
cn = cn[cn %in% colnames(x)]
scores[rn, cn]
})
}
return(ret)
}
# do cicero given a Seurat object, output gene activity score
doCicero_gascore <- function(seurat.obj, reduction = 'umap', chr_sizes,
gene_ann, npc = 30, coaccess_thr = 0.25,
min_frac_cell = 0.01){
## gene_ann: the first four columns: chr, start, end, gene name
set.seed(2019)
library(cicero)
mtx = GetAssayData(seurat.obj, slot = 'counts')
mtx = 1*(mtx > 0)
## remove peaks that only appear in less than 0.5% of cells
rs = Matrix::rowMeans(mtx > 0)
mtx = mtx[rs > min_frac_cell, ]
# change rownames using _ to delimited
rnames = rownames(mtx)
new.rnames = sapply(rnames, function(x) unlist(strsplit(x, ','))[1])
new.rnames = sapply(new.rnames, function(x) gsub('-', '_', x))
rownames(mtx) <- new.rnames
#dt = reshape2::melt(as.matrix(mtx), value.name = 'Count')
#dt = dt[dt$Count > 0, ]
dt = mefa4::Melt(mtx)
rm(mtx)
names(dt) = c('Peak', 'Cell', 'Count')
dt$Cell = as.character(dt$Cell)
dt$Peak = as.character(dt$Peak)
input_cds <- make_atac_cds(dt, binarize = T)
rm(dt)
input_cds <- detectGenes(input_cds)
input_cds <- estimateSizeFactors(input_cds)
if(reduction == 'tsne') {
if(is.null(seurat.obj@reductions$tsne))
seurat.obj <- RunTSNE(seurat.obj, dims = 1:npc, check_duplicates = F)
redu.coords = seurat.obj@[email protected]
}
if(reduction == 'umap') {
if(is.null(seurat.obj@reductions$umap))
seurat.object <- RunUMAP(seurat.object, dims = 1:npc)
redu.coords = seurat.obj@[email protected]
}
#make the cell id consistet
cicero_cds <- make_cicero_cds(input_cds, reduced_coordinates = redu.coords)
## get connections
conns <- run_cicero(cicero_cds, chr_sizes)
## get cicero gene activity score
names(gene_ann)[4] <- "gene"
input_cds <- annotate_cds_by_site(input_cds, gene_ann)
# generate unnormalized gene activity matrix
unnorm_ga <- build_gene_activity_matrix(input_cds, conns)
# make a list of num_genes_expressed
num_genes <- pData(input_cds)$num_genes_expressed
names(num_genes) <- row.names(pData(input_cds))
# normalize
cicero_gene_activities <- normalize_gene_activities.corrected(unnorm_ga, num_genes)
# if you had two datasets to normalize, you would pass both:
# num_genes should then include all cells from both sets
#unnorm_ga2 <- unnorm_ga
#cicero_gene_activities <- normalize_gene_activities(list(unnorm_ga, unnorm_ga2), num_genes)
conns = data.table(conns)
conns = conns[coaccess > coaccess_thr, ]
res = list('conns' = conns, 'ga_score' = cicero_gene_activities)
return(res)
}
# do cicero given a Seurat object, just return the connection
doCicero_conn <- function(seurat.obj, reduction = 'tsne',
chr_sizes, npc = 30, coaccess_thr = 0.25,
min_frac_cell = 0.01){
## gene_ann: the first four columns: chr, start, end, gene name
set.seed(2019)
library(cicero)
mtx = GetAssayData(seurat.obj, slot = 'counts')
rs = Matrix::rowMeans(mtx > 0)
mtx = mtx[rs > min_frac_cell, ]
# change rownames using _ to delimited
rnames = rownames(mtx)
new.rnames = sapply(rnames, function(x) unlist(strsplit(x, ','))[1])
new.rnames = sapply(new.rnames, function(x) gsub('-', '_', x))
rownames(mtx) <- new.rnames
dt = mefa4::Melt(mtx)
rm(mtx)
names(dt) = c('Peak', 'Cell', 'Count')
dt$Cell = as.character(dt$Cell)
dt$Peak = as.character(dt$Peak)
input_cds <- make_atac_cds(dt, binarize = T)
rm(dt)
input_cds <- detectGenes(input_cds)
input_cds <- estimateSizeFactors(input_cds)
if(reduction == 'tsne') {
if(is.null(seurat.obj@reductions$tsne))
seurat.obj <- RunTSNE(seurat.obj, dims = 1:npc, check_duplicates = F)
redu.coords = seurat.obj@[email protected]
}
if(reduction == 'umap') {
if(is.null(seurat.obj@reductions$umap))
seurat.obj <- RunUMAP(seurat.obj, dims = 1:npc)
redu.coords = seurat.obj@[email protected]
}
#make the cell id consistet
cicero_cds <- make_cicero_cds(input_cds, reduced_coordinates = redu.coords)
## get connections
conns <- run_cicero(cicero_cds, chr_sizes)
conns = data.table(conns)
conns = conns[coaccess > coaccess_thr, ]
return(conns)
}
## query the resoltuion parameters given a seurat object and the number of clusters
## using binary seach
queryResolution4Seurat <- function(seurat.obj, k = 10, reduction = 'umap', npc = 20,
min_resl = 0.1, max_resl = 1, max_iter = 15, doPCA = F){
max.dim = ifelse(reduction == 'pca', npc, 2)
if(doPCA) {
seurat.obj <- RunPCA(seurat.obj, npcs = npc, verbose = F)
seurat.obj <- RunTSNE(seurat.obj, dims = 1:npc, verbose = F)
seurat.obj <- RunUMAP(seurat.obj, dims = 1:npc, verbose = F)
}
seurat.obj <- FindNeighbors(seurat.obj, reduction = reduction, verbose = F, dims = 1:max.dim)
tmp.cluster1 <- FindClusters(seurat.obj, resolution = min_resl)@active.ident
tmp.cluster2 <- FindClusters(seurat.obj, resolution = max_resl)@active.ident
len1 = length(levels(tmp.cluster1))
len2 = length(levels(tmp.cluster2))
k1 = k2 = 0
while(len1 > k ){
k1 = k1 + 1
message('min_resl too large, trying to divided it by 2')
min_resl = min_resl/2
tmp.cluster1 <- FindClusters(seurat.obj, resolution = min_resl)@active.ident
len1 = length(levels(tmp.cluster1))
if(k1 == 10) stop('Please specify a much smaller min_res')
}
while(len2 < k){
k2 = k2 + 1
message('max_resl too small, trying to multiply it by 2')
max_resl = max_resl * 2
tmp.cluster2 <- FindClusters(seurat.obj, resolution = max_resl)@active.ident
len2 = length(levels(tmp.cluster2))
if(k2 == 10) stop('Please specify a much bigger max_res')
}
if(len1 == k) {
return(min_resl)
}
if(len2 == k) {
return(max_resl)
}
# repeat in other case
i = 0
repeat{
i = i + 1
resl0 = min_resl/2 + max_resl/2
tmp.cluster <- FindClusters(seurat.obj, resolution = resl0)@active.ident
len = length(levels(tmp.cluster))
if(len == k){
return(resl0)
}
if(len < k){
min_resl = resl0
len1 = len
}
if(len > k){
max_resl = resl0
len2 = len
}
if(i == max_iter) break
}
return(resl0)
}
queryResolution4Seurat = cmpfun(queryResolution4Seurat)
## query the resoltuion parameters given a seurat object (transformed from cistopic object) and the number of clusters
## using binary seach
queryResolution4Topic <- function(seurat.obj, k = 10, min_resl = 0.1, max_resl = 1, max_iter = 15){
# skip find neighbors
tmp.cluster1 <- FindClusters(seurat.obj, resolution = min_resl, graph.name = 'snn')@active.ident
tmp.cluster2 <- FindClusters(seurat.obj, resolution = max_resl, graph.name = 'snn')@active.ident
len1 = length(levels(tmp.cluster1))
len2 = length(levels(tmp.cluster2))
k1 = k2 = 0
while(len1 > k ){
k1 = k1 + 1
message('min_resl too large, trying to divided it by 2')
min_resl = min_resl/2
tmp.cluster1 <- FindClusters(seurat.obj, resolution = min_resl, graph.name = 'snn')@active.ident
len1 = length(levels(tmp.cluster1))
if(k1 == 10) stop('Please specify a much smaller min_res')
}
while(len2 < k){
k2 = k2 + 1
message('max_resl too small, trying to multiply it by 2')
max_resl = max_resl * 2
tmp.cluster2 <- FindClusters(seurat.obj, resolution = max_resl, graph.name = 'snn')@active.ident
len2 = length(levels(tmp.cluster2))
if(k2 == 10) stop('Please specify a much bigger max_res')
}
if(len1 == k) {
return(min_resl)
}
if(len2 == k) {
return(max_resl)
}
# repeat in other case
i = 0
repeat{
i = i + 1
resl0 = min_resl/2 + max_resl/2
tmp.cluster <- FindClusters(seurat.obj, resolution = resl0, graph.name = 'snn')@active.ident
len = length(levels(tmp.cluster))
if(len == k){
return(resl0)
}
if(len < k){
min_resl = resl0
len1 = len
}
if(len > k){
max_resl = resl0
len2 = len
}
if(i == max_iter) break
}
return(resl0)
}
queryResolution4Topic = cmpfun(queryResolution4Topic)
# fit cistopic model and using the predicted cell * topic probability matrix
# for clustering
run_cisTopic <- function(mtx, nCores = 4, frac_in_cell = 0.025){
library(cisTopic)
# prepare the right format of rownames
rnames = data.table('region' = rownames(mtx))
tmp = tidyr::separate(rnames, col = 'region', into = c('chr', 'start', 'end'))
rnames = paste0(tmp$chr, ':', tmp$start, '-', tmp$end)
rownames(mtx) = rnames
mtx0 = 1 * (mtx > 0)
rr = Matrix::rowMeans(mtx0)
mtx = mtx[rr >= frac_in_cell, ]
cisTopicObject <- createcisTopicObject(mtx, project.name='scATAC')
rm(mtx, mtx0)