-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathINfORM_functions.R
More file actions
executable file
·1771 lines (1619 loc) · 74 KB
/
INfORM_functions.R
File metadata and controls
executable file
·1771 lines (1619 loc) · 74 KB
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
suppressMessages(library(igraph))
suppressMessages(library(TopKLists))
suppressMessages(library(org.Hs.eg.db))
suppressMessages(library(org.Mm.eg.db))
suppressMessages(library(GO.db))
suppressMessages(library(plyr))
suppressMessages(library(GSEABase))
suppressMessages(library(GOSemSim))
suppressMessages(library(treemap))
suppressMessages(library(abind))
suppressMessages(library(minet))
suppressMessages(library(foreach))
suppressMessages(library(parallel))
suppressMessages(library(doParallel))
suppressMessages(library(ggplot2))
suppressMessages(library(visNetwork))
suppressMessages(library(radarchart))
suppressMessages(library(WriteXLS))
suppressMessages(library(gplots))
suppressMessages(library(flock))
net_attr <- c("betweenness", "cc", "degree", "eccentricity", "closeness", "eigenvector")
methods <- c("clr","aracne","mrnet","mrnetb") # i
est.opt <- c("pearson","spearman","kendall","mi.empirical","mi.mm","mi.shrink","mi.sg")# j
disc.opt <- c("none","equalfreq","equalwidth","globalequalwidth") # k
shiny_app_vars <- NULL
shiny_app_env <- NULL
combineList <- function(...){
myParam <- list(...)
#c(myParam)
myParam
}
utils::globalVariables(names=c("GO.db"))
#' Infer correlation matrix from gene expression table by using mutual information.
#'
#' calculate_correlation_matrix uses the MINET package to create correlation matrix by mutual information method. User can specify
#' the inference algorithms, correlation calculation methods and discretization methods to create mutiple combinations of parameters
#' for multiple runs of minet(). Multiple inferences are unified by taking median to create a consensus matrix.
#'
#' @importFrom parallel detectCores makeCluster stopCluster
#' @importFrom minet minet
#' @importFrom doParallel registerDoParallel
#' @importFrom foreach foreach getDoParWorkers getDoParName %dopar%
#' @importFrom plyr aaply laply
#' @importFrom stats quantile median
#' @importFrom utils capture.output
#'
#' @param gx_table Gene expression table as a data frame.
#' @param iMethods Vector of valid inference algorithms for MINET package.
#' @param iEst Vector of valid correlation methods for MINET package.
#' @param iDisc Vector of valid discretization methods for MINET package.
#' @param summ_by Measure for summarizing the co-expression score of gene pairs from a set of netword to create a consensus network; options:median, mean, max; default:median.
#' @param ncores Number of cores for running instances of MINET in parallel default:2.
#' @param debug_output Print help and status messages to help debug the running of the function default:FALSE.
#' @param updateProgress Shiny application can request for update of progress from this function default:NULL.
#' @return A binary symmetrix matrix representing the median of mutual information correlation computed across various MINET combinations
#' @examples
#' \dontrun{
#' calculate_correlation_matrix(gx_table=gene_expression.df,
#' iMethods=c("clr","aracne","mrnet","mrnetb"),
#' iEst=c("pearson","spearman","kendall","mi.empirical","mi.mm","mi.shrink","mi.sg"),
#' iDisc=c("none","equalfreq","equalwidth","globalequalwidth"),
#' summ_by="median",
#' ncores=2,
#' debug_output=TRUE,
#' updateProgress=NULL)
#' }
#' @keywords internal
#' @export
calculate_correlation_matrix <- function(gx_table, iMethods, iEst, iDisc, summ_by="median", ncores=2, debug_output=FALSE, updateProgress=NULL){
parList <- list()
out.GX.list<- list()
out.tmp.list<- list()
out.list<- list()
tGX <- t(gx_table)
stdGX <- scale(tGX)
if(is.null(iMethods)){
stop("Please Select atLeast One Inference Algorithm!")
}
if(is.null(iEst)){
stop("Please Select At Least One Correlation!")
}
if(is.null(iDisc)){
stop("Please Select At Least One Discretization Method!")
}
cntr <- 0
for(i in 1:length(iMethods)){
#print(methods2[i])
for(j in 1:length(iEst)){
#print(paste("-",est.opt2[j]))
for(k in 1:length(iDisc)){
if(grepl("mi\\..*", est.opt[j]) && disc.opt[k]=="none"){
next
}
cntr <- cntr + 1
parList[[cntr]] <- list()
parList[[cntr]][["mt"]] <- iMethods[i]
parList[[cntr]][["est"]] <- iEst[j]
parList[[cntr]][["disc"]] <- iDisc[k]
}
}
}
#print(paste0("List of MINET Combinations: ", parList))
if(ncores > parallel::detectCores()){
ncores <- parallel::detectCores()
}
cl <- parallel::makeCluster(ncores, outfile="")
doParallel::registerDoParallel(cl)
print(paste("Total Cores: ", parallel::detectCores(), sep=""))
print(paste("Total Workers: ", foreach::getDoParWorkers(), sep=""))
print(paste("DoPar Name: ", foreach::getDoParName(), sep=""))
print(paste0("Before For Each, ", "Number of Combinations:", length(parList)))
#utils::capture.output(print(paste0("Starting Parallel Cluster For ", length(parList), " Combinations ", timestamp())), file="minet-log.txt", append=TRUE)
#utils::capture.output(print(paste0("Starting Parallel Cluster For ", length(parList), " Combinations ", timestamp())), file="minet-to-run.txt", append=TRUE)
#utils::capture.output(print(paste0("Starting Parallel Cluster For ", length(parList), " Combinations ", timestamp())), file="minet-completed.txt", append=TRUE)
utils::capture.output(print(paste0("Starting Parallel Cluster For ", length(parList), " Combinations ", timestamp())), file="minet-log.txt")
utils::capture.output(print(paste0("Starting Parallel Cluster For ", length(parList), " Combinations ", timestamp())), file="minet-to-run.txt")
utils::capture.output(print(paste0("Starting Parallel Cluster For ", length(parList), " Combinations ", timestamp())), file="minet-completed.txt")
#out.tmp.list <- foreach(i=1:length(parList)) %do% {
#tmpDir <- tempdir()
#if(is.null(env)){
# env <- environment()
#}
logDir <- "./"
env <- environment()
parallel::clusterExport(cl, list("logDir"), envir=env)
lockFile <- tempfile()
out.tmp.list <- foreach::foreach(i=1:length(parList)) %dopar% {
#testLog <- tempfile(tmpdir=logDir, pattern="minet-test", fileext=".txt")
#utils::capture.output(print("Start For Each"), file=testLog, append=TRUE)
mt <- parList[[i]]$mt
est <- parList[[i]]$est
disc <- parList[[i]]$disc
#if((est == "mi.empirical" | est == "mi.mm" | est == "mi.shrink" | est == "mi.sg") & disc == "none") {
# miMat <- -1
# miMatName <- "np"
#}
#else{
if(debug_output==TRUE){
locked <- flock::lock(lockFile)
utils::capture.output(print(paste("----",mt,est,disc, sep="__")), file="minet-log.txt", append=TRUE)
flock::unlock(locked)
}
locked <- flock::lock(lockFile)
utils::capture.output(print(paste0("Iteration-", i, ": ", mt, "-", est, "-", disc)), file="minet-to-run.txt", append=TRUE)
flock::unlock(locked)
#utils::capture.output(print(paste0("Iteration-", i, ": ", mt, "-", est, "-", disc)), file=testLog, append=TRUE)
ptm <- proc.time()
miMat <- minet::minet(stdGX, method=mt, estimator=est, disc=disc)
locked <- flock::lock(lockFile)
utils::capture.output(print(paste0("Iteration-", i, ", ", mt, "-", est, "-", disc, ": ", "MINET Execution Time - ", round(proc.time() - ptm)[3], " sec")), file="minet-completed.txt", append=TRUE)
flock::unlock(locked)
#utils::capture.output(print(paste0("Iteration-", i, ", ", mt, "-", est, "-", disc, ": ", "MINET Execution Time - ", round(proc.time() - ptm)[3], " sec")), file=testLog, append=TRUE)
miMatName <- paste(mt,est,disc,sep="__")
#}
out.list <- list("mat"=miMat, "name"=miMatName)
}
utils::capture.output(print("For Each Finished, Stopping Cluster..."), file="minet-log.txt", append=TRUE)
parallel::stopCluster(cl)
for(i in 1:length(out.tmp.list)){
out.GX.list[[i]] <- out.tmp.list[[i]]$mat
names(out.GX.list)[[i]] <- out.tmp.list[[i]]$name
}
#if(debug_output==TRUE)
#print(paste("Got minet list of lists --- ", str(out.GX.list)))
#removing ones having no values
#llGX <- out.GX.list[-(which(names(out.GX.list)=="np"))]
idx <- which(names(out.GX.list)=="np")
if(length(idx)>0){
llGX <- out.GX.list[-idx]
}else{
llGX <- out.GX.list
}
if(length(llGX)>1){
print(paste0("Making ", summ_by, " Matrix..."))
arr1<-abind::abind(llGX,along=3)
if(summ_by=="median"){
matGX <- apply(arr1,c(1,2),function(x){median(x, na.rm=TRUE)})
}else if(summ_by=="mean"){
matGX <- apply(arr1,c(1,2),function(x){mean(x, na.rm=TRUE)})
}else if(summ_by=="max"){
matGX <- apply(arr1,c(1,2),function(x){max(x, na.rm=TRUE)})
}
}else{
cat("Only one matrix, not computing ", summ_by, " matrix!\n")
matGX <- llGX[[1]]
}
print("Return Matrix")
return(matGX)
}
#' Create edge ranked inference matrix by combining information from different inference algorithms with the help of internal function calculate_correlation_matrix().
#'
#' get_ranked_consensus_matrix uses the internal function calculate_correlation_matrix() to get a single consensus matrix per inference algorithm. User can specify
#' the inference algorithms, correlation calculation methods and discretization methods, a combination of parameters will be created per inference algorithm to run calculate_correlation_matrix(),
#' this will generate a consensus matrix per inference algorithm. The consesus matrices from different inference algorithms are used to create a single binary matrix by rank based selection of edges.
#'
#' @importFrom TopKLists Borda
#'
#' @param gx_table Gene expression table as a data frame.
#' @param iMethods Vector of valid inference algorithms for MINET package.
#' @param iEst Vector of valid correlation methods for MINET package.
#' @param iDisc Vector of valid discretization methods for MINET package.
#' @param ncores Number of cores for running instances of MINET in parallel; default:2.
#' @param matList List of co-expression matrices provided by user; default:NULL.
#' @param mat_weights Type of scores in the user provided matrices; default:rank.
#' @param ensemble_strategy Strategy to use for ensemble "minet" for minet generated matrices, or "user" for only user provided matrices, or "minet+user" to combine minet generated matrices and user provided matrices; default:minet.
#' @param debug_output Print help and status messages to help debug the running of the function; default:FALSE.
#' @param updateProgress Shiny application can request for update of progress from this function; default:NULL.
#' @return A symmetrix matrix with edge ranks representing the edge rank based consensus from different inference algorithms.
#' @examples
#' \dontrun{
#' get_ranked_consensus_matrix(gx_table=gene_expression.df,
#' iMethods=c("clr","aracne","mrnet","mrnetb"),
#' iEst=c("pearson","spearman","kendall","mi.empirical","mi.mm","mi.shrink","mi.sg"),
#' iDisc=c("none","equalfreq","equalwidth","globalequalwidth"),
#' ncores=12,
#' matList=list(mat1, mat2, matN),
#' mat_weights="rank",
#' ensemble_strategy="minet",
#' debug_output=TRUE,
#' updateProgress=TRUE)
#' }
#' @keywords internal
#' @export
#get_ranked_consensus_binary_matrix <- function(gx_table, iMethods, iEst, iDisc, ncores=2, debug_output=FALSE, updateProgress=NULL){
get_ranked_consensus_matrix <- function(gx_table=NULL, iMethods=NULL, iEst=NULL, iDisc=NULL, summ_by="median", score_type="median", ncores=2, matList=NULL, mat_weights="rank", ensemble_strategy="minet", debug_output=FALSE, updateProgress=NULL){
mat_ll <- list()
ranked_edges_ll <- list()
if(!score_type %in% c("mean", "median", "geo.mean", "l2norm")){
print(paste0("score_type : '", score_type, "' is not a valid Borda score!"))
return(NULL)
}
if(length(grep("minet" ,ensemble_strategy))>0){
mthdCount <- 1
totalMthds <- length(iMethods)+1
for(mthd in iMethods){
if (is.function(updateProgress)) {
text <- paste0("'", mthd, "' consensus by ", summ_by)
value <- mthdCount / totalMthds
updateProgress(detail = text, value = value)
}
mthdCount <- mthdCount + 1
print(paste0("Calculate correlation matrix for method : ", mthd))
mat_ll[[mthd]] <- calculate_correlation_matrix(gx_table=gx_table, iMethods=mthd, iEst=iEst, iDisc=iDisc, summ_by=summ_by, ncores=ncores)
print(paste0("Get ranked edges for method : ", mthd))
mat_ll[[mthd]][lower.tri(mat_ll[[mthd]], diag=TRUE)] <- NA
edge_df <- as.data.frame(as.table(mat_ll[[mthd]]))
print("Minet edge_df before:")
print(str(edge_df))
edge_df <- edge_df[-which(is.na(edge_df$Freq)),]
edge_df <- data.frame(edge=paste0(edge_df$Var1,";",edge_df$Var2), weight=edge_df$Freq, stringsAsFactors=FALSE)
print("Minet edge_df after:")
print(str(edge_df))
ranked_edges_ll[[mthd]] <- edge_df[order(edge_df$weight, decreasing=TRUE), "edge"]
}
}
if(length(grep("user", ensemble_strategy))>0){
matList <- as.list(matList)
for(i in c(1:length(matList))){
itmName <- paste0("user_", i)
matList[[i]][lower.tri(matList[[i]], diag=TRUE)] <- NA
edge_df <- as.data.frame(as.table(matList[[i]]))
print("User edge_df before:")
print(str(edge_df))
edge_df <- edge_df[-which(is.na(edge_df$Freq)),]
edge_df <- data.frame(edge=paste0(edge_df$Var1,";",edge_df$Var2), weight=edge_df$Freq, stringsAsFactors=FALSE)
hasNulls <- FALSE
if(mat_weights=="rank"){
nullIdx <- which(edge_df$weight==0)
if(length(nullIdx)>0){
edge_df_null <- edge_df[nullIdx,]
edge_df <- edge_df[-nullIdx,]
hasNulls <- TRUE
}
}
print("User edge_df after:")
print(str(edge_df))
ordOption <- ifelse(mat_weights=="rank", FALSE, TRUE)
print(paste0("ordOption : ", ordOption))
edge_df <- edge_df[order(edge_df$weight,decreasing=ordOption),]
if(hasNulls){
edge_df <- as.data.frame(rbind(edge_df, edge_df_null), stringsAsFactors=FALSE)
}
#ranked_edges_ll[[itmName]] <- edge_df[order(edge_df$weight, decreasing=ordOption), "edge"]
ranked_edges_ll[[itmName]] <- edge_df$edge
}
}
print("ranked_edges_ll:")
print(length(ranked_edges_ll))
print(names(ranked_edges_ll))
print(lapply(ranked_edges_ll, length))
if(is.function(updateProgress)) {
updateProgress(detail = "Consensus Binary", value = 1)
}
print("Perform Borda on list of list of ranked edges.")
borda_res <- TopKLists::Borda(ranked_edges_ll)
#Borda.plot(borda_res)
print("Get a consensus binary matrix by selecting the most significant ranked edges from median rank of Borda result.")
if(length(mat_ll)>0){
rank_mat <- mat_ll[[1]]
}else{
rank_mat <- matList[[1]]
}
rank_mat[,] <- 0
print("rank_mat")
print(dim(rank_mat))
ra_list <- borda_res$TopK[[score_type]]
#Kendall.plot(ranked_edges_ll, median_list)
#if(edge_selection_strategy=="default"){
# #input_genes <- dim(gx_table)[1]
# input_genes <- nrow(rank_mat)
# genes <- NULL
# total_genes <- 0
# cutoffIdx <- NULL
# for(i in c(1:length(median_list))){
# if(total_genes<input_genes){
# local_genes <- strsplit(median_list[i], ";")[[1]]
# rank_mat[local_genes[1],local_genes[2]] <- i
# rank_mat[local_genes[2],local_genes[1]] <- i
# genes[local_genes[1]] <- 1
# genes[local_genes[2]] <- 1
# total_genes <- length(genes)
# }else{
# cutoffIdx <- i-1
# break
# }
# }
#}else if(edge_selection_strategy=="top"){
# cutOff <- round((as.numeric(topN)*length(median_list))/100)
# for(i in c(1:length(median_list))){
# if(i<=cutOff){
# local_genes <- strsplit(median_list[i], ";")[[1]]
# rank_mat[local_genes[1],local_genes[2]] <- i
# rank_mat[local_genes[2],local_genes[1]] <- i
# }else{
# break
# }
# }
#}
print("ra_list:")
print(str(ra_list))
print(length(ra_list))
print(head(ra_list))
for(i in c(1:length(ra_list))){
local_genes <- strsplit(ra_list[i], ";")[[1]]
rank_mat[local_genes[1],local_genes[2]] <- i
rank_mat[local_genes[2],local_genes[1]] <- i
}
print("Rank matrix computed, returning!")
return(rank_mat)
}
#' Get edge rank list and binary inference matrix from edge rank matrix computed by get_ranked_consensus_matrix().
#'
#' parse_edge_rank_matrix parses the edge rank matrix created by using the internal function get_ranked_consensus_matrix_matrix() to get a ranked edge list and a binary matrix.
#'
#' @importFrom TopKLists Borda
#'
#' @param edge_rank_matrix A symmetrix matrix with edge ranks as weight.
#' @param edge_selection_strategy Strategy to select edges for ensemble, "default" selects ranked edges untill all nodes have degree>=1, "top" swtiches to top N percentage ranked genes specfied by topN parameter.
#' @param mat_weights Type of scores in the ranked matrix; default:rank.
#' @param topN Top N percentage ranked edges to create ensemble if the edge_selection_strategy is "top"; default:10
#' @param debug_output Print help and status messages to help debug the running of the function; default:FALSE.
#' @param updateProgress Shiny application can request for update of progress from this function; default:NULL.
#' @return A list containing a vector of consensus edge ranks and a binary symmetrix matrix representing the edge rank matrix.
#' @examples
#' \dontrun{
#' parse_edge_rank_matrix <- function(edge_rank_matrix,
#' edge_selection_strategy="default",
#' mat_weights="rank",
#' topN=10,
#' debug_output=FALSE,
#' updateProgress=NULL)
#' }
#' @keywords internal
#' @export
parse_edge_rank_matrix <- function(edge_rank_matrix, edge_selection_strategy="default", mat_weights="rank", topN=10, debug_output=FALSE, updateProgress=NULL){
bin_mat <- edge_rank_matrix
#idx <- which(bin_mat>0)
#if(length(idx)>0){
# print("Creating binary matrix...")
# bin_mat[which(bin_mat>0)] <- 1
#}
bin_mat[,] <- 0
print("Getting edge list ordered by rank...")
rank_matrix <- edge_rank_matrix
rank_matrix[lower.tri(rank_matrix, diag=TRUE)] <- NA
edge_df <- as.data.frame(as.table(rank_matrix))
edge_df <- edge_df[-which(is.na(edge_df$Freq)),]
edge_df <- data.frame(edge=paste0(edge_df$Var1,";",edge_df$Var2), weight=edge_df$Freq, stringsAsFactors=FALSE)
edge_df <- edge_df[which(edge_df$weight>0),]
ordOption <- ifelse(mat_weights=="rank", FALSE, TRUE)
print(paste0("ordOption : ", ordOption))
print(class(edge_df$weight))
edge_rank <- edge_df$edge[order(edge_df$weight, decreasing=ordOption)]
print(paste0("edge rank before:", length(edge_rank)))
print(head(edge_rank))
if(edge_selection_strategy=="default"){
#input_genes <- nrow(rank_matrix)
input_genes <- length(unique(unlist(strsplit(edge_rank, ";"))))
print(paste0("input genes : ", input_genes))
genes <- NULL
total_genes <- 0
cutoffIdx <- NULL
for(i in c(1:length(edge_rank))){
if(total_genes<input_genes){
local_genes <- strsplit(edge_rank[i], ";")[[1]]
bin_mat[local_genes[1],local_genes[2]] <- 1
bin_mat[local_genes[2],local_genes[1]] <- 1
genes[local_genes[1]] <- 1
genes[local_genes[2]] <- 1
total_genes <- length(genes)
cutoffIdx <- i
}else{
print(paste0("Cutoff before break:", cutoffIdx))
break
}
}
}else if(edge_selection_strategy=="top"){
cutoffIdx <- round((as.numeric(topN)*length(edge_rank))/100)
for(i in c(1:length(edge_rank))){
if(i<=cutoffIdx){
local_genes <- strsplit(edge_rank[i], ";")[[1]]
bin_mat[local_genes[1],local_genes[2]] <- 1
bin_mat[local_genes[2],local_genes[1]] <- 1
}else{
break
}
}
}
print(paste0("Cutoff:", cutoffIdx))
edge_rank <- edge_rank[c(1:cutoffIdx)]
print(paste0("edge rank after:", length(edge_rank)))
res_ll <- list(bin_mat=bin_mat, edge_rank=edge_rank)
print("Returning!")
return(res_ll)
}
#' Create iGraph object from a symmetrical adjacency matrix, annotate it with centrality attributes and return the annotated iGraph.
#'
#' @importFrom igraph graph.adjacency vertex_attr betweenness closeness degree eigen_centrality transitivity edge_attr list.vertex.attributes
#'
#' @param adj_mat Binary consensus matrix computed by using get_ranked_consensus_binary_matrix() function.
#' @return Annotated igraph object representing the binary consensus matrix computed by get_ranked_consensus_binary_matrix() function.
#' @examples
#' \dontrun{
#' get_iGraph(adj_mat=binary.inference.matrix)
#' }
#' @keywords internal
#' @export
get_iGraph <- function(adj_mat){
if(is.null(adj_mat)){
stop("Input Adjacency Matrix is NULL!")
}
if(!isSymmetric(adj_mat)){
print("Matrix is not symmetric. Getting symmetric matrix!")
#adj_mat <- get_symmetric_matrix(adj_mat)
adj_mat <- pmax(adj_mat, t(adj_mat))
}
iG <- igraph::graph.adjacency(adj_mat, mode="undirected", weighted=NULL)
igraph::vertex_attr(iG, name="betweenness") <- as.vector(igraph::betweenness(iG))
igraph::vertex_attr(iG, name="closeness") <- as.vector(igraph::closeness(iG, normalized=TRUE))
igraph::vertex_attr(iG, name="degree") <- as.vector(igraph::degree(iG))
igraph::vertex_attr(iG, name="eigenvector") <- as.vector(igraph::eigen_centrality(iG)$vector)
igraph::vertex_attr(iG, name="cc") <- igraph::transitivity(iG, type="local", isolates="zero")
igraph::vertex_attr(iG, name="color") <- "#D3D3D3"
igraph::vertex_attr(iG, name="highlightcolor") <- "#A9A9A9"
igraph::edge_attr(iG, name="color") <- "#D3D3D3"
igraph::edge_attr(iG, name="highlightcolor") <- "#A9A9A9"
print(igraph::list.vertex.attributes(iG))
iG
}
#' Annotate iGraph object with centrality attributes and return the annotated iGraph.
#'
#' @importFrom igraph vertex_attr betweenness closeness degree eigen_centrality transitivity edge_attr list.vertex.attributes list.edge.attributes
#'
#' @param iG igraph object created from the binary consensus matrix computed by using get_ranked_consensus_binary_matrix() function.
#' @return Annotated igraph object representing the binary consensus matrix computed by get_ranked_consensus_binary_matrix() function.
#' @examples
#' \dontrun{
#' annotate_iGraph(iG=inferred.iGraph)
#' }
#' @keywords internal
#' @export
annotate_iGraph <- function(iG){
igraph::vertex_attr(iG, name="betweenness") <- as.vector(igraph::betweenness(iG))
igraph::vertex_attr(iG, name="closeness") <- as.vector(igraph::closeness(iG, normalized=TRUE))
igraph::vertex_attr(iG, name="degree") <- as.vector(igraph::degree(iG))
igraph::vertex_attr(iG, name="eigenvector") <- as.vector(igraph::eigen_centrality(iG)$vector)
igraph::vertex_attr(iG, name="cc") <- igraph::transitivity(iG, type="local", isolates="zero")
vertex_attr_list <- igraph::list.vertex.attributes(iG)
edge_attr_list <- igraph::list.edge.attributes(iG)
if(!("color" %in% vertex_attr_list)){
igraph::vertex_attr(iIG, name="color") <- "#D3D3D3"
}
if(!("highlightcolor" %in% vertex_attr_list)){
igraph::vertex_attr(iIG, name="highlightcolor") <- "#A9A9A9"
}
if(!("color" %in% edge_attr_list)){
igraph::edge_attr(iIG, name="color") <- "#D3D3D3"
}
if(!("highlightcolor" %in% edge_attr_list)){
igraph::edge_attr(iIG, name="highlightcolor") <- "#A9A9A9"
}
print(igraph::list.vertex.attributes(iG))
return(iG)
}
#' Set general vertex colors and also colors to highlight the identified important vertices.
#'
#' @importFrom igraph vertex_attr V
#' @importFrom stats quantile
#'
#' @param iGraph igraph object created from the binary consensus matrix computed by using get_ranked_consensus_binary_matrix() function.
#' @param gx_data_table Gene expression table as a data frame, must have gene symbols as rownames and sample names as colnames.
#' @param dgx_table Differential Gene expression table as a data frame, must have gene symbols as rownames but should not have colnames.
#' @param pos_cor_color Valid color name or hex code for genes positively associated with differential gene expression.
#' @param pos_cor_highlight_color Valid color name or hex code for highlighted genes positively associated with differential gene expression.
#' @param neg_cor_color Valid color name or hex code for genes negatively associated with differential gene expression.
#' @param neg_cor_highlight_color Valid color name or hex code for highlighted genes negatively associated with differential gene expression.
#' @param pos_perc Percentile cutoff for positive association of genes with differential gene expression score, default:0.95.
#' @param neg_perc Percentile cutoff for negative association of genes with differential gene expression score, default:0.05.
#' @return igraph object with user provided vertex color for normal and highlighted vertices.
#' @examples
#' \dontrun{
#' set_vertex_color(iGraph=inferred.igraph,
#' gx_data_table=gene_expression.df,
#' dgx_table=differential_gene_expression.df,
#' pos_cor_color=color.pos, pos_cor_highlight_color=color.pos.highlight,
#' neg_cor_color=color.neg,
#' neg_cor_highlight_color=color.neg.highlight,
#' pos_perc=pos.threshold,
#' neg_perc=neg.threshold
#' )
#' }
#' @keywords internal
#' @export
set_vertex_color <- function(iGraph, gx_data_table, dgx_table, pos_cor_color="#FA8072", pos_cor_highlight_color="#FF0000", neg_cor_color="#ADD8E6", neg_cor_highlight_color="#4169E1", pos_perc=0.95, neg_perc=0.05){
#Intitialize color vectors
col_length <- vcount(iGraph)
color_vector <- rep("#D3D3D3", col_length)
highlight_color_vector <- rep("#A9A9A9", col_length)
vNames <- igraph::V(iGraph)$name
if("score" %in% list.vertex.attributes(iGraph))
{
posCor <- vNames[which(igraph::V(iGraph)$score>=stats::quantile(igraph::V(iGraph)$score, pos_perc))]
negCor <- vNames[which(igraph::V(iGraph)$score<=stats::quantile(igraph::V(iGraph)$score, neg_perc))]
}
else{
dgx_table <- as.matrix(dgx_table)
dgx_table <- dgx_table[vNames,]
scoreColIdx <- NULL
if("score" %in% colnames(dgx_table)){
scoreColIdx <- which(colnames(dgx_table)=="score")
}else if(any(c("lfc", "logfc", "log.fc", "log-fc") %in% tolower(colnames(dgx_table)))){
scoreColIdx <- which(tolower(colnames(dgx_table))%in%c("lfc", "logfc", "log.fc", "log-fc"))
}else{
if(ncol(dgx_table)>=2){
scoreColIdx <- 2
}else{
scoreColIdx <- 1
}
}
posCor <- rownames(dgx_table)[which(dgx_table[,scoreColIdx]>= stats::quantile(as.vector(dgx_table[,scoreColIdx]), pos_perc))]
negCor <- rownames(dgx_table)[which(dgx_table[,scoreColIdx]<= stats::quantile(as.vector(dgx_table[,scoreColIdx]), neg_perc))]
}
print("For Loop for populating vertex color vector...")
#for(i in c(which(is.element(rownames(gx_data_table),posCor)))){
for(i in c(which(is.element(vNames,posCor)))){
color_vector[i] <- pos_cor_color
highlight_color_vector[i] <- pos_cor_highlight_color
}
#for(i in c(which(is.element(rownames(gx_data_table),negCor)))){
for(i in c(which(is.element(vNames,negCor)))){
color_vector[i] <- neg_cor_color
highlight_color_vector[i] <- neg_cor_highlight_color
}
igraph::vertex_attr(iGraph, name="color") <- color_vector
igraph::vertex_attr(iGraph, name="highlightcolor") <- highlight_color_vector
return(iGraph)
}
#' Set general edge colors and also colors to highlight the identified important edges.
#'
#' set_edge_color assigns color and highlight color to the edges. User provided gene expression table is used to compute correlation
#' between the genes, edges with positive value of correlation are assigned specific colors and edges with negative value of correlation
#' are assigned specific colors. The highlight colors are used to faciliate sub-network extraction and highlighting the seed genes used for
#' extracting the sub-networks.
#'
#' @importFrom igraph get.edges edge_attr E
#' @importFrom stats cor
#'
#' @param iGraph igraph object created from the binary consensus matrix computed by using get_ranked_consensus_binary_matrix() function.
#' @param gx_data_table Gene expression table as a data frame, must have gene symbols as rownames and sample names as colnames.
#' @param pos_cor_color Valid color name or hex code for edges showing positive correlation between genes.
#' @param pos_cor_highlight_color Valid color name or hex code for highlighted edges showing positive correlation between genes.
#' @param neg_cor_color Valid color name or hex code for edges showing negative correlation between genes.
#' @param neg_cor_highlight_color Valid color name or hex code for highlighted edges showing negative correlation between genes.
#' @return igraph object with user provided vertex color for normal and highlighted vertices.
#' @examples
#' \dontrun{
#' set_edge_color(iGraph=inferred.igraph,
#' gx_data_table=gene_expression.df,
#' pos_cor_color=color.pos,
#' pos_cor_highlight_color=color.pos.highlight,
#' neg_cor_color=color.neg,
#' neg_cor_highlight_color=color.neg.highlight
#' )
#' }
#' @keywords internal
#' @export
set_edge_color <- function(iGraph, gx_data_table, pos_cor_color="#FA8072", pos_cor_highlight_color="#FF0000", neg_cor_color="#ADD8E6", neg_cor_highlight_color="#4169E1"){
tGX <- t(gx_data_table)
corGX <- cor(tGX)
matColor <- ifelse(corGX<=0, neg_cor_color, pos_cor_color)
matHighlightColor <- ifelse(corGX<=0, neg_cor_highlight_color, pos_cor_highlight_color)
#edgeIDs <- igraph::get.edges(iGraph, igraph::E(iGraph))
edgeIDs <- igraph::ends(iGraph, igraph::E(iGraph), names=TRUE)
#print("edgeIDs")
#print(edgeIDs)
cols <- apply(edgeIDs, 1, function(x) {
matColor[x[1],x[2]]
})
#print(cols)
igraph::edge_attr(iGraph, name="color") <- apply(edgeIDs, 1, function(x) {
matColor[x[1],x[2]]
})
igraph::edge_attr(iGraph, name="highlightcolor") <- apply(edgeIDs, 1, function(x) {
matHighlightColor[x[1],x[2]]
})
return(iGraph)
}
#' Get top ranked candidates computed by Borda on the provided list of attributes and the cutoff.
#'
#' get_ranked_gene_list uses the annotation associated with each vertex to rank them and generated a list of vertices names ordered by rank.
#' By default the annotations calculated by INfORM are "betweenness", "cc", "degree", "eccentricity", "closeness" & "eigenvector". The vertices are
#' ranked by each annotation separately nad then the ranks are unified by means of Borda(). User must provide the annotations to use in ranking scheme,
#' if the user has custom annotations such as "score" for differential gene expression then it can also be used for ranking.
#'
#' @importFrom igraph get.vertex.attribute
#' @importFrom TopKLists Borda
#' @importFrom utils head
#'
#' @param iGraph igraph object created from the binary consensus matrix computed by using get_ranked_consensus_binary_matrix() function.
#' @param rank_list_attr Vector of network attributes/scores to use for generating a combined gene rank
#' @param debug_output Print help and status messages to help debug the running of the function default:FALSE.
#' @return vector of genes ordered by rank, based on the selected attributes associated to each gene.
#' @examples
#' \dontrun{
#' get_ranked_gene_list(iGraph=inferred.igraph,
#' rank_list_attr=c("betweenness",
#' "cc",
#' "degree",
#' "eccentricity",
#' "closeness",
#' "eigenvector",
#' "score"),
#' debug_output=FALSE
#' )
#' }
#' @keywords internal
#' @export
get_ranked_gene_list <- function(iGraph, rank_list_attr, debug_output=FALSE){
if(is.null(rank_list_attr)){
stop("List of attributes for ranking is NULL!")
}
attrOrdMat <- list()
for(a in 1:length(rank_list_attr)){
val_ord=TRUE
if(debug_output==TRUE)
print(paste("Using attribute: ", rank_list_attr[a], sep=""))
attrValueVector <- igraph::get.vertex.attribute(iGraph, rank_list_attr[a])
if(rank_list_attr[a] == "score")
attrValueVector <- abs(attrValueVector)
attrOrdList <- cbind(igraph::V(iGraph)$name, attrValueVector)[order(attrValueVector, decreasing=val_ord)]
if(debug_output==TRUE)
print(utils::head(attrOrdList))
attrOrdMat[[a]] <- attrOrdList
}
attrBorda <- TopKLists::Borda(attrOrdMat)
if(debug_output==TRUE)
print(utils::head(attrBorda$TopK, n=10))
return(attrBorda$TopK$median)
}
#' Get subgraph from the main igraph.
#'
#' Extract a subgraph from the main graph by using a list of genes to identify and select genes interconnected in a hub with them.
#'
#' @importFrom igraph neighborhood V induced.subgraph
#'
#' @param iGraph igraph object representing the main graph from which the subgraph should be extracted.
#' @param selected_vertices Vector of genes to be used for identifying interconnected hub.
#' @param vertex_level define the area of inclusion around the selected_vertices default:1.
#' @param shortest_paths Use shortest paths between selected_vertices to identify interconnected hubs default:FALSE.
#' @return igraph object representing the extracted subgraph
#' @examples
#' \dontrun{
#' get_sub_graph(iGraph=main.graph, selected_vertices, vertex_level=1, shortest_paths=TRUE)
#' }
#' @keywords internal
#' @export
get_sub_graph <- function(iGraph, selected_vertices, vertex_level=1, shortest_paths=FALSE)
{
tmpVertices <- NULL
#print("Getting nodes in the neighborhood...")
theHood <- igraph::neighborhood(graph=iGraph, nodes=selected_vertices, order=vertex_level)
for(i in 1:length(theHood))
{
tmpVertices <- c(tmpVertices, theHood[[i]])
}
#print("Getting Shortest Paths!")
for(i in 1:length(selected_vertices))
{
fromVertex <- selected_vertices[i]
#print("Pre shortes_path function!")
#pathObject <- shortest_paths(graph=iGraph, from=fromVertex, to=selected_vertices)
pathObject <- shortest_paths(graph=iGraph, from=fromVertex, to=selected_vertices[-i])
#print("Post shortes_path function!")
pathVertices <- pathObject$vpath
for(j in 1:length(pathVertices))
{
tmpVertices <- c(tmpVertices, pathVertices[[j]])
}
}
#print("Got All vertices!")
vertices4SubGraph <- unique(tmpVertices)
subiGraph <- induced.subgraph(graph=iGraph, vids=vertices4SubGraph)
print(list.vertex.attributes(subiGraph))
#vertices2Highlight <- which(get.vertex.attribute(subiGraph,"name") %in% selected_vertices)
#igraph::V(subiGraph)$color[vertices2Highlight] <- igraph::V(subiGraph)$highlightcolor[vertices2Highlight]
subiGraph
}
#' Get modules from the main igraph.
#'
#' Extract modules from the main graph by using a specified community detection algorithm from igraph.
#'
#' @importFrom igraph cluster_walktrap cluster_spinglass cluster_louvain cluster_fast_greedy
#'
#' @param iGraph igraph object representing the main graph from which the subgraph should be extracted.
#' @param method community detection method from igraph.
#' @return communities object cotaining communities identified from igraph object by using a specific method
#' @examples
#' \dontrun{
#' get_modules(iGraph=main.graph, method="walktrap")
#' }
#' @keywords internal
#' @export
get_modules <- function(iGraph, method="walktrap")
{
switch(method,
"walktrap" = {
optimalStep <- c(2:10)[which.max(sapply(c(2:10), function(x){igraph::modularity(igraph::cluster_walktrap(iGraph, step=x))}))]
igraph::cluster_walktrap(iGraph, step=optimalStep)
},
"spinglass" = igraph::cluster_spinglass(iGraph),
"louvain" = igraph::cluster_louvain(iGraph),
"greedy" = igraph::cluster_fast_greedy(iGraph)
)
}
#' Annotate modules identified from the main igraph.
#'
#' Annotate modules and return list-of-list containing igraph objects, annotation enrichment and ranks.
#'
#' @import org.Hs.eg.db
#' @import org.Mm.eg.db
#' @importFrom AnnotationDbi select
#' @importFrom igraph communities induced.subgraph get.edgelist
#'
#' @param iGraph igraph object representing the main graph from which the subgraph should be extracted.
#' @param modules Modules detected from the main igraph with specific community detection method.
#' @param rl Ordered ranked list of genes obtained by taking median rank from Borda over all scores.
#' @param rl.c Ordered ranked list of genes obtained by taking median rank from Borda over centrality scores.
#' @param rl.pv Ordered ranked list of genes by P.Value obtained from differential expression analysis.
#' @param rl.lfc Ordered ranked list of genes by Log FC obtained from differential expression analysis.
#' @param rl.edge Ordered ranked list of edges obtained by taking median rank from Borda over ranked edges from matrices inferred by different algorithms.
#' @param annDB Organism specific annotation library default:'org.Hs.eg.db'.
#' @param p_value P.Value cutoff for the enriched GO terms default:0.05.
#' @param min_mod_size Minimum module size to select modules for annotation and to be added in results; DEFAULT:10.
#' @param prefix string to prefix module names; DEFAULT:NULL.
#' @return list-of-list containing igraph objects, annotation enrichment and median values for vertice and edges by different rank lists in each module
#' @examples
#' \dontrun{
#' annotate_modules(iGraph=main.graph,
#' modules,
#' rl,
#' rl.c,
#' rl.pv=NULL,
#' rl.lfc=NULL,
#' rl.edge=NULL,
#' annDB="org.Hs.eg.db",
#' p_value=0.05,
#' min_mod_size=10,
#' prefix=NULL
#' )
#' }
#' @keywords internal
#' @export
annotate_modules <- function(iGraph, modules, rl, rl.c, rl.pv=NULL, rl.lfc=NULL, rl.edge=NULL, annDB="org.Hs.eg.db", p_value=0.05, min_mod_size=10, prefix=NULL){
res_ll <- list()
res_ll[["names"]] <- igraph::communities(modules)
#Filter modules by size
len_vec <- as.vector(unlist(lapply(res_ll[["names"]], length)))
idx <- which(len_vec<min_mod_size)
if(length(idx)>0){
res_ll[["names"]] <- res_ll[["names"]][-idx]
}
if(!is.null(prefix)){
names(res_ll[["names"]]) <- paste0(prefix, "_", c(1:length(res_ll[["names"]])))
}
res_ll[["ig"]] <- lapply(res_ll[["names"]], function(x){igraph::induced.subgraph(iGraph, x)})
res_ll[["ae"]] <- lapply(
res_ll[["names"]], function(x){
res <- annotation_enrichment(genelist=x, annDB=annDB)
#res <- res[res$ease<=0.05,]
res <- res[res$ease<=p_value,]
if(nrow(res)==0)
return(NULL)
selectAnnDF <- AnnotationDbi::select(GO.db, keys=as.vector(res$ID), columns=c("TERM", "ONTOLOGY"), keytype="GOID")
#res <- cbind(selectAnnDF, res[,c(3,2)])
#colnames(res)[c(4,5)] <- c("Score", "Genes")
res <- cbind(selectAnnDF, res[,c("pValue", "ease", "User_Genes", "Symbols")])
colnames(res)[c(4:ncol(res))] <- c("P_Value", "EASE_Score", "Gene_Count", "Genes")
res
}
)
res_ll[["ranks"]] <- lapply(
res_ll[["names"]],
function(x){
tmp_list <- list()
tmp_list[["rank_combined"]] <- round(1-(median(which(rl %in% x))/length(rl)),2)
tmp_list[["rank_centrality"]] <- round(1-(median(which(rl.c %in% x))/length(rl.c)),2)
if(!is.null(rl.pv)){
tmp_list[["rank_pv"]] <- round(1-(median(which(rl.pv %in% x))/length(rl.pv)),2)
}
if(!is.null(rl.lfc)){
tmp_list[["rank_lfc"]] <- round(1-(median(which(rl.lfc %in% x))/length(rl.lfc)),2)
}
if(!is.null(rl.edge)){
el <- apply(igraph::get.edgelist(igraph::induced.subgraph(iGraph, x)), 1, paste, collapse=";")
tmp_list[["rank_edge"]] <- round(1-(median(which(rl.edge %in% el))/length(rl.edge)),2)
}
tmp_list
}
)
return(res_ll)
}
#' Get table containing score for genes in the iGraph by th euser provided ranked lists.
#'
#' Get table containing score for genes in the iGraph by th euser provided ranked lists.
#'
#' @importFrom igraph communities induced.subgraph get.edgelist
#'
#' @param iGraph igraph object representing the main graph from which the subgraph should be extracted.
#' @param gene_ll Named list of character vectors containing gene symbols, representing the genes present in modules.
#' @param rl Ordered ranked list of genes obtained by taking median rank from Borda over all scores.
#' @param rl.c Ordered ranked list of genes obtained by taking median rank from Borda over centrality scores.
#' @param rl.pv Ordered ranked list of genes by P.Value obtained from differential expression analysis.
#' @param rl.lfc Ordered ranked list of genes by Log FC obtained from differential expression analysis.
#' @param rl.edge Ordered ranked list of edges obtained by taking median rank from Borda over ranked edges from matrices inferred by different algorithms.
#' @return Data frame containing median(ranks), size and GO within similarity.
#' @examples
#' \dontrun{
#' get_rank_table(iGraph=main.graph,
#' gene_ll,
#' rl,
#' rl.c,
#' rl.pv=NULL,
#' rl.lfc=NULL,
#' rl.edge=NULL)
#' }
#' @keywords internal
#' @export
get_rank_table <- function(iGraph, gene_ll, rl, rl.c, rl.pv, rl.lfc, rl.edge){
#res_ll <- list()
res_ll <- lapply(
gene_ll,
function(x){
res <- c()
res["rank_combined"] <- round(1-(median(which(rl %in% x))/length(rl)),2)
res["rank_centrality"] <- round(1-(median(which(rl.c %in% x))/length(rl.c)),2)
if(!is.null(rl.pv)){
res["rank_pv"] <- round(1-(median(which(rl.pv %in% x))/length(rl.pv)),2)
}
if(!is.null(rl.lfc)){
res["rank_lfc"] <- round(1-(median(which(rl.lfc %in% x))/length(rl.lfc)),2)
}
if(!is.null(rl.edge)){
el <- apply(igraph::get.edgelist(igraph::induced.subgraph(iGraph, x)), 1, paste, collapse=";")
res["rank_edge"] <- round(1-(median(which(rl.edge %in% el))/length(rl.edge)),2)
}
res["size"] <- round(length(x)/igraph::vcount(iGraph),2)
res
}
)
resDF <- as.data.frame(t(as.data.frame(res_ll)))
#resDF[,"GO"] <- rep(NA, nrow(resDF))
#tmp_vec <- unlist(lapply(ae_ll, function(x) get_jaccard_sim(x, x, IC_ll=IC_ll)))
#idx <- which(rownames(resDF) %in% names(tmp_vec))
#if(length(idx)>0){
# resDF[idx,"GO"] <- tmp_vec
#}
return(resDF)
}
#' Convert annotated modules list-of-list to data frame containing rank and size.
#'
#' Converts the list-of-list object of annotated modules and returns a data frame with annotation information, ready to be used for plotting.
#'
#' @import org.Hs.eg.db
#' @import org.Mm.eg.db
#' @importFrom AnnotationDbi select
#' @importFrom igraph vcount
#'
#' @param iGraph igraph object representing the main graph from which the subgraph should be extracted.
#' @param annotated_modules_ll list-of-list containing igraph objects, annotation enrichment and ranks for each module.