forked from BiKC/Rhea_pipeline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.R
4827 lines (4243 loc) · 163 KB
/
app.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
# These library lines are required for shinyapps.io deployment
# library("shiny")
# library("shinyjqui")
# library("GUniFrac")
# library("vegan")
# library("ade4")
# library("phangorn")
# library("cluster")
# library("fpc")
# library("compare")
# library("plotrix")
# library("PerformanceAnalytics")
# library("reshape")
# library("ggplot2")
# library("gridExtra")
# library("grid")
# library("ggrepel")
# library("gtable")
# library("Matrix")
# library("cowplot")
# library("Hmisc")
# library("corrplot")
# library("shinycssloaders")
# library("fs")
# library("dplyr")
##### Load and install shiny libraries alternative (not on shinyio) #####
# Check if required packages are already installed, and install if missing
packages <-
c("shinyjqui","GUniFrac","vegan","ade4","phangorn","cluster","fpc","compare",
"plotrix","PerformanceAnalytics","reshape","ggplot2","gridExtra","grid",
"ggrepel","gtable","Matrix","cowplot","Hmisc","corrplot","shinycssloaders","fs",
"dplyr")
# # Function to check whether the package is installed
InsPack <- function(pack)
{
if ((pack %in% installed.packages()) == FALSE) {
install.packages(pack, repos = "http://cloud.r-project.org/")
}
}
# # Applying the installation on the list of packages
lapply(packages, InsPack)
# # Make the libraries
lib <- lapply(packages, require, character.only = TRUE)
#
# # Check if it was possible to install all required libraries
# flag <- all(as.logical(lib))
#####
flag <- T
#####
ui <- function(req) {
#### Page layout
fluidPage(
#### Page Head
tags$head(
#### Javascript script that disables tabs + custom javascript function to enable them again when getting signal
tags$script(
"
window.onload = function() {
$('#mynavlist a:contains(\"Alpha-Diversity\")').attr('data-toggle','none').parent().addClass('disabled');
$('#mynavlist a:contains(\"Beta-Diversity\")').attr('data-toggle','none').parent().addClass('disabled');
$('#mynavlist a:contains(\"Taxonomic-Binning\")').attr('data-toggle','none').parent().addClass('disabled');
$('#mynavlist a:contains(\"Create-Input-Tables\")').attr('data-toggle','none').parent().addClass('disabled');
$('#mynavlist a:contains(\"Serial-Group-Comparisons\")').attr('data-toggle','none').parent().addClass('disabled');
$('#mynavlist a:contains(\"Correlations\")').attr('data-toggle','none').parent().addClass('disabled');
};
Shiny.addCustomMessageHandler('activeNavs', function(nav_label) {
$('#mynavlist a:contains(\"' + nav_label + '\")').attr('data-toggle','tab').parent().removeClass('disabled');
});
Shiny.addCustomMessageHandler('deactiveNavs', function(nav_label) {
$('#mynavlist a:contains(\"' + nav_label + '\")').attr('data-toggle','none').parent().addClass('disabled');
});
"
)
),
##### Main page
navbarPage(
title = "Rhea Pipeline",
id = "mynavlist",
# First tab
tabPanel(title = "Normalization",
# Define it is sidebar layout
sidebarLayout(
# Sidebar (left side of screen) Used for inputs (Not obliged: help message)
sidebarPanel(
fileInput(
inputId = "OTUtab",
label = "OTU table",
accept = ".tab"
),
radioButtons(
inputId = "method",
label = "Method",
choiceNames = c(
"No random subsampling, no rounding",
"Random subsampling with rounding"
),
choiceValues = c(0, 1)
),
numericInput(
inputId = "labelCutoff",
label = "Label cutoff to present independently",
value = 5
),
actionButton(
inputId = "Submit1",
label = "Run normalization",
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help1",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext1")
),
# Main panel (right side of screen) used for outputs (Not obliged)
mainPanel(
conditionalPanel(
condition = "input.Submit1",
htmlOutput(outputId = "Error1"),
plotOutput(outputId = "distPlot") %>% withSpinner(),
plotOutput(outputId = "distPlot2"),
htmlOutput(outputId = "Files1")
)
)
)),
# Second tab
tabPanel(title = "Alpha-Diversity",
sidebarLayout(
sidebarPanel(
actionButton(
inputId = "Submit2",
label = "Run alpha-diversity",
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help2",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext2")
),
mainPanel(
conditionalPanel(condition = "input.Submit2",
htmlOutput("Files2") %>% withSpinner())
)
)),
# Third tab
tabPanel(title = "Beta-Diversity",
sidebarLayout(
sidebarPanel(
fileInput(
inputId = "input_meta",
label = "Metadata file",
accept = ".tab"
),
fileInput(
inputId = "input_tree",
label = "Phylogenetic tree",
accept = '.tre'
),
selectInput(
inputId = "group_name",
label = "Group from metadat file to analyze",
choices = c("")
),
radioButtons(
inputId = "label_samples",
"Label samples:",
choiceNames = c(
"Samples are not labeled in the MDS/NMDS plots",
"All Samples are labed in the MDS/NMDS plots"
),
choiceValues = c(0, 1)
),
selectizeInput(
inputId = "label_id",
"Samples that should be labeled",
choices = c(),
multiple = T
),
sliderInput(
inputId = "kmers_limit",
label = "Perform De-novo clustering for this many samples:",
min = 1,
max = 10,
value = 10,
step = 1
),
actionButton(
inputId = "Submit3",
label = 'Run beta-diversity',
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help3",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext3")
),
mainPanel(
conditionalPanel(
condition = "input.Submit3",
htmlOutput(outputId = "Error2"),
htmlOutput(outputId = "bdtreetext"),
plotOutput(outputId = "bdtree") %>% withSpinner(),
htmlOutput(outputId = "bdmdstext"),
plotOutput(outputId = "bdmds"),
htmlOutput(outputId = "bdnmdstext"),
plotOutput(outputId = "bdnmds"),
htmlOutput(outputId = "pdfviewer1text"),
htmlOutput(outputId = 'pdfviewer1'),
htmlOutput(outputId = "pdfviewer2text"),
htmlOutput(outputId = 'pdfviewer2'),
htmlOutput(outputId = "optclustertext"),
plotOutput(outputId = 'optcluster'),
htmlOutput(outputId = "Files3")
)
)
)),
# Fourth tab
tabPanel(
"Taxonomic-Binning",
sidebarLayout(
sidebarPanel(
actionButton(
inputId = "Submit4",
label = 'Run taxonomic-binning',
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help4",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext4")
),
mainPanel(
htmlOutput(outputId = "Error3"),
tabsetPanel(
type = "tabs",
tabPanel(
title = "Kingdom",
conditionalPanel(condition = "input.Submit4",plotOutput(outputId = "kingdom") %>% withSpinner())
),
tabPanel(
title = "Phyla",
conditionalPanel(condition = "input.Submit4", plotOutput(outputId = "phyla") %>% withSpinner())
),
tabPanel(
title = "Class",
conditionalPanel(condition = "input.Submit4", plotOutput(outputId = "class") %>% withSpinner())
),
tabPanel(
title = "Order",
conditionalPanel(condition = "input.Submit4", plotOutput(outputId = "order") %>% withSpinner())
),
tabPanel(
title = "Family",
conditionalPanel(condition = "input.Submit4", plotOutput(outputId = "family") %>% withSpinner())
),
tabPanel(
title = "Genus",
conditionalPanel(condition = "input.Submit4", plotOutput(outputId = "genus") %>% withSpinner())
)
),
htmlOutput(outputId = "Files4")
)
)
),
# Fifth tab
tabPanel(
"Create-Input-Tables",
sidebarLayout(
sidebarPanel(
actionButton(
inputId = "Submit5",
label = "Create input files",
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help5",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext5")
),
mainPanel(
htmlOutput(outputId = "Error4"),
conditionalPanel(condition = "input.Submit5", htmlOutput(outputId = "Files5") %>% withSpinner())
)
)
),
# Sixth tab
tabPanel(
"Serial-Group-Comparisons",
sidebarLayout(
sidebarPanel(
selectInput(
inputId = "sgcgroup",
"Name of independent variable that analysis will be performed on:",
choices = c("")
),
uiOutput(outputId = "grorder"),
numericInput(
inputId = "abundance_cutoff",
label = "Cutoff of relative abundance:",
value = 0.5,
min = 0,
max = 100,
step = 0.1
),
numericInput(
inputId = "prevalence_cutoff",
label = "Prevalence cutoff",
value = 0.3,
min = 0,
max = 100,
step = 0.1
),
numericInput(
inputId = "max_median_cutoff",
label = "Minimum median abundance value that must be observed in at least one group before statistical test is performed",
value = 1,
min = 0,
max = 100,
step = 0.1
),
checkboxInput(
inputId = "repzero",
"Replace 0 Value with NA",
value = TRUE
),
radioButtons(
"plotOption",
"Graphical output parameter",
choiceNames = c(
"without individual values as dots",
"with individual values as dots",
"with individual values as dots and with sample names"
),
choiceValues = c(1, 2, 3)
),
numericInput(
inputId = "sig.cutoff",
label = "Significance cutoff level",
value = 0.05,
min = 0,
max = 1,
step = 0.01
),
actionButton(
inputId = "Submit6",
label = "Run Serial group comparison",
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help6",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext6")
),
mainPanel(
conditionalPanel(
condition = "input.Submit6",
htmlOutput(outputId = "Error5"),
htmlOutput(outputId = "box") %>% withSpinner(),
htmlOutput(outputId = "boxpoint"),
htmlOutput(outputId = "violin"),
htmlOutput(outputId = "Files6")
)
)
)
),
# Not implemented tab
# tabPanel("Over-Time-Serial-Comparisons",
# sidebarLayout(
# sidebarPanel(
# selectInput(inputId = "sgcgroupot","Name of independent variable that analysis will be performed on:",choices = c("")),
# uiOutput(outputId = "grorderot"),
# numericInput(inputId = "abundance_cutoffot",label="Cutoff of relative abundance:", value = 0.5, min=0,max=100,step = 0.1),
# numericInput(inputId = "prevalence_cutoffot",label="Prevalence cutoff", value = 0.3, min=0,max=100,step = 0.1),
# numericInput(inputId = "max_median_cutoffot",label="Minimum median abundance value that must be observed in at least one
# group before statistical test is performed", value = 1, min=0,max=100,step = 0.1),
# checkboxInput(inputId = "repzeroot","Replace 0 Value with NA",value = TRUE),
# radioButtons("plotOptionot","Graphical output parameter",choiceNames = c("without individual values as dots",
# "with individual values as dots","with individual values as dots and with sample names"),choiceValues = c(1,2,3)),
# numericInput(inputId = "sig.cutoffot",label = "Significance cutoff level",value = 0.05,min = 0,max = 1,step = 0.01),
# actionButton(inputId = "Submit7", label= "Run over-time-serial-comparisons", icon=icon("refresh"))
# ),
# mainPanel(
#
# )
# )
# ),
# Seventh tab
tabPanel("Correlations",
sidebarLayout(
sidebarPanel(
numericInput(
inputId = "signf_cutoff",
label = "cutoff for significance:",
value = 0.05,
min = 0,
max = 1,
step = 0.01
),
radioButtons(
"includeTax",
label = "Calculate correlation among taxonomic variables",
choiceNames = c(
"Calculate correlations within OTUs or taxa",
"No test within taxonomic variables"
),
choiceValues = c(1, 0),
selected = 0
),
radioButtons(
"includeMeta",
label = "Calculate correlation among meta-variables",
choiceNames = c(
"Calculate correlations within meta-variables",
"No test within meta-variables"
),
choiceValues = c(1, 0),
selected = 0
),
radioButtons(
"fill_NA",
label = "Handling of missing values for meta-variables",
choiceNames = c(
"Missing values are filled with the mean for the corresponding variable",
"NO imputation (replacing missing data with substituted values)"
),
choiceValues = c(1, 0),
selected = 0
),
radioButtons(
"replace_zeros",
label = "Treat zeros in taxonomic variables as missing values",
choiceNames = c(
"Consider taxonomic zeros as missing values",
"Keep zeros for the calculation of correlations"
),
choiceValues = c(1, 0),
selected = 1
),
numericInput(
inputId = "prevalence_exclusion",
label = "Cutoff for the minimum number of values (prevalence) for a given taxonomic variable to be considered for calculation",
value = 0.3,
min = 0,
max = 1,
step = 0.01
),
sliderInput(
inputId = "min_pair_support",
label = "Cutoff for the minimal number of pairs observations required for calculation of correlations",
value = 4,
min = 0,
max = 10,
step = 1
),
numericInput(
inputId = "plot_pval_cutoff",
label = "Set a significance cutoff for graphical output",
value = 0.05,
min = 0,
max = 1,
step = 0.01
),
numericInput(
inputId = "plot_corr_cutoff",
label = "Correlation coefficient cutoff for graphical output",
value = 0.5,
min = 0,
max = 1,
step = 0.01
),
actionButton(
inputId = "Submit8",
label = "Run correlations",
icon = icon("refresh")
),
tags$br(),
tags$br(),
actionButton(
inputId = "Help7",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext7")
),
mainPanel(
conditionalPanel(
condition = "input.Submit8",
htmlOutput(outputId = "Error6"),
plotOutput(outputId = "corrplot") %>% withSpinner(),
htmlOutput(outputId = "Finalpdf")
)
)
)),
# Eight tab
tabPanel(
"Download",
downloadButton(outputId = "Download", label = "Download all files as .zip"),
tags$br(),
tags$br(),
actionButton(
inputId = "Help8",
label = "Help",
icon = icon("question-circle")
),
htmlOutput(outputId = "Helptext8")
)
)
)
}
# Define server logic required to draw a histogram
server <- function(input, output, session) {
##### Randomized string function #####
randomString <- function(n = 5000) {
a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}
##### Each user gets new temp directory, also in www directory #####
wd <- randomString(1)[1]
dir.create(wd)
dir.create(paste0("www/", wd))
##### remove temp directory on end of script #####
session$onSessionEnded(function() {
system(paste("rm -Rf", wd))
system(paste("rm -Rf", paste0("www/", wd)))
})
##### Help Messages #####
observeEvent(input$Help1, {
output$Helptext1 <- renderUI({
tags$iframe(src = "Normalization Script ReadMe.pdf",
height = 600,
width = "100%")
})
})
observeEvent(input$Help2, {
output$Helptext2 <- renderUI({
tags$iframe(src = "Alpha Diversity Script ReadMe.pdf",
height = 600,
width = "100%")
})
})
observeEvent(input$Help3, {
output$Helptext3 <- renderUI({
tags$iframe(src = "Beta Diversity Script ReadMe.pdf",
height = 600,
width = "100%")
})
})
observeEvent(input$Help4, {
output$Helptext4 <- renderUI({
tags$iframe(src = "Taxonomic Binning Script ReadMe.pdf",
height = 600,
width = "100%")
})
})
observeEvent(input$Help5, {
output$Helptext5 <- renderText({
"Intermediate step that creates some files needed for serial group comparisson"
})
})
observeEvent(input$Help6, {
output$Helptext6 <- renderUI({
tags$iframe(src = "Serial Group Comparisons Script ReadMe.pdf",
height = 600,
width = "100%")
})
})
observeEvent(input$Help7, {
output$Helptext7 <- renderUI({
tags$iframe(src = "Correlations Script ReadMe.pdf",
height = 600,
width = "100%")
})
})
observeEvent(input$Help8, {
#struct <<- dir_tree(wd,recurse = T)
output$Helptext8 <- renderText({
bdgroup <-
ifelse(input$group_name != "",
input$group_name,
"{chosen beta-diveristy group name}")
sgcgroup <-
ifelse(
input$sgcgroup != "",
input$sgcgroup,
"{chosen serial group comparisson group name}"
)
paste0(
#paste(struct,collapse = "<br>"),
"<pre>Creates a zip file that has 5 folders with the output files created so far.
Folder structure:
1.Normalization
. OTUs_Table-norm.tab
. OTUs_Table-norm-rel.tab
. OTUs_Table-norm-rel-tax.tab
. OTUs_Table-norm-tax.tab
. RarefactionCurve.pdf
. RarefactionCurve.tab
2.Alpha-Diversity
. alpha-diversity.tab
. OTUs_Table-norm.tab
3.Beta-Diversity
. ",bdgroup,
"* ",bdgroup,"_beta-diversity.pdf
* ",bdgroup,"_distance-matrix-gunif.tab
* phylogram.pdf
. de-novo-clustering.pdf
. distance-matrix-gunif.tab
. OTUs_table-norm.tab
. samples-Tree.nwk
4.Taxonomic-Binning
. 0.Kingdom.all.tab
. 1.Phyla.all.tab
. 2.Classes.all.tab
. 3.Orders.all.tab
. 4.Families.all.tab
. 5.Genera.all.tab
. tax.summary.all.tab
. taxonomic-overview.pdf
5.Serial-Group-Comparisons
. ",sgcgroup,"_OTUsCombined_2019-12-10
* ",sgcgroup,"plotbox.pdf
* my_analysis_log.txt
* OTUsCombined-",sgcgroup,"-modified.txt
* ",sgcgroup,"plotboxpoint.pdf
* OTUsCombined-",sgcgroup,"-FisherTestAll.tab
* OTUsCombined-",sgcgroup,"-pvalues.tab
* ",sgcgroup,"plotviolin.pdf
* OTUsCombined-",sgcgroup,"-FisherTestPairWise.tab
* OTUsCombined-",sgcgroup,"-sign_pairs.tab
. mapping_file.tab
. OTUsCombined.tab
. TaxaCombined.tab
. alpha-diversity.tab
. OTUs_Table-norm-rel.tab
. tax.summary.all.tab
6.Correlations
. OTUsCombined_Corr_input_table.tab
. OTUsCombined_Corr_input_table_2019-12-10
* corrplot.pdf
* linear_sign_pairs.pdf
* OTUsCombined_Corr_input_table_2019-12-10
- correlation-table.tab
- cutoff-pairs-corr-sign.tab
- plotted-pairs-stat.tab
- pval-table.tab
- support-table.tab
- transformed.tab</pre>"
)
})
})
##### Actual script #####
observeEvent(input$Submit1, {
setwd(wd)
# Test if file is actually submitted
if (!is.null(input$OTUtab)) {
# Create output folders
tryCatch(error=function(e){
output$Error1 <- renderUI(
tags$pre(
paste0("Error received:",
as.character(e),
"Something might be wrong with the input file")
,style="color:red")
)
output$distPlot <- renderPlot(NULL)
output$distPlot2 <- renderPlot(NULL)
output$Files1 <- renderUI(NULL)
session$sendCustomMessage('deactiveNavs', 'Alpha-Diversity')
session$sendCustomMessage('deactiveNavs', 'Beta-Diversity')
session$sendCustomMessage('deactiveNavs', 'Taxonomic-Binnin')
session$sendCustomMessage('deactiveNavs', 'Create-Input-Tables')
session$sendCustomMessage('deactiveNavs', 'Serial-Group-Comparisons')
session$sendCustomMessage('deactiveNavs', 'Correlations')
},
warning=function(w) NA,
expr = {
dir.create("1.Normalization", showWarnings = F)
dir.create("2.Alpha-Diversity", showWarnings = F)
dir.create("3.Beta-Diversity", showWarnings = F)
dir.create("4.Taxonomic-Binning", showWarnings = F)
dir.create("5.Serial-Group-Comparisons", showWarnings = F)
dir.create("6.Correlations", showWarnings = F)
################### Read input ####################
output$Error1 <- renderText("")
file_name<-isolate(input$OTUtab$datapath)
################### Read all required input files ####################
# Load the tab-delimited file containing the values to be be checked (rownames in the first column)
otu_table <- read.table (
file_name,
check.names = FALSE,
header = TRUE,
dec = ".",
sep = "\t",
row.names = 1,
comment.char = ""
)
# Clean table from empty lines
otu_table <-
otu_table[!apply(is.na(otu_table) |
otu_table == "", 1, all), ]
#################### Normalize OTU Table ###################
# Save taxonomy information in vector
taxonomy <- as.vector(otu_table$taxonomy)
# Delete column with taxonomy information in dataframe
otu_table$taxonomy <- NULL
# Determine cutoff (Filter for inpossible values)
labelCutoff <-
max(1, min(isolate(input$labelCutoff), ncol(otu_table)))
updateNumericInput(session, "labelCutoff", value = labelCutoff)
# Calculate the minimum sum of all columns/samples
min_sum <- min(colSums(otu_table))
if (isolate(input$method) == 0) {
# Divide each value by the sum of the sample and multiply by the minimal sample sum
norm_otu_table <-
t(min_sum * t(otu_table) / colSums(otu_table))
} else {
# Rarefy the OTU table to an equal sequencing depth
norm_otu_table <- Rarefy(t(otu_table), depth = min_sum)
norm_otu_table <-
t(as.data.frame(norm_otu_table$otu.tab.rff))
}
# Calculate relative abundances for all OTUs over all samples
# Divide each value by the sum of the sample and multiply by 100
rel_otu_table <- t(100 * t(otu_table) / colSums(otu_table))
# Re-insert the taxonomy information in normalized counts table
norm_otu_table_tax <- cbind(norm_otu_table, taxonomy)
# Reinsert the taxonomy information in relative abundance table
rel_otu_table_tax <- cbind(rel_otu_table, taxonomy)
################################################################################
# Generate a twosided pdf with a rarefaction curve for all samples and a curve
pdf(file = "1.Normalization/RarefactionCurve.pdf")
# Plot the rarefaction curve for all samples
rarefactionCurve <- rarecurve(
data.frame(t(otu_table)),
step = 20,
col = "black",
lty = "solid",
label = F,
xlab = "Number of Reads",
ylab = "Number of Species",
main = "Rarefaction Curves of All Samples"
)
# Generate empy vectors for the analysis of the rarefaction curve
slope = vector()
SampleID = vector()
# Iterate through all samples
for (i in seq_along(rarefactionCurve)) {
# If the sequencing depth is greater 100 the difference between the last and last-100 richness is calcualted
richness <-
ifelse(
length(rarefactionCurve[[i]]) >= 100,
rarefactionCurve[[i]][length(rarefactionCurve[[i]])] - rarefactionCurve[[i]][length(rarefactionCurve[[i]]) -
100],
1000
)
slope <- c(slope, richness)
SampleID <- c(SampleID, as.character(names(otu_table)[i]))
}
# Generate the output table for rarefaction curve
curvedf <- cbind(SampleID, slope)
order <- order(curvedf[, 2], decreasing = TRUE)
# Order the table
curvedf <- curvedf[order(curvedf[, 2], decreasing = TRUE), ]
# Generates a graph with all samples
# Underestimated cases are shown in red
for (i in 1:labelCutoff) {
N <- attr(rarefactionCurve[[order[i]]], "Subsample")
lines(N, rarefactionCurve[[order[i]]], col = "red")
}
# Determine the plotting width and height
Nmax <-
sapply(rarefactionCurve, function(x)
max(attr(x, "Subsample")))
Smax <- sapply(rarefactionCurve, max)
# Creates an empty plot for rarefaction curves of underestimated cases
plot(
c(1, max(Nmax)),
c(1, max(Smax)),
xlab = "Number of Reads",
ylab = "Number of Species",
type = "n",
main = paste(labelCutoff, "- most undersampled cases")
)
for (i in 1:labelCutoff) {
N <- attr(rarefactionCurve[[order[i]]], "Subsample")
lines(N, rarefactionCurve[[order[i]]], col = "red")
text(max(attr(rarefactionCurve[[order[i]]], "Subsample")), max(rarefactionCurve[[order[i]]]), curvedf[i, 1], cex =
0.6)
}
dev.off()
#################################################################################
###### Write Output Files ######
#################################################################################
# Write the normalized table in a file and copy in directories alpha-diversity and beta-diversity if existing
write.table(
norm_otu_table,
"1.Normalization/OTUs_Table-norm.tab",
sep = "\t",
col.names = NA,
quote = FALSE
)
suppressWarnings (try(write.table(
norm_otu_table,
"2.Alpha-Diversity/OTUs_Table-norm.tab",
sep = "\t",
col.names = NA,
quote = FALSE
),
silent = TRUE)
)
suppressWarnings (try(write.table(
norm_otu_table,
"3.Beta-Diversity/OTUs_Table-norm.tab",
sep = "\t",
col.names = NA,
quote = FALSE)
,
silent = TRUE)
)
# Write the normalized table with taxonomy in a file
write.table(
norm_otu_table_tax,
"1.Normalization/OTUs_Table-norm-tax.tab",
sep = "\t",
col.names = NA,
quote = FALSE)
# Write the normalized relative abundance table in a file and copy in directory Serial-Group-Comparisons if existing
write.table(
rel_otu_table,
"1.Normalization/OTUs_Table-norm-rel.tab",
sep = "\t",
col.names = NA,
quote = FALSE
)
suppressWarnings (try(write.table(
rel_otu_table,
"5.Serial-Group-Comparisons/OTUs_Table-norm-rel.tab",
sep = "\t",
col.names = NA,
quote = FALSE
),
silent = TRUE)
)
# Write the normalized relative abundance with taxonomy table in a file and copy in directory Taxonomic-Binning if existing
write.table(
rel_otu_table_tax,
"1.Normalization/OTUs_Table-norm-rel-tax.tab",
sep = "\t",
col.names = NA,
quote = FALSE)
suppressWarnings (try(write.table(
rel_otu_table_tax,
"4.Taxonomic-Binning/OTUs_Table-norm-rel-tax.tab",
sep = "\t",
col.names = NA,
quote = FALSE
),
silent = TRUE)
)
# Write the rarefaction table
write.table(
curvedf,
"1.Normalization/RarefactionCurve.tab",
sep = "\t",
quote = FALSE,
row.names = FALSE)
output$distPlot <- renderPlot({
# Plot the rarefaction curve for all samples
rarefactionCurve <- rarecurve(
data.frame(t(otu_table)),
step = 20,
col = "black",
lty = "solid",
label = F,
xlab = "Number of Reads",
ylab = "Number of Species",
main = "Rarefaction Curves of All Samples"
)
# Generate empy vectors for the analysis of the rarefaction curve
slope = vector()
SampleID = vector()