-
Notifications
You must be signed in to change notification settings - Fork 0
/
customFunctions.R
2382 lines (1937 loc) · 101 KB
/
customFunctions.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
#!/usr/bin/Rscript
library(Seurat)
library(tidyverse)
library(clustree)
library(stringr)
library(DoubletFinder)
library(patchwork)
library(scales)
library(cowplot)
library(ggrepel)
library(colorspace)
library(DESeq2)
library(pheatmap)
library(RColorBrewer)
library(SeuratDisk)
library(SingleR)
library(viridis)
library(reshape)
library(lemon)
library(ggsankey)
library(msigdbr)
library(clusterProfiler)
library(slingshot)
library(ggpubr)
library(scRNAseq)
library(scuttle)
library(ape)
library(ggtree)
############ gg_color_hue ############
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
############ hsv2rgb ############
#taken from: https://datascienceconfidential.github.io/r/graphics/2017/11/23/soothing-pastel-colours-in-r.html
hsv2rgb <- function(x){
# convert an hsv colour to rgb
# input: a 3 x 1 matrix (same as output of rgb2hsv() function)
# output: vector of length 3 with values in [0,1]
# recover h, s, v values
h <- x[1,1]
s <- x[2,1]
v <- x[3,1]
# follow the algorithm from Wikipedia
C <- s*v
# in R, h takes values in [0,1] rather than [0, 360], so dividing by
# 60 degrees is the same as multiplying by six
hdash <- h*6
X <- C * (1 - abs(hdash %% 2 -1))
if (0 <= hdash & hdash <=1) RGB1 <- c(C, X, 0)
if (1 <= hdash & hdash <=2) RGB1 <- c(X, C, 0)
if (2 <= hdash & hdash <=3) RGB1 <- c(0, C, X)
if (3 <= hdash & hdash <=4) RGB1 <- c(0, X, C)
if (4 <= hdash & hdash <=5) RGB1 <- c(X, 0, C)
if (5 <= hdash & hdash <=6) RGB1 <- c(C, 0, X)
# the output is a vector of length 3. This is the most convenient
# format for using as the col argument in an R plotting function
RGB1 + (v-C)
}
############ pastellize ############
#taken from: https://datascienceconfidential.github.io/r/graphics/2017/11/23/soothing-pastel-colours-in-r.html
pastellize <- function(x, p){
# x is a colour
# p is a number in [0,1]
# p = 1 will give no pastellization
# convert hex or letter names to rgb
if (is.character(x)) x <- col2rgb(x)/255
# convert vector to rgb
if (is.numeric(x)) x <- matrix(x, nr=3)
col <- rgb2hsv(x, maxColorValue=1)
col[2,1] <- col[2,1]*p
col <- hsv2rgb(col)
# return in convenient format for plots
rgb(col[1], col[2], col[3])
}
############ load10x ############
load10x <- function(din = NULL, dout = NULL, outName = NULL, testQC = FALSE,
nFeature_RNA_high = 4500, nFeature_RNA_low = 200, nCount_RNA_high = 20000, nCount_RNA_low = 100, percent.mt_high = 10,
removeDubs = TRUE, removeRBC_pal = TRUE, pal_feats = NULL,
featPlots = c("PTPRC", "CD3E", "CD8A", "GZMA", "IL7R", "ANPEP", "FLT3", "DLA-DRA", "CD4", "MS4A1", "PPBP","HBM"), isolatePalRBC = FALSE){
if (testQC == FALSE){
print(paste0("The QC parameters are: nFeature_RNA < ", nFeature_RNA_high, " & nFeature_RNA > ", nFeature_RNA_low, " & percent.mt < ", percent.mt_high, " & nCount_RNA < ", nCount_RNA_high," & nCount_RNA > ", nCount_RNA_low, sep = ""))
}
fpath <- paste("./", din,"/", sep = "")
files <- list.files(path = fpath, pattern=NULL, all.files=FALSE,
full.names=F)
df.list <- list()
#foreach (infile = files, .combine = 'c') %dopar% {
for (infile in files) {
#set up df for export
if (removeRBC_pal == TRUE){
df <- data.frame(matrix(ncol = 4, nrow = 0))
colnames(df) <- c("Initial","Filtered","Platelet_rbc_rm","Singlets")
} else {
df <- data.frame(matrix(ncol = 3, nrow = 0))
colnames(df) <- c("Initial","Filtered","Singlets")
}
#set import path
pwd <- paste("./", din,"/", infile, sep = "")
#read 10X data
indata <- Read10X(pwd)
#create seurat object
seu_obj <- CreateSeuratObject(counts = indata,
project = infile,
min.cells = 3,
min.features = 200)
#Add mitochondrial QC data to seurat metadata
seu_obj[["percent.mt"]] <- PercentageFeatureSet(seu_obj, pattern = "^MT-")
seu_obj[["percent.hbm"]] <- PercentageFeatureSet(seu_obj, pattern = "HBM")
seu_obj[["percent.ppbp"]] <- PercentageFeatureSet(seu_obj, pattern = "PPBP")
if(!is.null(pal_feats)){
data <- lapply(pal_feats, function(x){PercentageFeatureSet(seu_obj, pattern = x)})
data <- as.data.frame(bind_cols(data))
seu_obj[["percent.pal"]] <- rowSums(data)
}
#visualize QC metrics as a violin plot
outfile <- paste("./",dout,"/", infile,"_QC_S1.png", sep = "")
p <- VlnPlot(seu_obj, features = c("nFeature_RNA", "nCount_RNA", "percent.mt"))
ggsave(outfile)
if (testQC == TRUE){
next
}
df[1,1] <- dim(seu_obj)[2]
#set QC cutoffs based on above plots ### MODIFY VALUES based on your data!! ###
seu_obj <- subset(seu_obj,
subset = nFeature_RNA < nFeature_RNA_high & nFeature_RNA > nFeature_RNA_low &
percent.mt < percent.mt_high & nCount_RNA < nCount_RNA_high & nCount_RNA > nCount_RNA_low
)
#next steps normalize, scale, and run UMAP
seu_obj <- NormalizeData(seu_obj,
normalization.method = "LogNormalize",
Scale.factor = 10000) ###change method to scran???
seu_obj <- FindVariableFeatures(seu_obj,
selection.method = "vst",
nfeatures = 2500) #can change number of feats used
all.genes <- rownames(seu_obj)
seu_obj <- ScaleData(seu_obj, features = all.genes)
seu_obj <- RunPCA(seu_obj, features = VariableFeatures(object = seu_obj))
seu_obj <- FindNeighbors(seu_obj,
dims = 1:10
) #can change dims
seu_obj <- FindClusters(seu_obj,
resolution = 0.1
) #can change resolution
seu_obj <- RunUMAP(seu_obj,
dims = 1:15
) #can change dims
#visulize UMAP featPlots
outfile <- paste("./",dout,"/", infile,"_featPlotDefault_S1.png", sep = "")
p <- FeaturePlot(seu_obj,features = featPlots)
ggsave(outfile, width = 12, height = 8)
#visulize UMAP
outfile <- paste("./",dout,"/", infile,"_uMAP_S1.png", sep = "")
p <- DimPlot(seu_obj, reduction = "umap")
ggsave(outfile)
#stash initial cluster IDs
seu_obj[["int.clusID"]] <- Idents(object = seu_obj)
df[1,2] <- dim(seu_obj)[2]
if (removeRBC_pal == TRUE){
#find the rbc cluster
if(length(AverageExpression(seu_obj, features = "HBM")) != 0){
rbc.df <- as.data.frame(AverageExpression(seu_obj, features = "HBM"), header = TRUE)
rbc.clus <- str_split(as.character(colnames(rbc.df)[max.col(rbc.df,ties.method="first")]),"[.]")[[1]][2]
sus.rbc.size <- as.numeric(length(WhichCells(seu_obj, expression = HBM > 0)))
sus.rbc.clus.size <- as.numeric(length(WhichCells(seu_obj, idents = rbc.clus )))
sus.rbc.comp.pct <- sus.rbc.size/sus.rbc.clus.size
rbc.clus <- ifelse(sus.rbc.comp.pct > 0.8, rbc.clus, "NULL")
print(rbc.clus)
} else{rbc.clus <- "NULL"}
#find the palelet cluster
if(length(AverageExpression(seu_obj, features = "PPBP")) != 0){
pal.df <- as.data.frame(AverageExpression(seu_obj, features = "PPBP"), header = TRUE)
pal.clus <- str_split(as.character(colnames(pal.df)[max.col(pal.df,ties.method="first")]),"[.]")[[1]][2]
sus.pal.size <- as.numeric(length(WhichCells(seu_obj, expression = PPBP > 0)))
sus.pal.clus.size <- as.numeric(length(WhichCells(seu_obj, idents = pal.clus )))
sus.pal.comp.pct <- sus.pal.size/sus.pal.clus.size
pal.clus <- ifelse(sus.pal.comp.pct > 0.8, pal.clus, "NULL")
print(pal.clus)
} else{pal.clus <- "NULL"}
if(rbc.clus != "NULL" | pal.clus != "NULL"){
if(isolatePalRBC == F){
seu_obj <- subset(seu_obj,
subset = int.clusID != pal.clus & int.clusID != rbc.clus)
}
else{
seu_obj <- subset(seu_obj,
subset = int.clusID == pal.clus | int.clusID == rbc.clus)
}
} else{print("No platelets of rbcs detected in sample!")}
df[1,3] <- dim(seu_obj)[2]
}
#next steps complete doublet identification using DoubletFinder
sweep.res.list_seu_obj <- paramSweep_v3(seu_obj, PCs = 1:10, sct = FALSE)
sweep.stats_seu_obj <- summarizeSweep(sweep.res.list_seu_obj, GT = FALSE)
bcmvn_seu_obj <- find.pK(sweep.stats_seu_obj)
pk_val <- as.numeric(as.character(bcmvn_seu_obj$pK[bcmvn_seu_obj$BCmetric == max(bcmvn_seu_obj$BCmetric)]))
annotations <- [email protected]$seurat_clusters
homotypic.prop <- modelHomotypic(annotations)
#determine expected doublet rate -- this formula assumes 0.5% doublet per 1000 cells (lower than 10x recommendation to account for homoypic doublets and cells removed during QC)
expceted_dub_rate <- dim(seu_obj)[2]/1000*0.5/100
nExp_poi <- round(expceted_dub_rate*length([email protected]$orig.ident)) ### MODIFY VALUE; should be percentage expected to be doublets based on 10X expected values ###
nExp_poi.adj <- round(nExp_poi*(1-homotypic.prop))
pN_value <- 0.25 ### MODIFY VALUE as needed ###
pANN_value <- paste0("pANN_",pN_value,"_",pk_val,'_',nExp_poi, sep = "")
seu_obj <- doubletFinder_v3(seu_obj, PCs = 1:10, pN = pN_value, pK = pk_val, nExp = nExp_poi, reuse.pANN = FALSE, sct = FALSE)
dfClass <- paste0("DF.classifications_",pN_value,"_",pk_val,'_',nExp_poi, sep = "")
dfmeta <- paste0("[email protected]$",dfClass, sep = "")
seu_obj[["doublet"]] <- eval(parse(text = dfmeta))
#export UMAP highlighting doublet vs singlet cells
outfile <- paste("./",dout,"/", infile,"_DF_S1.png", sep = "")
DimPlot(seu_obj,pt.size = 1,label=TRUE, label.size = 5,reduction = "umap",group.by = dfClass )
ggsave(outfile)
if (removeDubs == TRUE){
#remove putative doublets
seu_obj <- subset(seu_obj,
subset = doublet == "Singlet"
)
}
#update user
if (removeRBC_pal == TRUE){
df[1,4] <- dim(seu_obj)[2]
} else {df[1,3] <- dim(seu_obj)[2]
}
rownames(df) <- infile
df.list[[which(infile == files)]] <- df
#recluster the data with all unwanted cells removed
seu_obj <- RunPCA(seu_obj, features = VariableFeatures(object = seu_obj))
seu_obj <- FindNeighbors(seu_obj,
dims = 1:10
) #can change dims
seu_obj <- FindClusters(seu_obj,
resolution = 0.1
) #can change resolution
seu_obj <- RunUMAP(seu_obj,
dims = 1:15
) #can change dims
outfile <- paste("./",dout,"/", infile,"_featPlotDefault_postRBC_pal_rm_S1.png", sep = "")
p <- FeaturePlot(seu_obj,features = featPlots)
ggsave(outfile, width = 12, height = 8)
#export final umap
outfile <- paste("./",dout,"/", infile,"_uMAP_postRBC_pal_rm_S1.png", sep = "")
DimPlot(seu_obj, reduction = "umap")
ggsave(outfile)
#identify cycling cells
seu_obj <- CellCycleScoring(
object = seu_obj,
s.features = cc.genes.updated.2019$s.genes,
g2m.features = cc.genes.updated.2019$g2m.genes, set.ident = FALSE
)
#export UMAP with cycling data
outfile <- paste("./",dout,"/", infile,"_uMAP_cellCylce_postRBC_pal_rm_S1.png", sep = "")
DimPlot(seu_obj, reduction = "umap", group.by = "Phase")
ggsave(outfile)
#store cell cycle state
seu_obj[["clusters"]] <- Idents(object = seu_obj)
#export processed seurat object as an .RDS file
outfile <- paste("./",dout,"/", infile,"_S1.rds", sep = "")
saveRDS(seu_obj, file = outfile)
}
cellCounts <- do.call(rbind, df.list)
outfile <- paste("./",dout,"/", outName, "_cell_counts_S1.csv", sep = "")
write.csv(cellCounts, file = outfile)
}
############ sctIntegrate ############
sctIntegrate <- function(din = "", dout = "./output/", outName = "", vars.to.regress = c("percent.mt"), nfeatures = 2000,
featTOexclude = NULL, pattern = "S1.rds"
) {
#get seurat objects to process and integrate
fpath <- paste("./", din,"/", sep = "")
files <- list.files(path = fpath, pattern = pattern, all.files=FALSE,
full.names=TRUE)
create.seu.call <- function(x) {
readRDS(x)
}
#load all seurat objects and store in a large list
seu.obj <- mapply(create.seu.call, files)
#use SCT inegration to merge the samples
seu.obj <- lapply(seu.obj,
SCTransform,
vars.to.regress = vars.to.regress,
verbose = TRUE,
conserve.memory=TRUE)
SelectedFeatures <- SelectIntegrationFeatures(object.list = seu.obj,
nfeatures = nfeatures)
if(!is.null(featTOexclude)){
SelectedFeatures <- SelectedFeatures[!SelectedFeatures %in% featTOexclude]
if(nfeatures != length(SelectedFeatures)){
message <- paste("NOTE: ", featTOexclude, " was/were excluded from the variable features used in integration!",sep = "")
print(message)
SelectedFeatures <- SelectIntegrationFeatures(object.list = seu.obj,
nfeatures = nfeatures+(nfeatures-length(SelectedFeatures))
)
SelectedFeatures <- SelectedFeatures[!SelectedFeatures %in% featTOexclude]
}else{
message <- paste("NOTE: The features to exclude (", featTOexclude, ") was/were not included in the variable features used in integration, so the option was not used.",sep = "")
print(message)
}
}
seu.integrated <- PrepSCTIntegration(
object.list = seu.obj,
anchor.features = SelectedFeatures,
verbose = TRUE
)
gc()
seu.integrated.anchors <- FindIntegrationAnchors(
object.list = seu.integrated,
normalization.method = "SCT",
anchor.features = SelectedFeatures,
verbose = TRUE
)
#clean up environment a bit
rm(seu.integrated)
gc()
#integrate data and keep full gene set - still might not be retaining all genes
seu.integrated.obj <- IntegrateData(
anchorset = seu.integrated.anchors,
normalization.method = "SCT",
verbose = TRUE
)
#clean up environment a bit
rm(seu.integrated.anchors)
gc()
seu.integrated.obj <- RunPCA(seu.integrated.obj)
p <- ElbowPlot(seu.integrated.obj, ndims = 50)
outfile <- paste(dout, outName, "_seu.integrated.obj_S2_elbow.png", sep = "")
ggsave(outfile)
DefaultAssay(seu.integrated.obj) <- "integrated"
outfile <- paste(dout, outName, "_seu.integrated.obj_S2.rds", sep = "")
saveRDS(seu.integrated.obj, file = outfile)
}
############ clusTree ############
#uses too much ram if paralellized
clusTree <- function(seu.obj = NULL, dout = "./output/", outName = "", test_dims = c(50,45,40,35), algorithm = 3, resolution = c(0.01, 0.05, 0.1, seq(0.2, 2, 0.1)),
prefix = "integrated_snn_res."
) {
for (dimz in test_dims){
seu.test <- FindNeighbors(object = seu.obj, dims = 1:dimz)
seu.test <- FindClusters(object = seu.test, algorithm = algorithm, resolution = resolution)
p <- clustree::clustree(seu.test, prefix = prefix) + ggtitle(paste0("The number of dims used:", dimz, sep = ""))
outfile <- paste(dout,dimz ,"_clustree_", outName,".png", sep = "")
png(file = outfile, height = 1100, width = 2000)
print(p)
dev.off()
}
}
############ dataVisUMAP ############
dataVisUMAP <- function(file = NULL, seu.obj = NULL, outDir = "", outName = "", final.dims = NULL, final.res = NULL, stashID = "clusterID", returnFeats = T,
algorithm = 3, prefix = "integrated_snn_res.", min.dist = 0.6, n.neighbors = 75, assay = "integrated", saveRDS = T, return_obj = T,
features = c("PTPRC", "CD3E", "CD8A", "GZMA",
"IL7R", "ANPEP", "FLT3", "DLA-DRA",
"CD4", "MS4A1", "PPBP","HBM")
) {
if(!is.null(file)){
try(seu.integrated.obj <- readRDS(file), silent = T)
}else if(!is.null(seu.obj)){
seu.integrated.obj <- seu.obj
}
#perform clustering: Neighbor finding and resolution parameters
DefaultAssay(seu.integrated.obj ) <- assay
seu.integrated.obj <- FindNeighbors(object = seu.integrated.obj, dims = 1:final.dims)
seu.integrated.obj <- FindClusters(object = seu.integrated.obj, algorithm = algorithm, resolution = final.res)
#choose appropriate clustering resolution
res <- paste(prefix, final.res,sep = "")
seu.integrated.obj <- SetIdent(object = seu.integrated.obj, value = res)
# Run UMAP embedding
seu.integrated.obj <- RunUMAP(seu.integrated.obj,
dims = 1:final.dims,
min.dist = min.dist,
n.neighbors = n.neighbors
)
#save cluster number as "clusterID"
seu.integrated.obj[[stashID]] <- [email protected]
#build hierarchical clustering based on clustering results
DefaultAssay(seu.integrated.obj) <- "RNA"
seu.integrated.obj <- NormalizeData(seu.integrated.obj)
seu.integrated.obj <- BuildClusterTree(seu.integrated.obj, assay = "RNA", dims = 1:final.dims)
#export UMAP colored by sample ID and cluster
outfile <- paste(outDir, outName, "_res", final.res, "_dims", final.dims, "_dist",min.dist, "_neigh",n.neighbors, "_cluster_S3.png", sep = "")
p <- DimPlot(seu.integrated.obj, label = TRUE, reduction = "umap", group.by = stashID)
ggsave(outfile)
outfile <- paste(outDir, outName, "_res", final.res, "_dims", final.dims, "_dist",min.dist, "_neigh",n.neighbors, "_sample_S3.png", sep = "")
p <- DimPlot(seu.integrated.obj, reduction = "umap", group.by = "orig.ident")
ggsave(outfile)
if(returnFeats == T){
#visulize UMAP featPlots
outfile <- paste(outDir, outName, "_res", final.res, "_dims", final.dims, "_dist",min.dist, "_neigh",n.neighbors, "_featPlotDefault_S3.png", sep = "")
p <- FeaturePlot(seu.integrated.obj,features = features)
ggsave(outfile, width = 12, height = 8)
}
#stash identy by healthy vs OS & store as cellSource - add feature
#Idents(seu.integrated.obj) <- "orig.ident" #need to do smthg about this
#seu.integrated.obj$cellSource <- ifelse(grepl("ealthy", [email protected]$orig.ident), "Healthy", "Osteosarcoma")
#save seurat object as rds
if(saveRDS == T){
outfile <- paste(outDir, outName, "_res", final.res, "_dims", final.dims, "_dist",min.dist, "_neigh",n.neighbors,"_S3.rds", sep = "")
saveRDS(seu.integrated.obj, file = outfile)
}
if(return_obj == T){
return(seu.integrated.obj)
}
}
############ indReClus ############
#adopteed from final post on Dec 4, 2021 at https://github.com/satijalab/seurat/issues/1883
indReClus <- function(seu.obj = NULL, group.by = NULL, sub = NULL, outDir = "", subName = "", preSub = F, seu.list = NULL, featTOexclude = NULL, nfeatures = 2000, k = NULL, saveRDS = T, returnObj = T,ndims = 50,
vars.to.regress = "percent.mt", z = 30
) {
#print(paste0("The seurat object loaded: ", seu.obj, sep = ""))
#print(paste0("The seurat object will be subset on: ", sub, sep = ""))
print(paste0("The subclustered object will be output as: ", outDir, subName,"_S2.rds", sep = ""))
#read in data
if(preSub == F){
Idents(seu.obj) <- group.by
seu.sub <- subset(seu.obj, idents = sub)
}else{
seu.sub <- seu.obj
}
options(future.globals.maxSize = 100000 * 1024^2)
if(is.null(seu.list)){
seu.sub.list <- SplitObject(seu.sub, split.by = "orig.ident")
z <- table([email protected]$orig.ident)
print(z)
k <- ifelse(min(z)>100, 100, min(z))
print(k)
}else{
seu.sub.list <- seu.list
k <- ifelse(is.null(k),100,k)
print(k)
}
seu.obj <- lapply(seu.sub.list,
SCTransform,
vars.to.regress = vars.to.regress,
verbose = FALSE,
conserve.memory=TRUE)
SelectedFeatures <- SelectIntegrationFeatures(object.list = seu.obj,
nfeatures = nfeatures)
if(!is.null(featTOexclude)){
SelectedFeatures <- SelectedFeatures[!SelectedFeatures %in% featTOexclude]
if(nfeatures != length(SelectedFeatures)){
message <- paste("NOTE: ", featTOexclude, " was/were excluded from the variable features used in integration!",sep = "")
print(message)
SelectedFeatures <- SelectIntegrationFeatures(object.list = seu.obj,
nfeatures = nfeatures+(nfeatures-length(SelectedFeatures))
)
SelectedFeatures <- SelectedFeatures[!SelectedFeatures %in% featTOexclude]
}else{
message <- paste("NOTE: The features to exclude (", featTOexclude, ") was/were not included in the variable features used in integration, so the option was not used.",sep = "")
print(message)
}
}
seu.integrated <- PrepSCTIntegration(
object.list = seu.obj,
anchor.features = SelectedFeatures,
verbose = FALSE
)
gc()
seu.integrated.anchors <- FindIntegrationAnchors(
object.list = seu.integrated,
normalization.method = "SCT",
anchor.features = SelectedFeatures,
dims = 1:ifelse(min(z)>30, 30, min(z)-1),
k.filter = ifelse(min(z)>200, 200, min(z)-1),
k.score = ifelse(min(z)>30, 30, min(z)-1)
)
#clean up environment a bit
rm(seu.sub)
rm(seu.sub.list)
rm(seu.obj)
rm(seu.integrated)
gc()
#integrate data and keep full gene set - still might not be retaining all genes
seu.integrated.obj <- IntegrateData(
anchorset = seu.integrated.anchors,
normalization.method = "SCT",
k.weight = k,
verbose = FALSE
)
#clean up environment a bit
rm(seu.integrated.anchors)
gc()
seu.integrated.obj <- RunPCA(seu.integrated.obj)
outfile <- paste(outDir, subName,"_S2_elbow.png", sep = "")
p <- ElbowPlot(seu.integrated.obj, ndims = ndims)
ggsave(outfile)
DefaultAssay(seu.integrated.obj) <- "integrated"
if(saveRDS){
outfile <- paste(outDir, subName,"_S2.rds", sep = "")
saveRDS(seu.integrated.obj, file = outfile)
}
if(returnObj){
return(seu.integrated.obj)
}
}
############ prettyFeats ############
prettyFeats <- function(seu.obj = NULL, nrow = 3, ncol = NULL, features = "", color = "black", order = FALSE, titles = NULL, noLegend = F, bottomLeg = F, min.cutoff = NA, pt.size = NULL, title.size = 18, legJust = "bottom"
) {
DefaultAssay(seu.obj) <- "RNA"
features <- features[features %in% c(unlist(seu.obj@assays$RNA@counts@Dimnames[1]),unlist(colnames([email protected])))]
if(is.null(ncol)){
ncol = ceiling(sqrt(length(features)))
}
if(is.null(titles)){
titles <- features #- add if statement
}
#strip the plots of axis and modify titles and legend -- store as large list
plots <- Map(function(x,y,z) FeaturePlot(seu.obj,features = x, pt.size = pt.size, order = order, min.cutoff = min.cutoff) + labs(x = "UMAP1", y = "UMAP2") +
theme(axis.text= element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
axis.line = element_blank(),
title = element_text(size= title.size, colour = y),
legend.position = "none"
) +
scale_color_gradient(breaks = pretty_breaks(n = 3), limits = c(NA, NA), low = "lightgrey", high = "darkblue") +
ggtitle(z), x = features, y = color, z = titles)
asses <- ggplot() + labs(x = "UMAP1", y = "UMAP2") +
theme(axis.line = element_line(colour = "black",
arrow = arrow(angle = 30, length = unit(0.1, "inches"),
ends = "last", type = "closed"),
),
axis.title.y = element_text(colour = "black", size = 20),
axis.title.x = element_text(colour = "black", size = 20),
panel.border = element_blank(),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
if(!noLegend){
leg <- FeaturePlot(seu.obj,features = features[1], pt.size = 0.1) +
theme(legend.position = 'bottom',
legend.direction = 'vertical',
legend.justification = "center",
panel.border = element_blank(),
panel.background = element_rect(fill = "transparent",colour = NA),
plot.background = element_rect(fill = "transparent",colour = NA),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
) +
scale_color_gradient(breaks = pretty_breaks(n = 1), labels = c("low", "high"), limits = c(0,1), low = "lightgrey", high = "darkblue") +
guides(color = guide_colourbar(barwidth = 1))
if(bottomLeg){
leg <- leg + theme(legend.direction = 'horizontal') + guides(color = guide_colourbar(barwidth = 8))
}
legg <- get_legend(leg)
}
#nrow <- ceiling(length(plots)/ncol) - add if statement
patch <- area()
counter=0
for (i in 1:nrow) {
for (x in 1:ncol) {
counter = counter+1
if (counter <= length(plots)) {
patch <- append(patch, area(t = i, l = x, b = i, r = x))
}
}
}
if(!noLegend){
if(!bottomLeg){
legPos <- ifelse(legJust == "bottom",ceiling(length(features)/ncol),1)
patch <- append(patch, area(t = legPos, l = ncol+1, b = legPos, r = ncol+1))
}else{
patch <- append(patch, area(t = ceiling(length(features)/ncol)+1, l = ncol, b = ceiling(length(features)/ncol)+1, r = ncol))
}
}
p <- Reduce( `+`, plots ) +
{if(!noLegend){legg}} + plot_layout(guides = "collect") +
{if(!noLegend & bottomLeg){plot_layout(design = patch, heights = c(rep.int(1, nrow),0.2))}else if(!noLegend & !bottomLeg){plot_layout(design = patch, widths = c(rep.int(1, ncol),0.2))}else{plot_layout(design = patch, widths = rep.int(1, ncol))}}
return(p)
}
############ linDEG ############
#features to add
#error if more than 2 levels ORR make if so user specifies contrast
linDEG <- function(seu.obj = NULL, threshold = 1, thresLine = T, groupBy = "clusterID", comparision = "cellSource", outDir = "./output/", outName = "", cluster = NULL, labCutoff = 20,
colUp = "red", colDwn = "blue", subtitle = T, returnUpList = F, returnDwnList = F, forceReturn = F, useLineThreshold = F, pValCutoff = 0.01, flipLFC = F, saveGeneList = F, addLabs = ""
) {
#set active.ident
Idents(seu.obj) <- groupBy
#loop through active.ident to make plots for each group
lapply(if(is.null(cluster)){levels(seu.obj)}else{cluster}, function(x) {
seu.sub <- subset(seu.obj, idents = x)
[email protected][[groupBy]] <- droplevels([email protected][[groupBy]])
geneList <- vilnSplitComp(seu.obj = seu.sub, groupBy = groupBy, refVal = comparision, outDir = outDir, outName = outName,
saveOut = F, saveGeneList = saveGeneList, returnGeneList = T
)
geneList <- geneList[[1]]
geneList <- geneList[geneList$p_val_adj < pValCutoff,]
if(flipLFC){
geneList$avg_log2FC <- -geneList$avg_log2FC
}
geneList$gene <- rownames(geneList)
Idents(seu.sub) <- comparision
avg.seu.sub <- log1p(AverageExpression(seu.sub, verbose = FALSE)$RNA)
avg.seu.sub <- as.data.frame(avg.seu.sub)
avg.seu.sub <- avg.seu.sub[!grepl("ENSCAFG", row.names(avg.seu.sub)),] #make better
avg.seu.sub <- avg.seu.sub[!grepl("HBM", row.names(avg.seu.sub)),] #make better
colnames(avg.seu.sub) <- c("X","Y")
#calculate which points fall outside threshold, so they can be labled --- NEED TO FIX THIS....
if(!useLineThreshold){
avg.seu.sub <- avg.seu.sub %>% mutate(gene=rownames(avg.seu.sub)) %>%
left_join(geneList, by = "gene") %>%
mutate(direction=case_when(avg_log2FC > 0 ~ "up",
avg_log2FC < 0 ~ "dwn",
is.na(avg_log2FC) ~ "NA"),
residual=case_when(direction == "up" ~ abs(Y-X),
direction == "dwn" ~ abs(Y-X),
direction == "NA" ~ 0)) %>% arrange(desc(residual)) %>% group_by(direction) %>%
#arrange(p_val_adj) %>%
mutate(lab=ifelse(row_number() <= labCutoff
& direction != "NA"
& gene %in% rownames(geneList), gene, NA),
lab_col=case_when(direction == "up" ~ colUp,
direction == "dwn" ~ colDwn,
direction == "NA" ~ "black")
)
}else{
avg.seu.sub <- avg.seu.sub %>% mutate(gene=rownames(avg.seu.sub),
up=threshold+1*X,
dn=-threshold+1*X,
direction=case_when(Y > up ~ "up",
Y < dn ~ "dwn",
Y < up && Y > dn ~ "NA"),
residual=case_when(direction == "up" ~ Y-up,
direction == "dwn" ~ dn-Y,
direction == "NA" ~ 0),
) %>% group_by(direction) %>%
arrange(desc(residual)) %>%
mutate(lab=ifelse(row_number() <= labCutoff
& direction != "NA"
& gene %in% c(rownames(geneList),addLabs), gene, NA),
lab_col=case_when(direction == "up" ~ colUp,
direction == "dwn" ~ colDwn,
direction == "NA" ~ "black")
)
}
if(length(na.omit(avg.seu.sub$lab)) > 0 | forceReturn == T){
outfile <- paste(outDir,outName, "_", x,"_linear_deg_by_", groupBy,".png", sep = "")
p <- ggplot(data=avg.seu.sub, aes(x = X, y = Y, label=lab)) +
ggtitle(x,
if(subtitle == T) {subtitle = paste("Average gene expression (", levels(seu.sub)[2]," vs ", levels(seu.sub)[1],")", sep = "")}
#paste("Cluster",x, sep = " "),
) +
geom_point(color = avg.seu.sub$lab_col) +
labs(x = levels(seu.sub)[1], y = levels(seu.sub)[2]) +
{if(thresLine)geom_abline(intercept = threshold, slope = 1)} +
{if(thresLine)geom_abline(intercept = -threshold, slope = 1)} +
geom_label_repel(max.overlaps = Inf, size=5, color = avg.seu.sub$lab_col) +
theme_classic() +
theme(axis.title = element_text(size= 20),
axis.text = element_text(size= 14),
title = element_text(size= 24),
plot.subtitle = element_text(size= 14)
)
ggsave(outfile)
if(returnUpList){
up <- avg.seu.sub[avg.seu.sub$direction == "up",]
upList <- up$gene
return(upList)
}
if(returnDwnList){
dwn <- avg.seu.sub[avg.seu.sub$direction == "dwn",]
dwnList <- dwn$gene
return(dwnList)
}
}
})
}
############ formatUMAP ############
formatUMAP <- function(plot = NULL) {
pi <- plot + labs(x = "UMAP1", y = "UMAP2") +
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_text(size= 20),
plot.title = element_blank(),
title = element_text(size= 20),
axis.line = element_blank(),
panel.border = element_rect(color = "black",
fill = NA,
size = 2)
)
return(pi)
}
############ cusUMAP ############
#this function requires a UMAP plot gerneated using DimPlot with label = T, label.box = T
cusLabels <- function(plot = NULL, shape = 21, labCol = "black", size = 8, alpha = 1, rm.na = T, nudge_x = NULL, nudge_y = NULL
) {
pi <- formatUMAP(plot)
#extract label coords and colors
g <- ggplot_build(pi)
#pointData <- as.data.frame(g$data[[1]][!duplicated(g$data[[1]][,"colour"]),])
#rownames(pointData) <- NULL
#pointData$group <- pointData$group-1
#pointData$group <- as.factor(pointData$group)
labCords <- as.data.frame(g$data[2]) #add error if labels are not present
labCordz <- labCords[,c(1:4,7)]
colnames(labCordz) <- c("colour", "UMAP1", "UMAP2", "clusterID", "labCol")
# labCordz$clusterID <- as.character(labCordz$clusterID)
# labCordz$clusterID <- labCordz$clusterID-1
#labCordz <- left_join(labCordz, pointData[ , c("group", "colour")], by = c("clusterID" = "group"), keep = T)
labCordz <- labCordz[order(labCordz$clusterID),]
labCordz$labCol <- labCol
#rownames(labCordz) = seq(length=nrow(labCordz))
#labCordz$clusterID <- as.factor(sort(as.numeric(as.character(labCordz$clusterID))))
#labCordz <- labCordz[order(as.numeric(as.character(labCordz$clusterID))),]
if(rm.na == T){
labCordz <- na.omit(labCordz)
}
if(!is.null(nudge_x)){
labCordz$UMAP1 <- labCordz$UMAP1 + nudge_x
}
if(!is.null(nudge_y)){
labCordz$UMAP2 <- labCordz$UMAP2 + nudge_y
}
#rownames(labCordz) <- NULL
#remove old labels
pi$layers[2] <- NULL
#add labels to the stripped plot to create final image
plot <- pi + geom_point(data = labCordz, aes(x = UMAP1, y = UMAP2),
shape=shape,
size=size,
fill=labCordz$colour,
stroke=1,
alpha=alpha,
colour="black") +
geom_text(data = labCordz, size = 4, mapping = aes(x = UMAP1, y = UMAP2), label = labCordz$clusterID, color = labCordz$labCol)
return(plot)
}
############ freqPlots ############
#approach adopted from https://github.com/ajwilk/2020_Wilk_COVID (10.1038/s41591-020-0944-y)
freqPlots <- function(seu.obj = NULL, groupBy = "clusterID", refVal = "orig.ident", comp = "cellSource", colz = NULL, namez = NULL, method = 1, nrow = 3, title = F, legTitle = NULL, no_legend = F, showPval = T
) {
if(method == 1){
fq <- prop.table(table([email protected][[groupBy]], [email protected][,refVal]), 2) *100
df <- reshape2::melt(fq, value.name = "freq", varnames = c(groupBy,
refVal))
} else if(method == 2){
Idents(seu.obj) <- refVal
set.seed(12)
seu.sub <- subset(x = seu.obj, downsample = min(table([email protected][[refVal]])))
fq <- prop.table(table([email protected][[refVal]], [email protected][,groupBy]), 2) *100
df <- reshape2::melt(fq, value.name = "freq", varnames = c(refVal,
groupBy))
} else{print("Method is not recognized. Options are method = 1 (by sample) OR method = 2 (by cluster).")
break()
}
df <- df %>% left_join([email protected][ ,c(refVal,comp)][!duplicated([email protected][ ,c(refVal,comp)][,1]),], by = refVal)
#df <- df[grepl("\\b9\\b|12|28|33|41",df$clusterID),] #12 # add grep for only certain groupBy vals
#colnames(df) <- c("clusterID","orig.ident","freq","cellSource")
if(!is.null(colz)){
if(length(colz) == 1){
df <- df %>% left_join([email protected][ ,c(refVal,colz)][!duplicated([email protected][ ,c(refVal,colz)][,1]),], by = refVal)
warn1 <- F
}else{print("Warning: It is ideal if colors are stored in meta.data slot of the Seurat object. Colors may be mismatched.")
warn1 <- T
}
}else{warn1 <- F}
if(is.null(namez)){namez <- refVal}
if(ifelse(length(namez) > 1, "", namez) != refVal){
if(length(namez) == 1){
df <- df %>% left_join([email protected][ ,c(refVal,namez)][!duplicated([email protected][ ,c(refVal,namez)][,1]),], by = refVal)
warn2 <- F
}else{print("Warning: It is ideal if names are stored in meta.data slot of the Seurat object. Names may be mismatched.")
warn2 <- T
}
}else{warn2 <- F}
p <- ggplot(df, aes_string(y = "freq", x = comp)) +
labs(x = NULL, y = "Proportion (%)") +
theme_bw() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
strip.background = element_rect(fill = NA, color = NA),
strip.text = element_text(face = "bold"),
axis.ticks.x = element_blank(),
axis.text = element_text(color = "black") )
if(is.null(legTitle)){
legTitle <- refVal
}
#note these are not corrected p-values
pi <- p + facet_wrap(groupBy, scales = "free_y", nrow = nrow) +
guides(fill = "none") +
geom_boxplot(aes_string(x = comp), alpha = 0.25, outlier.color = NA) +
geom_point(size = 2, position = position_jitter(width = 0.25),
aes_string(x = comp, y = "freq", color = refVal)) +
labs(color = legTitle) +
{if(showPval){ggpubr::stat_compare_means(aes(label = paste0("p = ", ..p.format..)), label.x.npc = "left", label.y.npc = 1,vjust = -1, size = 3)}} +
scale_y_continuous(expand = expansion(mult = c(0.05, 0.2))) +
theme(panel.grid.major = element_line(color = "grey", size = 0.25),
#legend.position = "none",
text = element_text(size = 12)
) +
{if(!is.null(colz)){
scale_color_manual(labels = if(warn1){
namez
}else{
levels(df[[namez]])
},
values = if(warn2){
colz
}else{
levels(df[[colz]])
})}} + {if(no_legend == T){NoLegend()}}
return(pi)
}
############ vilnSplitComp ############
vilnSplitComp <- function(seu.obj = NULL, groupBy = "clusterID", refVal = "cellSource", outName = "", nPlots = 9, saveOut = T, saveGeneList = F, returnGeneList = F,
outDir = "./output/"
) {
DefaultAssay(seu.obj) <- "RNA"
[email protected]$cluster.condition <- paste([email protected][[groupBy]], [email protected][[refVal]], sep = "_")
ident.level <- levels([email protected][[groupBy]])
Idents(seu.obj) <- "cluster.condition"
p <- lapply(ident.level, function(x) {
comp1 <- paste(x, unique([email protected][[refVal]])[1], sep = "_") # need to improve this - what iff more than 2 groups?????
comp2 <- paste(x, unique([email protected][[refVal]])[2], sep = "_")
cluster.markers <- FindMarkers(seu.obj, ident.1 = comp1, ident.2 = comp2, min.pct = 0, logfc.threshold = 0.5)
if(saveGeneList){
outfile <- paste(outDir, outName,"_", x,"geneList.csv", sep = "")
write.csv(cluster.markers, file = outfile)
}
if(returnGeneList){