-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.R
1121 lines (945 loc) · 31 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
server <- function(input, output, session) {
# GENERAL OPTIONS ######
source("app.R", local = TRUE)
# increase maximum upload size
options(shiny.maxRequestSize = 500 * 1024^2)
# shut down R session when browser window is closed
session$onSessionEnded(function() {
stopApp()
})
# Prefer regular to scientific number connotation, except for very large numbers
options(scipen = 5)
# >>> TRACE TAB <<<######
# TRACE FILE PROPERTIES ------------------------------
# get input files
# create reactive value for input files
tracefile <- reactiveValues()
# if input files are uploaded, use file paths and names from these
observeEvent(input$tracefile, {
tracefile$datapath <- input$tracefile$datapath
tracefile$name <- input$tracefile$name
})
# if 'example 1' button is pressed, load example 1 from example folder
observeEvent(input$exampletrace1, {
tracefile$datapath <- list.files("example/", "\\.trace\\>", full.names = TRUE)
tracefile$name <- list.files("example/", "\\.trace\\>", full.names = FALSE)
})
# if 'example 2' button is pressed, load example 2 from example folder
observeEvent(input$exampletrace2, {
tracefile$datapath <- list.files("example/", "\\.p\\>", full.names = TRUE)
tracefile$name <- list.files("example/", "\\.p\\>", full.names = FALSE)
})
# if 'info' button is pressed, show popup that explains examples
observeEvent(input$exampletraceinf, {
showModal(modalDialog(
title = "postpb comes with two sets of example data:",
includeMarkdown("modals/examples.md"),
size = "m"
))
})
# get number of generations from tracefiles
ngen <- reactive({
req(tracefile$datapath)
get.ngen(tracefile)
})
# Get names of chains from file names provided
chainnames <- reactive({
# get names of chains from trace file names
strsplit(tracefile$name[1:length(tracefile$name)], "\\.trace\\>|\\.p\\>")
})
# Reading the trace files
tracedata_raw <- reactive({
req(tracefile$datapath)
read.trace(tracefile, chainnames())
})
# Thinning the tracefiles
tracedata_thin <- reactive({
# Applies thinning
tracelist <- lapply(tracedata_raw(), thin.trace, tracethin())
# rename first column in all dfs to "iter"
lapply(tracelist, function(dflist) {
names(dflist)[1] <- "iter"
dflist
})
})
# Removing burnin from the tracefiles, and merge all into df
tracedata <- reactive({
tracelist.as.df(lapply(tracedata_thin(), burn.trace, input$burnin))
})
# filter tracedata to only plot selected trace files in checkbox (default= select all)
traceDF <- reactive({
req(tracefile$datapath)
choose.trace(tracedata(), input$whichchain)
})
#| UI ELEMENTS FOR TRACE TAB SIDEBAR ------------------------------
# display burnin slider using the number of generations read from trace file
output$burnin <- renderUI({
req(tracefile)
sliderInput("burnin", "Burnin [# of iterations]:",
min = 0,
max = trunc(ngen() / 10),
value = trunc(ngen() / 10 * 0.2), # default = 20% of iterations
# default for step 10 for 100–999 gens, 100 for 1000-9999 etc
step = 10^(ceiling(log10(ngen() / 10 * 0.02)))
)
})
# Set the default value of trace file thinning to 10
tracethin <- reactiveVal(10)
# Update the tree thinning value for calculating the consensus
# only after burnin has changed
observeEvent(input$burnin, {
tracethin(input$tracethin)
})
# Update the burnin after tree thinning button is pressed
observeEvent(input$trecalc, {
thinval <- input$tracethin
# Update burnin slider
updateSliderInput(session, "burnin",
label = "Burnin [# of iterations]:",
min = 0,
max = trunc(ngen() / thinval),
step = 10^(ceiling(log10(ngen() / thinval * 0.02))),
value = ngen() / thinval * 0.2
)
})
# display checkbox to select which trace file to plot
output$whichchain <- renderUI({
req(tracefile$datapath[2])
names <- lapply(chainnames(), `[[`, 1)
prettyCheckboxGroup(
inputId = "whichchain",
label = "Select trace file[s] to plot",
choices = names,
selected = names,
inline = FALSE,
status = "primary",
icon = icon("check")
)
})
# Button that toggles graphics parameters for the statistics
observeEvent(input$traceplotsopts, ignoreInit = TRUE, {
toggle("tplotopts")
})
# Button that toggles explanations for the statistics
observeEvent(input$explanation, {
toggle("stats")
})
#| CREATE PLOTS ------------------------------
#| General display options ------------------------------
# get height & width of plot area from slider inputs
plotheight <- reactive({
input$height
})
plotwidth <- reactive({
input$width
})
plotcex <- reactive({
input$cex
})
# calculate scale factor from height & width given – is used for e.g., line width, cex, etc in plots
scalefactor <- reactive({
(input$height + input$width) / 2000
})
# Set theme for all trace plots
tracetheme <- reactive({
req(scalefactor())
theme_light() +
theme(
axis.title = element_blank(),
legend.title = element_blank(),
legend.spacing.x = unit(0.2, "cm"),
axis.text = element_text(size = 11 * scalefactor() * 0.8),
legend.text = element_text(size = 12 * scalefactor() * 1.1),
legend.key = element_rect(size = 12 * scalefactor() * 0.8),
strip.text = element_text(size = 12 * scalefactor())
)
})
# create color vector for consistent color schemes across all plots
tracecolors <- reactive({
set.trace.colors(tracedata())
})
#| # Tab 1 (Trace) -----
tP <- reactive({
xyplot(traceDF(), tracecolors(), tracetheme(), input$traceplotstyle, input$facetcol, input$cex)
})
output$tracePlot <- renderPlot({
tP()
})
output$tracePlot.ui <- renderUI({
shinycssloaders::withSpinner(plotOutput("tracePlot",
height = input$height,
width = input$width
),
color = "#2C4152", size = 0.5
)
})
#| # Tab 2 (Violin) -----
vP <- reactive({
violinplot(traceDF(), tracecolors(), tracetheme(), input$facetcol, input$cex, input$violinplotstyle)
})
output$violinPlot <- renderPlot({
vP()
})
output$violinPlot.ui <- renderUI({
shinycssloaders::withSpinner(plotOutput("violinPlot",
height = input$height,
width = input$width
),
color = "#2C4152", size = 0.5
)
})
#| # Tab 3 (Density) -----
# density plot for traces
dP <- reactive({
densityplot(traceDF(), tracecolors(), tracetheme(), input$facetcol)
})
output$densePlot <- renderPlot({
dP()
})
output$densePlot.ui <- renderUI({
shinycssloaders::withSpinner(plotOutput("densePlot",
height = input$height,
width = input$width
),
color = "#2C4152", size = 0.5
)
})
# Create pdf download handle for plots
output$downloadPDF <- downloadHandler(
filename = "traceplots.pdf",
content = function(file) {
pdf(file, height = input$height / 72, width = input$width / 72)
grid.arrange(tP(), ncol = 1)
grid.arrange(vP(), ncol = 1)
grid.arrange(dP(), ncol = 1)
dev.off()
}
)
#| SUMMARY STATISTICS (Tab 4) ------------------------------
output$table <- DT::renderDataTable({
req(tracefile)
# calculate summary stats
sum.stats <- calc.sum.stats(traceDF())
# Use DT package for flexible table formatting
style.table(sum.stats, traceDF())
})
# >>> TREE TAB <<<#####
#| TREE FILE PROPERTIES #------------------------------
treefile <- reactiveValues()
example <- reactiveValues()
# if input files are uploaded, use file paths and names from these
observeEvent(input$treefile, {
treefile$datapath <- input$treefile$datapath
treefile$name <- input$treefile$name
example$click <- 0
})
# if 'example' button is pressed, load example from example folder
observeEvent(input$exampletree1, {
treefile$datapath <- list.files("example/", "\\.treelist\\>", full.names = TRUE)
treefile$name <- list.files("example/", "\\.treelist\\>", full.names = FALSE)
example$click <- 1
showNotification("Loading example 1. This may take some time.",
id = "ex2",
duration = NULL
)
})
observeEvent(input$exampletree2, {
treefile$datapath <- list.files("example/", "\\.t\\>", full.names = TRUE)
treefile$name <- list.files("example/", "\\.t\\>", full.names = FALSE)
example$click <- 2
showNotification("Loading example 2. This may take some time.",
id = "ex2",
duration = NULL
)
})
# if 'info' button is pressed, show popup that explains examples
observeEvent(input$exampletreeinf, {
showModal(modalDialog(
title = "postpb comes with two sets of example data:",
includeMarkdown("modals/examples.md"),
size = "m"
))
})
# read in tree files
completetrees <- reactive({
req(treefile$datapath)
# only update tree format when new files are uploaded
input$treefile
isolate(read.treefiles(treefile))
})
alltrees <- reactive({
req(length(completetrees()) >= 1)
if (length(completetrees()) == 1) {
alltrees <- completetrees()
}
if (length(completetrees()) > 1 & !is.null(input$whichtree)) {
alltrees <- completetrees()[which(treenames() %in% input$whichtree)]
}
if (is.null(input$whichtree) & length(completetrees()) > 1) {
alltrees <- completetrees()
}
alltrees
})
# Tree thinning
thintrees <- reactive({
req(alltrees())
thin.trees(alltrees(), treethin())
})
# After tree files have been read in, reset tree format radio buttons
observeEvent(alltrees(), {
updatePrettyRadioButtons(session, "treefiletype",
choices = c("Newick (e.g., Phylobayes)", "Nexus (e.g., MrBayes)"),
selected = "character(0)",
inline = TRUE,
prettyOptions = list(
shape = "round",
status = "primary"
)
)
# Also, remove Notifications
removeNotification("ex1")
removeNotification("ex2")
})
# determine number of tree generations (smallest number from all files)
ngentree <- reactive({
alltrees()
treegen <- min(unlist(lapply(alltrees(), length)))
treegen
})
# extract the tree tip labels (= taxon names)
tipnames <- reactive({
req(treefile$datapath)
tree1 <- completetrees()[[1]][[1]]
labels <- sort(tree1$tip.label)
# pickerInput requires list
as.list(labels)
})
# get the names of the chains from the tree file names
treenames <- reactive({
req(treefile$datapath)
strsplit(treefile$name[1:length(treefile$name)], "\\.treelist\\>|\\.t\\>")
})
#| UI ELEMENTS FOR TREE TAB SIDEBAR #------------------------------
# Some tree calculations benefit from parallelization.
# Get the number of cores interactively, and set the default to ( total cores -1 )
totalcores <- reactive({
parallel::detectCores()[1]
})
observe({
totalcores()
doParallel::registerDoParallel(cores = input$ncores)
})
output$ncores <- renderUI({
numericInput("ncores",
label = "Number of cores",
min = 1,
max = totalcores(),
value = totalcores() - 1
)
})
# display check box to select which tree file to plot
output$whichtree <- renderUI({
req(treefile$datapath[2])
treenames <- lapply(treenames(), `[[`, 1)
shinyWidgets::prettyCheckboxGroup(
inputId = "whichtree",
label = "Select tree file[s] to analyse",
choices = treenames,
selected = treenames,
inline = FALSE,
status = "primary",
icon = icon("check")
)
})
# Slider that determines the number of burnin generations
output$conburnin <- renderUI({
req(treefile$datapath)
sliderInput("conburnin", "Burnin [# of iterations]:",
min = 0,
max = trunc(ngentree() / 10),
step = 10^(ceiling(log10(ngentree() / 10 * 0.02))),
value = ngentree() / 10 * 0.2
) # default burnin = 20% of all trees
})
# Set the default value of tree thinning to 10
treethin <- reactiveVal(10)
# Update the tree thinning value for calculating the consensus
# only if burnin has changed
observeEvent(input$conburnin, {
treethin(input$treethin)
})
# Update the burnin after tree thinning button is pressed
observeEvent(input$recalc, {
thinval <- input$treethin
treegens <- ngentree()
# Burnin slider
updateSliderInput(session, "conburnin",
label = "Burnin [# of iterations]:",
min = 0,
max = trunc(treegens / thinval),
step = 10^(ceiling(log10(ngentree() / 10 * 0.02))),
value = treegens / thinval * 0.2
)
})
# Picker input to chose outgroup
output$outgroups <- renderUI({
req(treefile$datapath)
pickerInput("outgroup",
label = "Select outgroup(s) for rooting",
choices = c(tipnames()),
multiple = TRUE,
options = list(
`selected-text-format` = "count > 2", # show names of up to 2 outgroup taxa
`count-selected-text` = "{0} outgroup taxa", # show number of outgroups if more than 2 taxa are selected
`live-search` = TRUE
), # this enables a search box in the selector
inline = FALSE
)
})
# After outgroup rooting has been performed, reset chosen outgroups
observeEvent(roottree(), {
updatePickerInput(session, "outgroup",
label = "Select outgroup(s) for rooting",
choices = c(tipnames())
)
})
# Similar picker input to chose which taxa to highlight
output$highlight <- renderUI({
req(treefile$datapath)
pickerInput("highlight",
label = HTML("Select taxa to highlight"),
choices = tipnames(),
multiple = TRUE,
options = list(
`selected-text-format` = "count > 2",
`count-selected-text` = "{0} taxa",
`actions-box` = TRUE, # enables 'select-all' and 'select none' buttons
`live-search` = TRUE
),
inline = FALSE
)
})
# Button that toggles graphics parameters for the tree plots
observeEvent(input$treeplotsopts, ignoreInit = TRUE, {
toggle("trplotopts")
})
#| FURTHER TREE DISPLAY OPTIONS #------------------------------
# Reset outgroup only when button is pressed, default is no outgroup
og <- reactiveValues(outgroup = "<None>")
# observe midpoint button
observeEvent(input$midpoint, {
og$outgroup <- "<Midpoint>"
})
# observe unroot button
observeEvent(input$unroot, {
og$outgroup <- "<None>"
})
# observe reroot button
observeEvent(input$outgroup, {
og$outgroup <- input$outgroup
})
# observe as new tree files are being read in
# Also reset outgroups when new tree files are loaded
observeEvent(completetrees(), {
og$outgroup <- "<None>"
})
# get further tree options from UI ("Tree plots")
treeopts <- reactive({
set.tree.opts(input$treeopts)
})
# get further tree options from UI ("Tree labels")
treefont <- reactive({
set.tree.font(input$treefont)
})
# this gets height and width for plots from the slider inputs and creates a scale factor to be used in plots
treeheight <- reactive({
input$treeheight
})
treewidth <- reactive({
input$treewidth
})
treescalefactor <- reactive({
(input$treeheight + input$treewidth) / 1800
})
#| TREE PLOTS ------------------------------
#| Interactive features -----
# Enable interactive selection of taxon selection for rooting
# create a dataframe of tip labels
tipDF <- reactive({
req(input$plot_brush)
get.tip.df(roottree())
})
# get the names of selected tips from the interactive 'brush' click+drag
# important here are only the ymin & ymax values: ape plots each tree from 0 (bottom) to Ntaxa, and difference between taxa is always 1
conroot <- reactive({
req(input$plot_brush)
# get names
tipDF <- tipDF() %>%
filter(tiporder >= input$plot_brush$ymin) %>%
filter(tiporder <= input$plot_brush$ymax)
as.character(tipDF$tips)
})
# Once selected, use popup to decide what to do with selected taxa (highlight or rooting)
observeEvent(input$plot_brush, {
showModal(modalDialog(
title = NULL,
HTML(paste("You have selected ", length(conroot()), " taxa\n", "<br><br>")),
align = "center",
actionButton("rootbutton", HTML("Re-root with<br>selection"),
width = "150px",
style = "border:2px solid; border-radius: 4px; margin:5px; background-color:white; color:black; font-weight:bold"
),
actionButton("colbutton",
HTML("Higlight<br>selection"),
width = "150px",
style = "border:2px solid; border-radius: 4px; margin:5px; background-color:white; color:black; font-weight:bold"
),
easyClose = TRUE,
footer = tagList(
modalButton("Cancel")
)
))
})
# If any of the buttons is pressed, close popup
observeEvent(input$rootbutton, {
removeModal()
})
observeEvent(input$colbutton, {
removeModal()
})
# With this selection made, update selection in outgroup pickerInput...
observeEvent(input$rootbutton, {
updatePickerInput(session, "outgroup",
label = "Select outgroup(s) for rooting",
choices = c(tipnames()),
selected = conroot()
)
session$resetBrush("plot_brush")
og$outgroup <- conroot()
})
# ... or highlight pickerInput
observeEvent(input$colbutton, {
updatePickerInput(session, "highlight",
choices = c(tipnames()),
selected = unique(conroot())
)
session$resetBrush("plot_brush")
})
# create reactive values for highlighting
highcol <- reactiveValues()
# Whenever new tree files are loaded, reset color vector
observeEvent(completetrees(), ignoreInit = FALSE, {
# When rooted tree is first plotted, create a dataframe with tip names and colors (here: all black)
# Only do this once
observeEvent(roottree(), once = T, {
highcol$df <- as_tibble(cbind(roottree()$tip.label, rep("black", length(roottree()$tip.label))))
})
})
# If taxa are selected, update the colors for the selected taxa in the dataframe
observeEvent(input$highlight, {
highcol$df <- highcol$df %>%
mutate(V2 = ifelse(V1 %in% input$highlight, input$high1, V2))
})
# Same when colors are changed
observeEvent(input$high1, {
req(input$highlight)
highcol$df <- highcol$df %>%
mutate(V2 = ifelse(V1 %in% input$highlight, input$high1, V2))
})
#| # Tab 1 (Consensus) -----
# Plot 1 is a consensus plot
# merge trees from all chains into single object
treesall <- reactive({
req(length(alltrees()) >= 1)
if (length(completetrees()) > 1) {
req(length(input$whichtree) > 0)
}
combine.trees(thintrees(), input$conburnin)
})
# calculate consensus tree
contree.p <- reactive({
calc.cons(treesall())
})
# collapse nodes lower than threshold chosen by user
contree <- reactive({
collapse.nodes(contree.p(), input$postprop)
})
# root the tree
roottree <- reactive({
# require these for interactive rooting
input$reroot
input$midpoint
input$unroot
# only update when button is pressed
isolate(outgroup <- og$outgroup)
# root the tree
root.tree(contree(), outgroup)
})
# now render consensus plot
consensusplot <- reactive({
req(highcol$df)
req(roottree())
render.contree(roottree(), highcol$df, thintrees(), input$treecex, treeopts(), treefont(), input$annot)
recordPlot()
})
output$consensusPlot <- renderPlot({
consensusplot()
})
# render consensus plot with spinner
output$consensusPlot.ui <- renderUI({
withSpinner(plotOutput("consensusPlot",
height = treeheight(),
# brush here enables interactive selection of taxa
brush = brushOpts(
id = "plot_brush", # this enables selecting
resetOnNew = TRUE,
delay = 2000,
direction = "y", # selection using y axis only
fill = "#ccc",
delayType = "debounce"
),
width = treewidth() * 0.75
),
color = "#2C4152",
size = 0.5
)
})
# PDF download handle for consensus plot
output$consensusPDF <- downloadHandler(
filename = "consensus.pdf",
contentType = "application/pdf",
content = function(file1) {
pdf(file1, height = input$treeheight / 72, width = input$treewidth / 72)
replayPlot(consensusplot())
dev.off()
}
)
# also export the tree as newick if wanted
output$newick <- downloadHandler(
filename = "consensus.nwk",
content = function(file4) {
write.tree(roottree(),
file = file4, append = FALSE,
digits = 10, tree.names = FALSE
)
}
)
#| # Tab 2 (Trees) ----
# Slider that determines the tree generation currently displayed
output$treegens <- renderUI({
req(treefile$datapath)
sliderInput("generation", "Tree generation",
min = 1,
max = trunc(ngentree() / treethin()),
value = 1,
step = 1,
ticks = FALSE,
animate = animationOptions(
interval = 1000, # this adds a button that animates an iteration through all tree generations
loop = TRUE,
# this make the buttons pretty
playButton = tags$button("PLAY", style = "border:2px solid; border-radius: 4px; margin:5px; padding:2px 10px; font-size:90%; background-color:white; color:black; font-weight:bold"),
pauseButton = tags$button("PAUSE", style = "border:2px solid; border-radius: 4px; margin:5px; padding:2px 10px; font-size:90%; background-color:white; color:black; font-weight:bold")
)
)
})
# This plot shows a single tree per iteration and chain
treeplot <- reactive({
# require these for interactive rooting
input$reroot
input$midpoint
input$unroot
# Make sure trees for plotting are selected
if (length(completetrees()) > 1) {
req(length(input$whichtree) > 0)
}
# get outgroup from ui, but isolate so that rerooting is only done when button is pressed
isolate(outgroup <- og$outgroup)
# plot tree
render.singletrees(thintrees(), outgroup, input$generation, highcol$df, input$treecex, treefont(), treeopts(), input$whichtree)
recordPlot()
})
output$treeplot <- renderPlot({
treeplot()
})
# render the plot with spinner & using the height and widths from ui
output$treePlot.ui <- renderUI({
req(treefile$datapath)
withSpinner(plotOutput("treeplot",
height = treeheight(),
width = treewidth()
),
color = "#2C4152",
size = 0.5
)
})
# PDF download handle for single trees plot
output$singletreePDF <- downloadHandler(
filename = "single_tree.pdf",
contentType = "application/pdf",
content = function(file2) {
pdf(file2, height = input$treeheight / 72, width = input$treewidth / 72)
replayPlot(treeplot())
dev.off()
}
)
#| # Tab 3 (Difference) -----
# Plot 3 shows 2 consensus plots with comparison
differenceplot <- reactive({
# require these for interactive rooting
input$reroot
input$midpoint
input$unroot
# check if at least 2 tree files are present and if rooting other than midpoint is selected. Throw error if not.
isolate(outgroup <- og$outgroup)
render.treediff(thintrees(), alltrees(), outgroup, input$conburnin, highcol$df, input$treecex, treefont(), input$whichtree)
recordPlot()
})
output$differencePlot <- renderPlot({
differenceplot()
})
# PDF download handle for difference plot
output$differencePDF <- downloadHandler(
filename = "difference.pdf",
contentType = "application/pdf",
content = function(file4) {
pdf(file4, height = input$treeheight / 72, width = input$treewidth / 72)
replayPlot(differenceplot())
dev.off()
}
)
# finally, render this plot with spinner
output$differencePlot.ui <- renderUI({
shinycssloaders::withSpinner(plotOutput("differencePlot", height = treeheight(), width = treewidth()), color = "#2C4152", size = 0.5)
})
#| # Tab 4 (All topologies) -----
# Look at all topologies found in the dataset, and at their frequencies
# Info button shows some explanations
observeEvent(input$topoinfo, {
showModal(modalDialog(
title = "Determining unique topologies",
includeMarkdown("modals/topologies.md"),
size = "m"
))
})
# subsample trees only if checkbox is activated
treessampled <- eventReactive(input$toposamplego, {
req(treesall())
if(input$toposample == TRUE){
sample(treesall(), 100)
}
else {
treesall()
}
})
# extract unique trees
unitops <- reactive({
req(contree.p)
uniq.trees(treessampled())
})
# extract determine frequencies of all unique topologies
topfreq <- reactive({
req(unitops())
topology.freqs(treessampled(), unitops())
})
# make frequency bar plot
tfP <- reactive({
req(topfreq())
plot.topo.freq(topfreq())
})
output$topology.freqplot <- renderPlot({
tfP()
})
# create download button for plot
output$downloadfreq <- downloadHandler(
filename = "RFplot.pdf",
content = function(file8) {
pdf(file8) #, height = input$treeheight / 72, width = input$treewidth / 72)
gridExtra::grid.arrange(tfP(), ncol = 1)
dev.off()
}
)
# selectinput for which topology to display
output$toposelect <- renderUI({
req(topfreq())
topochoice <- as.factor(topfreq()$treefreq)
names(topochoice) <- paste0("Topology ", topfreq()$order, ": ", topfreq()$Freq, "/", sum(topfreq()$Freq), " trees")
selectInput("toposelect",
label = ("Select topology to plot"),
choices = topochoice
)
})
# currently selected topology
currtopo <- reactive({
req(unitops())
req(input$toposelect)
# require these for interactive rooting
input$reroot
input$midpoint
input$unroot
isolate(outgroup <- og$outgroup)
tn <- as.numeric(input$toposelect)
root.tree(unitops()[[tn]], outgroup)
})
# Create plot
uniq.topoplot <- reactive({
req(currtopo())
tn <- as.numeric(input$toposelect)
render.uniq.topo(currtopo(), topfreq(), tn, highcol$df, input$treecex, treeopts(), treefont())
recordPlot()
})
output$uniq.topo.P <- renderPlot({
uniq.topoplot()
})
# PDF download handle for topology plot
output$downloadtop <- downloadHandler(
filename = function() paste0("unique.topology_", input$toposelect, ".pdf"),
contentType = "application/pdf",
content = function(file7) {
pdf(file7, height = input$treeheight / 72, width = input$treewidth / 72)
replayPlot(uniq.topoplot())
dev.off()
}
)
# render the plot with spinner & using the height and widths from ui
output$uniqtopo.ui <- renderUI({
withSpinner(plotOutput("uniq.topo.P",
height = treeheight(),
width = treewidth()
),
color = "#2C4152",
size = 0.5
)
})
#| # Tab 5 (Pairwise Robinson-Foulds) -----
# Plot 5 shows differences between trees across iterations and between chains
# Calculate RF distances in parallel if multiple cores are available
rP <- reactive({
req(treefile$datapath)
if (length(completetrees()) > 1) {
req(length(input$whichtree) > 0)
}
render.rfplot(thintrees(), input$conburnin, input$whichtree, input$treecex, treescalefactor())
})
output$rfPlot <- renderPlot({
rP()
})
output$rfPlot.ui <- renderUI({
req(treefile$datapath)
shinycssloaders::withSpinner(plotOutput("rfPlot", height = treeheight(), width = treewidth()),
color = "#2C4152", size = 0.5
)
})
# create download button for plot
output$downloadrfplot <- downloadHandler(
filename = "RFplot.pdf",
content = function(file5) {
pdf(file5, height = input$treeheight / 72, width = input$treewidth / 72)
gridExtra::grid.arrange(rP(), ncol = 1)
dev.off()
}
)
#| # Tab 6 (Bipartition support) -----