-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.R
2029 lines (1746 loc) · 75.8 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
# This is the server logic for a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#
#source("./Report/R/report.R")
#Sys.setenv(R_ZIPCMD="/usr/bin/zip")
options(shiny.maxRequestSize=30*1024^2)
filtered_rRNA_obj <- list()
shinyServer(function(input, output, session) {
#---------- listen for session reset -------#
observeEvent(input$reset_button, {js$reset()})
#---------- rRNA object import -------------#
importObj <- reactive({
# validate(
# need(input$biom != "", "Please select a biom file")
# )
validate(
need(grepl(".biom", as.character(input$e_data$name)) | grepl(".csv", as.character(input$e_data$name)), "Data file must be in .biom or .csv format")
)
# validate(
# need(input$qiime != "", "Please select a qiime file")
# )
validate(
need(input$e_data != "", "Please select a data file")
)
validate(
need(input$f_data != "", "Please select a sample metadata file")
)
if (!grepl(pattern = "\\.biom$", x = input$e_data$datapath)) {
validate(need(input$e_meta != "", message = "Please upload feature metadata file"))
}
# check for e_meta file
if (is.null(input$e_meta$name) & grepl(".biom", as.character(input$e_data$name))) {
return(pmartRseq::import_seqData(e_data_filepath = as.character(input$e_data$datapath),
f_data_filepath = as.character(input$f_data$datapath),
e_meta_filepath = NULL))
}
# import e_meta if there is one
if (!is.null(input$e_meta$name) & !grepl(".biom", as.character(input$e_data$name))) {
return(pmartRseq::import_seqData(e_data_filepath = as.character(input$e_data$datapath),
f_data_filepath = as.character(input$f_data$datapath),
e_meta_filepath = as.character(input$e_meta$datapath)))
}
}) #end rRNAobj import
# Guess at column identifiers
output$e_data_cname <- reactive(importObj()$guessed_edata_cname)
output$f_data_cname <- reactive(importObj()$guessed_fdata_cname)
output$new_edata_cname <- renderUI({
selectInput(inputId = "new_e_data_cname", label = "New expression data identifier is:",
choices = colnames(importObj()$e_data),
selected = importObj()$guessed_edata_cname,
multiple = FALSE)
})
output$new_fdata_cname <- renderUI({
selectInput(inputId = "new_f_data_cname", label = "New metadata identifier is:",
choices = colnames(importObj()$f_data),
selected = importObj()$guessed_fdata_cname,
multiple = FALSE)
})
# output$edata_cname <- renderUI({
# selectInput("edata_cname",
# label = "Identifier column name in data",
# choices = colnames(importObj()$e_data),
# selected = importObj()$guessed_edata_cname,
# multiple = FALSE)
# })
#
# output$fdata_cname <- renderUI({
# selectInput("fdata_cname",
# label = "Sample column name in sample metadata",
# choices = colnames(importObj()$f_data),
# selected = importObj()$guessed_fdata_cname,
# multiple = FALSE)
# })
#
# output$taxa_cname <- renderUI({
# selectInput("taxa_cname",
# label = "Taxonomic column of interest in feature metadata",
# choices = colnames(importObj()$e_meta),
# selected = importObj()$guessed_taxa_cname,
# multiple = FALSE)
# })
#rRNAobj <- reactive({ return(importObj()) })
#observeEvent(input$Upload,{
rRNAobj <- reactive({
validate(
need(importObj, message = "Please upload data files to begin analysis"),
need(!is.null(importObj()$guessed_fdata_cname), message = "Please upload data files to begin analysis"),
need(!is.null(importObj()$guessed_edata_cname), message = "Please upload data files to begin analysis"),
need(!is.null(importObj()$guessed_taxa_cname), message = "Please upload data files to begin analysis"),
need(!is.null(input$new_f_data_cname), message = "Please upload data files to begin analysis")
)
tmp <- pmartRseq::as.seqData(e_data = importObj()$e_data,
f_data = importObj()$f_data,
e_meta = importObj()$e_meta,
fdata_cname = input$new_f_data_cname,
edata_cname = input$new_e_data_cname,
taxa_cname = importObj()$guessed_taxa_cname,
data_type = "rRNA")
if(ncol(tmp$e_meta) <= 2){
tmp <- pmartRseq::split_emeta(tmp, cname=attr(tmp,"cnames")$taxa_cname, split1=",", numcol=7, split2="__", num=2, newnames=NULL)
}else{
tmp <- pmartRseq::split_emeta(tmp, cname=attr(tmp,"cnames")$edata_cname, split1=NULL, numcol=7, split2="__", num=2, newnames=NULL)
}
return(tmp)
})
output$rollup <- renderUI({
selectInput("rollup",
label = "Which taxonomic level should analysis be performed at?",
choices = c("Kingdom","Phylum","Class","Order","Family","Genus","Species",attr(rRNAobj(), "cnames")$edata_cname),
selected = attr(rRNAobj(), "cnames")$edata_cname,
multiple = FALSE)
})
rRNA_agg <- reactive({
validate(
need(length(input$rollup) == 1, "Need to specify a taxonomic level")
)
return(pmartRseq::taxa_rollup(omicsData = rRNAobj(), level = input$rollup, taxa_levels = NULL))
})
output$sample_data <- DT::renderDataTable(expr =
data.frame(rRNA_agg()$e_data), rownames = FALSE, class = 'cell-border stripe compact hover',
options = list(columnDefs = list(list(
targets = c(1:(ncol((rRNA_agg()$e_data)) - 1)),
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
))), callback = JS('table.page(3).draw(false);'))
output$datsum <- renderPrint({
validate(
need(!(is.null(rRNA_agg())), message = "please import sample metadata")
)
validate(
need(!(is.null(rRNA_agg())) , message = "Upload data first")
)
summary(rRNA_agg())
})
fursumm <- reactive({
validate(
need(!(is.null(rRNA_agg())), message = "please import sample metadata")
)
validate(
need(!(is.null(rRNA_agg())), message = "Upload data first")
)
temp <- rRNA_agg()$e_meta
names <- c("Kingdom","Phylum","Class","Order","Family","Genus","Species")
temp$TAXONOMY <- apply(temp[,which(colnames(temp) %in% names)], 1, function(x) paste(x, collapse="; "))
temp <- merge(reshape2::melt(rRNA_agg()$e_data), temp, by=attr(rRNA_agg(), "cnames")$edata_cname)
vars <- c(attr(rRNA_agg(), "cnames")$edata_cname, attr(rRNA_agg(), "cnames")$taxa_cname, "TAXONOMY")
vars <- lapply(vars, as.symbol)
temp <- temp %>% dplyr::mutate(Tot=sum(value,na.rm=TRUE)) %>%
dplyr::group_by_(.dots=vars) %>%
dplyr::summarise("Mean Across Samples"=mean(value, na.rm=TRUE),
"Median Across Samples"=median(value, na.rm=TRUE),
"Max Across Samples"=max(value, na.rm=TRUE),
"Min Across Samples"=min(value, na.rm=TRUE),
"Sum Across Samples"=sum(value, na.rm=TRUE),
"Percentage of Total"=sum(value,na.rm=TRUE)/unique(Tot)*100)
return(temp)
})
output$further_summary <- DT::renderDataTable(expr =
data.frame(fursumm()), rownames = FALSE, class = 'cell-border stripe compact hover',
options = list(columnDefs = list(list(
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
)), pageLength=5, order=list(3, 'desc')), callback = JS('table.page(3).draw(false);'))
# ################ Group Designation Tab #################
group_vars <- reactive({
intersect(which(lapply(apply(rRNA_agg()$f_data, 2, function(z) table(z))[unlist(lapply(apply(rRNA_agg()$f_data, 2, function(x) table(x)), function(y) any(is.finite(y))))], function(w) max(w)) > 2), which(apply(rRNA_agg()$f_data, 2, function(v) length(unique(v))) >= 2))
})
output$gdfMainEffect <- renderUI({
selectInput("gdfMainEffect",
label = "Main Effect(s) to use for Groupings",
choices = colnames(rRNA_agg()$f_data)[group_vars()],
multiple = TRUE)
})
# output$covs <- renderUI({
# checkboxInput("covs",
# label = "Any covariates?")
# })
# input$cov1 <- NA
# input$cov2 <- NA
#observeEvent(input$covs, {
# output$cov1 <- renderUI({
# selectInput("cov1",
# label = "Covariate 1",
# choices = c("NA",colnames(rRNA_agg()$f_data)),
# selected = NULL)
# })
#
# output$cov2 <- renderUI({
# selectInput("cov2",
# label = "Covariate 2",
# choices = c("NA",colnames(rRNA_agg()$f_data)),
# selected = NULL)
# #groupDesignation
# })
# #})
# Create groups with main effects
groupDF <<- reactive({
mainEffects <- input$gdfMainEffect
# if(!is.na(input$cov1) | !is.na(input$cov2)){
# covariates <- c(input$cov1, input$cov2)
# if(any(is.na(covariates))){
# covariates <- covariates[!is.na(covariates)]
# }
# }
validate(
need(length(mainEffects) > 0, "There needs to be at least one grouping variable")
)
return(pmartRseq::group_designation(rRNA_agg(), main_effects = mainEffects))
})
# Show the groupings data frame
#observeEvent(input$groupDF_go,
group_df_tab <- reactive({
attr(groupDF(), "group_DF")
})
output$group_DF <- DT::renderDataTable(group_df_tab())
#)
# Also output a table showing the number of reps in each group
group_freq_tab <- reactive({
as.data.frame(table(attr(groupDF(),"group_DF")$Group))
})
output$group_tab <- DT::renderDataTable(group_freq_tab())
#})
# ################ Filtering Tab #################
#-------- filter history support -----------#
filters <- reactiveValues(otu = list(), sample = list(), taxa = list(), metadata = list(), outlier = list())
#--------- kovera observer ---------#
observeEvent(input$otu_filter_go,{
filters$otu[[input$otu_filter_go]] <- otu_filter_obj()
})
#--------- sample observer ---------#
observeEvent(input$sample_filter_go, {
filters$sample[[input$sample_filter_go]] <- sample_filter_obj()
})
#--------- taxa observer ---------#
observeEvent(input$taxa_filter_go, {
filters$taxa[[input$taxa_filter_go]] <- taxa_filter_obj()
})
#--------- metadata observer ---------#
observeEvent(input$metadata_filter_go, {
filters$metadata[[input$metadata_filter_go]] <- sample_metadata_filter_obj()
})
#--------- filter application observer ---------#
filtered_rRNA_obj <- NULL
#filt1 <- NULL
observeEvent(groupDF(), {
filtered_rRNA_obj <<- groupDF()
}, priority = 10)
#--------- apply filter applications on click ---------#
observeEvent(input$otu_filter_go, {
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$otu[[input$otu_filter_go]],
omicsData = filtered_rRNA_obj,
num_samps = input$filter_kOverA_sample_threshold,
min_num = input$filter_count_threshold)
})
observeEvent(input$sample_filter_go, {
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$sample[[input$sample_filter_go]],
omicsData = filtered_rRNA_obj,
min_num = input$n)
})
observeEvent(input$taxa_filter_go, {
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$taxa[[input$taxa_filter_go]],
omicsData = filtered_rRNA_obj,
keep_taxa = input$keep_taxa)
})
observeEvent(input$metadata_filter_go, {
# get the intersection of the samples left after checkbox groups are removed
temp <- filtered_rRNA_obj$f_data
column_class <- sapply(temp, class)
categorical <- temp[, which(column_class %in% c("character", "factor", "logical"))]
# If categorical check for non-uniqueness
non_unique_columns <- which(unlist(lapply(categorical, function(x) length(unique(x)) != nrow(categorical) & length(unique(x)) != 1)))
if(length(non_unique_columns > 0)){
check_boxes <- names(categorical)[non_unique_columns]
} else {
check_boxes <- names(categorical)
}
sample_names <- list()
for (i in 1:length(check_boxes)) {
sample_names[[i]] <- dplyr::filter_(temp, interp(~v%in%input[[check_boxes[i]]], v=as.name(check_boxes[i]))) %>%
dplyr::select(eval(quote(attr(filtered_rRNA_obj, "cnames")$fdata_cname)))#find the column name and associated check box
}
sample_names <- Reduce(dplyr::intersect, sample_names)
#check if there are no samples to remove
if (nrow(sample_names) == length(temp[, attr(filtered_rRNA_obj, "cnames")$fdata_cname])) {
#if no samples to remove return unmodified object
return(filtered_rRNA_obj)
} else {
# remove the samples
to_remove <- temp[ which(!(as.character(temp[, attr(filtered_rRNA_obj, "cnames")$fdata_cname]) %in% as.character(unlist(sample_names)))),
attr(filtered_rRNA_obj, "cnames")$fdata_cname]
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$metadata[[input$metadata_filter_go]],
omicsData = filtered_rRNA_obj,
samps_to_remove = to_remove)
}
})
#----------------- observe resets ----------#
observeEvent(input$otu_reset_button, {
kovera_k <- 1
maxSamples = reactive({
# Create logical indicating the samples to keep, or dummy logical if nonsense input
validate(
need(!(is.null(metadata_obj())), message = "please import sample metadata")
)
if (!is.null(metadata_obj())) {
return(nrow(metadata_obj()))
} else {
return(NULL)
}
})
output$filter_ui_kOverA_k <- renderUI({
numericInputRow("filter_kOverA_sample_threshold", "",
min = 1, max = maxSamples(), value = kovera_k, step = 1)
})
filt1 <- groupDF()
# no sample filter yet
if (input$sample_filter_go == 0) {
filtered_rRNA_obj <<- filt1
#return(filtered_rRNA_obj)
}else{
# apply sample filter
isolate({
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$sample[[input$sample_filter_go]],
omicsData = filt1,
min_num = input$n)
#return(filtered_rRNA_obj)
})
}
if(input$taxa_filter_go == 0){
filtered_rRNA_obj <<- filtered_rRNA_obj
}else{
isolate({
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filter$taxa[[input$taxa_filter_go]],
omicsData = filtered_rRNA_obj,
keep_taxa = input$keep_taxa)
})
}
return(filtered_rRNA_obj)
})
observeEvent(input$sample_reset_button, {
updateNumericInput(session, "n",
value = 0)
if (input$otu_filter_go == 0) {
filt1 <<- groupDF()
}else{
# apply k over a filter
isolate({
filt1 <<- pmartRseq::applyFilt(filter_object = filters$otu[[input$otu_filter_go]],
omicsData = groupDF(),
num_samps = input$filter_kOverA_sample_threshold,
min_num = input$filter_count_threshold)
})
}
if(input$taxa_filter_go == 0){
filt1 <<- filt1
}else{
isolate({
filt1 <<- pmartRseq::applyFilt(filter_object = filter$taxa[[input$taxa_filter_go]],
omicsData = filt1,
keep_taxa = input$keep_taxa)
})
}
# no sample filter yet
filtered_rRNA_obj <<- filt1
return(filtered_rRNA_obj)
})
observeEvent(input$taxa_reset_button, {
# output$criteria <- renderUI({
# selectInput("criteria",
# label = "Which taxonomic level to use for filtering",
# choices = colnames(groupDF()$e_meta),
# multiple = FALSE)
# })
#
# keep_taxa = reactive({
# # Create logical indicating the samples to keep, or dummy logical if nonsense input
# validate(
# need(!(is.null(groupDF()$e_meta)), message = "please import feature metadata")
# )
# if (!is.null(groupDF()$e_meta)) {
# return(unique(groupDF()$e_meta[,input$criteria]))
# } else {
# return(NULL)
# }
#
# })
#
# output$keep_taxa <- renderUI({
# selectInput("keep_taxa",
# label = "Which taxa to keep in the analysis",
# choices = c(keep_taxa),
# multiple = TRUE)
# })
output$criteria <- renderUI({
selectInput("criteria",
label = "Which taxonomic level to use for filtering",
choices = colnames(groupDF()$e_meta),
selected = colnames(groupDF()$e_meta)[2],
multiple = FALSE)
})
output$keep_taxa <- renderUI({
selectInput("keep_taxa",
label = "Which taxonomies to keep",
choices = unique(groupDF()$e_meta[,2]),
multiple = TRUE)
})
filt1 <- groupDF()
# no sample filter yet
if (input$sample_filter_go == 0) {
filtered_rRNA_obj <<- filt1
#return(filtered_rRNA_obj)
}else{
# apply sample filter
isolate({
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$sample[[input$sample_filter_go]],
omicsData = filt1,
min_num = input$n)
#return(filtered_rRNA_obj)
})
}
# no otu filter yet
if (input$otu_filter_go == 0) {
filtered_rRNA_obj <<- filtered_rRNA_obj
#return(filtered_rRNA_obj)
}else{
# apply sample filter
isolate({
filtered_rRNA_obj <<- pmartRseq::applyFilt(filter_object = filters$otu[[input$otu_filter_go]],
omicsData = filtered_rRNA_obj,
num_samps = input$filter_kOverA_sample_threshold,
min_num = input$filter_count_threshold)
})
}
return(filtered_rRNA_obj)
})
#})
#--------- Metadata Object for filtering -----------#
metadata_obj <- reactive({
#------- TODO: need to display an error if the rRNA object isn't created! ---------#
validate(
need(!(is.null(groupDF()$f_data)), message = "rRNA object fail. Check to make sure file paths are correct")
)
input$metadata_filter_go
input$metadata_reset_button
input$sample_filter_go
input$sample_reset_button
input$otu_filter_go
input$otu_reset_button
if (is.null(input$f_data)) {
return(NULL)
}else{
temp <- filtered_rRNA_obj$f_data
inds <- lapply(temp, function(x) sum(is.na(x)) == length(x) )
results <- temp[,!(unlist(inds))]
return(results)
}
})
output$sample_metadata <- DT::renderDataTable(expr =
data.frame(metadata_obj()), rownames = FALSE, class = 'cell-border stripe compact hover',
options = list(columnDefs = list(list(
targets = c(1:(ncol((metadata_obj())) - 1)),
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
))), callback = JS('table.page(3).draw(false);'))
#---- Charts for f_meta filtering -------#
#
sample_metadata_filter_obj <- reactive({
return(pmartRseq::sample_based_filter(omicsData = groupDF(), fn = "criteria"))
})
observeEvent(input$metadata_reset_button, {
output$sample_metadata <- DT::renderDataTable(
groupDF()$f_data, rownames = FALSE, class = 'cell-border stripe compact hover',
options = list(columnDefs = list(list(
targets = c(1:(ncol((metadata_obj())) - 1)),
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
))), callback = JS('table.page(3).draw(false);')) })
observeEvent(groupDF(), {
# If the metadata has been loaded, create the charts
output$plots <- renderUI({get_plot_output_list(metadata_obj())})
output$boxes <- renderUI({get_checkbox_output_list(groupDF()$f_data)})
# Initialize new_metadata_obj object. If no metadata filtering then it's a copy of metadata_obj.
# If metadata filtering, will be overwritten with filters
# If the user brushes a chart, input$selected_indices will change
# If that change is observed, subset new_metadata_obj and
# create subsetted charts and table
observeEvent(input$selected_indices, {
new_metadata_obj <- reactive({
print(input$selected_indices)
return(metadata_obj()[input$selected_indices + 1, ]) # add one because javascript is zero-indexed
})
output$plots <- renderUI({get_plot_output_list(new_metadata_obj())})
output$new_samples <- DT::renderDataTable(
data.frame( new_metadata_obj()), rownames = FALSE, class = 'cell-border stripe compact hover',
options = list(columnDefs = list(list(
targets = c(1:(ncol(metadata_obj()) - 1)),
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
))), callback = JS('table.page(3).draw(false);'))
})
# render the first charts as soon as the data becomes available
outputOptions(output, "plots", suspendWhenHidden = FALSE)
#outputOptions(output, "library_sizes", suspendWhenHidden = FALSE)
#outputOptions(output, "sample_metadata", suspendWhenHidden = FALSE)
})
#------- Reset everything or keep the filtered subset -------#
observeEvent(input$metadata_reset_button,{
output$plots <- renderUI({get_plot_output_list(metadata_obj())})
output$new_samples <- DT::renderDataTable(
data.frame(metadata_obj()), rownames = FALSE, class = 'cell-border stripe compact hover',
options = list(columnDefs = list(list(
targets = c(1:(ncol(metadata_obj()) - 1)),
render = JS(
"function(data, type, row, meta) {",
"return type === 'display' && data.length > 10 ?",
"'<span title=\"' + data + '\">' + data.substr(0, 10) + '...</span>' : data;",
"}")
))), callback = JS('table.page(3).draw(false);'))
})
observeEvent(input$metadata_reset_button, {
output$boxes <- renderUI({get_checkbox_output_list(rRNA_agg()$f_data)})
})
# end sample metadata filtering
# end sample metadata filtering
#--------------- k over a filtering -----------------#
kovera_k <- 1
observeEvent(groupDF(), {
maxSamples = reactive({
# Create logical indicating the samples to keep, or dummy logical if nonsense input
validate(
need(!(is.null(metadata_obj())), message = "please import sample metadata")
)
if (!is.null(metadata_obj())) {
return(nrow(metadata_obj()))
} else {
return(NULL)
}
})
output$filter_ui_kOverA_k <- renderUI({
if (input$count_filter_fun == "ka") {
return(numericInputRow("filter_kOverA_sample_threshold", "in",
min = 1, max = maxSamples(), value = kovera_k, step = 1))
} else {
return(NULL)
}
})
})
otu_filter_obj <- reactive({
validate(
need(length(filtered_rRNA_obj) > 0 , message = "Upload data first")
)
return(pmartRseq::count_based_filter(groupDF(), fn = input$count_filter_fun))
})
output$read_counts_plot <- renderPlot({
validate(
need( input$filter_count_threshold >= 0, message = "Enter a count minimum >= 0")
#need( input$filter_kOverA_sample_threshold >= 0, message = "Enter a sample minimum >= 0")
)
if (input$sample_filter_go == 0 & input$otu_filter_go == 0 & input$taxa_filter_go == 0) {
plot(otu_filter_obj(), min_num = input$filter_count_threshold, min_samp = input$filter_kOverA_sample_threshold)
} else{
otu_filt_obj <- pmartRseq::count_based_filter(filtered_rRNA_obj, fn = input$count_filter_fun)
if (input$count_filter_fun == "ka") {
plot(otu_filt_obj, min_num = input$filter_count_threshold, min_samp = input$filter_kOverA_sample_threshold)
}
if (input$count_filter_fun != "ka") {
plot(otu_filt_obj, min_num = input$filter_count_threshold)
}
}
})
#-------------- Library read filtering -----------#
sample_filter_obj <- reactive({
return(pmartRseq::sample_based_filter(omicsData = groupDF(), fn = "sum"))
})
output$sample_counts_plot <- renderPlot({
validate(
need(input$n >= 0, message = "Enter a count minimum >= 0")
)
if (input$sample_filter_go == 0 & input$otu_filter_go == 0) {
plot(sample_filter_obj(), min_num = input$n)
} else {
sample_filt_obj <- pmartRseq::sample_based_filter(omicsData = filtered_rRNA_obj, fn = "sum")
plot(sample_filt_obj, min_num = input$n)
}
})
#-------------- taxa filtering -----------#
output$criteria <- renderUI({
selectInput("criteria",
label = "Which taxonomic level to use for filtering",
choices = colnames(groupDF()$e_meta),
selected = colnames(groupDF()$e_meta)[2],
multiple = FALSE)
})
output$keep_taxa <- renderUI({
selectInput("keep_taxa",
label = "Which taxonomies to keep",
choices = unique(groupDF()$e_meta[,input$criteria]),
multiple = TRUE)
})
taxa_filter_obj <- reactive({
if(length(input$criteria) == 0){
criteria <- colnames(groupDF()$e_meta)[2]
}else{
criteria <- input$criteria
}
return(pmartRseq::metadata_based_filter(omicsData = groupDF(), criteria = criteria))
})
output$taxa_counts <- renderPrint({
validate(
need(length(input$keep_taxa) > 0, message = "Need taxa criteria")
)
if (input$taxa_filter_go == 0 & input$otu_filter_go == 0 & input$sample_filter_go == 0) {
#table(taxa_filter_obj()[which(taxa_filter_obj()[,input$criteria] %in% input$keep_taxa),input$criteria])
#which(taxa_filter_obj()[,input$criteria] %in% input$keep_taxa)
cat("This keeps ",length(which(taxa_filter_obj()[,input$criteria] %in% input$keep_taxa))," out of a possible ",nrow(taxa_filter_obj()), " features (roughly ", length(which(taxa_filter_obj()[,input$criteria] %in% input$keep_taxa))/nrow(taxa_filter_obj())*100,"%). This correlates to a total number of ",sum(taxa_filter_obj()$Sum[which(taxa_filter_obj()[,input$criteria] %in% input$keep_taxa)], na.rm=TRUE)," sequences kept out of a possible ",sum(taxa_filter_obj()$Sum, na.rm=TRUE)," sequences (roughly ",sum(taxa_filter_obj()$Sum[which(taxa_filter_obj()[,input$criteria] %in% input$keep_taxa)], na.rm=TRUE)/sum(taxa_filter_obj()$Sum, na.rm=TRUE)*100,"%).")
} else {
taxa_filter_obj <- pmartRseq::metadata_based_filter(omicsData = filtered_rRNA_obj, criteria = input$criteria)
cat("This keeps ",length(which(taxa_filter_obj[,input$criteria] %in% input$keep_taxa))," out of a possible ",nrow(taxa_filter_obj), " features (roughly ", length(which(taxa_filter_obj[,input$criteria] %in% input$keep_taxa))/nrow(taxa_filter_obj)*100,"%). This correlates to a total number of ",sum(taxa_filter_obj$Sum[which(taxa_filter_obj[,input$criteria] %in% input$keep_taxa)], na.rm=TRUE)," sequences kept out of a possible ",sum(taxa_filter_obj$Sum, na.rm=TRUE)," sequences (roughly ",sum(taxa_filter_obj$Sum[which(taxa_filter_obj[,input$criteria] %in% input$keep_taxa)], na.rm=TRUE)/sum(taxa_filter_obj$Sum, na.rm=TRUE)*100,"%).")
}
})
#------------ reactive filtered data for downstream processing --------------#
#--------- outlier observer ---------#
outlier_filter_obj <- reactive({
validate(
need(length(filtered_rRNA_obj) > 0 , message = "Upload data first"),
need(!is.null(groupDF()), message = "Need group designation first")
)
return(pmartRseq::sample_based_filter(omicsData = filtered_rRNA_obj, fn = "criteria"))
})
observeEvent(input$remove_outliers, priority = 2, {
filters$outliers[[input$remove_outliers]] <- outlier_filter_obj()
filtO <- pmartRseq::applyFilt(omicsData = filtered_rRNA_obj, outlier_filter_obj(), samps_to_remove = outlier_jaccard()[outlier_jaccard()$jaqsID %in% selected_outliers()[["key"]], "jaqsID"])
filtered_rRNA_obj <<- filtO
})
filtered_data <- reactive({
event_data("plotly_selected")
input$gdfMainEffect
input$metadata_filter_go
input$metadata_reset_button
input$sample_filter_go
input$sample_reset_button
input$otu_filter_go
input$otu_reset_button
input$taxa_filter_go
input$taxa_reset_button
input$remove_outliers
return(filtered_rRNA_obj)
})
output$summ_filt <- renderPrint({
validate(
need(!(is.null(metadata_obj())), message = "please import sample metadata")
)
validate(
need(!(is.null(filtered_data())) , message = "Upload data first")
)
summary(filtered_data())
})
output$nrow_edata <- renderPrint({
nrow(filtered_data()$e_data)
})
################# Outliers Tab #################
outlier_jaccard <- reactive({
event_data("plotly_selected")
jaqs <- pmartRseq::jaccard_calc(omicsData = filtered_data())
jaqs$jaqsID <- jaqs[, attr(jaqs,"cname")$fdata_cname]
return(jaqs)
})
jac_plot_obj <- reactive({
plot(outlier_jaccard())
})
#define global plotly style
f <<- list(
family = "Courier New, monospace",
size = 18,
color = "#7f7f7f"
)
output$outlier_jaccard_plot <- renderPlotly({
d <- event_data("plotly_selected")
p <- plotly::plot_ly(data = outlier_jaccard(),
x = ~jaqsID,
y = ~Average) %>%
add_markers(key = ~jaqsID, color = I("black"))
if (!is.null(d)) {
m <- outlier_jaccard()[outlier_jaccard()$jaqsID %in% d[["key"]], ]
p <- add_markers(p, data = m, color = I("red"))
}
x <- list(
title = "",
titlefont = f
)
y <- list(
title = "Jaccard Dis/similarity",
titlefont = f
)
p$elementId <- NULL
layout(p, dragmode = "lasso", showlegend = FALSE, xaxis = x, yaxis = y)
})
selected_outliers <- reactive({
input$remove_outliers
event_data("plotly_selected")
})
output$audies <- renderTable({
outlier_jaccard()[outlier_jaccard()$jaqsID %in% selected_outliers()[["key"]], ]
})
abundance <- reactive({
event_data("plotly_selected")
input$remove_outliers
abundances <- abundance_calc(omicsData = filtered_data())
abundances$abundID <- rownames(abundances)
return(abundances)
})
output$outlier_abundance_plot <- renderPlotly({
d <- event_data("plotly_selected")
p <- plotly::plot_ly(data = data.frame(abundance()),
x = ~abundID,
y = ~abundance) %>%
add_markers(key = ~abundID, color = I("black"))
if (!is.null(d)) {
m <- abundance()[abundance()$abundID %in% d[["key"]], ]
p <- add_markers(p, data = m, color = I("red"))
}
x <- list(
title = "",
titlefont = f
)
y <- list(
title = "Abundance",
titlefont = f
)
p$elementId <- NULL
layout(p, dragmode = "lasso", showlegend = FALSE, xaxis = x, yaxis = y) })
output$outlier_richness_plot <- renderPlotly({
d <- event_data("plotly_selected")
long_richness <- reshape2::melt(rich_raw())
p <- plotly::plot_ly(data = long_richness,
x = ~variable,
y = ~value) %>%
add_markers(key = ~variable, color = I("black"))
if (!is.null(d)) {
m <- long_richness[long_richness$variable %in% d[["key"]], ]
p <- add_markers(p, data = m, color = I("red"))
}
x <- list(
title = "",
titlefont = f
)
y <- list(
title = "Richness",
titlefont = f
)
p$elementId <- NULL
layout(p, dragmode = "lasso", showlegend = FALSE, xaxis = x, yaxis = y) })
# ################ Normalization Tab #################
# Select which normalization function to use
output$normFunc <- renderUI({
selectInput("normFunc",
label = "Normalization Function",
choices = c("percentile","tss","rarefy","poisson","deseq","tmm","css","log","clr","none"),
selected = "css")
})
# Create normalized data
normalized_data <- reactive({
validate(need(length(input$normFunc) == 1, "Need to specify a normalization function."))
validate(need(input$normFunc %in% c("percentile","tss","rarefy","poisson","deseq","tmm","css","log","clr","none"), "Normalization function must be one of the options specified."))
#return(pmartRseq::split_emeta(pmartRseq::normalize_data(omicsData=filtered_data(), norm_fn=input$normFunc, normalize=TRUE), cname="OTU", split1=NULL, numcol=7, split2="__", num=2, newnames=NULL))
return(pmartRseq::normalize_data(omicsData=filtered_data(), norm_fn=input$normFunc, normalize=TRUE))
})
# Look at normalized results
output$normData <- DT::renderDataTable(normalized_data()$e_data, rownames = FALSE)
output$norm_class <- renderUI({
selectInput("norm_class",
label = "Taxonomic level to plot",
choices = colnames(normalized_data()$e_meta)[-which(colnames(normalized_data()$e_meta)==attr(normalized_data(),"cnames")$edata_cname)])
})
norm_plot_obj <- reactive({
plot(normalized_data(), class=input$norm_class)
})
# Try to make a stacked bar plot - not working right now
output$norm_plot <- renderPlotly({
#plot(normalized_data(), class="Phylum")
#print(norm_plot_obj())
#plotly::ggplotly( plot(normalized_data(), class=input$norm_class))
p <- plotly::ggplotly(norm_plot_obj(), tooltip = c("x", "y", "fill"))
p$elementId <- NULL
p
})
# Calculate abundance on normalized data
abun_norm <- reactive({
return(suppressWarnings(pmartRseq::abundance_calc(normalized_data())))
})
# Calculate abundance on raw data
abun_raw <- reactive({
event_data("plotly_selected")
return(suppressWarnings(pmartRseq::abundance_calc(filtered_data())))
})
# Calculate richness on normalized data
rich_norm <- reactive({
return(suppressWarnings(pmartRseq::richness_calc(normalized_data(), index="observed")))
})
# Calculate richness on raw data
rich_raw <- reactive({
event_data("plotly_selected")
input$remove_outliers
return(suppressWarnings(pmartRseq::richness_calc(filtered_data(), index="observed")))
})
ra_raw_plot <- reactive({
plot(abun_raw(), rich_raw(), plot_title="Raw Data", samplabel = attr(normalized_data(),"cnames")$fdata_cname)
})
# Create a plot of raw abundance vs raw richness
output$ra_raw <- renderPlotly({
#plot(abun_raw(), rich_raw(), plot_title="Raw Data")
p <- plotly::ggplotly(ra_raw_plot(), tooltip = c("x", "y","colour", "label"))
p$elementId <- NULL
p
})
ra_norm_plot <- reactive({
plot(abun_norm(), rich_norm(), plot_title="Normalized Data", samplabel = attr(normalized_data(),"cnames")$fdata_cname)
})
# Create a plot of normalized abundance vs normalized richness to see if there is a reduction in correlation
output$ra_norm <- renderPlotly({
#plot(abun_norm(), rich_norm(), plot_title="Normalized Data")
p <- plotly::ggplotly(ra_norm_plot(), tooltip = c("x", "y", "colour", "label"))
p$elementId <- NULL
p
})
################ Community Metrics Tab #################
# Select what variable to put on x-axis in community metrics plots
output$xaxis <- renderUI({
selectInput("xaxis",
label = "x-axis",
choices = c(colnames(attr(normalized_data(),"group_DF"))),
selected = "Group")
})
# Select what variable to color by in community metrics plots
output$color <- renderUI({
selectInput("color",
label = "color",
choices = c(colnames(attr(normalized_data(),"group_DF"))),
selected = "Group")
})
#----------- alpha diversity example ----------#