-
Notifications
You must be signed in to change notification settings - Fork 0
/
Clinical_CTD.Rmd
1849 lines (1672 loc) · 85.4 KB
/
Clinical_CTD.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
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
---
title: "Clinical Paper"
author: "Thistlethwaite LR & Li X"
date: "2/18/2022"
output:
html_document:
code_folding: hide
toc: true
toc_depth: 2
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
w.dir=getwd() #""
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_knit$set(root.dir = w.dir)
setwd(w.dir)
require(R.utils)
graph.dir="graphs"
rank.dir="ranks"
model.dir="models"
OP.dir="OP"
sapply(c(graph.dir,rank.dir,model.dir,OP.dir),mkdirs)
```
## Data Load
```{r get-data}
rm(list=setdiff(ls(),grep("dir",ls(),value = T)))
require(R.utils)
require(CTD)
require(CTDext)
require(openxlsx)
url="https://static-content.springer.com/esm/art%3A10.1038%2Fs41598-022-10415-5/MediaObjects/41598_2022_10415_MOESM2_ESM.xlsx"
download.file(url,destfile = "data_mx.xlsx")
data_mx.og=read.xlsx("data_mx.xlsx",
sheet = "Z-score",startRow = 2,
colNames = T,rowNames = T,skipEmptyRows = TRUE,skipEmptyCols = TRUE,)
data_mx.og=data_mx.og[
,!colnames(data_mx.og) %in% c("PATHWAY_SORTORDER", "SUPER_PATHWAY", "SUB_PATHWAY",
"CHEMICAL_ID", "RI", "MASS",
"PUBCHEM", "CAS", "KEGG", "HMDB_ID" )]
# 6 alaimo samples with diseases diagnosed were also used for model training
dupNames=matrix(nrow = 6, ncol = 2)
dupNames[,1]=c(
"ALAIMO-68b", "ALAIMO-68a","ALAIMO-44", "ALAIMO-85", "ALAIMO-136", "ALAIMO-13" )
dupNames[,2]=c(
"EDTA-ABAT-5", "EDTA-ABAT-6", "EDTA-AADC-2", "EDTA-ABAT-7", "EDTA-AADC-3", "EDTA-OTC-17")
temp=data_mx.og[,dupNames[,1]]
colnames(temp)=dupNames[,2]
data_mx.og=cbind(data_mx.og,temp)
models=sort(c("zsd","rcdp","arg","otc","asld","abat","aadc","adsl","cit","cob","ga","gamt","msud","mma","pa","pku"))
cohorts=sapply(c(models,"hep-ref", "edta-ref", "alaimo"),
function(x) grep(paste(x,"-",sep = ""),colnames(data_mx.og),value = T,ignore.case = T))
names(cohorts)[names(cohorts)=="hep-ref"]="hep_refs"
names(cohorts)[names(cohorts)=="edta-ref"]="edta_refs"
# binary code argininosuccinate
data_mx.raw=read.xlsx(system.file("dataset/dataset1.xlsx",package = "CTDext"),
sheet = "Raw intensity",startRow = 2,
colNames = T,rowNames = T,skipEmptyRows = TRUE,skipEmptyCols = TRUE,)
data_mx.raw=data_mx.raw[,colnames(data_mx.og)[colnames(data_mx.og)%in%colnames(data_mx.raw)]]
ptZeroFromRaw=colnames(data_mx.raw[,is.na(unlist(data_mx.raw["argininosuccinate",]))])
pt10FromRaw=colnames(data_mx.raw[,!is.na(unlist(data_mx.raw["argininosuccinate",]))])
temp=data_mx.og[,!colnames(data_mx.og) %in% colnames(data_mx.raw)]
ptZeroFromOg=colnames(temp)[ is.na(unlist(temp["argininosuccinate",]))| as.numeric(unlist(temp["argininosuccinate",]))==0]
data_mx.ogBnry=data_mx.og # Jul
data_mx.ogBnry["argininosuccinate",c(ptZeroFromRaw,ptZeroFromOg)]=0
data_mx.ogBnry["argininosuccinate",pt10FromRaw]=10
# data_mx.og: load("clinical_data_July2020.RData")
# data_mx.ogBnry : "clinical_data_Oct2020.RData"
rm(list=setdiff(ls(),grep("dir|data_mx|cohorts|dupNames",ls(),value = T)))
save.image("clinical_data.RData")
```
## Get number of metabolites detected
``` {r counts}
rm(list=setdiff(ls(),c(grep("dir|model|cohort",ls(),value = T),lsf.str())))
data_mx=loadToEnv("clinical_data.RData")[["data_mx.raw"]]
data_mx_unnamed = data_mx[grep("x -", rownames(data_mx)),
which(colnames(data_mx) %in% c(unlist(cohorts)))]
zscore_cts = apply(data_mx_unnamed, 2, function(i) length(which(!is.na(i))))
mean(zscore_cts)
min(zscore_cts)
max(zscore_cts)
data_mx_named = data_mx[-grep("x -", rownames(data_mx)),
which(colnames(data_mx) %in% c(unlist(cohorts)))]
zscore_cts = apply(data_mx_named, 2, function(i) length(which(!is.na(i))))
mean(zscore_cts)
min(zscore_cts)
max(zscore_cts)
```
## Building a Gaussian Graphical Model to Diagnose 16 Different Metabolic Disorders (skip if using github-saved networks)
Metabolites represented in at least 50% of reference and 50% of disease cases were included in network learning. This is a time-consuming step
``` {r learn-nets_heparin}
require(R.utils)
require(CTD)
require(huge)
rm(list=setdiff(ls(),c(grep("dir|model|cohort",ls(),value = T),lsf.str())))
data_mx=loadToEnv("clinical_data.RData")[["data_mx.ogBnry"]]
cohorts=loadToEnv("clinical_data.RData")[["cohorts"]]
data_mx=data_mx[,grep("hep-",colnames(data_mx),ignore.case = T)]
data_mx=data_mx[rowSums(is.na(data_mx)) != ncol(data_mx),]
refs=data_mx[,grep("ref",colnames(data_mx),ignore.case = T)]
ref_fill = apply(refs, 1, function(i) sum(is.na(i))/length(i))
# refs2=refs[which(ref_fill[rownames(data_mx)]>0.8),]
refs2=refs
cohorts = lapply(cohorts, function(i) i[which(i %in% colnames(data_mx))])
# We perfer training models on edta samples for various reasons (latest dataset); here we show an example of network learning on Citrullinemia disease that only contains heparin samples; include "msud", "mma", "pa", "pku", "cob", "ga", "gamt" if you want to train all 8 models
for (model in c("cit")) { #, "msud", "mma", "pa", "pku", "cob", "ga", "gamt"
for (fold in 1:length(cohorts[[model]])) {
print(sprintf("Learning graphs for diag %s, fold %d...", model, fold))
diag_pts = cohorts[[model]][-fold]
print(diag_pts)
fill.rate = apply(data_mx[,which(colnames(data_mx) %in% diag_pts)], 1, function(i) sum(is.na(i))/length(i))
diag_data = data_mx[intersect(which(ref_fill<0.5), which(fill.rate<=0.50)), which(colnames(data_mx) %in% diag_pts)]
diag_data = diag_data[which(rownames(diag_data) %in% rownames(refs2)),]
print("Individual samples as training data. Latent variable embedding and network pruning.")
diag_data = CTD::data.surrogateProfiles(data = diag_data, std = 1, ref_data = refs2)
print(dim(diag_data))
# Disease Network: GLASSO approach
inv_covmatt = huge(t(diag_data), method="glasso")
inv_covmatt_select = huge.select(inv_covmatt, criterion = "stars")
inv_covmat = as.matrix(inv_covmatt_select$icov[[which(inv_covmatt_select$lambda==inv_covmatt_select$opt.lambda)]])
diag(inv_covmat) = 0;
colnames(inv_covmat) = rownames(diag_data)
ig = graph.adjacency(as.matrix(inv_covmat), mode="undirected", weighted=TRUE, add.colnames='name')
V(ig)$name = rownames(diag_data)
print(ig)
# Reference Network: GLASSO approach
ref_data = data.surrogateProfiles(data = refs2, std = 1, ref_data = refs2)#useMnDiseaseProfile = FALSE, addHealthyControls = TRUE,
ref_data = ref_data[,-which(duplicated(colnames(ref_data)))]
print(dim(ref_data))
inv_covmatt = huge(t(ref_data), method="glasso", lambda = inv_covmatt_select$opt.lambda)
inv_covmat = as.matrix(inv_covmatt$icov[[1]])
diag(inv_covmat) = 0;
colnames(inv_covmat) = rownames(ref_data)
ig_ref = graph.adjacency(as.matrix(inv_covmat), mode="undirected", weighted=TRUE, add.colnames='name')
V(ig_ref)$name = rownames(ref_data)
print(ig_ref)
ig_pruned = graph.naivePruning(ig, ig_ref)
print(ig_pruned)
save(ig, ig_ref, ig_pruned, file=sprintf("%s/bg_%s_fold%d.RData",graph.dir, model, fold))
rm(ig, ig_pruned)
}
}
```
``` {r learn-networks_edta}
rm(list=setdiff(ls(),c(grep("dir|model|cohort",ls(),value = T),lsf.str())))
require(CTD)
require(huge)
require(R.utils)
data_mx=loadToEnv("clinical_data.RData")[["data_mx.ogBnry"]]
cohorts=loadToEnv("clinical_data.RData")[["cohorts"]]
data_mx=data_mx[,grep("edta",colnames(data_mx),ignore.case = T)]
data_mx=data_mx[rowSums(is.na(data_mx)) != ncol(data_mx),]
data_mx["argininosuccinate", which(is.na(data_mx["argininosuccinate",]))] = 0
refs = data_mx[, which(colnames(data_mx) %in% cohorts$edta_refs)]
ref_fill = apply(refs, 1, function(i) sum(is.na(i))/length(i))
cohorts = lapply(cohorts, function(i) i[which(i %in% colnames(data_mx))])
# here we show an example of training one disease cohort that only contains EDTA samples; include "aadc", "abat", "adsl", "arg","zsd", "rcdp","otc" if you want to train all edta models
for (model in c("asld")) {#,"aadc", "abat", "adsl", "arg","zsd", "rcdp","otc"
for (fold in 1:length(cohorts[[model]])) {
print(sprintf("Learning graphs for diag %s, fold %d...", model, fold))
diag_pts = cohorts[[model]][-fold]
print(diag_pts)
fill.rate = apply(data_mx[,which(colnames(data_mx) %in% diag_pts)], 1, function(i) sum(is.na(i))/length(i))
diag_data = data_mx[intersect(which(ref_fill<0.5), which(fill.rate<0.5)), which(colnames(data_mx) %in% diag_pts)]
print(nrow(diag_data))
print(diag_data["argininosuccinate",])
print("Individual samples as training data. Latent variable embedding and network pruning.")
refs2 = refs[which(rownames(refs) %in% rownames(diag_data)), ]
diag_data = data.surrogateProfiles(data = diag_data, std = 1, ref_data = refs2)
print(dim(diag_data))
# Disease Network: GLASSO approach
inv_covmatt = huge(t(diag_data), method="glasso")
inv_covmatt_select = huge.select(inv_covmatt, criterion = "stars")
inv_covmat = as.matrix(inv_covmatt_select$icov[[which(inv_covmatt_select$lambda==inv_covmatt_select$opt.lambda)]])
diag(inv_covmat) = 0;
colnames(inv_covmat) = rownames(diag_data)
ig = graph.adjacency(as.matrix(inv_covmat), mode="undirected", weighted=TRUE, add.colnames='name')
V(ig)$name = rownames(diag_data)
print(ig)
# Reference Network: GLASSO approach
ref_data = data.surrogateProfiles(data = refs2, std = 1, ref_data = refs2)
ref_data = ref_data[,-which(duplicated(colnames(ref_data)))]
print(dim(ref_data))
inv_covmatt = huge(t(ref_data), method="glasso", lambda = inv_covmatt_select$opt.lambda)
inv_covmat = as.matrix(inv_covmatt$icov[[1]])
diag(inv_covmat) = 0;
colnames(inv_covmat) = rownames(ref_data)
ig_ref = graph.adjacency(as.matrix(inv_covmat), mode="undirected", weighted=TRUE, add.colnames='name')
V(ig_ref)$name = rownames(ref_data)
print(ig_ref)
ig_pruned = graph.naivePruning(ig, ig_ref)
print(ig_pruned)
print(degree(ig_pruned, "argininosuccinate"))
save(ig, ig_ref, ig_pruned, file=sprintf("%s/bg_%s_fold%d.RData",graph.dir , model, fold))
rm(ig, ig_ref, ig_pruned)
}
}
# Network descriptive statistics
for (model in c("arg", "asld", "cit", "otc", "rcdp", "zsd", "abat", "aadc", "adsl", "mma", "msud", "pa", "pku", "cob", "ga", "gamt")) { #
print(model)
for (fold in 1:length(cohorts[[model]])) {
print(fold)
load(sprintf("Clinical_paper/graphs/bg_%s_fold%d.RData", model, fold))
print(sprintf("Disease-Control Network: %d-%d", length(V(ig)$name), length(E(ig)$weight)))
print(sprintf("Control-only Network: %d-%d", length(V(ig_ref)$name), length(E(ig_ref)$weight)))
print(sprintf("Disease-Specific Network: %d-%d", length(V(ig_pruned)$name), length(E(ig_pruned)$weight)))
}
}
```
## Get pre-compute ranks for each Gaussian Graphical Model. (skip if using github-saved ranks)
This part should preferably run on cluster (pbs system).
Scripts "wrapper_ranks.r" "getRanksN.r" "getRanks.pbs" are commented out.
```{r get-PreComputed-ranks}
#
# cohorts=loadToEnv("clinical_data.RData")[["cohorts"]]
# models=c(c("asld", "aadc", "abat", "adsl", "arg","zsd", "rcdp","otc"))
# cohorts[models]=sapply(models, function(x) grep("edta",cohorts[[x]],ignore.case = T,value = T))
# cohorts[["alaimo"]]=NULL
#
# for (model in models){
# fold.begin=1
# fold.end=length(cohorts[[model]])
# system(sprintf("Rscript wrapper_ranks.r %s %s %s %s %s",
# model, fold.begin, fold.end, w.dir, rank.dir, graph.dir))
# }
######################################## wrapper_ranks.r ########################################
# require(R.utils)
# require(igraph)
# args = commandArgs(trailingOnly=TRUE)
# model=as.character(args[1])
# fold.begin=as.numeric(args[2])
# fold.end=as.numeric(args[3])
# w.dir=as.character(args[4])
# rank.dir=as.character(args[5])
# graph.dir=as.character(args[6])
# diag=model
# setwd(sprintf("%s/%s",w.dir,rank.dir))
#
# for (fold in fold.begin:fold.end){
# dir.create(sprintf("./%s", model), showWarnings = FALSE)
# output_dir = sprintf("./%s/diag%s%d", model,diag,fold)
# str = sprintf("mkdir %s", output_dir)
# system(str)
#
# ig = loadToEnv(sprintf("../%s/bg_%s_fold%d.RData",graph.dir,model,fold))[["ig_pruned"]]
#
# totalN = length(V(ig)$name)
# print(sprintf("Total N = %d", totalN))
#
# for (n in 1:totalN) {
# str = sprintf("qsub -v diag=%s,fold=%d,n=%d,wkdir=%s,rankdir=%s,graphdir=%s getRanks.pbs",
# diag, fold, n, w.dir, rank.dir, graph.dir)
# system(str, wait=FALSE)
# system("sleep 0.1")
# }
#
#
# ready=FALSE
# last_sum = 0
# while (!ready) {
# f = list.files(sprintf("./%s/diag%s%d", model, diag, fold), pattern=".RData")
# print(sprintf("#permutation files ready = %d", length(f)))
# if (length(f)==totalN) {
# ready=TRUE
# } else {
# system("sleep 30")
# system("rm *.pbs.*")
# curr_sum = length(f)
# if (curr_sum > last_sum) {
# last_sum = curr_sum
# }
# }
# }
# system("rm *.pbs.*")
#
# # collate permutations into one R object
# all_nodes = V(ig)$name
# permutationByStartNode = list()
# for (n in 1:length(all_nodes)) {
# load(sprintf("./%s/diag%s%d/%d.RData",model, diag, fold, n))
# permutationByStartNode[[n]] = toupper(current_node_set)
# }
# names(permutationByStartNode) = all_nodes
# save.image(file=sprintf("./%s/%s%d-ranks.RData",model, toupper(diag), fold))
# print("collate complete...")
# str = sprintf("rm -r ./%s/diag%s%d",model, diag, fold)
# system(str)
#
# }
################################ end of wrapper_ranks.r #########################################
################################ getRanksN.r ################################################
# require(igraph)
# require(CTD)
# require(R.utils)
# singleNode.getNodeRanksN = function(n, G, S=NULL, num.misses=NULL, verbose=FALSE) {
# if (!is.null(num.misses)) {
# if (is.null(S)) {
# print("You must supply a subset of nodes as parameter S if you supply num.misses.")
# return(0)
# }
# }
# all_nodes = names(G)
# if (verbose) {
# print(sprintf("Calculating node rankings %d of %d.", n, length(all_nodes)))
# }
# current_node_set = NULL
# stopIterating=FALSE
# startNode = all_nodes[n]
# currentGraph = G
# numMisses = 0
# current_node_set = c(current_node_set, startNode)
# while (stopIterating==FALSE) {
# # Clear probabilities
# currentGraph[1:length(currentGraph)] = 0 #set probabilities of all nodes to 0
# #determine base p0 probability
# baseP = p0/(length(currentGraph)-length(current_node_set))
# #set probabilities of unseen nodes to baseP
# currentGraph[!(names(currentGraph) %in% current_node_set)] = baseP
# # Sanity check. p0_event should add up to exactly p0 (global variable)
# p0_event = sum(unlist(currentGraph[!(names(currentGraph) %in% current_node_set)]))
# currentGraph = graph.diffuseP1(p1, startNode, currentGraph, current_node_set, 1, verbose=FALSE)
# # Sanity check. p1_event should add up to exactly p1 (global variable)
# p1_event = sum(unlist(currentGraph[!(names(currentGraph) %in% current_node_set)]))
# if (abs(p1_event-1)>thresholdDiff) {
# extra.prob.to.diffuse = 1-p1_event
# currentGraph[names(current_node_set)] = 0
# currentGraph[!(names(currentGraph) %in% names(current_node_set))] = unlist(currentGraph[!(names(currentGraph) %in% names(current_node_set))]) + extra.prob.to.diffuse/sum(!(names(currentGraph) %in% names(current_node_set)))
# }
# #Set startNode to a node that is the max probability in the new currentGraph
# maxProb = names(which.max(currentGraph))
# # Break ties: When there are ties, choose the first of the winners.
# startNode = names(currentGraph[maxProb[1]])
# if (!is.null(num.misses)) {
# if (startNode %in% S) {
# numMisses = 0
# } else {
# numMisses = numMisses + 1
# }
# current_node_set = c(current_node_set, startNode)
# if (numMisses>num.misses || length(c(startNode,current_node_set))>=(length(G))) {
# stopIterating = TRUE
# }
# } else {
# # Keep drawing until you've drawn all nodes.
# current_node_set = c(current_node_set, startNode)
# if (length(current_node_set)>=(length(G))) {
# stopIterating = TRUE
# }
# }
#
# }
# return(current_node_set)
# }
#
# args = commandArgs(trailingOnly=TRUE)
# diag = as.character(args[1])
# fold = as.numeric(args[2])
# n = as.numeric(args[3])
# wkdir = as.character(args[4])
# rankdir = as.character(args[5])
# graphdir = as.character(args[6])
#
# model=diag
# print(diag)
# print(fold)
# print(n)
#
# setwd(sprintf("%s/%s",wkdir,rankdir))
# ig = loadToEnv(sprintf("../%s/bg_%s_fold%d.RData", graphdir, model,fold))[["ig_pruned"]]
#
# print(ig)
# V(ig)$name = tolower(V(ig)$name)
# G = vector(mode="list", length=length(V(ig)$name))
# names(G) = V(ig)$name
# adjacency_matrix = list(as.matrix(get.adjacency(ig, attr="weight")))
# p0=0.1
# p1=0.9
# thresholdDiff=0.01
# all_nodes = tolower(V(ig)$name)
# print(head(all_nodes))
# current_node_set = singleNode.getNodeRanksN(n, G)
# new_dir = sprintf("./%s/diag%s%d",model, diag, fold)
# if (!dir.exists(new_dir)) {
# str = sprintf("mkdir %s", new_dir)
# system(str)
# }
# save(current_node_set, file=sprintf("./%s/diag%s%d/%d.RData",model, diag, fold, n))
#
################################ end of getRanksN.r ##########################################
################################### getRanks.pbs ##############################################
# # Request 1 processors on 1 node
# #PBS -l nodes=1:ppn=1
#
# #Request x number of hours of walltime
# #PBS -l walltime=1:00:00
#
# #Request that regular output and terminal output go to the same file
# #PBS -j oe
# #PBS -m abe
#
# module load R/3.5
#
# diag=${diag}
# fold=${fold}
# n=${n}
# wkdir=${wkdir}
# rankdir=${rankdir}
# cd ${wkdir}/${rankdir}
#
# Rscript ../getRanksN.r $diag $fold $n $wkdir ${rankdir} ${graphdir} > ranks:$diag-$fold-$n.out
# rm ranks:$diag-$fold-$n.out
###################################### end of getRanks.pbs ########################################
```
## Get the main disease module for each disease-specific network model. (skip if using github-saved ranks)
```{r getDisMod}
rm(list=setdiff(ls(),c(grep("dir|models",ls(),value = T),lsf.str())))
# Add CTDsim distance from "downtown module" as second quantitative variable
disFromDowntown = function(dis_mod, ptBSbyK.dis, p2.sig.nodes, p2.optBS, ranks, G) {
p1.e = mle.getEncodingLength(ptBSbyK.dis, NULL, ptID, G)[,"IS.alt"]
p2.e = mle.getEncodingLength(p2.optBS, NULL, ptID2, G)[,"IS.alt"]
# Using predefined node ranks, get optimal bitstring for encoding of patient1's union patient2's subsets.
p12.sig.nodes = unique(c(dis_mod, p2.sig.nodes))
p12.e = c()
for (k in 1:length(ptBSbyK.dis)) {
dis_mod_cpy = dis_mod
p2.sig.nodes_cpy = p2.sig.nodes
dis_mod_k = names(which(ptBSbyK.dis[[k]]==1))
p2.sig.nodes_k = names(which(p2.optBS[[k]]==1))
while (length(dis_mod_k)<k) {
dis_mod_k = unique(c(dis_mod_k, dis_mod_cpy[1]))
dis_mod_cpy = dis_mod_cpy[-1]
}
while (length(p2.sig.nodes_k)<k) {
p2.sig.nodes_k = unique(c(p2.sig.nodes_k, p2.sig.nodes_cpy[1]))
p2.sig.nodes_cpy = p2.sig.nodes_cpy[-1]
}
p12.sig.nodes_k = sapply(unique(c(dis_mod_k, p2.sig.nodes_k)), trimws)
p12.optBS = mle.getPtBSbyK(p12.sig.nodes_k, ranks)
res = mle.getEncodingLength(p12.optBS, NULL, NULL, G)
p12.e[k] = res[which.max(res[,"d.score"]), "IS.alt"] + log2(choose(length(G), 1))*(length(p12.sig.nodes_k)-which.max(res[,"d.score"]))
}
return (list(p1.e=p1.e, p2.e=p2.e, p12.e=p12.e,
NCD=(p12.e-apply(cbind(p1.e, p2.e), 1, min))/apply(cbind(p1.e, p2.e), 1, max)))
}
data_mx=apply(loadToEnv("clinical_data.RData")[["data_mx.ogBnry"]],c(1,2),as.numeric)
cohorts=loadToEnv("clinical_data.RData")[["cohorts"]]
models=c(c("asld", "aadc", "abat", "adsl", "arg","zsd", "rcdp","otc"))
cohorts[models]=sapply(models, function(x) grep("edta",cohorts[[x]],ignore.case = T,value = T))
cohorts[["alaimo"]]=NULL
data_mx=data_mx[,colnames(data_mx) %in% unlist(cohorts)]
data_mx=data_mx[rowSums(is.na(data_mx)) != ncol(data_mx),]
table(data_mx["argininosuccinate",])
p0=0.1
p1=0.9
thresholdDiff=0.01
# Get downtown disease modules for all modelled disease states
disMod = list()
data_mx0=data_mx
# use edta samples for model arg; edta sampels for model asld; hep samples for otc
cohorts[["arg"]]=cohorts[["arg"]][grep("EDTA",cohorts[["arg"]])]
cohorts[["asld"]]=cohorts[["asld"]][grep("EDTA",cohorts[["asld"]])]
cohorts[["otc"]]=cohorts[["otc"]][grep("HEP",cohorts[["otc"]])]
# showing one example
for (model in c("cit")) { # "aadc", "abat", "adsl", "arg", "asld", ,"otc", "cob", "ga", "gamt", "msud", "mma", "pa", "zsd", "rcdp", "pku"
print(sprintf("%s...", toupper(model)))
data_mx=data_mx0
mn = apply(data_mx[,which(colnames(data_mx) %in% cohorts[[model]])], 1, function(i) mean(na.omit(i)))
mn = mn[-which(is.na(mn))]
downtown_disease_module = c()
for (pt in 1:length(cohorts[[model]])) {
# ig = loadToEnv(sprintf("%s/bg_%s_fold%d.RData",graph.dir, model, pt))[["ig_pruned"]]
ig = loadToEnv(system.file(sprintf("networks/ind_foldNets/bg_%s_fold%d.RData", model, pt),package = "CTDext"))[["ig_pruned"]]
# ranks = loadToEnv(sprintf("%s/bg_%s_fold%d.RData",rank.dir, model, pt))[["ig_pruned"]]
ranks = loadToEnv(system.file(sprintf("ranks/ind_ranks/%s%d-ranks.RData", model, pt),package = "CTDext"))[["permutationByStartNode"]]
ranks = lapply(ranks, tolower)
adjacency_matrix = list(as.matrix(get.adjacency(ig, attr="weight")))
G = vector(mode="list", length=length(V(ig)$name))
names(G) = V(ig)$name
S = mn[which(abs(mn)>2)]
S = S[which(names(S) %in% names(G))]
it=0
while (length(S)<15) {
S = mn[which(abs(mn)>(2-0.1*it))]
S = S[which(names(S) %in% names(G))]
it = it + 1
}
ptBSbyK = mle.getPtBSbyK(names(S), ranks)
res = mle.getEncodingLength(ptBSbyK, NULL, NULL, G)
downtown_disease_module = c(downtown_disease_module, names(which(ptBSbyK[[which.max(res[,"d.score"])]]==1)))
}
print(model)
length(unique(downtown_disease_module))
# Estimate disease module "purity" based on 2 size thresholds and known case mean distances
fold=1
# ig = loadToEnv(sprintf("graphs_GMpaper/bg_%s_fold%d.RData",graph.dir, model, fold))[["ig_pruned"]]
ig = loadToEnv(system.file(sprintf("networks/ind_foldNets/bg_%s_fold%d.RData", model, fold),package = "CTDext"))[["ig_pruned"]]
# ranks = loadToEnv(sprintf("%s/%s%d-ranks.RData",rank.dir ,model, fold))[["permutationByStartNode"]]
ranks = loadToEnv(system.file(sprintf("ranks/ind_ranks/%s%d-ranks.RData", model, fold),package = "CTDext"))[["permutationByStartNode"]]
ranks = lapply(ranks, tolower)
adjacency_matrix = list(as.matrix(get.adjacency(ig, attr="weight")))
G = vector(mode="list", length=length(V(ig)$name))
names(G) = V(ig)$name
data_mx = data_mx[which(rownames(data_mx) %in% V(ig)$name), ]
data_mx = data_mx[,which(colnames(data_mx) %in% cohorts[[model]])]
purity_mets = list()
purity = c()
# Size1: Full downtown disease module
tmp.mm = unique(downtown_disease_module)
tmp.mm = tmp.mm[which(tmp.mm %in% names(G))]
ptBSbyK.dis = mle.getPtBSbyK(tmp.mm, ranks)
res = mle.getEncodingLength(ptBSbyK.dis, NULL, ptID, G)
downtown_disease_mod = names(which(ptBSbyK.dis[[which.max(res[,"d.score"])]]==1))
print(length(unique(downtown_disease_mod)))
dd = c()
for (pt in 1:length(cohorts[[model]])) {
ptBSbyK.dis = mle.getPtBSbyK(unique(downtown_disease_mod), ranks)
p2.sig.nodes = names(data_mx[order(abs(data_mx[,pt]), decreasing = TRUE), pt][1:length(unique(downtown_disease_mod))])
p2.optBS = mle.getPtBSbyK(p2.sig.nodes, ranks)
ctdsim = disFromDowntown(unique(downtown_disease_mod), ptBSbyK.dis, p2.sig.nodes, p2.optBS, ranks, G)
dd[pt] = min(ctdsim$NCD)
}
purity_mets[[1]] = unique(downtown_disease_module)
purity[1] = mean(dd)
# Size2: Smaller disease module
downtown_disease_module = names(which(table(downtown_disease_module)>(length(cohorts[[model]])/2)))
tmp.mm = unique(downtown_disease_module)
tmp.mm = tmp.mm[which(tmp.mm %in% names(G))]
ptBSbyK.dis = mle.getPtBSbyK(unique(downtown_disease_module), ranks)
res = mle.getEncodingLength(ptBSbyK.dis, NULL, ptID, G)
downtown_disease_mod = names(which(ptBSbyK.dis[[which.max(res[,"d.score"])]]==1))
print(length(unique(downtown_disease_mod)))
dd = c()
for (pt in 1:length(cohorts[[model]])) {
ptBSbyK.dis = mle.getPtBSbyK(unique(downtown_disease_mod), ranks)
p2.sig.nodes = names(data_mx[order(abs(data_mx[,pt]), decreasing = TRUE), pt][1:length(unique(downtown_disease_mod))])
p2.optBS = mle.getPtBSbyK(p2.sig.nodes, ranks)
ctdsim = disFromDowntown(unique(downtown_disease_mod), ptBSbyK.dis, p2.sig.nodes, p2.optBS, ranks, G)
dd[pt] = min(ctdsim$NCD)
}
purity_mets[[2]] = downtown_disease_module
purity[2] = mean(dd)
# Selected disease module based on "purity" estimates
downtown_disease_module = purity_mets[[which.min(purity)]]
disMod[[model]] = downtown_disease_module
}
lapply(disMod, length)
save(disMod, file=sprintf("%s/disMod.RData",model.dir))
```
## Run CTD on Metabolomics Profiles to Interpret Perturbation Patterns in Disease Context
``` {r runCTD}
# Note: Do not include Alaimo patients in this result - must have known diagnosis from one of the 16 disease network models,
# or be a healthy control (heparin or EDTA).
require(R.utils)
require(CTD)
rm(list=setdiff(ls(),c(grep("dir|models",ls(),value = T),lsf.str())))
data_mx=apply(loadToEnv("clinical_data.RData")[["data_mx.ogBnry"]],c(1,2),as.numeric)
cohorts=loadToEnv("clinical_data.RData")[["cohorts"]]
dupNames=loadToEnv("clinical_data.RData")[["dupNames"]]
data_mx=data_mx[,-which(colnames(data_mx) %in% dupNames[,1])]
data_mx=data_mx[rowSums(is.na(data_mx)) != ncol(data_mx),]
data_mx.0=data_mx
p0=0.1
p1=0.9
thresholdDiff=0.01
kmx=30
disMod=loadToEnv(system.file("shiny-app/disMod_Oct2020.RData",package = "CTDext"))[["disMod"]]
# Add CTDsim distance from "downtown module" as second quantitative variable
disFromDowntown = function(dis_mod, ptBSbyK.dis, p2.sig.nodes, p2.optBS, ranks, G, mn_prof, p2_prof) {
p1.e = mle.getEncodingLength(ptBSbyK.dis, NULL, ptID, G)[,"IS.alt"]
p2.e = mle.getEncodingLength(p2.optBS, NULL, ptID2, G)[,"IS.alt"]
dirSim = vector("numeric", length = length(ptBSbyK.dis))
for (k in 1:length(ptBSbyK.dis)) {
p1.sn = dis_mod[1:k]
p2.sn = p2.sig.nodes[1:k]
p1.dirs = mn_prof[p1.sn]
p1.dirs[which(!(p1.dirs > 0))] = 0
p1.dirs[which(p1.dirs > 0)] = 1
p2.dirs = p2_prof[p2.sn]
p2.dirs[which(!(p2.dirs > 0))] = 0
p2.dirs[which(p2.dirs > 0)] = 1
p1.snn = sprintf("%s%d", p1.sn, p1.dirs)
p2.snn = sprintf("%s%d", p2.sn, p2.dirs)
dirSim[k] = 1 - (length(intersect(p1.snn, p2.snn))/length(union(p1.snn, p2.snn)))
}
# Using predefined node ranks, get optimal bitstring for encoding of patient1's union patient2's subsets.
p12.sig.nodes = unique(c(dis_mod, p2.sig.nodes))
p12.e = c()
for (k in 1:length(ptBSbyK.dis)) {
dis_mod_cpy = dis_mod
p2.sig.nodes_cpy = p2.sig.nodes
dis_mod_k = names(which(ptBSbyK.dis[[k]]==1))
p2.sig.nodes_k = names(which(p2.optBS[[k]]==1))
while (length(dis_mod_k)<k) {
dis_mod_k = unique(c(dis_mod_k, dis_mod_cpy[1]))
dis_mod_cpy = dis_mod_cpy[-1]
}
while (length(p2.sig.nodes_k)<k) {
p2.sig.nodes_k = unique(c(p2.sig.nodes_k, p2.sig.nodes_cpy[1]))
p2.sig.nodes_cpy = p2.sig.nodes_cpy[-1]
}
p12.sig.nodes_k = sapply(unique(c(dis_mod_k, p2.sig.nodes_k)), trimws)
p12.optBS = mle.getPtBSbyK(p12.sig.nodes_k, ranks)
res = mle.getEncodingLength(p12.optBS, NULL, NULL, G)
p12.e[k] = res[which.max(res[,"d.score"]), "IS.alt"] + log2(choose(length(G), 1))*(length(p12.sig.nodes_k)-which.max(res[,"d.score"]))
}
return (list(p1.e=p1.e, p2.e=p2.e, p12.e=p12.e,
JAC = dirSim,
NCD=(p12.e-apply(cbind(p1.e, p2.e), 1, min))/apply(cbind(p1.e, p2.e), 1, max)))
}
# First, run CTDdisMod for all models (kmx doesn't matter).
for (model in c("aadc","cob","pa","abat", "adsl", "arg", "asld", "cit", "otc", "ga", "gamt", "msud", "mma", "pa", "zsd", "rcdp", "pku")) { #
data_mx=data_mx.0
table(data_mx["argininosuccinate",])
# Selected disease module
mn = apply(data_mx[,which(colnames(data_mx) %in% cohorts[[model]])], 1, function(i) mean(na.omit(i)))
mn = mn[-which(is.na(mn))]
downtown_disease_module = disMod[[model]]
# For each network fold, run CTDdm against several diagnoses
for (fold in 1:length(cohorts[[model]])) {
print(sprintf("Fold %d/%d...", fold, length(cohorts[[model]])))
# ig = loadToEnv(sprintf("%s/bg_%s_fold%d.RData", graph.dir, model, fold))[["ig_pruned"]]
ig = loadToEnv(system.file(sprintf("networks/ind_foldNets/bg_%s_fold%d.RData", model, fold),package = "CTDext"))[["ig_pruned"]]
# ranks = loadToEnv(sprintf("%s/%s%d-ranks.RData",rank.dir, model, fold))[["permutationByStartNode"]]
ranks = loadToEnv(system.file(sprintf("ranks/ind_ranks/%s%d-ranks.RData", toupper(model), fold),package = "CTDext"))[["permutationByStartNode"]]
ranks = lapply(ranks, tolower)
adjacency_matrix = list(as.matrix(get.adjacency(ig, attr="weight")))
G = vector(mode="list", length=length(V(ig)$name))
names(G) = V(ig)$name
data_mx = data_mx[which(rownames(data_mx) %in% V(ig)$name), ]
data_mx = data_mx[,which(colnames(data_mx) %in% unlist(cohorts))]
tmp.mm = unique(downtown_disease_module)
tmp.mm = tmp.mm[which(tmp.mm %in% names(G))]
ptBSbyK.dis = mle.getPtBSbyK(tmp.mm, ranks)
res = mle.getEncodingLength(ptBSbyK.dis, NULL, ptID, G)
downtown_disease_mod = names(which(ptBSbyK.dis[[which.max(res[,"d.score"])]]==1))
ptBSbyK.dis = mle.getPtBSbyK(downtown_disease_mod, ranks)
df_disMod = data.frame(ptID=character(), diag=character(), ctdDisMod=numeric(), jac=numeric(), stringsAsFactors = FALSE)
for (p in 1:ncol(data_mx)) {
#print(sprintf("Patient %d/%d...", p, ncol(data_mx)))
ptID = colnames(data_mx)[p]
if (ptID %in% unlist(cohorts)) {diag = names(cohorts)[which(unlist(lapply(cohorts, function(i) ptID %in% i)))]}else{diag = "reference"}
# CTD: get module best explained by network's connectivity
S = data_mx[order(abs(data_mx[,p]), decreasing = TRUE),p]
p2.sig.nodes = names(S)[1:length(downtown_disease_mod)]
p2.optBS = mle.getPtBSbyK(p2.sig.nodes, ranks)
ctdDisMod = disFromDowntown(downtown_disease_mod, ptBSbyK.dis, p2.sig.nodes, p2.optBS, ranks, G, mn, S)
#if (ptID=="X606789") {print(min(ctdDisMod$NCD))}
df_disMod[p, "ptID"] = colnames(data_mx)[p]
df_disMod[p, "diag"] = diag[1]
df_disMod[p, "ctdDisMod"] = min(ctdDisMod$NCD)
df_disMod[p, "jac"] = min(ctdDisMod$JAC)
}
save(df_disMod, file=sprintf("%s/ctdDisMod_%s_fold%d.RData",model.dir, model, fold))
}
}
# Next, run CTD on all models for K=30
for (kmx in c(30)) {
for (model in c( "aadc","cob","pa", "abat", "adsl", "arg", "asld", "cit", "otc", "ga", "gamt", "msud", "mma", ,"zsd", "rcdp", "pku")) { #
data_mx=data_mx.0
# table(data_mx["argininosuccinate",])
# For each network fold, runCTD against several diagnoses
for (fold in 1:length(cohorts[[model]])) {
# ig = loadToEnv(sprintf("%s/bg_%s_fold%d.RData", graph.dir, model, fold))[["ig_pruned"]]
ig = loadToEnv(system.file(sprintf("networks/ind_foldNets/bg_%s_fold%d.RData", model, fold),package = "CTDext"))[["ig_pruned"]]
# ranks = loadToEnv(sprintf("%s/%s%d-ranks.RData", model, rank.dir fold))[["permutationByStartNode"]]
ranks = loadToEnv(system.file(sprintf("ranks/ind_ranks/%s%d-ranks.RData", toupper(model), fold),package = "CTDext"))[["permutationByStartNode"]]
ranks = lapply(ranks, tolower)
adjacency_matrix = list(as.matrix(get.adjacency(ig, attr="weight")))
G = vector(mode="list", length=length(V(ig)$name))
names(G) = V(ig)$name
data_mx = data_mx[which(rownames(data_mx) %in% V(ig)$name), ]
data_mx = data_mx[,which(colnames(data_mx) %in% unlist(cohorts))]
df_ctd = data.frame(ptID=character(), S=character(), lenS=numeric(), optT=numeric(), fishers=numeric(), I0=numeric(), IA=numeric(), d=numeric(), stringsAsFactors = FALSE)
r=1
ptBSbyK = list()
for (p in 1:ncol(data_mx)) {
ptID = colnames(data_mx)[p]
if (ptID %in% unlist(cohorts)) {diag = names(cohorts)[which(unlist(lapply(cohorts, function(i) ptID %in% i)))]}else{diag = "reference"}
S = data_mx[order(abs(data_mx[,p]), decreasing = TRUE),p][1:kmx]
ptBSbyK[[ptID]] = mle.getPtBSbyK(names(S), ranks)
res = mle.getEncodingLength(ptBSbyK[[ptID]], NULL, ptID, G)
#if (ptID=="X606789") {
# print(sprintf("Patient %d/%d...", p, ncol(data_mx)))
# print(max(res[,"d.score"]))
#}
for (k in 1:kmx) {
df_ctd[r, "ptID"] = colnames(data_mx)[p]
df_ctd[r, "diag"] = diag[1]
df_ctd[r, "S"] = paste(names(S)[1:k], collapse="/")
df_ctd[r, "lenS"] = k
df_ctd[r, "optT"] = res[k, "opt.T"]
df_ctd[r, "I0"] = res[k, "IS.null"]
df_ctd[r, "IA"] = res[k, "IS.alt"]
df_ctd[r, "d"] = res[k, "d.score"]
r = r + 1
}
}
save(ptBSbyK, df_ctd, file=sprintf("%s/ctd_%s_fold%d_kmx%d.RData", model.dir, model, fold, kmx))
}
}
}
# Rbind df_ctdDisMod to df_ctd
rm(list=setdiff(ls(),c(grep("dir|cohorts",ls(),value = T),lsf.str())))
for (model in c("aadc","cob","pa", "abat", "adsl", "arg", "asld", "cit", "otc", "cob", "ga", "gamt", "msud", "mma", "pa", "zsd", "rcdp", "pku")) { ##"
for (fold in 1:length(cohorts[[model]])) {
load(sprintf("%s/ctdDisMod_%s_fold%d.RData",model.dir, model, fold))
for (kmx in c(30)) {
load(sprintf("%s/ctd_%s_fold%d_kmx%d.RData", model.dir, model, fold, kmx))
df = data.frame(ptID=character(), S=character(), lenS=numeric(), optT=numeric(),
fishers=numeric(), I0=numeric(), IA=numeric(), d=numeric(),
ctdDisMod=numeric(), jac=numeric(), stringsAsFactors = FALSE)
r = 1
for (p in 1:nrow(df_disMod)) {
for (k in 1:kmx) {
df[r, "ptID"] = df_ctd[r,"ptID"]
df[r, "diag"] = df_ctd[r,"diag"]
df[r, "S"] = df_ctd[r,"S"]
df[r, "lenS"] = df_ctd[r,"lenS"]
df[r, "optT"] = df_ctd[r,"optT"]
df[r, "I0"] = df_ctd[r,"I0"]
df[r, "IA"] = df_ctd[r,"IA"]
df[r, "d"] = df_ctd[r,"d"]
df[r, "ctdDisMod"] = df_disMod[p,"ctdDisMod"]
df[r, "jac"] = df_disMod[p,"jac"]
r = r + 1
}
}
save(ptBSbyK, df, file=sprintf("%s/model_%s_fold%d_kmx%d.RData", model.dir, model, fold, kmx))
system(sprintf("rm %s/ctd_%s_fold%d_kmx%d.RData", model.dir, model, fold, kmx))
}
system(sprintf("rm %s/ctdDisMod_%s_fold%d.RData", model.dir, model, fold))
}
}
# Collapse fold signal to LOOCV signal, where the test patients scores are averaged across folds, and cases
# signal is the left out fold score.
require(CTD)
require(R.utils)
require(R.utils)
require(CTD)
rm(list=setdiff(ls(),c(grep("dir|models",ls(),value = T),lsf.str())))
data_mx=apply(loadToEnv("clinical_data.RData")[["data_mx.ogBnry"]],c(1,2),as.numeric)
cohorts=loadToEnv("clinical_data.RData")[["cohorts"]]
dupNames=loadToEnv("clinical_data.RData")[["dupNames"]]
data_mx=data_mx[,-which(colnames(data_mx) %in% dupNames[,1])]
data_mx=data_mx[rowSums(is.na(data_mx)) != ncol(data_mx),]
data_mx.0=data_mx
which(apply(data_mx, 2, function(i) sum(na.omit(i)==0)/length(na.omit(i)))==1)
for (kmx in c(30)) { #
for (model in c("aadc", "abat", "adsl", "arg", "asld", "cit", "otc", "cob", "ga", "gamt", "zsd", "rcdp", "msud", "mma", "pa", "pku")) { #
df_model = data.frame(fold=numeric(), pt=numeric(), bits=numeric(), ctdDisMod=numeric(), jac=numeric(), diag=character(), stringsAsFactors = FALSE)
for (fold in 1:length(cohorts[[model]])) {
df = loadToEnv(sprintf("%s/model_%s_fold%d_kmx%d.RData", model.dir , model, fold, kmx))[["df"]]
df = df[!is.na(df$ptID),]
pts = unique(df$ptID)
df_best = data.frame(pt=numeric(), ptID=character(), bits=numeric(), diag=character(),
ctdDisMod=numeric(), jac=numeric(), stringsAsFactors = FALSE)
for (pt in 1:length(pts)) {
pt_data = df[which(df$ptID==pts[pt]),]
ptID = unique(df[which(df$ptID==pts[pt]), "ptID"])
if (pt_data[1,"diag"]==model) {
df_best[pt, "pt"] = which(cohorts[[model]]==ptID)
}
df_best[pt, "ptID"] = ptID
df_best[pt, "bits"] = max(df[which(df$ptID==pts[pt]), "d"])-log2(nrow(pt_data))
df_best[pt, "jac"] = pt_data[1, "jac"]
df_best[pt, "diag"] = unique(pt_data[,"diag"])
df_best[pt, "ctdDisMod"] = pt_data[1, "ctdDisMod"]
}
df_best$bits[which(df_best$bits<0)] = 0
df_best$fold = rep(fold, nrow(df_best))
df_model = rbind(df_model, df_best)
}
# Do not do multiple hypothesis test correction here.
#df_model$bits = -log2(p.adjust(2^-(df_model$bits), method="fdr"))
df_model$loocv = rep(0, nrow(df_model))
df_model$loocv[which(df_model$pt==df_model$fold)] = 1
df_model = df_model[-intersect(which(df_model$loocv==0), which(df_model$diag==model)), ]
b_bits = cbind(unique(df_model$ptID), sapply(unique(df_model$ptID), function(i) mean(df_model[which(df_model$ptID==i),"bits"])))
ctdDisMod_loocv = cbind(unique(df_model$ptID), sapply(unique(df_model$ptID), function(i) mean(df_model[which(df_model$ptID==i),"ctdDisMod"])))
jac_loocv = cbind(unique(df_model$ptID), sapply(unique(df_model$ptID), function(i) mean(df_model[which(df_model$ptID==i),"jac"])))
df_model = df_model[-which(duplicated(df_model$ptID)),]
df_model = df_model[order(df_model$ptID),]
b_bits = b_bits[order(b_bits[,1]),]
ctdDisMod_loocv = ctdDisMod_loocv[order(ctdDisMod_loocv[,1]),]
jac_loocv = jac_loocv[order(jac_loocv[,1]),]
df_model$bits = as.numeric(b_bits[,2])
df_model$ctdDisMod = as.numeric(ctdDisMod_loocv[,2])
df_model$jac = as.numeric(jac_loocv[,2])
print(any(is.na(df_model$bits)))
print(any(is.na(df_model$ctdDisMod)))
kmx = nrow(pt_data)
save(df_model, file=sprintf("%s/dd-%s-loocv-kmx%d.RData",model.dir, model, kmx))
#sapply(1:length(cohorts[[model]]), function(i) system(sprintf("rm model/model_%s_fold%d_kmx%d.RData", model, i, kmx)))
}
}
# kmx=30
# load("../clnms_map-macbook.RData")
# clnms_map=as.data.frame(clnms_map)
#
# for (names in dupNames[,1]){
# clnms_map[clnms_map$clnms==names,]=dupNames[dupNames[,1]==names,2]}
#
# for(model in c("aadc", "cob", "abat", "adsl", "arg", "asld", "cit", "otc", "ga", "gamt", "msud", "mma", "pa","zsd", "rcdp", "pku")){ #
# for (fold in 1:length(cohorts[[model]])) {
# load(sprintf("%s/dd-%s-loocv-kmx%d.RData",model.dir, model, kmx))
# df_model$ptID=clnms_map[,2][match(df_model$ptID,clnms_map[,1])]
# save(df_model, file=sprintf("%s/dd-%s-loocv-kmx%d.RData",model.dir, model, kmx))
# }
# }
# For each kmx, get a list of patient rankings across all 16 disease-specific network models
# Be sure to change ptIDs to coded ptIDs
require(EmpiricalBrownsMethod)
setwd(model.dir)
models = c("aadc", "abat", "adsl", "arg", "asld", "cit", "cob", "ga", "gamt", "mma", "msud", "otc", "pa", "pku", "rcdp", "zsd")
ff = list.files(".", pattern=sprintf("loocv-kmx%d.RData", 30))
dff = loadToEnv(ff[1])[["df_model"]]
pts = dff$ptID
for (kmx in 30) {#, 30, 5
ff = list.files(".", pattern=sprintf("loocv-kmx%d.RData", kmx))
df_models = list()
for (model in 1:length(models)) {
df_model = loadToEnv(ff[model])[["df_model"]]
ctd_pval_uncorrected = ifelse(2^-df_model[, "bits"]>1, 1, 2^-df_model[, "bits"])
df_model$bits2 = -log2(p.adjust(2^-(df_model$bits), method="bonferroni"))
ctd_pval = ifelse(2^-df_model[, "bits2"]>1, 1, 2^-df_model[, "bits2"])
ctdDisMod_percentile = sapply(df_model[, "ctdDisMod"], function(i) length(which(df_model$ctdDisMod<=i))/nrow(df_model))
combined_network = apply(cbind(ctd_pval, ctdDisMod_percentile), 1, function(i) empiricalBrownsMethod(data_matrix = rbind(df_model$bits, df_model$ctdDisMod), p_values = i, TRUE)$P_test)
names(ctd_pval) = df_model$ptID
names(ctdDisMod_percentile) = df_model$ptID
names(combined_network) = df_model$ptID
df_models[[models[model]]][["ctd_pval_uncorrected"]] = ctd_pval_uncorrected
df_models[[models[model]]][["ctd_pval"]] = ctd_pval
df_models[[models[model]]][["ctdDisMod_percentile"]] = ctdDisMod_percentile
df_models[[models[model]]][["combined_network"]] = combined_network
print(model)
}
pt_ranks = list()
for (pt in 1:length(pts)) {
ptID = pts[pt]
# ptID_coded = clnms_map[which(clnms_map[,1]==ptID), 2]
ptID_coded = ptID
for (pc in ptID_coded) {
df_pt = data.frame(model=character(), ctd=numeric(), ctdDisMod=numeric(), brown.comb=numeric(), stringsAsFactors = FALSE)
r = 1
for (model in 1:length(models)) {
ctd_pval = df_models[[models[model]]][["ctd_pval"]]
ctdDisMod_percentile = df_models[[models[model]]][["ctdDisMod_percentile"]]
combined_network = df_models[[models[model]]][["combined_network"]]
df_pt[r, "model"] = gsub(sprintf("dd-|-loocv-kmx%d.RData", kmx), "", ff[model])
df_pt[r, "ctd"] = ctd_pval[pt]
df_pt[r, "ctdDisMod"] = ctdDisMod_percentile[pt]
df_pt[r, "brown.comb"] = combined_network[pt] # Use Brown's combined for dependent tests
r = r + 1
}
pt_ranks[[pc]] = df_pt
}
}
save(pt_ranks, file=sprintf("ptRanks_kmx%d.RData", kmx))
}
# AUCs
setwd("../")
require(pROC)
require(pls)
require(EmpiricalBrownsMethod)
dff = data.frame(kmx=numeric(), model=character(), ctd.auc=numeric(), ctddismod.auc=numeric(),
jac.auc=numeric(), combined.auc=numeric(), stringsAsFactors = FALSE)
r= 1
for (model in c("aadc", "abat", "adsl", "arg", "asld", "cit", "cob", "ga", "gamt", "msud", "mma", "otc", "pa", "pku", "rcdp", "zsd")) {
for (kmx in c(30)) {
print(sprintf("MODEL %s...", model))
# df_model$bits add Bonferroni correction
load(sprintf("%s/dd-%s-loocv-kmx%d.RData", model.dir, model, kmx))
df_model = df_model[-which(df_model$diag %in% c("alaimo","maps")),]
df_model$bits = -log2(p.adjust(2^-(df_model$bits), method="bonferroni"))
df_model$diag = gsub("test_", "", df_model$diag)
print(toupper(model))
print(dim(df_model))
diags = df_model$diag
diags[-which(diags==model)] = 0
diags[which(diags==model)] = 1
# AUC, CTD only
ctd.auc = roc(diags, df_model$bits)
print(ctd.auc$auc)
# AUC, CTDdisMod only
#ctddismod.auc = roc(diags, df_model$ctdDisMod)
#print(ctddismod.auc$auc)
# AUC, Jaccard only
#jac.auc = roc(diags, df_model$jac)
#print(jac.auc$auc)
# AUC, Network-combined: CTD+CTDdisMod
ctd_pvals = 2^-(df_model$bits)
ctdDisMod_pvals = sapply(df_model$ctdDisMod, function(i) length(which(df_model$ctdDisMod<=i))/nrow(df_model))
combined_brown = apply(cbind(ctd_pvals, ctdDisMod_pvals), 1, function(i) empiricalBrownsMethod(data_matrix = rbind(df_model$bits, df_model$ctdDisMod), p_values = i, TRUE)$P_test)
network.auc = roc(diags, combined_brown)
print(network.auc$auc)
# AUC, all CTD+CTDdisMod+Jaccard, Browns combined
ctd_pvals = 2^-(df_model$bits)
ctdDisMod_pvals = sapply(df_model$ctdDisMod, function(i) length(which(df_model$ctdDisMod<=i))/nrow(df_model))
jac_pvals = sapply(df_model$jac, function(i) length(which(df_model$jac<=i))/nrow(df_model))
combined_brown = apply(cbind(ctd_pvals, ctdDisMod_pvals, jac_pvals), 1, function(i) empiricalBrownsMethod(data_matrix = rbind(df_model$bits, df_model$ctdDisMod, df_model$jac), p_values = i, TRUE)$P_test)
all.auc = roc(diags, combined_brown)
print(all.auc$auc)
dff[r, "kmx"] = kmx
dff[r, "model"] = model
dff[r, "ctd.auc"] = ctd.auc$auc
#dff[r, "ctddismod.auc"] = ctddismod.auc$auc
#dff[r, "jac.auc"] = jac.auc$auc
dff[r, "network.auc"] = network.auc$auc
dff[r, "all.auc"] = all.auc$auc
r = r + 1
}
}
save(dff,file=sprintf("%s/AUC_kmx%s.RData",model.dir,kmx))
# require(ggplot2)
# dff$kmx = as.factor(dff$kmx)
# temp=sapply(cohorts,length)
#
# dff$cohort.size=paste(toupper(dff$model)," (n=",temp[dff$model],")",sep = "")
# dff=dff[order(dff$network.auc),]