-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserver.R
executable file
·1627 lines (1457 loc) · 70.6 KB
/
server.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
options(repos = c(getOption("repos"), BiocManager::repositories()))
getOption("repos")
library(shiny)
library(rsconnect)
library(plyr)
library(data.table)
library(genefilter)
library(Biobase)
library(lmQCM)
library(WGCNA)
library(GEOquery)
library(dplyr)
library(enrichR)
library(DT)
library(plotly)
library(openxlsx)
library(survival)
library(naturalsort)
library(shinyWidgets)
library(progress)
# circos plot
library(circlize)
# library(topGO) # Somehow conflict with WGCNA and GEOquery. Deprecated.
options(shiny.maxRequestSize=300*1024^2) # to the top of server.R would increase the limit to 300MB
options(shiny.sanitize.errors = FALSE)
options(stringAsFactors = FALSE)
source("utils.R")
# setwd("/Users/zhi/Desktop/GeneCoexpression/RGUI"); #mac #remove when deploy to shinyapps.io
# source("./lmQCM/GeneCoExpressionAnalysis.R")
# ----------------------------------------------------
setClass("QCMObject", representation(clusters.id = "list", clusters.names = "list",
eigengene.matrix = "data.frame"))
# listEnrichrDbs()
# print(list.files())
# print(list.files("./data"))
path2TCGAdata <<- "./data/20190303_TCGA_gdac_mRNAseq/"#"http://web.ics.purdue.edu/~huang898/TSUNAMI_data/20190303_TCGA_gdac_mRNAseq/"
enrichr_dbs <<- c("GO_Biological_Process_2018",
"GO_Molecular_Function_2018",
"GO_Cellular_Component_2018",
"Jensen_DISEASES",
"Reactome_2016",
"KEGG_2016",
"Transcription_Factor_PPIs",
"Genome_Browser_PWMs",
"TRANSFAC_and_JASPAR_PWMs",
"ENCODE_TF_ChIP-seq_2015",
"Chromosome_Location",
"miRTarBase_2017",
"TargetScan_microRNA_2017",
"ChEA_2016")
TCGA.gdac.list <<- read.csv("./data/TCGA_gdac_metadata.csv", header = T)
server <- function(input, output, session) {
data <- reactiveVal(0)
data_final <- reactiveVal(0)
GEO <- reactiveVal(0)
GSE_name_title <- reactiveVal(0)
mygset <- reactiveVal(0)
finalExp <- reactiveVal(0)
finalSym <- reactiveVal(0)
sampleID <- reactiveVal(0)
finalSymChar <- reactiveVal(0)
text.final <- reactiveVal(0)
geneCharVector_global <- reactiveVal(0)
eigengene_matrix <- reactiveVal(0)
fname <- reactiveVal(0) # e.g. 12345_at
enriched <- reactiveVal(0) # all enrichr results
final_genes_str <- reactiveVal(0)
data.name <- reactiveVal(0)
###################### Website migration ######################
# reactiveValues object for storing current data set.
redirect.time <- 10
EventTime <- Sys.time() + redirect.time
# Return the UI for a modal dialog with data selection input. If 'failed' is
# TRUE, then display a message that the previous value was invalid.
dataModal <- function(failed = FALSE) {
modalDialog(
title = "Web server migration notice",
"Dear TSUNAMI user: We are switching from R shiny server page to Biolearns TSUNAMI. If you would like to use legacy R shiny server page, you can click stay button. Otherwise, click Redirect now button if you want to proceed now.",
HTML("<br><br>"),
output$eventTimeRemaining <- renderText({
invalidateLater(1000, session)
paste("Redirect to Biolearns in:",
round(difftime(EventTime, Sys.time(), units='secs')), 'secs')
}),
footer = tagList(
actionButton("stay", "Stay on this site"),
actionButton("redirect", "Redirect now")
)
)
}
showModal(dataModal())
# When OK button is pressed, attempt to load the data set. If successful,
# remove the modal. If not show another modal, but this time with a failure
# message.
observeEvent(input$stay, {
removeModal()
})
observeEvent(input$redirect, {
session$sendCustomMessage("redirectmessage", "redirectmessage")
})
dt <- 0 # Nb seconds
# Timer one second
autoInvalidate <- reactiveTimer(1000)
observe({
dt <<- dt + 1 # Increment one second
someCondition = FALSE
if(dt >= redirect.time){ # After 30 seconds
someCondition = TRUE
}
if(someCondition)
session$sendCustomMessage("redirectmessage", "redirectmessage")
else
autoInvalidate() # Restart timer
})
observeEvent(input$action1,{
print('tab1')
session$sendCustomMessage("myCallbackHandler", "tab1")
})
output$NCBI_GEO_Release_Date <- renderPlotly({
# Create a Progress object
progress <- shiny::Progress$new(session)
progress$set(message = "Loading NCBI GEO database. Last fetched version: 03/03/2019", value = 100)
# Close the progress when this reactive exits (even if there's an error)
on.exit(progress$close())
# NCBI GEO
load("./data/GEO_20190303.Rdata")
GEO.temp <- GEO
GEO.temp[["Actions"]] <- paste0('<div><button type="button" class="btn-analysis" id=GEO_dataset_analysis_',1:nrow(GEO.temp),'>Analyze</button></div>')
colnames(GEO.temp)[which(names(GEO.temp) == "Sample.Count")] <- "Samples"
GEO.temp <- GEO.temp %>% select("Samples", everything())
GEO.temp <- GEO.temp %>% select("Actions", everything())
GEO(GEO.temp)
# Basic process
TCGA.gdac.list[["Actions"]] <- paste0('<div><button type="button" class="btn-analysis" id=TCGA_dataset_analysis_',1:nrow(TCGA.gdac.list),'>Analyze</button></div>')
TCGA.gdac.list <- TCGA.gdac.list %>% select("Actions", everything())
output$mytable0 <- DT::renderDataTable({
DT::datatable(TCGA.gdac.list, extensions = 'Responsive', escape=F, selection = 'none',
options = list(paging = F, searching = T, dom='t',ordering=T), rownames = F)
})
output$mytable1 <- DT::renderDataTable({
DT::datatable(GEO(), extensions = 'Responsive', escape=F, selection = 'none', rownames = F)
})
# Other fancy processes
# number of samples
output$NCBI_GEO_Sample_Histogram <- renderPlotly({
GEO_sample_number <- GEO()$Samples
plot_ly(x = GEO_sample_number, type = "histogram") %>%
layout(title = "Samples Histogram (log scale)",font=list(size = 10),
xaxis = list(title = "Number of Samples"),
yaxis = list(title = "Occurence", type = "log")) %>%
layout(plot_bgcolor='transparent') %>%
layout(paper_bgcolor='transparent') %>% config(displayModeBar = F)
})
#release date
GEO_release_date <- as.Date(GEO()$Release.Date,format = "%B %d, %Y")
GEO_release_date_unique = cumsum(table(GEO_release_date)) #cummulative sum
font <- list(family = "Courier New, monospace", size = 12, color = "black")
x_axis <- list(title = "", titlefont = font, tickangle = 45, zeroline = TRUE)
y_axis <- list(title = "Number of GSE data", titlefont = font)
plot_ly(x = names(GEO_release_date_unique), y = as.numeric(GEO_release_date_unique),
type = 'scatter', mode = 'lines') %>%
layout(title = "Number of GSE Data Growing",font=list(size = 10), xaxis = x_axis, yaxis = y_axis) %>%
layout(plot_bgcolor='transparent') %>%
layout(paper_bgcolor='transparent') %>% config(displayModeBar = F)
})
observeEvent(input$dataset_lastClickId_mytable0,{
if (input$dataset_lastClickId_mytable0%like%"TCGA_dataset_analysis"){
row_of_TCGA <- as.numeric(gsub("TCGA_dataset_analysis_","",input$dataset_lastClickId_mytable0))
print(TCGA.gdac.list[row_of_TCGA,])
cancer.name = TCGA.gdac.list[row_of_TCGA,2]
data.name(cancer.name)
smartModal(error=F, title = sprintf("Loading TCGA %s Data", cancer.name),
content = sprintf("Loading TCGA %s Data ...", cancer.name))
load(paste0(path2TCGAdata, cancer.name, ".Rdata"))
# TCGA.mRNAseq = data.frame(cbind(rownames(TCGA.mRNAseq), TCGA.mRNAseq))
# colnames(TCGA.mRNAseq)[1] = "Gene"
data(TCGA.mRNAseq)
updateTextInput(session, "platform_text", value = "")
output$summary <- renderPrint({
print(sprintf("Data: %s", data.name() ))
print(sprintf("Number of Genes: %d",dim(data())[1]))
print(sprintf("Number of Samples: %d",dim(data())[2]))
})
print("GEO file is downloaded to server and processed.")
output$mytable4 <- DT::renderDataTable({
# Expression Value
DT::datatable(data(),extensions = 'Responsive', escape=F, selection = 'none')
})
output$mytable5 <- DT::renderDataTable({
# Expression Value
verified_data = data()[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data())[1],
ifelse(is.na(input$starting_col),1,input$starting_col):dim(data())[2]]
# colnames(verified_data)[1] <- "Gene"
DT::datatable(verified_data,extensions = 'Responsive', escape=F, selection = 'none')
})
print('tab2')
removeModal()
session$sendCustomMessage("myCallbackHandler", "tab2")
}
})
observeEvent(input$dataset_lastClickId_mytable1,{
if (input$dataset_lastClickId_mytable1%like%"GEO_dataset_analysis"){
row_of_GEO <- as.numeric(gsub("GEO_dataset_analysis_","",input$dataset_lastClickId_mytable1))
myGSE <- GEO()$Accession[row_of_GEO]
data.name(myGSE)
GSE_name_title(GEO()$Title[row_of_GEO])
message(GSE_name_title())
print(myGSE)
smartModal(error=F, title = sprintf("Loading %s file from NCBI GEO Database", myGSE),
content = "We are currently loading your selected file from NCBI GEO Database ...")
t <- try(gset <- getGEO(myGSE, GSEMatrix=TRUE, AnnotGPL=FALSE)) #AnnotGPL default is FALSE
if("try-error" %in% class(t)) {
removeModal()
print("HTTP error 404")
smartModal(error=T, title = "HTTP error 404", content = sprintf("%s is not available in NCBI GEO Database, please try other available GSE data (e.g., GSE17537, GSE73119). (Hint: Maybe bad Internet connection)",myGSE))
return()
}
# if (length(gset) > 1) idx <- grep("GPL90", attr(gset, "names")) else idx <- 1
if (length(gset) == 0){
removeModal()
print("This GSE accession doesn't contain any series matrix.")
smartModal(error=T, title = "This GSE accession doesn't contain any series matrix.", content = sprintf("%s doesn't contain any series matrix. Please try other available GSE data (e.g., GSE17537, GSE73119).",myGSE))
return()
}
mygset(gset[[1]])
# select index
if (length(gset) > 1){
gset.names = names(gset)
print(gset.names)
gset.names = paste0(rep(1:length(gset.names)), ". ", gset.names)
gset.names = paste0(gset.names, collapse = "\n")
removeModal()
inputSweetAlert(session, inputId = "whichgset", title = "This data contains multiple serie matrices.\nInput the ID (e.g. 1) to select desired one.",
text = gset.names,
type = "info", btn_labels = "Ok")
observeEvent(input$whichgset, {
mygset(gset[[as.numeric(input$whichgset)]])
})
}
}
})
observeEvent(data(),{
if (typeof(data()) == "double"){
return()
}
samples = colnames(data())[input$starting_col:dim(data())[2]]
output$data_sample_subgroup_ui <- renderUI({
checkboxGroupInput("data_sample_subgroup", "Choose samples:",
choiceNames = samples,
choiceValues = samples,
selected = samples
)
})
})
observeEvent(mygset(),{
if (typeof(mygset()) == "double"){
return()
}
smartModal(error=F, title = sprintf("Selecting table from NCBI GEO Database"),
content = "We are currently loading your selected file from NCBI GEO Database ...")
edata <- exprs(mygset()) #This is the expression matrix
if (dim(edata)[1] == 0 || is.null(dim(edata))){
removeModal()
print("No expression data")
smartModal(error=T, title = "Important message", content = sprintf("%s doesn't contain any expression data, please try other available GSE data (e.g., GSE17537, GSE73119).", myGSE))
return()
}
# pdata <- pData(mygset()) # data.frame of phenotypic information.
fname(featureNames(mygset())) # e.g. 12345_at
# data(cbind(fname(), edata))
# data.temp <- data()
# row.names(data.temp) <- seq(1, length(fname()))
# data(data.temp)
row.names(edata) <- fname()
data(edata)
updateTextInput(session, "platform_text", value = paste(annotation(mygset()), input$controller))
output$summary <- renderPrint({
print(sprintf("Data: %s", data.name() ))
print(sprintf("Number of Genes: %d",dim(edata)[1]))
print(sprintf("Number of Samples: %d",dim(edata)[2]))
print(sprintf("Annotation Platform: %s",annotation(mygset())))
})
print("GEO file is downloaded to server and processed.")
output$mytable4 <- DT::renderDataTable({
# Expression Value
DT::datatable(data(),extensions = 'Responsive', escape=F, selection = 'none')
})
output$mytable5 <- DT::renderDataTable({
# Expression Value
verified_data = data()[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data())[1],
ifelse(is.na(input$starting_col),1,input$starting_col):dim(data())[2]]
# colnames(verified_data)[1] <- "Gene"
DT::datatable(verified_data,extensions = 'Responsive', escape=F, selection = 'none')
})
print('tab2')
removeModal()
session$sendCustomMessage("myCallbackHandler", "tab2")
})
output$readingcsv <- reactive({
print("readingcsv = 1")
return(is.null(input$csvfile))
})
observeEvent(input$action2,{
options(stringsAsFactors = FALSE)
if(is.null(input$csvfile)){
print("no files!")
smartModal(error=T, title = "Important message", content = "No file uploaded! Please retry!")
return(NULL)
}
else {
print("Reading file.")
smartModal(error=F, title = "Intepreting uploaded file in progress", content = "Intepreting ...")
fileExtension <- getFileNameExtension(input$csvfile$datapath)
if(fileExtension == "csv"){
data.temp <- read.csv(input$csvfile$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
data(data.temp)
print("csv file Processed.")
}
else if(fileExtension == "txt"){
data_temp = as.matrix(readLines(input$csvfile$datapath), sep = '\n')
data_temp = strsplit(data_temp, split=input$sep)
max.length <- max(sapply(data_temp, length))
data_temp <- lapply(data_temp, function(v) { c(v, rep(NA, max.length-length(v)))})
data_temp <- data.frame(do.call(rbind, data_temp))
colnames(data_temp) = data_temp[1,]
data_temp = data_temp[2:dim(data_temp)[1],]
if (is.null(dim(data_temp))){
removeModal()
sendSweetAlert(session, title = "Error", text = "Input file extention TXT found, but cannot construct matrix. Please confirm your data format and separator.", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
return()
}
if(data_temp[dim(data_temp)[1],1] == "!series_matrix_table_end"){
print("remove last row with \"!series_matrix_table_end\" ")
data_temp = data_temp[-dim(data_temp)[1],]
}
# data_temp <- print.data.frame(data.frame(data_temp), quote=FALSE)
data(data_temp)
print("txt file Processed.")
} else if(fileExtension == "xlsx"){
data_temp <- read.xlsx(input$csvfile$datapath, sheet = 1, startRow = 1, colNames = TRUE)
if(data_temp[dim(data_temp)[1],1] == "!series_matrix_table_end"){
print("remove last row with \"!series_matrix_table_end\" ")
data_temp = data_temp[-dim(data_temp)[1],]
}
# data_temp <- print.data.frame(data.frame(data_temp), quote=FALSE)
data(data_temp)
print("xlsx file Processed.")
} else if(fileExtension == "xls"){
sendSweetAlert(session, title = "Error", text = "We discontinued to support XLS format. Please resubmit with another file format.", type = "error",
btn_labels = "Ok", html = FALSE, closeOnClickOutside = TRUE)
}
removeModal()
# first column as gene
data.temp = data()#[,2:dim(data())[2]]
rownames(data.temp) = data()[,1]
data(data.temp)
data.name('Uploaded Data')
output$summary <- renderPrint({
print(sprintf("Data: %s", data.name() ))
print(sprintf("Number of Genes: %d",dim(data())[1]))
print(sprintf("Number of Samples: %d",(dim(data())[2]-1)))
print("Annotation Platform: Unknown")
}, quoted = FALSE)
if ((dim(data())[2]-1) == 0){
print("Number of samples 0!")
smartModal(error=T, title = "Important message", content = sprintf("Target file contains no sample. This problem could because user pick a not matched separator (default: Comma), please try another seperator (e.g. Tab or Space)."))
return()
}
output$mytable4 <- DT::renderDataTable({
# Expression Value
DT::datatable(data(),extensions = 'Responsive', escape=F, selection = 'none')
})
output$mytable5 <- DT::renderDataTable({
# Verified data
verified_data = data()[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data())[1],
ifelse(is.na(input$starting_col),1,input$starting_col):dim(data())[2]]
# colnames(verified_data)[1] <- "Gene"
DT::datatable(verified_data,extensions = 'Responsive', escape=F, selection = 'none')
})
print('tab2')
session$sendCustomMessage("myCallbackHandler", "tab2")
}
})
# +------------------------------------------------------------+
# |
# |
# | Platform Convert
# |
# |
# +--------------------------------
observeEvent(input$action_platform,{
if(is.null(data())){
smartModal(error=T, title = "Operation Failed", content = "You have not selected any data. Please go to previous section.")
return()
}
smartModal(error=F, title = "Converting...", content = "We are currently converting probe ID to Gene Symbol...")
platform_name <- gsub(" ", "", input$platform_text, fixed = TRUE)
print(sprintf("Platform: %s",platform_name))
t <- try(gpl <- getGEO(platform_name))
if("try-error" %in% class(t)) {
removeModal()
print("HTTP error 404")
smartModal(error=c(T,F), title = "HTTP error 404", content = sprintf("Platform %s is not available in NCBI GEO Database, please try another!", platform_name))
return()
}
print("Platform Loaded.")
#https://www.rdocumentation.org/packages/GEOquery/versions/2.38.4/topics/GEOData-class
gpltable <- Table(gpl)
if (is.null(fname())){
# data is not from GEO
print("data is self-uploaded, so no fname defined.")
fname(data()[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data())[1], 1])# Gene ID
fname.temp <- fname()
fname.temp <- noquote(fname.temp) # convert "\"1553418_a_at\"" to "1553418_a_at" (safer)
fname.temp <- gsub("\"","",fname.temp) # convert "\"1553418_a_at\"" to "1553418_a_at"
fname(fname.temp)
# save(fname,file="/Users/zhi/Desktop/fname.Rdata")
}
fname2 <- fname()
if (!is.null(gpltable$`Gene Symbol`)){
print("load GPL table with name \"Gene Symbol\"")
fname2 <- gpltable$`Gene Symbol`[match(fname(), gpltable$ID)]
}
else if (!is.null(gpltable$`GENE_SYMBOL`)){
print("load GPL table with name \"GENE_SYMBOL\"")
fname2 <- gpltable$`GENE_SYMBOL`[match(fname(), gpltable$ID)]
}
else if (!is.null(gpltable$`CLONE_ID`)){
print("load GPL table with name \"CLONE_ID\"")
fname2 <- gpltable$`CLONE_ID`[match(fname(), gpltable$ID)]
}
else {
removeModal()
print("HTTP error 404")
smartModal(error=T, title = "Important message", content = sprintf("Error occured while loading %s. This issue could be different name defined on Gene Symbol (GENE_SYMBOL or others) in the platform.", platform_name))
return()
}
print(dim(data()))
print(length(fname2))
data.temp <- data()
# data.temp[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data.temp)[1],1] <- fname2
rownames(data.temp)[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data.temp)[1]] <- fname2
data(data.temp)
# row.names(data) <- seq(1, length(fname2))
output$mytable4 <- DT::renderDataTable({
# Expression Value
DT::datatable(data(),extensions = 'Responsive', escape=F, selection = 'none')
})
output$mytable5 <- DT::renderDataTable({
# Expression Value
verified_data = data()[ifelse(is.na(input$starting_row),1,input$starting_row):dim(data())[1],
ifelse(is.na(input$starting_col),2,input$starting_col):dim(data())[2]]
# colnames(verified_data)[1] <- "Gene"
DT::datatable(verified_data,extensions = 'Responsive', escape=F, selection = 'none')
})
print("Platform Conversion finished")
removeModal()
})
# +------------------------------------------------------------+
# |
# |
# | Cleaning the Data
# |
# |
# +--------------------------------
observe({
if(typeof(data()) != "double"){
samples = colnames(data())[input$starting_col:dim(data())[2]]
if(input$data_sample_subgroup_selectall == 0) return(NULL)
else if (input$data_sample_subgroup_selectall%%2 == 1)
{
updateCheckboxGroupInput(session,"data_sample_subgroup",choices=samples)
}
else
{
updateCheckboxGroupInput(session,"data_sample_subgroup",choices=samples, selected=samples)
}
}
})
observeEvent(input$action3,{
if(is.null(data())){
smartModal(error=T, title = "Operation Failed", content = "You have not selected any data. Please go to previous section.")
return()
}
smartModal(error=F, title = "Preprocessing input data", content = "Preprocessing ...")
RNA = data()
if(!is.null(input$data_sample_subgroup)){
RNA = RNA[, colnames(RNA) %in% input$data_sample_subgroup]
}
print(dim(RNA))
withProgress(message = 'Preprocessing input data', value = 0, {
# Step 0
# Increment the progress bar, and update the detail text.
incProgress(1/5, detail = "Parsing Input Data")
# if (!is.null(input$starting_col) && input$starting_col >= 2){
# geneID <- data.frame(RNA[,input$starting_col-1])
# } else{ # use rownames as gene ID
# geneID <- data.frame(rownames(RNA)[ifelse(is.na(input$starting_row),1,input$starting_row):dim(RNA)[1]])
# }
geneID <- data.frame(rownames(RNA)[ifelse(is.na(input$starting_row),1,input$starting_row):dim(RNA)[1]])
if(!is.null(input$data_sample_subgroup)){
RNA <- as.matrix(RNA[ifelse(is.na(input$starting_row),1,input$starting_row):dim(RNA)[1],])
} else{
RNA <- as.matrix(RNA[ifelse(is.na(input$starting_row),1,input$starting_row):dim(RNA)[1], ifelse(is.na(input$starting_col),2,input$starting_col):dim(RNA)[2]])
}
class(RNA) <- "numeric"
print(dim(RNA))
print(dim(geneID))
# convert na to 0
if (input$checkbox_NA){RNA[is.na(RNA)] <- 0}
# Remove data with lowest 20% mean exp value shared by all samples
percentile <- ifelse(is.na(input$mean_expval),0,input$mean_expval)/100.
percentile.mean <- percentile
print(sprintf("percentile 1: %f",percentile))
# save(RNA, file="~/Desktop/RNA.Rdata")
# save(geneID, file="~/Desktop/geneID.Rdata")
if (percentile > 0){
RNAmean = apply(RNA,1,mean)
RNA_filtered1 = RNA[RNAmean > quantile(RNAmean, percentile)[[1]], ]
geneID_filtered1 = geneID[RNAmean > quantile(RNAmean, percentile)[[1]], ]
}
else {
RNA_filtered1 = RNA
geneID_filtered1 = as.matrix(geneID)
}
print("after remove lowest k% mean exp value:")
print(dim(RNA_filtered1))
incProgress(1/5, detail = "Remove lowest k% mean exp value")
# Remove data with lowest 10% variance across samples
percentile <- ifelse(is.na(input$variance_expval),0,input$variance_expval)/100.
percentile.var <- percentile
print(sprintf("percentile 2: %f",percentile))
if (percentile > 0){
if (dim(RNA_filtered1)[2] > 3){
index <- varFilter2(eset = RNA_filtered1, var.cutoff = percentile)
RNA_filtered2 = RNA_filtered1[index, ]
geneID_filtered2 = geneID_filtered1[index]
}
else{
smartModal(error=F, title = "Preprocessing input data", content = "Preprocessing ... \n Cannot calculate order statistic on object with less than 3 columns, will not remove data based on variance.")
RNA_filtered2 = RNA_filtered1
geneID_filtered2 = geneID_filtered1
}
}
else {
RNA_filtered2 = RNA_filtered1
geneID_filtered2 = geneID_filtered1
}
print("after remove lowest l% var exp value:")
print(dim(RNA_filtered2))
incProgress(1/5, detail = "Remove lowest l% var exp value")
# expData <- RNA_filtered2
# res <- highExpressionProbes(geneID_filtered2, geneID_filtered2, expData)
# ind1 <- res$first
# uniGene <- as.character(res$second)
# tmpExp <- expData[ind1,]
uniGene <- geneID_filtered2
tmpExp <- RNA_filtered2
if (input$checkbox_logarithm){
# tmpExp[tmpExp <= 0] <- 0.000001
tmpExp <- log2(tmpExp+1)
}
if (input$checkbox_empty){
print(sprintf("data dimension before remove gene with empty symbol: %d x %d",dim(tmpExp)[1],dim(tmpExp)[2]))
uniGene_temp <- subset(uniGene, nchar(as.character(uniGene)) > 0)
tmpExp <- subset(tmpExp, nchar(as.character(uniGene)) > 0)
uniGene <- uniGene_temp
print(sprintf("data dimension after remove gene with empty symbol: %d x %d",dim(tmpExp)[1],dim(tmpExp)[2]))
}
if (input$checkbox_duplicated){
row2remove <- numeric()
finalSymCharTable <- table(uniGene)
for (i in 1:length(finalSymCharTable)){
if (as.numeric(finalSymCharTable[i]) > 1){ # if exist duplicated Gene
genename <- names(finalSymCharTable[i])
idx_with_max_mean <- which.max(rowMeans(tmpExp[which(uniGene == genename),]))
# print(idx_with_max_mean)
row2remove <- c( row2remove, (which(uniGene == genename)[-idx_with_max_mean]) )
}
}
if (length(row2remove) > 0){ # Otherwise numerical(0) will remove all data in tmpExp
tmpExp <- tmpExp[-row2remove,]
uniGene <- uniGene[-row2remove]
}
print(sprintf("data dimension after remove duplicated gene symbol: %d x %d",dim(tmpExp)[1],dim(tmpExp)[2]))
}
incProgress(1/5, detail = "Sort genes based on mean.")
nSample <- ncol(tmpExp)
res <- sort.int(rowMeans(tmpExp), decreasing = TRUE, index.return=TRUE)
sortMean <- res$x
sortInd <- res$ix
# topN <- min(ifelse(is.na(input$max_gene_retain),Inf,input$max_gene_retain), nrow(tmpExp))
#Remove gene symbol after vertical line: from ABC|123 to ABC:
uniGene <- gsub("\\|.*$","", uniGene)
finalExp(tmpExp[sortInd, ])
finalSym(uniGene[sortInd])
finalSymChar(as.character(finalSym()))
# save(finalExp, file = "~/Desktop/finalExp.Rdata")
# save(finalSym, file = "~/Desktop/finalSym.Rdata")
# save(finalSymChar, file = "~/Desktop/finalSymChar.Rdata")
incProgress(1/5, detail = "\nPost-processing...")
data_final(data.frame(cbind(finalSym(), finalExp())))
data_final.temp <- data_final()
colnames(data_final.temp)[1] = "Gene_Symbol"
data_final(data_final.temp)
# data_final.temp <- data.frame(finalExp())
# rownames(data_final.temp) <- finalSym()
# data_final(data_final.temp)
#finally no matter if just basic or advanced:
sampleID(colnames(finalExp()))
output$mytable_finaldata <- DT::renderDataTable({
DT::datatable(data_final(),
extensions = 'Responsive', escape=F, selection = 'none')
})
removeModal()
}) # progress bar finished.
# showModal(modalDialog(
# title = "Data After Preprocessing", footer = modalButton("OK"), easyClose = TRUE,
# div(class = "busy",
# p(sprintf("%d genes ---- Original.", dim(RNA)[1])),
# p(sprintf("%d genes remained after remove lowest %.2f%% means.", dim(RNA_filtered1)[1], percentile.mean*100)),
# p(sprintf("%d genes remained after remove lowest %.2f%% variances.", dim(RNA_filtered2)[1], percentile.var*100)),
# style = "margin: auto; text-align: left"
# )
# ))
sendSweetAlert(session, title = "Data After Preprocessing",
text = sprintf("%d genes ---- Original.\n%d genes remained after remove lowest %.2f%% means.\n%d genes remained after remove lowest %.2f%% variances.",
dim(RNA)[1], dim(RNA_filtered1)[1], percentile.mean*100, dim(RNA_filtered2)[1], percentile.var*100),
type = "success",
btn_labels = "OK", html = FALSE, closeOnClickOutside = TRUE)
print('tab3')
session$sendCustomMessage("download_finaldata_ready","-")
session$sendCustomMessage("myCallbackHandler", "tab3")
})
# +------------------------------------------------------------+
# |
# |
# | l m Q C M
# |
# |
# +--------------------------------
observeEvent(input$action4_lmQCM,{
if(is.null(finalExp())){
smartModal(error=T, title = "Operation Failed", content = "You have not selected any data. Please go to previous section.")
return()
}
#lmQCM
smartModal(error=F, title = "lmQCM [1/2]", content = "Calculating massive correlation coefficient matrix...")
data_in = finalExp()
gamma = input$gamma
t = input$t
lambda = input$lambda
beta = input$beta
minClusterSize = input$minClusterSize
CCmethod = tolower(input$massiveCC)
normalization = input$lmQCM_weight_normalization
#----------------------------------------------------------------------------
# lmQCM start
#----------------------------------------------------------------------------
withProgress(message = 'lmQCM [1/2]: ', value = 0, {
incProgress(1/16, detail = "Calculating massive correlation coefficient matrix...")
cMatrix <- cor(t(data_in), method = CCmethod)
diag(cMatrix) <- 0
incProgress(1/2, detail = "Find the local maximal edges")
if(normalization){
# Normalization
cMatrix <- abs(cMatrix)
D <- rowSums(cMatrix)
D.half <- 1/sqrt(D)
cMatrix <- apply(cMatrix, 2, function(x) x*D.half )
cMatrix <- t(apply(cMatrix, 1, function(x) x*D.half ))
}
C <- list()
nRow <- nrow(cMatrix)
maxV <- apply(cMatrix, 2, max)
maxInd <- apply(cMatrix, 2, which.max) # several diferrences comparing with Matlab results
# Step 1 - find the local maximal edges
lm.ind <- which(maxV == sapply(maxInd, function(x) max(cMatrix[x,])))
maxEdges <- cbind(maxInd[lm.ind], lm.ind)
maxW <- maxV[lm.ind]
res <- sort.int(maxW, decreasing = TRUE, index.return=TRUE)
sortMaxV <- res$x
sortMaxInd <- res$ix
sortMaxEdges <- maxEdges[sortMaxInd,]
message(sprintf("Number of Maximum Edges: %d", length(sortMaxInd)))
incProgress(7/16, detail = sprintf("Number of Maximum Edges: %d", length(sortMaxInd)))
currentInit <- 1
noNewInit <- 0
nodesInCluster <- matrix(0, nrow = 0, ncol = 1)
})
removeModal()
pb <- progress_bar$new(format = " Calculating [:bar] :percent eta: :eta",
total = length(sortMaxInd), clear = F, width=60)
iter = 0
progressSweetAlert(
session = session, id = "myprogress",
title = "lmQCM [2/2] Merging ...",
display_pct = TRUE, value = 0
)
while ((currentInit <= length(sortMaxInd)) & (noNewInit == 0)) {
pb$tick()
iter = iter + 1
updateProgressBar(
session = session,
id = "myprogress",
value = iter/length(sortMaxInd)*100
)
if (sortMaxV[currentInit] < (gamma * sortMaxV[1]) ) {
noNewInit <- 1
}
else {
if ( (is.element(sortMaxEdges[currentInit, 1], nodesInCluster) == FALSE) & is.element(sortMaxEdges[currentInit, 2], nodesInCluster) == FALSE) {
newCluster <- sortMaxEdges[currentInit, ]
addingMode <- 1
currentDensity <- sortMaxV[currentInit]
nCp <- 2
totalInd <- 1:nRow
remainInd <- setdiff(totalInd, newCluster)
# C = setdiff(A,B) for vectors A and B, returns the values in A that
# are not in B with no repetitions. C will be sorted.
while (addingMode == 1) {
neighborWeights <- colSums(cMatrix[newCluster, remainInd])
maxNeighborWeight <- max(neighborWeights)
maxNeighborInd <- which.max(neighborWeights)
c_v = maxNeighborWeight/nCp;
alphaN = 1 - 1/(2*lambda*(nCp+t));
if (c_v >= alphaN * currentDensity) {
newCluster <- c(newCluster, remainInd[maxNeighborInd])
nCp <- nCp + 1
currentDensity <- (currentDensity*((nCp-1)*(nCp-2)/2)+maxNeighborWeight)/(nCp*(nCp-1)/2)
remainInd <- setdiff(remainInd, remainInd[maxNeighborInd]);
}
else {
addingMode <- 0
}
}
nodesInCluster <- c(nodesInCluster, newCluster)
C <- c(C, list(newCluster))
}
}
currentInit <- currentInit + 1
}
if(length(C) == 0) {
removeModal()
sendSweetAlert(
session = session,
title ="Clusters size = 0 before merging. Please try other set of parameters. Program stopped.",
type = "error"
)
return()
}
closeSweetAlert(session = session)
sendSweetAlert(
session = session,
title ="lmQCM Calculation completed !",
type = "success"
)
t <- try(clusters <- merging_lmQCM(C, beta, minClusterSize))
if("try-error" %in% class(t)) {
removeModal()
sendSweetAlert(
session = session,
title ="Too few genes to perform lmQCM clustering and merging.",
type = "error"
)
clusters <- C
}
# map rownames to clusters
clusters.names = list()
for (i in 1:length(clusters)){
mc = clusters[[i]]
clusters.names[[i]] = rownames(data_in)[mc]
}
# calculate eigengene
eigengene.matrix <- matrix(0, nrow = length(clusters), ncol = dim(data_in)[2]) # Clusters * Samples
for (i in 1:(length(clusters.names))) {
geneID <- as.matrix(clusters.names[[i]])
X <- data_in[geneID,]
mu <- rowMeans(X)
stddev <- rowSds(as.matrix(X), na.rm=TRUE) # standard deviation with 1/(n-1)
XNorm <- sweep(X,1,mu) # normalize X
XNorm <- apply(XNorm, 2, function(x) x/stddev)
SVD <- svd(XNorm, LINPACK = FALSE)
eigengene.matrix[i,] <- t(SVD$v[,1])
}
eigengene.matrix = data.frame(eigengene.matrix)
colnames(eigengene.matrix) = colnames(data_in)
mergedCluster <- methods::new("QCMObject", clusters.id = clusters, clusters.names = clusters.names,
eigengene.matrix = eigengene.matrix)
message("Done.")
#----------------------------------------------------------------------------
# lmQCM finished
#----------------------------------------------------------------------------
# if("try-error" %in% class(t)) {
# removeModal()
# smartModal(error=T, title = "Error in lmQCM",
# content = sprintf("Too few genes to do lmQCM merging."))
# return()
# }
mergedCluster <- mergedCluster@clusters.id
geneCharVector <- matrix(0, nrow = 0, ncol = length(mergedCluster))
temp_eigengene <- matrix(0, nrow = length(mergedCluster), ncol = dim(finalExp())[2]) # Clusters * Samples
temptext <- ""
for (i in 1:(length(mergedCluster))) {
vector <- as.matrix(mergedCluster[[i]])
geneID <- vector
print(i)
print(vector)
# ===== Calculate Eigengene Start
X <- finalExp()[geneID,]
mu <- rowMeans(X)
stddev <- rowSds(as.matrix(X), na.rm=TRUE) # standard deviation with 1/(n-1)
#normalize X:
XNorm <- sweep(X,1,mu)
XNorm <- apply(XNorm, 2, function(x) x/stddev)
SVD <- svd(XNorm, LINPACK = FALSE)
temp_eigengene[i,] <- t(SVD$v[,1])
# ===== Calculate Eigengene Finished
geneChar <- c(toString(i), finalSymChar()[vector])
geneCharVector[i] <- list(geneChar)
temptext <- paste(temptext, capture.output(cat(geneChar, sep=',')), sep="\n")
}
temptext <- substring(temptext, 2) # remove firstfinal_genes_str \n separater
geneCharVector_global(geneCharVector)
text.final(temptext)
colnames(temp_eigengene) <- sampleID()
eigengene_matrix(temp_eigengene)
output$eigengene_matrix_select_row_ui <- renderUI({
selectInput(inputId="eigengene_matrix_select_row", label="Please select row:",
choices = 1:dim(eigengene_matrix())[1], selected = 1, multiple = FALSE,
selectize = TRUE, width = NULL, size = NULL)
})
## Compute maximum length
max.length <- max(sapply(geneCharVector, length))
## Add NA values to list elements
geneCharVector2 <- lapply(geneCharVector, function(v) { c(v, rep(NA, max.length-length(v)))})
## Rbind
geneCharVector2 <- data.frame(do.call(rbind, geneCharVector2))
output$clusterResult <- DT::renderDataTable({
geneCharVector2[["Actions"]] <- paste0('<div style="text-align: center"><button type="button" class="btn-analysis" id=go_analysis_',1:nrow(geneCharVector2),'>GO</button></div>')
geneCharVector2[["Plots"]] <- paste0('<div style="text-align: center"><button type="button" class="btn-plot" id=circos_',1:nrow(geneCharVector2),'>Circos</button></div>')
geneCharVector2 <- geneCharVector2 %>%
select(c("Actions","Plots"), everything())
colnames(geneCharVector2)[3:4] <- c("Cluster ID", "Genes")
# print(head(geneCharVector2))
DT::datatable(geneCharVector2, selection="none", escape=FALSE,
options = list(paging = F, searching = F, dom='t',ordering=T),
rownames = F#, colnames = NULL
)
})
output$mytable7 <- renderTable({
return(eigengene_matrix())
},rownames = TRUE, colnames = TRUE, na = "", bordered = TRUE, digits = 4)
removeModal()
print('tab4')
session$sendCustomMessage("download_cluster_ready","-")
session$sendCustomMessage("myCallbackHandler", "tab4")
})
#=================================================
#=================== ===================
#================== W G C N A ==================
#=================== ===================
#=================================================
observeEvent(input$checkPower, {
if(is.null(finalExp())){
smartModal(error=T, title = "Operation Failed", content = "You have not selected any data. Please go to previous section.")
return()
}
if (length(finalSym()) > 0){
#WGCNA
smartModal(error=F, title = "Preview the power", content = "Running ...")
finalExp.temp <- finalExp()
row.names(finalExp.temp) <- finalSym()
finalExp(finalExp.temp)
datExpr <- t(finalExp()) # gene should be colnames, sample should be rownames
# datExpr <- log(datExpr + 1) # uncomment if don't need logarithm
print(dim(datExpr))
# The following setting is important, do not omit.
options(stringsAsFactors = FALSE);
allowWGCNAThreads() #enableWGCNAThreads()
#=====================================================================================