-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
executable file
·1520 lines (1326 loc) · 78.2 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
library(shiny)
library(shinyjs)
library(shinyURL)
library(leaflet.extras)
shinyServer(function(input, output, session) {
options("stringsAsFactors" = FALSE)
#Load any saved datasets
values <- reactiveValues()
dataPath <- "./www/config/data/"
dataFiles <- list.files(dataPath,recursive=T)
for(i in dataFiles){
values[[i]] <- read.table(paste0(dataPath,i),sep=",",stringsAsFactors=FALSE,head=TRUE)
}
values$datasetlist <- dataFiles
# values[["ionomics"]] <- aggTable
# values$datasetlist <- dataFiles
#handles what displays in the sidebar based on what tab is selected
output$ui_All <- renderUI({
list(
conditionalPanel(condition = "input.datatabs == 'Manage'",
wellPanel(
uiOutput("datasets")
),
wellPanel(
conditionalPanel(condition = "input.dataType != 'examples'",
uiOutput("organism"),
fileInput('uploadfile', '', multiple=TRUE)
),
conditionalPanel(condition = "input.dataType == 'examples'",
actionButton('loadExampleData', 'Load examples')
)
)
),#end conditional Manage
conditionalPanel(condition = "input.datatabs == 'Table'",
wellPanel(
uiOutput("columns"),
tags$br(),tags$br(),tags$br(),tags$br(),tags$br(),tags$br(), #add some space between selection columns and subset search
# uiOutput("view_order"), checkboxInput("view_order_desc", "DESC", value = FALSE),
returnTextInput("dv_select", "Subset (e.g., score_AMM > 6 & EFFECT == 'missense variant')", '')
),
helpModal('Data Table View','view',includeMarkdown("tools/manage.md"))
),#end conditional Table
#the second part of the statement is what is allowing the detection of changing panels due to a click event, i couldn't figure out how to update input$datatabs with javascript
conditionalPanel(condition = "input.datatabs == 'panel1' || input.datatabs == 'panel2' || $('li.active a').first().html()==='Chromosome View'",
helpText(h5(p("Interactive Graphs for GWAS Data"))),
wellPanel(
uiOutput("traitColBoxes"),
uiOutput("legend"),
uiOutput("overlaps"),
conditionalPanel(condition = "input.overlaps==true",
uiOutput("overlapSize"),
uiOutput("numOverlapTraits")
)#end conditional for plotting only overlaps
)
#submitButton("Update View"),
),#end conditional for traitCols (genome view and chromosomeview)
conditionalPanel(condition = "input.datatabs == 'panel2' || $('li.active a').first().html()==='Chromosome View'",
wellPanel(
uiOutput("selectChr")
)
),#end conitional for chromsomeview (panel2)
conditionalPanel(condition = "input.datatabs == 'Annot' || input.datatabs == 'panel2' || $('li.active a').first().html()==='Chromosome View'",
wellPanel(
h5("Annotation window options:"),
h6("Click a point or type a basepair value:"),
uiOutput("selectedOut"),
uiOutput("windowOut")
)
),#end conditional panel for Annotation plot and Table
conditionalPanel(condition = "input.datatabs == 'Annot'",
helpText(h5(p(paste("Download a CSV of the annotations in the selected window.")))),
wellPanel(
downloadButton('downloadAnnot','Download')
)
),#end conditional panel for Annotation Table
conditionalPanel(condition = "input.datatabs == 'panel1' || input.datatabs == 'panel2' || $('li.active a').first().html()==='Chromosome View'",
helpModal('Browser Help','browser',includeMarkdown("tools/manage.md"))
)#add help button for browser tabs
)#end list
}) #end ui_All
outputOptions(output, "ui_All", suspendWhenHidden=FALSE)
# find the appropriate UI
output$ui_finder <- renderUI({
# if(is.null(input$datatabs)){
# get("ui_All")()
# }else{
# get(paste0('ui_',input$datatabs))()
# }
# if(input$tool == "data") {
# if(!is.null(input$datatabs)) get(paste0('ui_',input$datatabs))()
# } else {
# if(!is.null(input$tool)) get(paste0('ui_',input$tool))()
# }
})
outputOptions(output, "ui_finder", suspendWhenHidden=FALSE)
output$datasets <- renderUI({
inFile <- input$uploadfile
if(!is.null(inFile)) {
# iterating through the files to upload
isolate({
for(i in 1:(dim(inFile)[1])) {
loadUserData(inFile[i,'name'], inFile[i,'datapath'])
# unlink(inFile[i,'datapath'], recursive = FALSE, force = TRUE)
}
})
val <- values$datasetlist[1]
}else{
val <- "sigGWASsnpsCombinedIterations.longhorn.allLoc.csv"
}
# Drop-down selection of data set
# selectInput(inputId = "datasets", label = "Datasets:", choices = datasets, selected = datasets[1], multiple = FALSE)
selectInput(inputId = "datasets", label = "Choose a geo-environmental parameter:", choices = values$datasetlist, selected = values$datasetlist[values$datasetlist==val], multiple = FALSE, selectize=FALSE)
})
reactiveAnnotTable <- reactive({
if(is.null(input$datasets)) return()
centerBP <- as.numeric(input$selected[[1]])
winHigh <- centerBP+input$window[1]
winLow <- centerBP-input$window[1]
if(winLow < 0){winLow <- 0}
thisChrAnnot <- subset(annotGeneLoc[input$organism][[1]],chromosome==input$chr)
thisAnnot <- thisChrAnnot[thisChrAnnot$transcript_start >= winLow & thisChrAnnot$transcript_end <= winHigh,]
thisAnnot
})
#Returns the nicely formatted preview table
output$htmlDataExample <- reactive({
if(is.null(input$datasets)) return()
dat <- getdata()
# necessary when deleting a dataset
if(is.null(dat)) return()
# Show only the first 25 rows
nr <- min(25,nrow(dat))
dat <- data.frame(dat[1:nr,, drop = FALSE])
#dat <- date2character_dat(dat) #may be needed to print table if there is a data column
html <- print(xtable::xtable(dat), type='html', print.results = FALSE)
html <- sub("<TABLE border=1>","<table class='table table-condensed table-hover'>", html)
Encoding(html) <- 'UTF-8'
html
})
output$nrowDataset <- reactive({
if(is.null(input$datasets)) return()
dat <- getdata()
if(is.null(dat)) return()
nr <- nrow(dat)
if(nr>5000){
paste0('<p>First 25 rows shown of ',nr,' rows. See Data Table tab for details.<br>More than 5000 rows found, only the top 5000 will be plotted.</p>')
}else{
paste0('<p>First 25 rows shown of ',nr,' rows. See Data Table tab for details.</p>')
}
})
output$ui_data_tabs <- renderUI({ # htmlOutput("htmlDataExample")})
tabsetPanel(id = "datatabs", type = "pills",
tabPanel(title="Manage",value="Manage",htmlOutput("htmlDataExample"),
wellPanel(htmlOutput("nrowDataset")),
tags$div(
class = "container",
#tags$p(tags$br()),
row(
col(3, tags$br()),
col(7, wellPanel(
p("This is a Shiny implementation originally adapted from the", a("Zbrowse", href="http://www.baxterlab.org/untitled-cqi0")," viewer created by the",a("Baxter laboratory", href="http://www.baxterlab.org/"), " intended to explore the genetic variation associated with the environment."),
p("Navigation through the graphs and tables in Oryza CLIMGeno is done using the tabs at the top of the page, adjusting options on the sidebar panel, or clicking points on the plots. The user interface is designed to be intuitive and allow the user
to quickly zoom into a point of interest anywhere on the genome."),
p("To use this application choose the ExG association of interest from the left panel. The table on this tab provides a summary of the 25 variants with the strongest associations to the selected variable:"),
p("1. The Data Table tab provides a full description of the associated variants for the selected environmental variable. The user can easily manage the columns to be shown, rank based on score or q-value, or search and retrieve information for any associated variant. "),
p("2. The whole genome view tab provides an interactive Manhattan plot with the variants associated with the environmental variable of interest. The may manage the genetic variants on this plot based on its predicted effect (missense, synonymous variants, etc.). Scrolling over the variants in the plot retrieves the specific information on that variant. Clicking on it, automatically renders the plot shown in the next tab (chromosome view). Alternatively, the user can click and drag over a region of interest."),
p("3. In the chromosome view tab, the user obtains an amplified view of the genetic region of interest. Clicking any variant in the top plot will automatically render in the bottom plot, a window size determined by the user on the left panel. This feature allows for the exploration of the region within linkage disequilibrium for the selected variant. The user can then explore nearby genes as well as other variants associated with the environmental variable of interest within the same genetic region."),
p("4. The annotation table tab, provides an interactive table with the information in the genetic region selected in the previous tab. "),
p("We recommend the user of Oryza CLIMGeno to become familiar with the limitations inherent to genome-wide association studies, for which a description is available in the left panel."),
p("For a more detailed description of the logic behind the Zbrowse viewer in this tool visit the" ,a("user manual", href="Zbrowse.pdf"), "by Greg Ziegler.")
)),
col(7, wellPanel(
p("-", a("Zbrowse", href="http://www.baxterlab.org/untitled-cqi0"), "Ziegler, Greg R., Ryan H. Hartsock, and Ivan Baxter. Zbrowse: an interactive GWAS results browser PeerJ Computer Science 1 (2015): e3."),
)),
col(7, h4('Select appropriate columns to be used for plotting.'))
#HTML('<h4>Select appropriate columns to be used for plotting.</h4>'),
),
tags$hr(),
row(
#col(2, tags$br()),
col(2,uiOutput("chrColumn"),uiOutput("bpColumn")),
col(2,uiOutput("plotAll"),uiOutput("traitColumns")),
col(2,uiOutput("yAxisColumn"),uiOutput("logP")),
col(2,uiOutput("axisLimBool"),uiOutput("axisLim")),
col(2,actionButton("SubmitColsButton","Submit"))
),
tags$hr(),
row(
col(7, uiOutput("supportInterval"))#
),
row(
col(2, uiOutput("SIbpStart")),
col(2, uiOutput("SIyAxisColumn")),
col(2, uiOutput("SIaxisLimBool"),uiOutput("SIaxisLim"))
)
)
# col(
# 4,
# uiOutput("traitColumns"),
# uiOutput("yAxisColumn")
# )
# )
# # #HTML(dataDescriptionOutput())
# )
),
tabPanel(title="1. Data Table",value="Table",dataTableOutput("dataviewer")),
tabPanel(title="2. Whole Genome View",value="panel1",showOutput("gChart", "highcharts")),#showOutput("gChart","highcharts"))
tabPanel(title="3. Chromosome View",value="panel2",showOutput("pChart", "highcharts"),showOutput("zChart", "highcharts"),
tags$script('Shiny.addCustomMessageHandler("customMsg", function(bandOpts){
chartXAxis = $("#pChart").highcharts().xAxis[0]
chartXAxis.removePlotBand()
chartXAxis.addPlotBand(bandOpts)
})'
)),
tabPanel(title="4. Annotations Table",value="Annot",dataTableOutput("annotViewer")),
tabPanel(title = "Description of climate variables", mainPanel(fixedRow(
width = 12,
withSpinner(DT::dataTableOutput("a"))
)))
)#end tabsetPanel
})#end data tabs
descriptiondataset <-read.csv("www/datadescription.csv")
output$a <- DT::renderDataTable(descriptiondataset, filter = 'top', options = list(
pageLength = 25, autoWidth = TRUE))
outputOptions(output, "ui_data_tabs", suspendWhenHidden=FALSE)
output$annotViewer <- renderDataTable({
# if(is.null(input$datasets)) return()
# centerBP <- as.numeric(input$selected[[1]])
# winHigh <- centerBP+input$window[1]
# winLow <- centerBP-input$window[1]
# if(winLow < 0){winLow <- 0}
# thisChrAnnot <- subset(annotGeneLoc[input$organism][[1]],chromosome==input$chr)
# thisAnnot <- thisChrAnnot[thisChrAnnot$transcript_start >= winLow & thisChrAnnot$transcript_end <= winHigh,]
# thisAnnot
reactiveAnnotTable()
}, options = list(orderClasses = TRUE, bCaseInsensitive = TRUE,
lengthMenu = c(15, 50, 100, 200, 500), pageLength = 15,
"dom" = 'T<"clear">lfrtip',
"oTableTools" = list(
"sSwfPath" = "/tabletools/swf/copy_csv_xls_pdf.swf",
"aButtons" = list(
"copy",
"print",
list("sExtends" = "collection",
"sButtonText" = "Save",
"aButtons" = c("csv","xls","pdf")
)
)
)
)
)#end annotation table
output$dataviewer <-renderDataTable({
if(is.null(input$datasets) || is.null(input$columns)) return()
dat <- getdata()
#dat <- date2character()
if(!all(input$columns %in% colnames(dat))) return()
if(input$dv_select != '') {
selcom <- input$dv_select
selcom <- gsub(" ", "", selcom)
seldat <- try(do.call(subset, list(dat,parse(text = selcom))), silent = TRUE)
if(!is(seldat, 'try-error')) {
if(is.data.frame(seldat)) {
dat <- seldat
seldat <- NULL
}
}
}
##
observe({
lapply(input$columns, function(i){
if("Select All" %in% input[[i]]){
selected_choices <- sort(unique(values[[input$datasets]][,i]))
updateSelectizeInput(session, i, selected = selected_choices)
}
})
})
dat <- data.frame(dat[, input$columns, drop = FALSE])
dat
# html <- print(xtable::xtable(dat), type='html', print.results = FALSE)
# html <- sub("<TABLE border=1>","<table class='table table-condensed table-hover'>", html)
# html
}, options = list(orderClasses = TRUE, bCaseInsensitive = TRUE,
lengthMenu = c(15, 50, 100, 200, 500), pageLength = 15,
"dom" = 'T<"clear">lfrtip',
"oTableTools" = list(
"sSwfPath" = "/tabletools/swf/copy_csv_xls_pdf.swf",
"aButtons" = list(
"copy",
"print",
list("sExtends" = "collection",
"sButtonText" = "Save",
"aButtons" = c("csv","xls","pdf")
)
)
)
)
)#end dataviewer
output$downloadAnnot <- downloadHandler(
filename = function() {paste0("AnnotationsAround.chr",input$chr,".",input$selected[[1]],"bp.",input$organism,".csv")},
content = function(file) {write.csv(reactiveAnnotTable(),file,row.names=F)}
)
output$columns <- renderUI({
cols <- varnames()
lapply(input$traitColumns, function(i) {
traits <- c("Select All",sort(unique(values[[input$datasets]][,i])))
selectizeInput(inputId=i, label=paste0("Select ",i),cols,
selected="Select All",
multiple=TRUE, options = list(dropdownParent="body",plugins=list("remove_button")))
})
selectizeInput("columns", "Click on columns to show/omit:", choices = as.list(cols), selected = c("Chr","Pos","REF","ALT","MAF","EFFECT","SNPfold_CC","Locus_ID","Transcript_ID","Gene_Symbol","Gene_name","Description","score","FDR","bonferroni","Fst","Tajima_D","PI"), multiple = TRUE, options = list(dropdownParent="body",plugins=list("remove_button")))
})
output$axisLimBool <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
val = datasetProp()$axisLim[datasetProp()$dataset == input$datasets]
}else{
val = FALSE}
checkboxInput('axisLimBool', 'Set Y-axis Limits?', val)
})
output$logP <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
val = datasetProp()$logP[datasetProp()$dataset == input$datasets]
}else{
val = FALSE}
checkboxInput('logP', 'Take -log10 of column?', val)
})
output$organism <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = datasetProp()$organism[datasetProp()$dataset == input$datasets]
}else{
selected = "Indica"
}
# = c("Corn","Soybean","Arabidopsis","Sorghum")
choices<-list()
files<-list.files(path="./organisms/")
for(i in 1:length(files)){
if(tools::file_ext(files[i]) == "txt"){
filename=""
filename=paste("./organisms/",files[i],sep="")
conn=file(filename,open="r")
data<-readLines(conn)
choices[[i]] <- data[1]
close(conn)
}
}
choices <- c("Indica")
selectizeInput("organism", "Landrace variety:", choices, selected = "Indica", multiple = FALSE, options = list(dropdownParent="body"))
})
output$chrColumn <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = cols[datasetProp()$chrColumn[datasetProp()$dataset == input$datasets]]
}else{
selected = names(cols[1])
}
selectizeInput("chrColumn", "Chromosome Column:", choices = as.list(cols), selected = "Chr", multiple = FALSE, options = list(dropdownParent="body"))
})
output$bpColumn <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = cols[datasetProp()$bpColumn[datasetProp()$dataset == input$datasets]]
}else{
selected = names(cols[2])
}
#selectInput("bpColumn", "Base Pair Column:", choices = as.list(cols), selected = selected, multiple = FALSE, selectize = TRUE)
selectizeInput("bpColumn", "Base Pair Column:", choices = as.list(cols), selected = "Pos", multiple = FALSE, options = list(dropdownParent="body"))
})
output$traitColumns <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = cols[which(names(cols) %in% unlist(strsplit(datasetProp()$traitCol[datasetProp()$dataset == input$datasets],";")))]
}else{
selected = names(cols[3:4])
}
print(selected)
conditionalPanel(condition = "input.plotAll==false",
selectizeInput("traitColumns", "Group by these trait column(s):", choices = as.list(cols), selected = "EFFECT", multiple = TRUE, options = list(dropdownParent="body"))
)
})
#traits <- c("Select All",sort(unique(values[[input$datasets]][,i])))
output$plotAll <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
val = datasetProp()$plotAll[datasetProp()$dataset == input$datasets]
}else{
val = FALSE
}
checkboxInput('plotAll', 'All data is the same trait', val)
})
output$yAxisColumn <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = cols[datasetProp()$yAxisColumn[datasetProp()$dataset == input$datasets]]
}else{
#selected = names(cols[10])
selected = as.character(cols[10])
}
selectizeInput("yAxisColumn", "Y-axis column:", choices = as.list(cols), selected = "score", multiple = FALSE, options = list(dropdownParent="body"))
})
outputOptions(output, "yAxisColumn", suspendWhenHidden=FALSE)
output$axisLim <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
min = datasetProp()$axisMin[datasetProp()$dataset == input$datasets]
max = datasetProp()$axisMax[datasetProp()$dataset == input$datasets]
}else{
min = 0
max = 1
}
conditionalPanel(condition = "input.axisLimBool==true",
numericInput("axisMin","Min:",value=min),
numericInput("axisMax","Max:",value=max)
)
})
output$supportInterval <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
val = datasetProp()$supportInterval[datasetProp()$dataset == input$datasets]
}else{
val = FALSE}
checkboxInput('supportInterval', 'Plot base pair intervals (e.g., Joint linkage support intervals)?', val)
})
output$SIbpStart <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = cols[datasetProp()$SIbpStart[datasetProp()$dataset == input$datasets]]
selectedEnd = cols[datasetProp()$SIbpEnd[datasetProp()$dataset == input$datasets]]
}else{
selected = names(cols[2])
selectedEnd = names(cols[2])
}
conditionalPanel(condition = "input.supportInterval==true",
selectizeInput("SIbpStart", "Interval Base Pair Start:", choices = as.list(cols), selected = selected, multiple = FALSE, options = list(dropdownParent="body")),
selectizeInput("SIbpEnd", "Interval Base Pair End:", choices = as.list(cols), selected = selectedEnd, multiple = FALSE, options = list(dropdownParent="body"))
)
})
output$SIyAxisColumn <- renderUI({
if(is.null(input$datasets)){return()}
cols <- varnames()
if(input$datasets %in% datasetProp()$dataset){
selected = cols[datasetProp()$SIyAxisColumn[datasetProp()$dataset == input$datasets]]
}else{
#selected = names(cols[10])
selected = as.character(cols[10])
}
conditionalPanel(condition = "input.supportInterval==true",
selectizeInput("SIyAxisColumn", "Support Interval Y-axis column:", choices = as.list(cols), selected = selected, multiple = FALSE, options = list(dropdownParent="body"))
)
})
outputOptions(output, "SIyAxisColumn", suspendWhenHidden=FALSE)
output$SIaxisLimBool <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
val = datasetProp()$SIaxisLimBool[datasetProp()$dataset == input$datasets]
}else{
val = TRUE
}
conditionalPanel(condition = "input.supportInterval==true",
checkboxInput('SIaxisLimBool', 'Set Support Interval Y-axis Limits?', val)
)
})
output$SIaxisLim <- renderUI({
if(is.null(input$datasets)){return()}
if(input$datasets %in% datasetProp()$dataset){
min = datasetProp()$axisMin[datasetProp()$dataset == input$datasets]
max = datasetProp()$axisMax[datasetProp()$dataset == input$datasets]
}else{
min = 0
max = 1
}
conditionalPanel(condition = "input.supportInterval==true && input.SIaxisLimBool==true",
numericInput("SIaxisMin","Min:",value=min),
numericInput("SIaxisMax","Max:",value=max)
)
})
#builds list of multiple selection boxes for traits that have multiple columns in dataset
output$traitColBoxes <- renderUI({
if(is.null(input$datasets)){return()}
if(input$plotAll == TRUE){return()}
lapply(input$traitColumns, function(i) {
traits <- c("Select All",sort(unique(values[[input$datasets]][,i])))
selectizeInput(inputId=i, label=paste0("Select ",i),traits,
selected="Select All",
multiple=TRUE, options = list(dropdownParent="body",plugins=list("remove_button")))
})
})
observe({
lapply(input$traitColumns, function(i){
if("Select All" %in% input[[i]]){
selected_choices <- sort(unique(values[[input$datasets]][,i]))
updateSelectizeInput(session, i, selected = selected_choices)
}
})
})
#checkbox to suppress plot legend
output$legend <- renderUI({
if(is.null(input$datasets)){return()}
checkboxInput('legend', 'Suppress Legend', FALSE)
})
outputOptions(output, "legend", suspendWhenHidden=FALSE)
#checkbox for whether to filter for only overlapping SNPs
output$overlaps <- renderUI({
if(is.null(input$datasets)){return()}
# if(input$plotAll == TRUE){return()}
checkboxInput('overlaps', 'Show only overlapping SNPs', FALSE)
})
outputOptions(output, "overlaps", suspendWhenHidden=FALSE)
#how many traits must overlap to be included in output, 1 means traits that overlap with themselves will be included
output$numOverlapTraits <- renderUI({
numericInput("numOverlaps", "Minimum number of overlaps?", value=2,min=1)
})
#how big is the window when calculating whether two snps overlap
output$overlapSize <- renderUI({
numericInput(inputId="overlapSize",label="Overlap size around each point:",min=1,max=.5e6,value=10000)
})
output$selectChr <- renderUI({
if(is.null(input$organism)){return()}
selectInput("chr", "Chromosome:",chrName[input$organism][[1]],selectize = FALSE)
#selectInput("chr", "Chromosome:",1:length(chrSize[input$organism][[1]]),selectize = FALSE)
})
outputOptions(output, "selectChr", suspendWhenHidden=FALSE)
output$selectedOut <- renderUI({
numericInput("selected", "", value=100000)
})
outputOptions(output, "selectedOut", suspendWhenHidden=FALSE)
output$windowOut <- renderUI({
#sliderInput(inputId="window",label="Window size around selected point:",min=-1e6,max=1e6,value=c(-7.5e5,7.5e5))
sliderInput(inputId="window",label="Window size around selected point:",min=1000,max=.5e6,value=2.5e5)
})
outputOptions(output, "windowOut", suspendWhenHidden=FALSE)
#returns datasets from uploaded file
getdata <- reactive({
if(is.null(input$datasets)){return()}
values[[input$datasets]]
})
#builds list of column names and type in dataset
varnames <- reactive({
if(is.null(input$datasets)) return()
dat <- getdata_class()
vars <- names(dat)
names(vars) <- paste(vars, " {", dat, "}", sep = "")
vars
})
getdata_class <- reactive({
if(is.null(input$datasets)) return()
cls <- sapply(getdata(), function(x) class(x)[1])
gsub("ordered","factor", cls)
})
#Function to handle loading of data from a file or rObject
loadUserData <- function(filename, uFile) {
ext <- file_ext(filename)
# objname <- robjname <- sub(paste(".",ext,sep = ""),"",basename(filename))
objname <- sub(paste(".",ext,sep = ""),"",basename(filename))
ext <- tolower(ext)
if(ext == 'rda' || ext == 'rdata') {
# objname will hold the name of the object(s) inside the R datafile
robjname <- load(uFile)
if(length(robjname) > 1) {
#values[[objname]] <- data.frame(get(robjname[-which(robjname == "description")]))
values[[objname]] <- data.frame(get(robjname[1]))
#values[[paste0(objname,"_descr")]] <- get("description")
} else {
values[[objname]] <- data.frame(get(robjname)) # only work with data.frames
}
}
if(length(values[['datasetlist']]) == 0 || values[['datasetlist']][1] == '') {
values[['datasetlist']] <- c(objname)
} else {
values[['datasetlist']] <- unique(c(objname,values[['datasetlist']]))
}
if(ext == 'sav') {
values[[objname]] <- as.data.frame(as.data.set(spss.system.file(uFile)))
} else if(ext == 'dta') {
values[[objname]] <- read.dta(uFile)
} else{
values[[objname]] <- read.csv(uFile, header=input$header, sep=input$sep,stringsAsFactors=FALSE)
}
}
#add a totalBP column to an input dataset if not already present
calculateTotalBP <- reactive({
if("totalBP" %in% colnames(values[[input$datasets]])){
}else{
cumBP<-c(0,cumsum(as.numeric(chrSize[input$organism][[1]])))
#to order by desired chromosome add factor levels in the desired order to the chrColumn, any chr names that differ in gwas file compared
#to organism file will turn into NA
values[[input$datasets]][,input$chrColumn] <- factor(values[[input$datasets]][,input$chrColumn],levels=chrName[input$organism][[1]])
values[[input$datasets]] <- values[[input$datasets]][order(values[[input$datasets]][,input$chrColumn],values[[input$datasets]][,input$bpColumn]),]
numeachchr<-aggregate(values[[input$datasets]][,input$bpColumn],list(values[[input$datasets]][,input$chrColumn]),length)
# adjust<-rep(cumBP[1],numeachchr$x[numeachchr$Group.1==1])
adjust <- numeric()
for (i in 1:(length(cumBP)-1)){#max(unique(values[[input$datasets]][,input$chrColumn]))){
if(length(numeachchr$x[numeachchr$Group.1==chrName[input$organism][[1]][i]])==0){next;}
adjust<-c(adjust,rep(cumBP[i],numeachchr$x[numeachchr$Group.1==chrName[input$organism][[1]][i]]))
}
#newval <- values[[input$datasets]][600,input$bpColumn]+adjust[600]
values[[input$datasets]]$totalBP <- values[[input$datasets]][,input$bpColumn]+adjust
#values[[input$datasets]] <- adply(values[[input$datasets]],1,function(x){data.frame(totalBP=sum(x[[input$bpColumn]],chrSize$bp[chrSize$chr %in% if(x[[input$chrColumn]]==1) 0 else c(1:(x[[input$chrColumn]]-1))]))})
}
if(input$supportInterval == TRUE){
if("SIbpStartTotal" %in% colnames(values[[input$datasets]])){
}else{
cumBP<-c(0,cumsum(as.numeric(chrSize[input$organism][[1]])))
values[[input$datasets]][,input$chrColumn] <- factor(values[[input$datasets]][,input$chrColumn],levels=chrName[input$organism][[1]])
values[[input$datasets]] <- values[[input$datasets]][order(values[[input$datasets]][,input$chrColumn],values[[input$datasets]][,input$SIbpStart]),]
numeachchr<-aggregate(values[[input$datasets]][,input$SIbpStart],list(values[[input$datasets]][,input$chrColumn]),length)
adjust <- numeric()
for (i in 1:(length(cumBP)-1)){#max(unique(values[[input$datasets]][,input$chrColumn]))){
if(length(numeachchr$x[numeachchr$Group.1==chrName[input$organism][[1]][i]])==0){next;}
adjust<-c(adjust,rep(cumBP[i],numeachchr$x[numeachchr$Group.1==chrName[input$organism][[1]][i]]))
}
values[[input$datasets]]$SIbpStartTotal <- values[[input$datasets]][,input$SIbpStart]+adjust
}
if("SIbpEndTotal" %in% colnames(values[[input$datasets]])){
}else{
cumBP<-c(0,cumsum(as.numeric(chrSize[input$organism][[1]])))
values[[input$datasets]][,input$chrColumn] <- factor(values[[input$datasets]][,input$chrColumn],levels=chrName[input$organism][[1]])
values[[input$datasets]] <- values[[input$datasets]][order(values[[input$datasets]][,input$chrColumn],values[[input$datasets]][,input$SIbpEnd]),]
numeachchr<-aggregate(values[[input$datasets]][,input$SIbpEnd],list(values[[input$datasets]][,input$chrColumn]),length)
adjust <- numeric()
for (i in 1:(length(cumBP)-1)){#max(unique(values[[input$datasets]][,input$chrColumn]))){
if(length(numeachchr$x[numeachchr$Group.1==chrName[input$organism][[1]][i]])==0){next;}
adjust<-c(adjust,rep(cumBP[i],numeachchr$x[numeachchr$Group.1==chrName[input$organism][[1]][i]]))
}
values[[input$datasets]]$SIbpEndTotal <- values[[input$datasets]][,input$SIbpEnd]+adjust
}
} #end SI total bp calculation
})#end calculateTotalBP
output$pChart <- renderChart2({
#this function makes the chromsomeview chart
#subset whole chart based on selection
chromChart <- values[[input$datasets]]
chromChart <- chromChart[chromChart[,input$chrColumn]==input$chr,]
if(input$plotAll==FALSE){
for(i in input$traitColumns){
chromChart <- chromChart[chromChart[,i] %in% input[[i]],]
}
if(length(input$traitColumns) > 1){
chromChart$trait <- do.call(paste,c(chromChart[,input$traitColumns],sep="_"))
}else{
chromChart$trait <- chromChart[,input$traitColumns]
}
}else{
chromChart$trait <- input$datasets
}
#Separate Support Interval data from GWAS data, if support, GWAS data is assumed to be anything that has an NA in the SIbpStart column
if(input$supportInterval == TRUE){
SIchart <- chromChart[!(is.na(chromChart[,input$SIbpStart])),]
chromChart <- chromChart[is.na(chromChart[,input$SIbpStart]),]
}
#check if there is any data for the selected traits
chromChart <- chromChart[!(is.na(chromChart[,input$bpColumn])),]
chromChart <- chromChart[!(is.na(chromChart[,input$yAxisColumn])),]
#if checked, filter for only overlapping SNPs
if(!is.null(input$overlaps) & input$overlaps == TRUE){
chromChart <- findGWASOverlaps(chromChart)
}
if(nrow(chromChart)==0){ #nothing is in the window, but lets still make a data.frame
chromChart <- values[[input$datasets]][1,]
chromChart[,input$yAxisColumn] <- -1
if(length(input$traitColumns) > 1){
chromChart$trait <- do.call(paste,c(chromChart[,input$traitColumns],sep="_"))
}else{
chromChart$trait <- chromChart[,input$traitColumns]
}
}
colorTable <- colorTable()
#take -log10 of y-axis column if requested
if(input$logP == TRUE && chromChart[1,input$yAxisColumn] != -1){
chromChart[,input$yAxisColumn] <- -log(chromChart[,input$yAxisColumn],10)
}
#check if there is too much data (>5000 data points), trim to 5000
# if(nrow(chromChart)>5000){
# cutVal <- sort(chromChart[,input$yAxisColumn],decreasing = T)[5000]
# chromChart <- chromChart[chromChart[,input$yAxisColumn] >= cutVal,]
# }
#calculate window for plotband
pbWin <- isolate({
center <- as.numeric(input$selected[[1]])
winHigh <- center + input$window[1]
winLow <- center - input$window[1]
list(winLow=winLow,winHigh=winHigh)
})
pkTable <- data.frame(x=chromChart[,input$bpColumn],y=chromChart[,input$yAxisColumn],trait=chromChart$trait,
# name=sprintf("<table cellpadding='4' style='line-height:1.5'><tr><th>%1$s</th></tr><tr><td align='left'>Y-value: %2$s<br>Location: %3$s<br>Base Pair: %4$s<br>SNP: %5$s<br>Chromosome: %6$s</td></tr></table>",
#name=sprintf("<table cellpadding='4' style='line-height:1.5'><tr><th>%1$s</th></tr><tr><td align='left'>Y-value: %2$s<br>Base Pairs: %3$s<br>Chromosome: %4$s</td></tr></table>",
name=sprintf("Base Pair: %1$s<br/>Chromosome: %2$s<br/>",
# chromChart$trait,
# chromChart[,input$yAxisColumn],
# pk$loc,
prettyNum(chromChart[,input$bpColumn], big.mark = ","),
# pk$SNP,
chromChart[,input$chrColumn]
),
url="http://danforthcenter.org",
chr=chromChart[,input$chrColumn],
bp=chromChart[,input$bpColumn],stringsAsFactors=FALSE)
pkSeries <- lapply(split(pkTable, pkTable$trait), function(x) {
res <- lapply(split(x, rownames(x)), as.list)
names(res) <- NULL
res <- res[order(sapply(res, function(x) x$x))]
return(res)
})
#build JL series
if(input$supportInterval==TRUE){
if(nrow(SIchart)==0){ #nothing is in the window, but lets still make a data.frame
SIchart <- values[[input$datasets]][1,]
SIchart[,input$SIyAxisColumn] <- -1
if(length(input$traitColumns) > 1){
SIchart$trait <- do.call(paste,c(SIchart[,input$traitColumns],sep="_"))
}else{
SIchart$trait <- SIchart[,input$traitColumns]
}
}
SIchart$loc_el <- SIchart$trait
SIchart$trait <- paste(SIchart$trait,"Int",sep="_")
SIchart <- SIchart[order(SIchart[[input$SIbpStart]]),]
jlTable <- adply(SIchart,1,function(x) {data.frame(x=c(x[[input$SIbpStart]],x[[input$SIbpEnd]],x[[input$SIbpEnd]]),y=c(x[[input$SIyAxisColumn]],x[[input$SIyAxisColumn]],NA),trait=x$trait,
name=sprintf("<table cellpadding='4' style='line-height:1.5'><tr><td align='left'>Interval: %1$s-%2$s<br>Chromosome: %3$s</td></tr></table>",
# x$trait,
# x[[input$SIyAxisColumn]],
prettyNum(x[[input$SIbpStart]], big.mark = ","),
prettyNum(x[[input$SIbpEnd]], big.mark = ","),
x[[input$chrColumn]]
),loc_el=x$loc_el,bp=x[[input$bpColumn]],chr=x[[input$chrColumn]],stringsAsFactors=FALSE
#
# totalBP=x$totalBP,
# chr=x$Chromosome,stringsAsFactors=FALSE
)}#end jlTable and function
)#end adply
jlTable <- jlTable[,c("x","y","trait","name","loc_el","bp","chr")]
#jlTable <- jlTable[order(jlTable$x),]
}#end build jlTable if support intervals
a <- rCharts::Highcharts$new()
a$LIB$url <- 'highcharts/' #use the local copy of highcharts, not the one installed by rCharts
a$xAxis(title = list(text = "Base Pairs"),startOnTick=TRUE,min=1,max=chrSize[input$organism][[1]][as.numeric(input$chr)],endOnTick=FALSE,
plotBands = list(list(from=pbWin$winLow,to=pbWin$winHigh,color='rgba(68, 170, 213, 0.4)')))
# a$xAxis(title = list(text = "Base Pairs"),startOnTick=TRUE,min=1,max=30000000,endOnTick=TRUE)
if(input$axisLimBool == TRUE){
a$yAxis(title=list(text=input$yAxisColumn),min=input$axisMin,max=input$axisMax,startOnTick=FALSE)
}else{
a$yAxis(title=list(text=input$yAxisColumn),startOnTick=FALSE)
}
if(input$supportInterval==TRUE){
if(input$SIaxisLimBool == TRUE){
a$yAxis(title=list(text=input$SIyAxisColumn),min=input$SIaxisMin,max=input$SIaxisMax,gridLineWidth=0,minorGridLineWidth=0,startOnTick=FALSE,opposite=TRUE,replace=FALSE)
}else{
a$yAxis(title=list(text=input$SIyAxisColumn),gridLineWidth=0,minorGridLineWidth=0,startOnTick=FALSE,opposite=TRUE,replace=FALSE)
}
if(SIchart[1,input$SIyAxisColumn] != -1){
d_ply(jlTable,.(trait),function(x){
a$series(
data = toJSONArray2(x,json=F,names=T),
type = "line",
name = unique(x$trait),
yAxis=1,
color = colorTable$color[colorTable$trait == as.character(unique(x$loc_el))])})
}
}
if(chromChart[1,input$yAxisColumn] != -1){
invisible(sapply(pkSeries, function(x) {if(length(x)==0){return()};a$series(data = x, type = "scatter", turboThreshold=5000, name = paste0(x[[1]]$trait), color = colorTable$color[colorTable$trait == as.character(x[[1]]$trait)])}))
}
a$chart(zoomType="xy", alignTicks=FALSE,events=list(click = "#!function(event) {this.tooltip.hide();}!#"))
a$title(text=paste(input$datasets,"Results for Chromosome",input$Chr,sep=" "))
a$subtitle(text="Rollover for more info. Drag chart area to zoom. Click point for zoomed annotated plot.")
a$plotOptions(
scatter = list(
cursor = "pointer",
point = list(
events = list(
click = "#! function(){$('input#selected').val(this.options.bp); $('input#selected').trigger('change');} !#")),
marker = list(
symbol = "circle",
radius = 5
# states = list(hover = list(enabled = TRUE))
),
tooltip = list(
headerFormat = "<b>{series.name}</b><br/>{point.key}<br/>Y-value: {point.y}<br/>",
pointFormat = "",
followPointer = TRUE
)
),
line = list(
lineWidth = 10,
dashStyle = 'Solid',
cursor = "pointer",
point = list(
events = list(
click = "#! function(){$('input#selected').val(this.options.bp); $('input#selected').trigger('change');} !#")),
marker = list(
enabled = FALSE,
states = list(hover = list(enabled=FALSE))
)
),
spline = list(
lineWidth = 3,
cursor = "pointer"
)
)
#a$tooltip(useHTML = T, formatter = "#! function() { return this.point.name; } !#")
#a$tooltip(snap = 5, useHTML = T, formatter = "#! function() { return this.point.name; } !#")
a$exporting(enabled=TRUE,filename='chromChart',sourceWidth=2000)
a$set(dom = 'pChart')
return(a)
})#end pchart
#Genome wide chart
output$gChart <- renderChart2({
calculateTotalBP()
#subset whole chart based on selection
genomeChart <- values[[input$datasets]]
if(input$plotAll == FALSE){
for(i in input$traitColumns){
genomeChart <- genomeChart[genomeChart[,i] %in% input[[i]],]
}
if(length(input$traitColumns) > 1){
genomeChart$trait <- do.call(paste,c(genomeChart[,input$traitColumns],sep="_"))
}else{
genomeChart$trait <- genomeChart[,input$traitColumns]
}
}else{
genomeChart$trait <- input$datasets
}
#Separate Support Interval data from GWAS data, if support, GWAS data is assumed to be anything that has an NA in the SIbpStart column
if(input$supportInterval == TRUE){
SIchart <- genomeChart[!(is.na(genomeChart[,input$SIbpStart])),]
genomeChart <- genomeChart[is.na(genomeChart[,input$SIbpStart]),]
}
#filter genomeChart for only rows that have a base pair and yaxis value
genomeChart <- genomeChart[!(is.na(genomeChart[,input$bpColumn])),]
genomeChart <- genomeChart[!(is.na(genomeChart[,input$yAxisColumn])),]
#if checked, filter for only overlapping SNPs
if(!is.null(input$overlaps) & input$overlaps == TRUE){
genomeChart <- findGWASOverlaps(genomeChart)
}
#check if there is any data for the selected traits
if(nrow(genomeChart)==0){ #nothing is in the window, but lets still make a data.frame
genomeChart <- values[[input$datasets]][1,]
genomeChart[,input$yAxisColumn] <- -1
if(length(input$traitColumns) > 1){
genomeChart$trait <- do.call(paste,c(genomeChart[,input$traitColumns],sep="_"))
}else{
genomeChart$trait <- genomeChart[,input$traitColumns]
}
}
#take -log10 of y-axis column if requested
if(input$logP == TRUE && genomeChart[1,input$yAxisColumn] != -1){
genomeChart[,input$yAxisColumn] <- -log(genomeChart[,input$yAxisColumn],10)
}
#check if there is too much data (>5000 data points), trim to 5000
if(nrow(genomeChart)>5000){
cutVal <- sort(genomeChart[,input$yAxisColumn],decreasing = T)[5000]
genomeChart <- genomeChart[genomeChart[,input$yAxisColumn] >= cutVal,]
}
colorTable <- colorTable()
genomeTable <- data.frame(x=genomeChart$totalBP,y=genomeChart[,input$yAxisColumn],trait=genomeChart$trait,
name=sprintf("Base Pair: %1$s<br/>Chromosome: %2$s<br/>",
prettyNum(genomeChart[,input$bpColumn], big.mark = ","),
genomeChart[,input$chrColumn]
),
url="http://danforthcenter.org",
chr=genomeChart[,input$chrColumn],
bp=genomeChart[,input$bpColumn],stringsAsFactors=FALSE)
genomeSeries <- lapply(split(genomeTable, genomeTable$trait), function(x) {
res <- lapply(split(x, rownames(x)), as.list)
names(res) <- NULL
res <- res[order(sapply(res, function(x) x$x))]
return(res)
})
#
#build JL series
if(input$supportInterval==TRUE){
if(nrow(SIchart)==0){ #nothing is in the window, but lets still make a data.frame
SIchart <- values[[input$datasets]][1,]
SIchart[,input$SIyAxisColumn] <- -1
if(length(input$traitColumns) > 1){
SIchart$trait <- do.call(paste,c(SIchart[,input$traitColumns],sep="_"))
}else{
SIchart$trait <- SIchart[,input$traitColumns]