-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.R
2310 lines (1663 loc) · 112 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
# SPLITTING TERM CHANGED
ggthemes = list("Classic" = theme_classic(),
"Dark" = theme_dark(),
"Minimal" = theme_minimal(),
"Grey" = theme_grey(),
"Light" = theme_light(),
"Black/White" = theme_bw(),
"Void" = theme_void())
server = function(input, output, session) {
home_dir = getwd()
treeannotator_dir = paste(home_dir, "/TreeAnnotator.exe", sep = "")
logcombiner_dir = paste(home_dir, "/LogCombiner.exe", sep = "")
#access to the app from the homepage link
observeEvent(input$app, updateTabsetPanel(session = session, inputId = "tabset", selected = "app"))
################################################################################################
# RANDOM RESAMPLING OF FASTA FILE SEQUENCES
################################################################################################
# optionally read in an excel file of sequence names and predefined groups:
groups_resampling = reactive({
infile = input$resampling_groupings
if (is.null(infile)) {
return(NULL)
}
else{
resample_groups <<- read.csv(infile$datapath)
return(resample_groups)
}
}) # end of reactive
# select which column is the grouping and which is the sample names
observeEvent(input$resampling_groupings_uploaded, {
updateSelectInput(session,"resampling_group_col", choices=colnames(groups_resampling()))
updateSelectInput(session,"resampling_sample_name_col", choices=colnames(groups_resampling()))
})
# Read in the fasta file:
observe({
in_seqs = input$fasta_file
if (is.null(in_seqs)) {
return(NULL)
}
seqs = ape::read.FASTA(in_seqs$datapath)
# get the number of sequences in the alignment file
output$num_seqs = renderText({paste("There are ", length(seqs), " sequences in your alignment.")})
observeEvent(input$resample_fastas, {
if(input$resampling_approach == "Random resampling"){
# get the number of sequences to resample
num_fasta_seqs = floor( (input$fasta_subsample_percent/100) * length(seqs) )
# create an empty folder to store resampled fasta files
dir.create(input$resampled_fasta_folder_name)
# ITERATE THIS N TIMES
out_file = paste(input$resampled_fasta_folder_name, "/", input$resampled_fasta_file_name, sep = "")
if(input$set_seed_resampling == TRUE) set.seed(123)
# function from the FastaUtils github package, Guillem Salazar
fasta.sample<-function(infile=NULL,nseq=NULL,file.out=NULL,replacement=FALSE){
seqs<- Biostrings::readDNAStringSet(infile)
selected<-seqs[sample(1:length(seqs),nseq,replace=replacement)]
Biostrings::writeXStringSet(selected,filepath=file.out)}
withProgress(message = 'Resampling...', value = 0, {
for (i in 1:input$fasta_resample_iterations){
fasta.sample(infile = in_seqs$datapath, nseq = num_fasta_seqs, file.out = paste(out_file, "_", i, ".fasta", sep = ""),
replacement = FALSE)
# Increment the progress bar, and update the detail text.
incProgress(1/input$fasta_resample_iterations, detail = paste("Resampling file ", i, " of ", input$fasta_resample_iterations, "[ ", round(i/input$fasta_resample_iterations*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
}) # end of progressbar
shinyalert::shinyalert("Complete", "Successfully resampled", type = "success")
} # end of if statement re input$resampling_approach
else{ # if the user wishes to keep at least one sequence representative per predefined group
if(input$set_seed_resampling == TRUE) set.seed(123)
id_col = as.name(input$resampling_sample_name_col)
grp_col = as.name(input$resampling_group_col)
groups_resampling_df = groups_resampling()
groups_resampling_df[[grp_col]] = as.factor( groups_resampling_df[[grp_col]] )
num_fasta_seqs = floor( (input$fasta_subsample_percent/100) * length(seqs) )
num_groups = length( levels( groups_resampling_df[[grp_col]] ) )
if(num_fasta_seqs < num_groups) shinyalert::shinyalert("Warning", paste("Please select a larger percentage to resample. You need at least ", ceiling( num_groups/length(seqs) * 100 ), "%"), type = "warning")
else{
out_folder = paste(input$resampled_fasta_folder_name)
dir.create(out_folder)
withProgress(message = 'Resampling...', value = 0, {
for (k in 1:input$fasta_resample_iterations){
# subset each predefined group, and store them all in a list called "subset_groups"
subset_groups = c()
for(i in levels( groups_resampling_df[[grp_col]] )){
subset_groups[[i]] = subset(groups_resampling_df, groups_resampling_df[[grp_col]] == i)
}
# randomly select one sequence from each predefined group, and store it in a list called "extracted_samples"
extracted_samples = c()
for(j in 1:length(subset_groups)){
rand_ind = sample(nrow(subset_groups[[j]]), 1, replace = FALSE)
extracted_samples[[j]] = subset_groups[[j]][rand_ind,]
subset_groups[[j]] = subset_groups[[j]][-rand_ind, ]
}
# convert these lists into dataframes
extracted_samples = dplyr::bind_rows(lapply(extracted_samples, as.data.frame.list))
subset_groups = dplyr::bind_rows(lapply(subset_groups, as.data.frame.list))
# get the number of sequences to resample, taking into account the sequences that were already extracted to serve as representative sequences for each group
num = num_fasta_seqs - nrow(extracted_samples)
# randomly select from the remaining sequences
# get random indices (or one index, depending):
resampled_ind = sample(nrow(subset_groups), num, replace = FALSE)
# subset the associated rows based on those indices
resampled = subset_groups[resampled_ind,]
# bind the randomly selected sequences to the ones that were extracted in the beginning (one representative sequence for each group)
final = rbind(extracted_samples, resampled)
# extract the actual sequences in the fasta file based on the randomly selected names
seqs_subsetted = subset(seqs, labels(seqs) %in% final[[id_col]])
# write the fasta file
write.dna(seqs_subsetted, paste(out_folder, "/", input$resampled_fasta_file_name, "_", k, ".fasta", sep = ""), format = "fasta")
# Increment the progress bar, and update the detail text.
incProgress(1/input$fasta_resample_iterations, detail = paste("Resampling file ", k, " of ", input$fasta_resample_iterations, "[ ", round(k/input$fasta_resample_iterations*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
} # end of for loop
}) # end of progressbar
shinyalert::shinyalert("Complete", "Successfully resampled", type = "success")
} # end of else
} # end of else
}) # end of observeEvent
}) # end of observe
################################################################################################
# GENETIC DIVERGENCE CALCULATION
################################################################################################
# read in the groupings file
# groups_genetic_divergence = reactive({
#
# infile = input$genetic_divergence_groupings
#
# if (is.null(infile)) {
# return(NULL)
# }
#
# else{
# genetic_divergence_groups <<- read.csv(infile$datapath)
# return(genetic_divergence_groups)
# }
#
# }) # end of reactive
#
# # select which column is the grouping and which is the sample names
# observeEvent(input$genetic_divergence_groupings_uploaded, {
# updateSelectInput(session,"genetic_divergence_group_col", choices=colnames(groups_genetic_divergence()))
# updateSelectInput(session,"genetic_divergence_sample_name_col", choices=colnames(groups_genetic_divergence()))
# })
#
# # input the file path to the fasta files
#
# observeEvent(input$calculate_genetic_divergences,{
#
# fasta_file_path_gen_diverg = input$fasta_file_path_genetic_divergence
#
# if (!dir.exists(fasta_file_path_gen_diverg))
# shinyalert::shinyalert("Error", "File path does not exist", type = "error")
#
# else{
#
# setwd(fasta_file_path_gen_diverg)
# gen_diverg_fasta_files = gtools::mixedsort( list.files(pattern = "\\.fas") )
# w_group_dists = c()
# b_group_dists = c()
# o_group_dists = c()
#
# spp_dists = list()
#
# seq_name_col = as.name(input$genetic_divergence_sample_name_col)
# morphogroup_col = as.name(input$genetic_divergence_group_col)
#
# withProgress(message = 'Calculating genetic divergences...', value = 0, {
#
# for(i in seq(along = gen_diverg_fasta_files)){
#
# target = ape::read.FASTA(gen_diverg_fasta_files[i])
# dists = ape::dist.dna(target)
#
# seq_names = names(target)
#
# new_dat = data.frame(matrix(nrow = length(seq_names), ncol =2))
# colnames(new_dat) = c("seq_name", "group")
# new_dat$seq_name = seq_names
#
# for(m in (1:length(seq_names))){
# for(n in (1:nrow(genetic_divergence_groups))){
# if(seq_names[m] == genetic_divergence_groups[[seq_name_col]][n])
# new_dat$group[m] = genetic_divergence_groups[[morphogroup_col]][n]
# }
# }
#
# tryCatch({
#
# MD = vegan::meandist(dists, new_dat$group)
# MD_summary = summary(MD)
# w_group_dists[i] = MD_summary$W
# b_group_dists[i] = MD_summary$B
# o_group_dists[i] = MD_summary$D
#
# MD_df = as.data.frame(MD)
# vals = c()
#
# for(k in 1:nrow(MD_df)){
# vals[k] = MD_df[k,k]
# }
#
# spp_dists[[i]] = vals
#
# }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
#
# # Increment the progress bar, and update the detail text.
# incProgress(1/length(gen_diverg_fasta_files), detail = paste("Processing Fasta file ", i, " of ", length(gen_diverg_fasta_files), "[ ", round(i/length(gen_diverg_fasta_files)*100, 0), "% ]"))
# # Pause for 0.1 seconds to simulate a long computation.
# Sys.sleep(0.1)
#
# } # end of for loop
#
# group_dists_df = data.frame(matrix(nrow = length(gen_diverg_fasta_files), ncol = 4))
# colnames(group_dists_df) = c("filename", "intra_dist", "inter_dist", "overall_dist")
# group_dists_df$filename = gen_diverg_fasta_files
# group_dists_df$intra_dist = w_group_dists
# group_dists_df$inter_dist = b_group_dists
# group_dists_df$overall_dist = o_group_dists
#
# # tryCatch({
# # spp_dists = as.data.frame(do.call(rbind, spp_dists))
# # colnames(spp_dists) = levels(as.factor(genetic_divergence_groups[[morphogroup_col]]))
# # rownames(spp_dists) = gen_diverg_fasta_files
# # }, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
#
# }) # end of progress bar
#
# shinyalert::shinyalert("Complete", "Divergences Successfully Calculated", type = "success")
#
#
# } # end of else
#
# observeEvent(input$view_genetic_divergences, {
# output$genetic_divergence_table = renderTable(group_dists_df, rownames = TRUE, colnames = TRUE, digits = 3)
# })
#
#
# output$download_genetic_dists = downloadHandler(
#
# filename = function (){paste('genetic_dists', 'csv', sep = '.')},
# content = function (file){write.csv(group_dists_df, file, row.names = FALSE)}
# )
#
# # output$download_divergences_per_group = downloadHandler(
# #
# # filename = function (){paste('genetic_dists_per_morphogroup', 'csv', sep = '.')},
# # content = function (file){write.csv(spp_dists, file, row.names = FALSE)}
# # )
#
# }) # end of observeEvent
################################################################################################
# GENERATE XML FILES FOR BEAST
################################################################################################
observeEvent(input$create_xml_files, {
resampled_fasta_file_path = input$resampled_fasta_file_path
if (!dir.exists(resampled_fasta_file_path))
shinyalert::shinyalert("Error", "File path does not exist", type = "error")
else{
setwd(resampled_fasta_file_path)
resampled_fasta_files = gtools::mixedsort( list.files(pattern = "\\.fas") )
# different rate distribution options
rate_option = function(distribution_prior, n){
if(missing(n)){
switch(distribution_prior,
"Beta" = beautier::create_beta_distr(),
"Exponential" = beautier::create_exp_distr(),
"Gamma" = beautier::create_gamma_distr(),
"Inverse gamma" = beautier::create_inv_gamma_distr(),
"Laplace" = beautier::create_laplace_distr(),
"Log-normal" = beautier::create_log_normal_distr(),
"Normal" = beautier::create_normal_distr(),
"1/X" = beautier::create_distr_one_div_x(),
"Poisson" = beautier::create_poisson_distr(),
"Uniform" = beautier::create_uniform_distr())
}
else {
switch(distribution_prior,
"Beta" = beautier::create_beta_distr(value = n),
"Exponential" = beautier::create_exp_distr(value = n),
"Gamma" = beautier::create_gamma_distr(value = n),
"Inverse gamma" = beautier::create_inv_gamma_distr(value = n),
"Laplace" = beautier::create_laplace_distr(value = n),
"Log-normal" = beautier::create_log_normal_distr(value = n),
"Normal" = beautier::create_normal_distr(value = n),
"1/X" = beautier::create_distr_one_div_x(value = n),
"Poisson" = beautier::create_poisson_distr(value = n),
"Uniform" = beautier::create_uniform_distr(value = n))
}
}
# Set up the inference model
inference_model = beautier::create_inference_model(
site_model = switch(input$beast_site_model, "GTR" = beautier::create_gtr_site_model(),
"HKY" = beautier::create_hky_site_model(),
"JC69" = beautier::create_jc69_site_model(),
"TN93" = beautier::create_tn93_site_model()),
clock_model = switch(input$beast_clock_model, "Strict" = beautier::create_strict_clock_model(clock_rate_param = input$beast_clock_rate),
"Relaxed lognormal" = beautier::create_rln_clock_model(clock_rate_param = input$beast_clock_rate)),
tree_prior = switch(input$beast_tree_prior, "Birth-death" = beautier::create_bd_tree_prior(birth_rate_distr = rate_option(input$distr_b), death_rate_distr = rate_option(input$distr_d)),
"Coalescent Bayesian skyline" = beautier::create_cbs_tree_prior(group_sizes_dimension = input$cbs_group_sizes_dim),
"Coalescent constant-population" = beautier::create_ccp_tree_prior(pop_size_distr = rate_option(input$distr_ccp, n = input$pop_size_distribution)),
"Coalescent exponential-population" = beautier::create_cep_tree_prior(pop_size_distr = rate_option(input$distr_cep_pop), growth_rate_distr = rate_option(input$distr_cep_gr)),
"Yule" = beautier::create_yule_tree_prior(birth_rate_distr = rate_option(input$distr_yule))),
mcmc = beautier::create_mcmc(chain_length = input$beast_mcmc, store_every = input$beast_store_every)
)
# create xml files
withProgress(message = 'Creating XML files...', value = 0, {
for(i in seq(along = resampled_fasta_files)){
beautier::create_beast2_input_file_from_model(
input_filename = resampled_fasta_files[i],
inference_model = inference_model,
output_filename = paste(input$xml_folder_name,"/", tools::file_path_sans_ext(resampled_fasta_files[i]), ".xml", sep = "" )
)
# Increment the progress bar, and update the detail text.
incProgress(1/length(resampled_fasta_files), detail = paste("Processing fasta file ", i, " of ", length(resampled_fasta_files), "[ ", round(i/length(resampled_fasta_files)*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
}) # end of progress bar
shinyalert::shinyalert("Complete", "Successfully created XML files", type = "success")
} # end of else regarding setwd()
})
################################################################################################
# RUN BEAST ON THE GENERATED XML FILES
################################################################################################
observeEvent(input$run_beast, {
if (!dir.exists(input$xml_file_path))
shinyalert::shinyalert("Error", "File path does not exist", type = "error")
else{
setwd(input$xml_file_path)
xml_files = gtools::mixedsort( list.files(pattern = "\\.xml") )
withProgress(message = 'Running BEAST...', value = 0, {
for(i in seq(along = xml_files)){
beastier::run_beast2(
input_filename = xml_files[i],
verbose = TRUE,
use_beagle = input$run_beagle
)
# Increment the progress bar, and update the detail text.
incProgress(1/length(xml_files), detail = paste("Processing XML file ", i, " of ", length(xml_files), "[ ", round(i/length(xml_files)*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
}) # end of progress bar
shinyalert::shinyalert("Complete", "BEAST successfully run", type = "success")
} # end of else regarding setwd()
})
################################################################################################
# RUN TREEANNOTATOR ON BEAST .TREES FILES
################################################################################################
observeEvent(input$run_treeannotator, {
if (!dir.exists(input$beast_trees_file_path))
shinyalert::shinyalert("Error", "File path does not exist", type = "error")
else{
file.copy(treeannotator_dir, input$beast_trees_file_path)
setwd(input$beast_trees_file_path)
beast_tree_files = gtools::mixedsort( list.files(pattern = "\\.trees") )
burnin = paste("-burnin", input$treeannotator_burnin)
heights = paste("-heights", input$treeannotator_heights)
withProgress(message = 'Running TreeAnnotator...', value = 0, {
for(i in seq(along = beast_tree_files)){
in_file = beast_tree_files[i]
out_file = paste(tools::file_path_sans_ext(beast_tree_files[i]), ".nex", sep = "")
if(input$treeannotator_low_mem == TRUE)
treeannotator_command_line = paste("TreeAnnotator.exe", burnin, heights, "-lowMem", in_file, out_file)
else treeannotator_command_line = paste("TreeAnnotator.exe", burnin, heights, in_file, out_file)
system(treeannotator_command_line)
# Increment the progress bar, and update the detail text.
incProgress(1/length(beast_tree_files), detail = paste("Processing BEAST .trees file ", i, " of ", length(beast_tree_files), "[ ", round(i/length(beast_tree_files)*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
# this while loop delays the main loop so that it only goes into the next iteration after the file has been written.
# this seems to prevent the program from freezing up when treeannotator is run with very large file sizes
while (!file.exists( paste(tools::file_path_sans_ext( beast_tree_files[i] ), ".nex", sep = "") ) ) {
Sys.sleep(2)
}
}
}) # end of progress bar
shinyalert::shinyalert("Complete", "TreeAnnotator successfully run", type = "success")
} # end of else regarding setwd()
})
################################################################################################
# Run TRACER
################################################################################################
observeEvent(input$load_log_files, {
if (!dir.exists(input$beast_log_files_path))
shinyalert::shinyalert("Error", "File path does not exist", type = "error")
else{
setwd(input$beast_log_files_path)
log_files = gtools::mixedsort( list.files(pattern = "\\.log") )
updateSelectInput(session,"select_log_file", choices=log_files)
observeEvent(input$table_log_files, {
estimates <- tracerer::parse_beast_tracelog_file(input$select_log_file)
estimates <- tracerer::remove_burn_ins(estimates, burn_in_fraction = input$tracer_burnin)
esses <- tracerer::calc_esses(estimates, sample_interval = input$tracer_sample_interval)
ess_table <- t(esses)
colnames(ess_table) <- c("ESS")
output$tracer_ess = renderTable(ess_table, rownames = TRUE, colnames = TRUE, digits = 0)
output$tracer_plot = renderPlot({ ggplot2::ggplot(
data = tracerer::remove_burn_ins(estimates, burn_in_fraction = input$tracer_burnin),
ggplot2::aes(x = Sample)
) + ggplot2::geom_line(ggplot2::aes(y = posterior)) + ggplot2::ggtitle("Trace plot") + ggplot2::theme_classic()
})
})
} # end of else
})
################################################################################################
# RUN LOGCOMBINER
################################################################################################
observeEvent(input$run_logcombiner, {
if (!dir.exists(input$logcombiner_file_path))
shinyalert::shinyalert("Error", "File path does not exist", type = "error")
else{
file.copy(logcombiner_dir, input$logcombiner_file_path)
setwd(input$logcombiner_file_path)
# create an empty folder
dir.create(input$logcombiner_folder_results)
logcombiner_tree_files = gtools::mixedsort( list.files(pattern = "\\.trees") )
resampling = paste("-resample", input$resample_freq)
withProgress(message = 'Running LogCombiner...', value = 0, {
for(i in seq(along = logcombiner_tree_files)){
logcombiner_in_file = paste("-log", logcombiner_tree_files[i])
logcombiner_out_file = paste("-o", paste( input$logcombiner_folder_results, "/", tools::file_path_sans_ext(logcombiner_tree_files[i]), ".trees", sep = "") )
logcombiner_command_line = paste("LogCombiner.exe", logcombiner_in_file, logcombiner_out_file, resampling)
system(logcombiner_command_line)
# Increment the progress bar, and update the detail text.
incProgress(1/length(logcombiner_tree_files), detail = paste("Processing LogCombiner .trees file ", i, " of ", length(logcombiner_tree_files), "[ ", round(i/length(logcombiner_tree_files)*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
}
}) # end of progress bar
shinyalert::shinyalert("Complete", "LogCombiner successfully run", type = "success")
} # end of else re. setwd()
})
################################################################################################
################################################################################################
# get the filepath for the PATHD8 executable ready, if the user chooses to select it. It is in the PATHD8 folder, in the GitHub repo
# that is downloaded.
pathd8_filepath = paste(getwd(), "/PATHd8/PATHd8", sep="")
# tell the shinyhelper package what the file name of the help file is
# observe_helpers(help_dir = "HelpFile")
# I'm leaving this bit in, despite taking the option of a folder upload via a button out of the GUI
volumes = getVolumes()() # this presents all the folders on the user's PC
path = reactive({
shinyDirChoose(input, 'directory', roots= volumes, session=session)
return(parseDirPath(volumes, input$directory))
})
output$folder_path = renderText( path() ) # quick check to see if the directory is stored as 'path'
################################################################################################
# Read in an optional csv file with predefined grouping information for the GMYC analysis
################################################################################################
predefined_groups_uploaded = reactive({
infile = input$predefined_groups
if (is.null(infile)) {
return(NULL)
}
else{
groups = read.csv(infile$datapath)
return(groups)
}
}) # end of observe of input of predefined group file
################################################################################################
################################################################################################
observeEvent(input$group_data_uploaded, {
updateSelectInput(session,"col.group", choices=colnames(predefined_groups_uploaded()))
updateSelectInput(session,"sample_names", choices=colnames(predefined_groups_uploaded()))
})
################################################################################################
# Run the GMYC analysis
################################################################################################
observeEvent(input$run_gmyc, {
if (!dir.exists(input$raw_file_path))
shinyalert::shinyalert("Error", "File path does not exist", type = "error")
else{
manual_file_path = input$raw_file_path
################################################################################################
# check whether the user has neglected to select a folder or input a file path
################################################################################################
if (length(path()) == 0 && manual_file_path == "") shinyalert::shinyalert("No folder or path input", "You have not selected a folder or pasted in a folder path.", type = "warning")
if (length(path()) > 0 && manual_file_path != "") shinyalert::shinyalert("Issue: Two folder inputs", "You have selected a folder and inputted a file path. Please remove the manual file path and ensure that the desired folder has been selected.", type = "warning")
if (!is.null( predefined_groups_uploaded() ) && input$col.group == "" ) shinyalert::shinyalert("Confirm columns", "Please click the Confirm button, and then select columns for grouping and sample name informaiton for your .csv file data.", type = "warning")
################################################################################################
# If they have inputted one or the other, proceed:
################################################################################################
else{# else1
output$warn_files = renderText("")
################################################################################################
# check whether the user has inserted only a manual file path.
# If so, set that path as the working directory
################################################################################################
if (length(path()) == 0 && manual_file_path != "") {
path = manual_file_path
setwd(path)
}
################################################################################################
# Otherwise use the path stored from the folder input button
################################################################################################
else setwd(path())
if (input$tree_tool == "BEAST") files = gtools::mixedsort( list.files(pattern = "\\.nex") )
# populate the dropdown list to show all the files inputted, so that the user can plot one if they wish
updateSelectInput(session,"select_tree", choices=files)
updateSelectInput(session,"select_tree_speclist", choices=files)
################################################################################################
# check whether there are files in the folder that contain bestTree or .tre in their names
################################################################################################
#if (length(files) == 0) output$warn_files = renderText('<b>There are no appropriate tree files in the folder you have selected.')
if (length(files) == 0) shinyalert::shinyalert("No .tre or bestTree files", "There are no appropriate tree files in the folder you have selected.", type = "error")
################################################################################################
# If there are, then proceed:
################################################################################################
else{ # else2
output$warn_files = renderText("") # clear the warning if there was one before
# initialise the dataframes to store cluster and entity info
clust_ent = data.frame(matrix(nrow = length(files), ncol = 3))
colnames(clust_ent) = c("filename", "clusters", "entities")
# this initialises the dataframe below, even if the user doesn't input grouping info. Doesn't seem to work when these three lines are within the if statemetn for group_info
record = data.frame(matrix(nrow = length(files), ncol = 6))
colnames(record) = c("filename", "percentage_match", "percentage_match_excl_singles", "percentage_single_sample_GMYC_species", "splitting_ratio", "splitting_excl_singles")
record$filename = files
# create a list to which each gmyc tree is stored
tree_container = vector("list", length(files))
# create a list with gmyc.spec output for each file
gmyc_spec_container = vector("list", length = length(files))
# create a list of which predefined species are being oversplit by the gmyc algorithm
splitting_species = vector("list")
merged_gmyc_specs = vector("list")
################################################################################################
# Loop through the files in the chosen directory to create an ultrametric tree for each,
# then run the GMYC analysis,
# and store the entities and clusters
################################################################################################
withProgress(message = 'Running GMYC', value = 0, {
for(i in seq(along=files)) {
if(input$tree_tool == "BEAST") treex.ultra2 = ape::read.nexus(files[i])
else if(input$tree_tool == "Non-ultrametric: PATHD8"){
treex = ape::read.tree(files[i])
treex_tiplabels = treex$tip.label
# extract the first two tip labels (could be any two labels)
label1 = treex_tiplabels[1]
label2 = treex_tiplabels[2]
pathd8_params = data.frame(matrix(nrow = 1, ncol = 4))
colnames(pathd8_params) = c("tax1", "tax2", "age_type", "age")
pathd8_params[1,] = c(label1, label2, "root", 1)
tryCatch({
pathd8_result = ips::pathd8(phy = treex, exec = pathd8_filepath, seql = input$seqlength, calibration = pathd8_params)
treex.ultra = pathd8_result$mpl_tree
treex.ultra2 = ape::multi2di(treex.ultra, random = T) # makes the tree fully dichotomous
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
}
if (input$set_seed == TRUE) set.seed(1234)
# Run the GMYC analysis
# tryCatch skips through any possible errors with the gmyc function (e.g. nuclear genes that are identical)
tryCatch({
treex.gmyc = splits::gmyc(treex.ultra2, quiet = F, method = input$gmyc_threshold)
}, error=function(e){cat("ERROR :",conditionMessage(e), "\n")})
# treex.gmyc = gmyc(treex.ultra2, quiet = F, method = "multiple")
# store the gmyc in the tree_container list
tree_container[[i]] = treex.gmyc
# these three lines below write the files to the same folder:
# uncomment to write them
#sink(paste(files[i], c("gmyc_out.txt"), sep = ""))
#summary.gmyc(treex.gmyc)
#sink()
clust_ent[i,1] = files[i] # populate file name
clust_ent[i,2] = treex.gmyc$cluster[which.max(treex.gmyc$likelihood)] # extract the number of clusters
clust_ent[i,3] = treex.gmyc$entity[which.max(treex.gmyc$likelihood)] # extract the number of entities
########################################################################################################
# Do this bit only if the user uploaded a csv file with grouping data and clicked "CONFIRM"
########################################################################################################
if (!is.null( predefined_groups_uploaded() )){
groups = predefined_groups_uploaded()
groups_col = as.name( input$col.group )
sample_names_col = as.name (input$sample_names )
gmyc.spec = splits::spec.list(treex.gmyc)
gmyc.spec['ids'] = NA # add an empty column that will later have the predefined IDS as uploaded by the user
for (j in (1:nrow(gmyc.spec))){
for (k in (1:nrow(groups))) {
if (gmyc.spec$sample_name[j] == groups[[sample_names_col]][k])
gmyc.spec$ids[j] = groups[[groups_col]][k]
}
}
gmyc_spec_container[[i]] = gmyc.spec
# split the data by the species group numbers assigned by the GMYC
spec_split = split(gmyc.spec, gmyc.spec$GMYC_spec)
gmyc.spec$GMYC_spec = as.factor(gmyc.spec$GMYC_spec) # make the GMYC species a factor
gmyc.spec$ids = as.factor(gmyc.spec$ids) # make the user's predefined groups a factor
matches.df = data.frame(matrix(nrow = length(levels(gmyc.spec$GMYC_spec)), ncol = 2))
colnames(matches.df) = c("GMYC_spec", "match(y/n)")
matches.df$GMYC_spec = 1:nrow(matches.df)
# keep counts of the number of "yes", "no", and "single-sample" species:
y_count = 0
n_count = 0
single_sample_count = 0
for (m in 1:length(spec_split)){
len_unique = length(unique(spec_split[[m]]$ids))
len_values = length(spec_split[[m]]$ids)
if (len_unique == 1 && len_values > 1){
matches.df$`match(y/n)`[m] = "y"
y_count = y_count + 1
}
else if (len_values == 1){
matches.df$`match(y/n)`[m] = "single_sample"
single_sample_count = single_sample_count + 1
}
else {
matches.df$`match(y/n)`[m] = "n"
n_count = n_count + 1
}
}
# this total excludes single samples
total_excl_singles = y_count + n_count
# this total includes single samples
total_incl_singles = y_count + n_count + single_sample_count
#or just total_incl_singles = nrow(matches.df)
# this is only taking the matches for GMYC species groups that had more than one sample in it
success_excl_singles = round(y_count/total_excl_singles * 100, 2)
# this treats all single sample GMYC species as equivalent to a "yes" match, and will therefore be a larger value than the estimate
# that excludes them
success_incl_singles = round((y_count + single_sample_count)/total_incl_singles * 100, 2)
prop_single_samples = round(single_sample_count/nrow(matches.df) * 100, 2)
# populate the "record" dataframe
record[i,2] = success_incl_singles
record[i,3] = success_excl_singles
record[i,4] = prop_single_samples
num_predefined_groups = length(levels(gmyc.spec$ids))
num_gmyc_groups = length(levels(gmyc.spec$GMYC_spec))
num_gmyc_groups_excluding_single_spp = num_gmyc_groups - single_sample_count
# splitting ratio (ie. GMYC species to predefined groups)
record[i,5] = round( num_gmyc_groups/num_predefined_groups, 2 )
# splitting ratio excluding single species
record[i,6] = round( num_gmyc_groups_excluding_single_spp/num_predefined_groups, 2 )
# find which species are being over-split:
yes_indices = which(matches.df$`match(y/n)` == "y")
if(length(yes_indices) > 0){
predef_unique = c()
for (v in 1:length(yes_indices)){
predef_unique[v] = unique(spec_split[[yes_indices[v]]]$ids)
}
predef_unique_table = table(predef_unique)
predef_unique_table = predef_unique_table
predef_unique_table = as.data.frame(predef_unique_table)
splitting_species[[i]] = predef_unique_table
}
##################################
# added 18/10/2021:
# find which species are undersplit/merged:
no_indices = which(matches.df$`match(y/n)` == "n")
#print(no_indices)
merged_gmyc_specs[[i]] = no_indices
#if(length(no_indices) > 0){
# output$merged_gmyc_spec = renderText(paste("Merged GMYC species: ", no_indices))
# print(no_indices)
#
# for(w in length(no_indices)){
#
# print(spec_split[no_indices[w]])
#
# }
# }
###################################
}# end of if statement
################################################################################################
################################################################################################
# Increment the progress bar, and update the detail text.
incProgress(1/length(files), detail = paste("Processing tree file ", i, " of ", length(files), "[ ", round(i/length(files)*100, 0), "% ]"))
# Pause for 0.1 seconds to simulate a long computation.
Sys.sleep(0.1)
} # end of for loop
}) # end of progress bar bracket
shinyalert::shinyalert("Complete", "Please click on the tabs at the top of the window to view the results.", type = "success")
} # end of if re. !dir.exists()
if (!is.null( predefined_groups_uploaded() )) output$sp.numbers = renderText(c("You have ", length(unique(groups[[groups_col]])), " predefined species."))
gg_clust_ent = reshape2::melt(clust_ent) # get into the format the ggplot can work with
colnames(gg_clust_ent) = c("filename", "gmyc_cat", "count")
gg_clust_ent$gmyc_cat %>% as.factor()
if (!is.null( predefined_groups_uploaded() )){
splitting_species = splitting_species[!is.na(splitting_species)] # remove the NA lists
splitting_species_bound = dplyr::bind_rows(splitting_species)
splitting_species_bound = splitting_species_bound[splitting_species_bound$Freq > 1,] # remove rows with species that had a frequency of only one (ie those that were not oversplit)
exact_matches = dplyr::bind_rows(splitting_species)
exact_matches = exact_matches[exact_matches$Freq == 1,]
mean_oversplits_per_grp =
splitting_species_bound %>%
dplyr::group_by(predef_unique) %>%
dplyr::summarise(across(everything(), c(mean = mean, sd = sd, min = min, max = max)))
colnames(mean_oversplits_per_grp) = c("predefined_group", "mean", "sd", "min", "max")
mean_exact_matches_per_grp =
exact_matches %>%
dplyr::group_by(predef_unique) %>%
dplyr::summarise(across(everything(), c(sum=sum)))
colnames(mean_exact_matches_per_grp) = c("predefined_group", "sum")
mean_exact_matches_per_grp$mean = round(mean_exact_matches_per_grp$sum/length(files)*100, 2)
num_user_defined_groups = length(unique(groups[[groups_col]]))
num_exact_matches = nrow(mean_exact_matches_per_grp)
percentage_exact_matches = round(num_exact_matches/num_user_defined_groups*100, 2)
output$percent_exact_matches = renderText(c("<B>", "There are ", percentage_exact_matches, "% overall exact GMYC matches across GMYC results."))
}
################################################################################################
# View the GMYC species table with the predefined grouping information appended as the last column
################################################################################################
observeEvent(input$view_gmyc_spec, {
if (is.null( predefined_groups_uploaded() )) shinyalert::shinyalert("No grouping information uploaded", "You did not upload a .csv file with predefined grouping information for your sequences", type = "warning")
else{
gmyc_spec_to_show = input$select_tree_speclist # get the tree file name selected from the drop down menu
file_i = which(files == gmyc_spec_to_show) # get the index of that file to match up with the trees stored in the spec_list_container list
output$matches = renderTable(gmyc_spec_container[[file_i]], rownames = FALSE, colnames = TRUE, digits = 0)
if(length(merged_gmyc_specs[[file_i]]) > 0) merged_output_text = merged_gmyc_specs[[file_i]]
else merged_output_text = "None"
output$merges = renderText(c( "<B>", "These GMYC species (GMYC_spec) were merged: ", merged_output_text ))