-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanSEA_helper_20240913.R
2787 lines (2571 loc) · 130 KB
/
panSEA_helper_20240913.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
# Differential expression & enrichment analyses: global & phospho
# Author: Belinda B. Garana
# Created: 2023-12-06
# Last edit: 2024-04-25
library(readxl); library(panSEA); library(synapser)
library(stringr); library(tidyr)
library(dplyr); library(pheatmap); library(grid)
# get gmt information for GSEA relevant to Chr8
get_chr8_gmt1 <- function(gmt.list1 = c("msigdb_Homo sapiens_C2_CP:KEGG",
"msigdb_Homo sapiens_H",
"msigdb_Homo sapiens_C1",
"chr8_cancer_human"), min.per.set=6) {
if (file.exists("chr8_gmt1_run_contrasts_global_phospho_human.rds")) {
gmt1 <- readRDS("chr8_gmt1_run_contrasts_global_phospho_human.rds")
} else {
gmt1 <- list()
for (i in 1:length(gmt.list1)) {
if (is.character(gmt.list1[i])) {
if (grepl("msigdb", gmt.list1[i], ignore.case = TRUE)) {
gmt.info <- stringr::str_split(gmt.list1[i], "_")[[1]]
if (length(gmt.info) > 1) {
if (length(gmt.info) == 2) {
msigdb.info <- msigdbr::msigdbr(gmt.info[2])
} else if (length(gmt.info) == 3) {
msigdb.info <- msigdbr::msigdbr(gmt.info[2], gmt.info[3])
} else {
msigdb.info <- msigdbr::msigdbr(gmt.info[2], gmt.info[3], gmt.info[4])
}
# extract necessary info into data frame
msigdb.info <- as.data.frame(msigdb.info[, c(
"gene_symbol",
"gs_name",
"gs_description"
)])
gmt1[[i]] <- DMEA::as_gmt(
msigdb.info, "gene_symbol", "gs_name", min.per.set,
descriptions = "gs_description"
)
}
} else if (gmt.list1[i] == "chr8_cancer_human") {
msigdb.info <- msigdbr::msigdbr("Homo sapiens", "C1")
msigdb.info <- as.data.frame(msigdb.info[, c(
"gene_symbol",
"gs_name",
"gs_description"
)])
gmt <- DMEA::as_gmt(
msigdb.info, "gene_symbol", "gs_name", min.per.set,
descriptions = "gs_description"
)
Chr8.cancer.genes <- c("PLAG1", "CHCHD7", "SOX17", "TCEA1", "NCOA2", "TCEB1",
"HEY1", "RUNX1T1", "NBN", "CNBD1", "COX6C", "UBR5",
"RAD21", "EXT1", "MYC", "NDRG1", "EPPK1", "RECQL4")
gmt$genesets[[length(gmt$genesets)+1]] <- Chr8.cancer.genes
gmt$geneset.names[[length(gmt$geneset.names)+1]] <- "Chr8 cancer-associated genes"
gmt$geneset.descriptions[[length(gmt$geneset.descriptions)+1]] <- "Chr8 cancer-associated genes"
gmt1[[i]] <- gmt
}
} else {
gmt1[[i]] <- gmt.list1[[i]]
}
}
saveRDS(gmt1, "gmt1.rds")
}
return(gmt1)
}
# get gmt information for KSEA/SSEA relevant to chr8
get_chr8_gmt2 <- function() {
if (file.exists("chr8_gmt2_run_contrasts_global_phospho_human.rds")) {
gmt2 <- readRDS("chr8_gmt2_run_contrasts_global_phospho_human.rds")
} else {
stop("Chr8 gmt2 file not found in current directory")
}
saveRDS(gmt2, "gmt2.rds")
}
save_base_plot <- function(base.plot, filename, width = 7, height = 7) {
pdf(filename, width, height)
grid::grid.newpage()
grid::grid.draw(base.plot$gtable)
dev.off()
return()
}
# check if data frame is valid for hclust
filter_for_hclust <- function(expr.mat) {
if (nrow(expr.mat) > 1) {
validRows <- rowSums(is.na(expr.mat)) < (ncol(expr.mat)-1)
validCols <- colSums(is.na(expr.mat)) < (nrow(expr.mat)-1)
keep <- apply(dplyr::select_if(expr.mat, is.numeric), 1, function(x) length(unique(x[!is.na(x)])) != 1)
while (sum(keep, na.rm = TRUE) < nrow(expr.mat) |
sum(validRows, na.rm = TRUE) < nrow(expr.mat) |
sum(validCols, na.rm = TRUE) < ncol(expr.mat)) {
# remove invalid rows/columns
expr.mat <- expr.mat[validRows,] # require 2+ numeric values along rows
expr.mat <- expr.mat[,validCols] # require 2+ numeric values along columns
if(is.data.frame(expr.mat) & length(keep) > 0){
expr.mat <- expr.mat[keep,] # remove rows where all values are the same
# re-evaluate if there are any invalid rows/columns
validRows <- rowSums(is.na(expr.mat)) < (ncol(expr.mat)-1)
validCols <- colSums(is.na(expr.mat)) < (nrow(expr.mat)-1)
keep <- apply(dplyr::select_if(expr.mat, is.numeric), 1, function(x) length(unique(x[!is.na(x)])) != 1)
} else {
expr.mat <- data.frame()
return(expr.mat)
}
}
expr.mat <- as.data.frame(expr.mat[which(rowMeans(!is.na(expr.mat)) >= 0.5),]) # require at least 50% coverage for each feature
}
return(expr.mat)
}
## get expression of features from pathways of interest and heatmaps
get_pathways_of_interest <- function(expr.df, gsea.result, gmt, cc.df, n=5,
FDR = 0.25, p = 0.05, show_colnames = FALSE,
fontsize = 10, scale = TRUE, cluster = TRUE) {
# get top pathways of interest
sig.result <- gsea.result[gsea.result$FDR_q_value <= FDR &
gsea.result$p_value <= p,]
if (nrow(sig.result) > 0) {
top.pathways <- sig.result %>% slice_max(abs(NES), n = n)
top.gmt <- gmt$genesets[top.pathways$Feature_set]
poi.files <- try(R.utils::withTimeout(make_heatmaps(expr.df, cc.df, top.pathways, top.gmt, show_colnames,
fontsize, scale, cluster), timeout = 600, onTimeout="error"), silent = TRUE)
if (inherits(poi.files, "try-error")) {
poi.files <- list()
}
} else {
poi.files <- list()
}
return(poi.files)
}
make_heatmaps <- function(expr.df, cc.df, top.pathways = NULL, top.gmt, show_colnames = FALSE,
fontsize = 10, scale = TRUE, cluster = TRUE) {
expr.list <- list()
lead.list <- list()
my.clust.heatmaps <- list()
my.abs.heatmaps <- list()
my.clust.heatmaps.leads <- list()
my.abs.heatmaps.leads <- list()
for (i in 1:length(top.gmt)) {
# create heatmap names
clust.name <- file.path(paste0("Expression_of_", names(top.gmt)[i], "_heatmap_scaled.bp"))
abs.name <- file.path(paste0("Expression_of_", names(top.gmt)[i], "_heatmap_not_scaled.bp"))
clust.name.leads <- file.path(paste0("Expression_of_", names(top.gmt)[i], "_leading_edge_heatmap_scaled.bp"))
abs.name.leads <- file.path(paste0("Expression_of_", names(top.gmt)[i], "_leading_edge_heatmap_not_scaled.bp"))
# select numeric data
just.expr <- dplyr::select_if(expr.df, is.numeric)
# identify feature name
feature.name <- colnames(expr.df)[!(colnames(expr.df) %in% colnames(just.expr))]
# filter for gene set
temp.expr <- expr.df[expr.df[,feature.name] %in% top.gmt[[i]], ]
rownames(temp.expr) <- temp.expr[,feature.name]
expr.list[[names(top.gmt)[i]]] <- temp.expr
expr.mat <- dplyr::select_if(temp.expr, is.numeric)
expr.mat <- filter_for_hclust(expr.mat)
if (nrow(expr.mat) > 1) {
# create heatmaps
expr.mat <- as.matrix(expr.mat)
if (scale) {
my.clust.heatmaps[[clust.name]] <- pheatmap::pheatmap(expr.mat, color =
colorRampPalette(
c("navy", "white", "firebrick3"))(50),
cluster_rows = cluster, cluster_cols = cluster,
scale = "row", annotation_col = cc.df,
angle_col = "45",
show_colnames = show_colnames,
fontsize = fontsize)
}
my.abs.heatmaps[[abs.name]] <- pheatmap::pheatmap(expr.mat, color =
colorRampPalette(
c("navy", "white", "firebrick3"))(50),
cluster_rows = cluster, cluster_cols = cluster,
annotation_col = cc.df,
angle_col = "45",
show_colnames = show_colnames,
fontsize = fontsize)
# filter to leading edge features
if (!is.null(top.pathways)) {
temp.set <- names(top.gmt)[i]
temp.leads <- stringr::str_split(top.pathways[top.pathways$Feature_set == temp.set,]$Leading_edge, ", ")[[1]]
temp.expr.leads <- temp.expr[temp.leads,]
lead.list[[names(top.gmt)[i]]] <- temp.expr.leads
lead.mat <- dplyr::select_if(temp.expr.leads, is.numeric)
lead.mat <- filter_for_hclust(lead.mat)
if (nrow(lead.mat) > 1) {
# create heatmap
lead.mat <- as.matrix(lead.mat)
if (scale) {
my.clust.heatmaps.leads[[clust.name.leads]] <- pheatmap::pheatmap(lead.mat, color =
colorRampPalette(
c("navy", "white", "firebrick3"))(50),
cluster_rows = cluster, cluster_cols = cluster,
scale = "row", annotation_col = cc.df,
angle_col = "45",
show_colnames = show_colnames,
fontsize = fontsize)
}
my.abs.heatmaps.leads[[abs.name.leads]] <- pheatmap::pheatmap(lead.mat, color =
colorRampPalette(
c("navy", "white", "firebrick3"))(50),
cluster_rows = cluster, cluster_cols = cluster,
annotation_col = cc.df,
angle_col = "45",
show_colnames = show_colnames,
fontsize = fontsize)
}
}
}
}
all.expr.df <- data.table::rbindlist(expr.list, use.names = TRUE, idcol = "Feature_set")
all.leads.df <- data.table::rbindlist(lead.list, use.names = TRUE, idcol = "Feature_set")
lead.heatmaps <- list("Not_scaled" = my.abs.heatmaps.leads,
"Scaled" = my.clust.heatmaps.leads)
lead.files <- list("Expression_of_leading_edge_features.csv" =
all.leads.df,
"Heatmaps" = lead.heatmaps)
all.heatmaps <- list("Not_scaled" = my.abs.heatmaps,
"Scaled" = my.clust.heatmaps,
"Leading_edge_features_only" = lead.files)
poi.files <- list("Expression_of_pathways_of_interest.csv" =
all.expr.df,
"Heatmaps" = all.heatmaps)
return(poi.files)
}
## get gmt information for GSEA
get_gmt1 <- function(gmt.list1 = c("msigdb_Homo sapiens_C2_CP:KEGG",
"msigdb_Homo sapiens_H",
"msigdb_Homo sapiens_C1"), min.per.set=6) {
if (file.exists("gmt1.rds")) {
gmt1 <- readRDS("gmt1.rds")
} else {
if ("chr8" %in% gmt.list1) {
gmt1 <- get_chr8_gmt1(gmt.list1)
} else {
gmt1 <- list()
for (i in 1:length(gmt.list1)) {
if (is.character(gmt.list1[i])) {
if (grepl("msigdb", gmt.list1[i], ignore.case = TRUE)) {
gmt.info <- stringr::str_split(gmt.list1[i], "_")[[1]]
if (length(gmt.info) > 1) {
if (length(gmt.info) == 2) {
msigdb.info <- msigdbr::msigdbr(gmt.info[2])
} else if (length(gmt.info) == 3) {
msigdb.info <- msigdbr::msigdbr(gmt.info[2], gmt.info[3])
} else {
msigdb.info <- msigdbr::msigdbr(gmt.info[2], gmt.info[3], gmt.info[4])
}
# extract necessary info into data frame
msigdb.info <- as.data.frame(msigdb.info[, c(
"gene_symbol",
"gs_name",
"gs_description"
)])
gmt1[[i]] <- DMEA::as_gmt(
msigdb.info, "gene_symbol", "gs_name", min.per.set,
descriptions = "gs_description"
)
}
}
}else {
gmt1[[i]] <- gmt.list1[[i]]
}
}
}
}
saveRDS(gmt1, "gmt1.rds")
return(gmt1)
}
# uses more pathways
get_gmt1_v2 <- function(gmt.list1 = c("msigdb_Homo sapiens_C2_CP:KEGG",
"msigdb_Homo sapiens_H",
"msigdb_Homo sapiens_C1",
"msigdb_Homo sapiens_C3_TFT:GTRD",
"msigdb_Homo sapiens_C3_MIR:MIRDB",
"msigdb_Homo sapiens_C5_GO:BP",
"msigdb_Homo sapiens_C5_GO:CC",
"msigdb_Homo sapiens_C5_GO:MF",
"msigdb_Homo sapiens_C6",
"msigdb_Homo sapiens_C2_CP:BIOCARTA",
"msigdb_Homo sapiens_C2_CP:PID",
"msigdb_Homo sapiens_C2_CP:REACTOME",
"msigdb_Homo sapiens_C2_CP:WIKIPATHWAYS"),
names1 = c("KEGG", "Hallmark", "Positional", "TFT_GTRD",
"MIR_MIRDB", "GO_BP", "GO_CC", "GO_MF",
"Oncogenic_signatures", "BioCarta", "KEGG",
"PID", "Reactome", "WikiPathways"),
min.per.set=6) {
if (file.exists("gmt1.rds")) {
gmt1 <- readRDS("gmt1_more.rds")
} else {
if ("chr8" %in% gmt.list1) {
gmt1 <- get_chr8_gmt1(gmt.list1)
} else {
gmt1 <- list()
for (i in 1:length(gmt.list1)) {
if (is.character(gmt.list1[i])) {
if (grepl("msigdb", gmt.list1[i], ignore.case = TRUE)) {
gmt.info <- stringr::str_split(gmt.list1[i], "_")[[1]]
if (length(gmt.info) > 1) {
if (length(gmt.info) == 2) {
msigdb.info <- msigdbr::msigdbr(gmt.info[2])
} else if (length(gmt.info) == 3) {
msigdb.info <- msigdbr::msigdbr(gmt.info[2], gmt.info[3])
} else {
msigdb.info <- msigdbr::msigdbr(gmt.info[2], gmt.info[3], gmt.info[4])
}
# extract necessary info into data frame
msigdb.info <- as.data.frame(msigdb.info[, c(
"gene_symbol",
"gs_name",
"gs_description"
)])
gmt1[[i]] <- DMEA::as_gmt(
msigdb.info, "gene_symbol", "gs_name", min.per.set,
descriptions = "gs_description"
)
}
}
}else {
gmt1[[i]] <- gmt.list1[[i]]
}
}
}
}
names(gmt1) <- names1
saveRDS(gmt1, "gmt1_more.rds")
return(gmt1)
}
# uses feature names like ABC-S325s instead of ABC-S325
get_gmt2 <- function(gmt.list2 = c("ksdb_human", "sub"), phospho) {
if (file.exists("gmt2.rds")) {
gmt2 <- readRDS("gmt2.rds")
} else if ("chr8" %in% gmt.list2) {
gmt2 <- get_chr8_gmt2(gmt.list2)
} else {
gmt2 <- list()
for (i in 1:length(gmt.list2)) {
if (is.character(gmt.list2[i])) {
if (grepl("ksdb", gmt.list2[i], ignore.case = TRUE)) {
org <- stringr::str_split(gmt.list2[i], "_")[[1]][2]
gmt2[[i]] <- get_ksdb(organism = org)
} else if (gmt.list2[i] == "sub") {
SUB_SITE <- phospho$SUB_SITE
phospho.ref <- data.frame(SUB_SITE)
phospho.ref <- phospho.ref %>% tidyr::extract(SUB_SITE, "KINASE",
remove = FALSE)
SUB_SITE <- NULL
gmt2[[i]] <- DMEA::as_gmt(phospho.ref, "SUB_SITE", "KINASE")
}
} else {
gmt2 <- gmt.list2
break
}
}
saveRDS(gmt2, "gmt2.rds")
}
return(gmt2)
}
# uses feature names like ABC-S325 instead of ABC-S325s
get_gmt2_v2 <- function(gmt.list2 = c("ksdb_human", "sub"), phospho) {
if (file.exists("gmt2_v2.rds")) {
gmt2 <- readRDS("gmt2_v2.rds")
} else if ("chr8" %in% gmt.list2) {
gmt2 <- get_chr8_gmt2(gmt.list2)
} else {
gmt2 <- list()
for (i in 1:length(gmt.list2)) {
if (is.character(gmt.list2[i])) {
if (grepl("ksdb", gmt.list2[i], ignore.case = TRUE)) {
org <- stringr::str_split(gmt.list2[i], "_")[[1]][2]
gmt2[[i]] <- get_ksdb_v2(organism = org)
} else if (gmt.list2[i] == "sub") {
SUB_SITE <- phospho$SUB_SITE
phospho.ref <- data.frame(SUB_SITE)
phospho.ref <- phospho.ref %>% tidyr::extract(SUB_SITE, "KINASE",
remove = FALSE)
SUB_SITE <- NULL
gmt2[[i]] <- DMEA::as_gmt(phospho.ref, "SUB_SITE", "KINASE")
}
} else {
gmt2 <- gmt.list2
break
}
}
saveRDS(gmt2, "gmt2_v2.rds")
}
return(gmt2)
}
# get kinase-substrate database information in gmt format for KSEA
get_ksdb <- function(organism="human"){
if (!is.character(organism)) {
stop("organism must be character entry")
}
if (file.exists(file.path(paste0("gmt_ksdb_", organism, ".rds")))) {
gmt <- readRDS(file.path(paste0("gmt_ksdb_", organism, ".rds")))
} else if (organism == "human") {
url <- "https://raw.github.com/BelindaBGarana/panSEA/main/data/gmt_ksdb_human.rds"
httr::GET(url, httr::write_disk("gmt_ksdb_human.rds"))
gmt <- readRDS("gmt_ksdb_human.rds")
} else {
ksdb <- read.csv(paste0("https://raw.githubusercontent.com/BelindaBGarana/",
"panSEA/shiny-app/data/ksdb_20231101.csv"))
if (organism %in% unique(na.omit(ksdb$KIN_ORGANISM)) &
organism %in% unique(na.omit(ksdb$SUB_ORGANISM))) {
ksdb <- ksdb[ksdb$KIN_ORGANISM == organism &
ksdb$SUB_ORGANISM == organism, ]
}
ksdb$SUB_MOD_RSD_PNNL <- ksdb$SUB_MOD_RSD
ksdb$SUB_MOD_RSD_PNNL <- paste0(ksdb$SUB_MOD_RSD_PNNL,
tolower(substr(ksdb$SUB_MOD_RSD_PNNL,1,1)))
ksdb <- ksdb %>% unite("SUB_SITE", c("SUBSTRATE", "SUB_MOD_RSD_PNNL"),
sep = "-", remove = FALSE)
gmt <- DMEA::as_gmt(ksdb, "SUB_SITE", "KINASE",
descriptions = "KIN_ACC_ID")
saveRDS(gmt, file.path(paste0("ksdb_", organism, ".rds")))
}
return(gmt)
}
get_ksdb_v2 <- function(organism="human"){
if (!is.character(organism)) {
stop("organism must be character entry")
}
if (file.exists(file.path(paste0("gmt_ksdb_", organism, "_v2.rds")))) {
gmt <- readRDS(file.path(paste0("gmt_ksdb_", organism, "_v2.rds")))
} else {
ksdb <- read.csv(paste0("https://raw.githubusercontent.com/BelindaBGarana/",
"panSEA/shiny-app/data/ksdb_20231101.csv"))
if (organism %in% unique(na.omit(ksdb$KIN_ORGANISM)) &
organism %in% unique(na.omit(ksdb$SUB_ORGANISM))) {
ksdb <- ksdb[ksdb$KIN_ORGANISM == organism &
ksdb$SUB_ORGANISM == organism, ]
}
ksdb <- ksdb %>% unite("SUB_SITE", c("SUBSTRATE", "SUB_MOD_RSD"),
sep = "-", remove = FALSE)
gmt <- DMEA::as_gmt(ksdb, "SUB_SITE", "KINASE",
descriptions = "KIN_ACC_ID")
saveRDS(gmt, file.path(paste0("ksdb_", organism, "_v2.rds")))
}
return(gmt)
}
# get CCLE global proteomics data
get_CCLE_prot <- function() {
message("Loading CCLE proteomics")
if (file.exists("CCLE_proteomics.csv")) {
prot.df.noNA <- read.csv("CCLE_proteomics.csv")
} else {
# get CCLE proteomics
download.file("https://figshare.com/ndownloader/files/41466702", "proteomics.csv.gz")
prot.df <- read.csv(gzfile("proteomics.csv.gz"),fileEncoding="UTF-16LE")
allgenes = readr::read_csv("https://figshare.com/ndownloader/files/40576109")
genes = allgenes|>
dplyr::select(gene_symbol,entrez_id)|>
dplyr::distinct()
#genes <- genes[genes$gene_symbol %in% colnames(RNA.df)[2:ncol(RNA.df)], ]
allsamples = readr::read_csv('https://figshare.com/ndownloader/files/40576103')
CCLE.samples <- dplyr::distinct(allsamples[allsamples$id_source == "CCLE",
c("other_id","improve_sample_id")])
# merge prot.df with genes, samples to stop using improve IDs
prot.df <- merge(prot.df, CCLE.samples)
prot.df <- merge(prot.df, genes)
prot.df$entrez_id <- NULL
prot.df <- dplyr::distinct(prot.df)
# convert to wide format for DMEA
prot.df <- reshape2::dcast(prot.df, other_id ~ gene_symbol, mean,
value.var = "proteomics")
colnames(prot.df)[1] <- "CCLE_ID"
prot.df.noNA <- prot.df[, colSums(is.na(prot.df)) == 0] # 23304 gene names
}
write.csv(prot.df.noNA, "CCLE_proteomics.csv", row.names = FALSE)
return(prot.df.noNA)
}
get_CCLE_RNA <- function() {
message("Loading adherent CCLE RNA-seq data version 19Q4")
if (!file.exists("Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_1-200.Rbin")) {
download.file(
paste0(
"https://raw.github.com/BelindaBGarana/DMEA/shiny-app/Inputs/",
"Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_1-200.Rbin"
),
destfile =
"Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_1-200.Rbin"
)
}
if (!file.exists("Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_201-327.Rbin")) {
download.file(
paste0(
"https://raw.github.com/BelindaBGarana/DMEA/shiny-app/Inputs/",
"Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_201-327.Rbin"
),
destfile =
"Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_201-327.Rbin"
)
}
load("Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_1-200.Rbin")
load("Normalized_adherent_CCLE_RNAseq_19Q4_samples_in_PRISM_201-327.Rbin")
RNA.df <- rbind(RNA.first200, RNA.rest)
return(RNA.df)
}
## load BeatAML data formatted for DMEA
# input: file path where BeatAML data should be saved
# output: list of BeatAML meta, drug AUC, global, and phospho data frames
load_BeatAML_for_DMEA <- function(BeatAML.path = "BeatAML_DMEA_inputs") {
message("Loading Beat AML data for DMEA")
BeatAML_synapse_id <- list("drug_response.csv" = "syn51674470",
"Ex10_metadata.txt" = "syn25807733",
"ptrc_ex10_crosstab_global_gene_corrected.txt" = "syn25714248",
"ptrc_ex10_crosstab_phospho_siteID_corrected(1).txt" = "syn25714921")
gmt.drug <- readRDS(gzcon(url("https://raw.github.com/BelindaBGarana/panSEA/main/Examples/Inputs/gmt_BeatAML_drug_MOA.rds")))
### download files if any not already downloaded
if (!file.exists(BeatAML.path)) {
lapply(BeatAML_synapse_id, synapser::synGet, downloadLocation = BeatAML.path)
} else if (!any(FALSE %in% lapply(names(BeatAML_synapse_id), file.exists))) {
lapply(BeatAML_synapse_id, synapser::synGet, downloadLocation = BeatAML.path)
}
### load files
drug.BeatAML <- read.csv(file.path(BeatAML.path, names(BeatAML_synapse_id)[1]))
meta.BeatAML <- read.table(file.path(BeatAML.path, names(BeatAML_synapse_id)[2]),
sep = "\t", header = TRUE)
global.BeatAML <- read.table(file.path(BeatAML.path, names(BeatAML_synapse_id)[3]),
sep = "\t", header = TRUE)
phospho.BeatAML <- read.table(file.path(BeatAML.path, names(BeatAML_synapse_id)[4]),
sep = "\t", header = TRUE)
### format BeatAML data for DMEA
sample.names <- "Barcode.ID"
## format drug sensitivity data frame
# format drug.BeatAML wide (samples in first column, drug names for rest of columns)
drug.BeatAML <- reshape2::dcast(drug.BeatAML, sample_id ~ inhibitor,
value.var = "auc", fill = NA)
# # remove drugs without moa annotations and drug combos
# valid.drugs <-
# names(drug.BeatAML)[names(drug.BeatAML) %in%
# moa.BeatAML[!is.na(moa.BeatAML),]$Drug] # 167 drugs
# drug.BeatAML <- drug.BeatAML[ , c("sample_id", valid.drugs)] # 167 drugs
# moa.BeatAML <-
# moa.BeatAML[moa.BeatAML$Drug %in% names(drug.BeatAML)[2:ncol(drug.BeatAML)], ]
# change sample column name to match expression data
names(drug.BeatAML)[1] <- sample.names
## format global proteomics data frame
# change global.BeatAML column names from SampleID.abbrev to
# Barcode.ID to match drug.BeatAML
global.ids <- names(global.BeatAML)
# remove X and any 0's from start of each column name and then
# replace SampleID.abbrev with Barcode.ID to match drug.BeatAML
for(i in seq_len(length(global.ids))){
global.ids[i] <- substr(global.ids[i], 2, nchar(global.ids[i]))
if(substring(global.ids[i], 1, 1) == 0){
global.ids[i] <- substr(global.ids[i], 2, nchar(global.ids[i]))
}
if(global.ids[i] %in% meta.BeatAML$SampleID.abbrev){
global.ids[i] <- meta.BeatAML[meta.BeatAML$SampleID.abbrev == global.ids[i], ]$Barcode.ID
}
}
# replace global.BeatAML column names
names(global.BeatAML) <- global.ids
# transpose global.BeatAML so that first column is Barcode.ID and
# rest of columns are gene symbols
global.BeatAML <- as.data.frame(t(global.BeatAML))
# make first column Barcode.ID
global.BeatAML[, "Barcode.ID"] <- rownames(global.BeatAML)
global.BeatAML <-
global.BeatAML[ , c("Barcode.ID",
names(global.BeatAML[ , 1:(ncol(global.BeatAML)-1)]))]
## format phospho-proteomics data frame
# change global.BeatAML column names from SampleID.abbrev to Barcode.ID to match drug.BeatAML
phospho.ids <- names(phospho.BeatAML)
# remove X and any 0's from start of each column name and then
# replace SampleID.abbrev with Barcode.ID to match drug.BeatAML
for(i in seq_len(length(phospho.ids))){
phospho.ids[i] <- substr(phospho.ids[i], 2, nchar(phospho.ids[i]))
if(substring(phospho.ids[i], 1, 1) == 0){
phospho.ids[i] <- substr(phospho.ids[i], 2, nchar(phospho.ids[i]))
}
if(phospho.ids[i] %in% meta.BeatAML$SampleID.abbrev){
phospho.ids[i] <- meta.BeatAML[
meta.BeatAML$SampleID.abbrev == phospho.ids[i], ]$Barcode.ID
}
}
# replace phospho.BeatAML column names
names(phospho.BeatAML) <- phospho.ids
# transpose phospho.BeatAML so that first column is Barcode.ID and rest of columns are gene symbols
phospho.BeatAML <- as.data.frame(t(phospho.BeatAML))
# make first column Barcode.ID
phospho.BeatAML[, "Barcode.ID"] <- rownames(phospho.BeatAML)
phospho.BeatAML <- phospho.BeatAML[ , c("Barcode.ID", names(phospho.BeatAML[ , 1:(ncol(phospho.BeatAML)-1)]))]
return(list(meta = meta.BeatAML, drug = drug.BeatAML, gmt = gmt.drug,
global = global.BeatAML, phospho = phospho.BeatAML))
}
load_not_norm_BeatAML_for_DMEA <- function(BeatAML.path = "BeatAML_DMEA_inputs_not_normalized") {
message("Loading Beat AML data for DMEA")
BeatAML_synapse_id <- list("drug_response.csv" = "syn51674470",
"Ex10_metadata.txt" = "syn25807733",
"ptrc_ex10_crosstab_global_gene_original.txt" = "syn25714254",
"ptrc_ex10_crosstab_phospho_siteID_original.txt" = "syn25714936")
gmt.drug <- readRDS(gzcon(url("https://raw.github.com/BelindaBGarana/panSEA/main/Examples/Inputs/gmt_BeatAML_drug_MOA.rds")))
### download files if any not already downloaded
if (!file.exists(BeatAML.path)) {
lapply(BeatAML_synapse_id, synapser::synGet, downloadLocation = BeatAML.path)
} else if (!any(FALSE %in% lapply(names(BeatAML_synapse_id), file.exists))) {
lapply(BeatAML_synapse_id, synapser::synGet, downloadLocation = BeatAML.path)
}
### load files
drug.BeatAML <- read.csv(file.path(BeatAML.path, names(BeatAML_synapse_id)[1]))
meta.BeatAML <- read.table(file.path(BeatAML.path, names(BeatAML_synapse_id)[2]),
sep = "\t", header = TRUE)
global.BeatAML <- read.table(file.path(BeatAML.path, names(BeatAML_synapse_id)[3]),
sep = "\t", header = TRUE)
phospho.BeatAML <- read.table(file.path(BeatAML.path, names(BeatAML_synapse_id)[4]),
sep = "\t", header = TRUE)
### format BeatAML data for DMEA
sample.names <- "Barcode.ID"
## format drug sensitivity data frame
# format drug.BeatAML wide (samples in first column, drug names for rest of columns)
drug.BeatAML <- reshape2::dcast(drug.BeatAML, sample_id ~ inhibitor,
value.var = "auc", fill = NA)
# # remove drugs without moa annotations and drug combos
# valid.drugs <-
# names(drug.BeatAML)[names(drug.BeatAML) %in%
# moa.BeatAML[!is.na(moa.BeatAML),]$Drug] # 167 drugs
# drug.BeatAML <- drug.BeatAML[ , c("sample_id", valid.drugs)] # 167 drugs
# moa.BeatAML <-
# moa.BeatAML[moa.BeatAML$Drug %in% names(drug.BeatAML)[2:ncol(drug.BeatAML)], ]
# change sample column name to match expression data
names(drug.BeatAML)[1] <- sample.names
## format global proteomics data frame
# change global.BeatAML column names from SampleID.abbrev to
# Barcode.ID to match drug.BeatAML
global.ids <- names(global.BeatAML)
# remove X and any 0's from start of each column name and then
# replace SampleID.abbrev with Barcode.ID to match drug.BeatAML
for(i in seq_len(length(global.ids))){
global.ids[i] <- substr(global.ids[i], 2, nchar(global.ids[i]))
if(substring(global.ids[i], 1, 1) == 0){
global.ids[i] <- substr(global.ids[i], 2, nchar(global.ids[i]))
}
if(global.ids[i] %in% meta.BeatAML$SampleID.abbrev){
global.ids[i] <- meta.BeatAML[meta.BeatAML$SampleID.abbrev == global.ids[i], ]$Barcode.ID
}
}
# replace global.BeatAML column names
names(global.BeatAML) <- global.ids
# subtract sample medians
sample.names <- colnames(dplyr::select_if(global.BeatAML, is.numeric))
#global.BeatAML[,sample.names] <- log(global.BeatAML[,sample.names], 2)
global_sample_coef <- apply(global.BeatAML[,sample.names], 2, median, na.rm = T)
global.BeatAML[,sample.names] <- sweep(global.BeatAML[,sample.names], 2, global_sample_coef, FUN = '-')
# transpose global.BeatAML so that first column is Barcode.ID and
# rest of columns are gene symbols
global.BeatAML <- as.data.frame(t(global.BeatAML))
# make first column Barcode.ID
global.BeatAML[,"Barcode.ID"] <- rownames(global.BeatAML)
global.BeatAML <-
global.BeatAML[ , c("Barcode.ID",
names(global.BeatAML[ , 1:(ncol(global.BeatAML)-1)]))]
## format phospho-proteomics data frame
# change global.BeatAML column names from SampleID.abbrev to Barcode.ID to match drug.BeatAML
phospho.ids <- names(phospho.BeatAML)
# remove X and any 0's from start of each column name and then
# replace SampleID.abbrev with Barcode.ID to match drug.BeatAML
for(i in seq_len(length(phospho.ids))){
phospho.ids[i] <- substr(phospho.ids[i], 2, nchar(phospho.ids[i]))
if(substring(phospho.ids[i], 1, 1) == 0){
phospho.ids[i] <- substr(phospho.ids[i], 2, nchar(phospho.ids[i]))
}
if(phospho.ids[i] %in% meta.BeatAML$SampleID.abbrev){
phospho.ids[i] <- meta.BeatAML[
meta.BeatAML$SampleID.abbrev == phospho.ids[i], ]$Barcode.ID
}
}
# replace phospho.BeatAML column names
names(phospho.BeatAML) <- phospho.ids
# subtract sample medians
sample.names <- colnames(dplyr::select_if(phospho.BeatAML, is.numeric))
#phospho.BeatAML[,sample.names] <- log(phospho.BeatAML[,sample.names], 2)
phospho_sample_coef <- apply(phospho.BeatAML[,sample.names], 2, median, na.rm = T)
phospho.BeatAML[,sample.names] <- sweep(phospho.BeatAML[,sample.names], 2, phospho_sample_coef, FUN = '-')
# transpose phospho.BeatAML so that first column is Barcode.ID and rest of columns are gene symbols
phospho.BeatAML <- as.data.frame(t(phospho.BeatAML))
# make first column Barcode.ID
phospho.BeatAML[, "Barcode.ID"] <- rownames(phospho.BeatAML)
phospho.BeatAML <- phospho.BeatAML[ , c("Barcode.ID", names(phospho.BeatAML[ , 1:(ncol(phospho.BeatAML)-1)]))]
return(list(meta = meta.BeatAML, drug = drug.BeatAML, gmt = gmt.drug,
global = global.BeatAML, phospho = phospho.BeatAML))
}
## get list of top n mountain plots (if any)
# input: EA output (e.g., mGSEA.result or mDMEA.result)
# output: list of top n mountain plots
get_top_mtn_plots <- function(base.result, n.top = 10, EA.type = "GSEA",
sets = "Feature_set") {
all.mtn <- base.result$mtn.plots
temp.results <- base.result$result
if (length(all.mtn) > 0) {
if (length(all.mtn) > n.top) {
# identify top significant enrichments
mtn.results <- temp.results[temp.results[ , sets] %in% names(all.mtn), ]
top.mtn.results <- mtn.results %>% slice_max(abs(NES), n = n.top)
all.top.mtn <- all.mtn[names(all.mtn) %in% top.mtn.results[ , sets]]
} else {
all.top.mtn <- all.mtn
}
# create list of mtn plots for files
mtn.file.names <- c()
for (i in 1:length(all.top.mtn)) {
mtn.file.names <- c(mtn.file.names,
paste0(EA.type, "_mtn_plot_", names(all.top.mtn)[i], ".pdf"))
}
names(all.top.mtn) <- mtn.file.names
} else {
all.top.mtn <- list()
}
return(all.top.mtn)
}
# save folder and nested files/subfolders to Synapse - more efficient
save_to_synapse_v2 <- function(temp.files, resultsFolder = NULL,
width = 7, height = 7, dot.scale = 4) {
for (i in names(temp.files)) {
# if file, save appropriately
if (grepl("[.]", i) & is.list(temp.files[[i]]) & length(temp.files[[i]]) > 0) {
# local save
if (endsWith(tolower(i), ".csv")) {
write.csv(temp.files[[i]], i, row.names = FALSE)
} else if (endsWith(tolower(i), ".pdf")) {
if (grepl("_bar_plot", i) | grepl("_dot_plot", i)) {
ggplot2::ggsave(i, temp.files[[i]], device = "pdf",
width = dot.scale*width, height = height)
} else {
ggplot2::ggsave(i, temp.files[[i]], device = "pdf",
width = width, height = height)
}
} else if (endsWith(tolower(i), ".svg")) {
if (grepl("_bar_plot", i) | grepl("_dot_plot", i)) {
ggplot2::ggsave(i, temp.files[[i]], device = "svg",
width = dot.scale*width, height = height)
} else {
ggplot2::ggsave(i, temp.files[[i]], device = "svg",
width = width, height = height)
}
} else if (endsWith(tolower(i), ".html")) {
visNetwork::visSave(temp.files[[i]], i)
} else if (endsWith(tolower(i), ".bp")) {
temp.name <- paste0(substr(i, 1, nchar(i)-3), ".pdf")
save_base_plot(temp.files[[i]], temp.name,
width = width, height = height)
i <- temp.name
}
# save to synapse if relevant
if (!is.null(resultsFolder)) {
# save to synapse
mySynFile <- synapser::File(i, parent = resultsFolder)
synapser::synStore(mySynFile)
}
} else {
# else create subfolder
temp.base <- getwd()
dir.create(i)
setwd(i)
if (!is.null(resultsFolder)) {
subFolder <-
synapser::synStore(synapser::Folder(i, parent = resultsFolder))
} else {
subFolder <- NULL
}
sub.base <- file.path(temp.base, i)
save_to_synapse_v2(temp.files[[i]], subFolder, width, height, dot.scale)
setwd(temp.base)
}
}
}
# save folder and nested files/subfolders to Synapse
save_to_synapse <- function(temp.files, resultsFolder = NULL,
width = 7, height = 7, dot.scale = 4) {
CSV.files <- names(temp.files)[grepl(".csv", names(temp.files),
ignore.case = TRUE)]
if (length(CSV.files) > 0) {
# save locally
for (j in 1:length(CSV.files)) {
write.csv(temp.files[[CSV.files[j]]], CSV.files[j], row.names = FALSE)
}
if (!is.null(resultsFolder)) {
# save to synapse
CSVs <- lapply(as.list(CSV.files), synapser::File,
parent = resultsFolder)
lapply(CSVs, synapser::synStore)
}
}
PDF.files <- names(temp.files)[grepl(".pdf", names(temp.files),
ignore.case = TRUE)]
if (length(PDF.files) > 0) {
# save locally
for (j in 1:length(PDF.files)) {
if (is.list(temp.files[[PDF.files[j]]])) {
if (endsWith(PDF.files[j], "_bar_plot.pdf") |
endsWith(PDF.files[j], "_dot_plot.pdf") |
endsWith(PDF.files[j], "_dot_plot_withSD.pdf")) {
ggplot2::ggsave(PDF.files[j], temp.files[[PDF.files[j]]],
device = "pdf", width = dot.scale*width, height = height)
} else {
ggplot2::ggsave(PDF.files[j], temp.files[[PDF.files[j]]],
device = "pdf", width = width, height = height)
}
}
}
if (!is.null(resultsFolder)) {
# save to synapse
PDF.files <- list.files(pattern = ".*.pdf", full.names = TRUE)
PDFs <- lapply(as.list(PDF.files), synapser::File,
parent = resultsFolder)
lapply(PDFs, synapser::synStore)
}
}
SVG.files <- names(temp.files)[grepl(".svg", names(temp.files),
ignore.case = TRUE)]
if (length(SVG.files) > 0) {
# save locally
for (j in 1:length(SVG.files)) {
ggplot2::ggsave(PDF.files[j], temp.files[[PDF.files[j]]],
device = "svg", width = width, height = height)
}
if (!is.null(resultsFolder)) {
# save to synapse
SVGs <- lapply(as.list(SVG.files), synapser::File,
parent = resultsFolder)
lapply(SVGs, synapser::synStore)
}
}
HTML.files <- names(temp.files)[grepl(".html", names(temp.files),
ignore.case = TRUE)]
if (length(HTML.files) > 0) {
# save locally
for (j in 1:length(HTML.files)) {
if (is.list(temp.files[[HTML.files[j]]])) {
if (length(temp.files[[HTML.files[j]]]) > 0) {
visNetwork::visSave(temp.files[[HTML.files[j]]], HTML.files[j])
}
} else {
HTML.files <- HTML.files[HTML.files != HTML.files[j]]
}
}
if (!is.null(resultsFolder)) {
# save to synapse
HTMLs <- lapply(HTML.files, synapser::File,
parent = resultsFolder)
lapply(HTMLs, synapser::synStore)
}
}
base.plot.files <- names(temp.files)[grepl(".bp", names(temp.files),
ignore.case = TRUE)]
if (length(base.plot.files) > 0) {
# save locally
for (j in 1:length(base.plot.files)) {
if (is.list(temp.files[[base.plot.files[j]]])) {
if (length(temp.files[[base.plot.files[j]]]) > 0) {
temp.name <- paste0(substr(base.plot.files[j], 1, nchar(base.plot.files[j])-3), ".pdf")
save_base_plot(temp.files[[base.plot.files[j]]], temp.name,
width = width, height = height)
base.plot.files[j] <- temp.name
}
} else {
base.plot.files <- base.plot.files[base.plot.files != base.plot.files[j]]
}
}
if (!is.null(resultsFolder)) {
# save to synapse
base.plots <- lapply(base.plot.files, synapser::File,
parent = resultsFolder)
lapply(base.plots, synapser::synStore)
}
}
# save subfolders if relevant
subfolders <- names(temp.files)[!grepl("[.]", names(temp.files))]
if (length(subfolders) > 0) {
temp.base <- getwd()
for (m in 1:length(subfolders)) {
# create folder for mtn plots
dir.create(subfolders[m])
setwd(subfolders[m])
if (!is.null(resultsFolder)) {
subFolder <-
synapser::synStore(synapser::Folder(subfolders[m],
parent = resultsFolder))
} else {
subFolder <- NULL
}
sub.base <- file.path(temp.base, subfolders[m])
save_to_synapse(temp.files[[subfolders[m]]], subFolder)
setwd(temp.base)
}
}
}
get_expr_for_mDMEA <- function(expression) {
if ("adherent CCLE" %in% expression) {
for (i in which(expression == "adherent CCLE")) {
expression[[i]] <- get_CCLE_RNA()