server.R 38.7 KB
Newer Older
1
options(shiny.maxRequestSize = 30*1024^2)
Midoux Cedric's avatar
Midoux Cedric committed
2

3
library(shinydashboard)
Midoux Cedric's avatar
Midoux Cedric committed
4
library(dplyr)
Midoux Cedric's avatar
Midoux Cedric committed
5
library(glue)
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

shinyServer
(function(input, output, session)
{
  checkNull <- function(x) {
    if (!exists(as.character(substitute(x)))) {
      return(NULL)
    } else if (is.null(x)) {
      return(NULL)
    } else if (length(x) > 1) {
      return(x)
    }
    else if (x %in% c(0, "", NA, "NULL")) {
      return(NULL)
    } else {
      return(x)
    }
  }
24
  
25
26
27
28
29
30
31
32
33
  beautifulTable <- function(data)  {
    DT::datatable(
      data = data,
      rownames = FALSE,
      filter = "top",
      extensions = c("Buttons", "ColReorder", "FixedColumns"),
      options = list(
        dom = "lBtip",
        pageLength = 10,
Midoux Cedric's avatar
Midoux Cedric committed
34
        lengthMenu = list(c(10, 25, 50, 100, -1), list('10', '25', '50', '100', 'All')),
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
        buttons = list(
          'colvis',
          list(
            extend = 'collection',
            buttons = c('copy', 'csv', 'excel', 'pdf'),
            text = 'Download'
          )
        ),
        colReorder = TRUE,
        scrollX = TRUE,
        fixedColumns = list(leftColumns = 1, rightColumns = 0)
      ),
      width = "auto",
      height = "auto"
    )
  }
51
  
Midoux Cedric's avatar
Midoux Cedric committed
52
53
54
55
56
57
58
59
60
61
62
  collapsedBox <- function(data, title = title)  {
    box(
      title = title,
      width = NULL,
      status = "primary",
      collapsible = TRUE,
      collapsed = TRUE,
      data
    )
  }
  
63
64
65
  source({
    "https://raw.githubusercontent.com/mahendra-mariadassou/phyloseq-extended/master/R/load-extra-functions.R"
  })
66
  
67
  source("internals.R")
68
  
69
  data16S <- reactive({
70
    ## BIOM input
71
72
    if (input$dataset == "input")
    {
73
      ## Unhappy path
74
75
      if (is.null(input$fileBiom))
        return()
76
      
77
78
79
      ## Happy path
      ## Import biom
      d <- .import_biom(input)
80
      
81
82
      ## Format tax table
      tax_table(d) <- .format_tax_table(tax_table(d))
83
      
84
85
      ## import metadata and store it in phyloseq object
      sample_data(d) <- .import_sample_data(input, d)
86
      
87
      ## Rarefy data
88
89
90
91
92
93
94
95
96
97
      if (input$rareData) {
        d <- rarefy_even_depth(
          d,
          replace = FALSE,
          rngseed = as.integer(Sys.time()),
          verbose = FALSE
        )
      }
      return(d)
    }
98
    
99
    ## Rdata input
100
101
    if (input$dataset == "rdata")
    {
102
      ## .import_from_rdata(input) ## does not work as a function for some reason
103
      
104
      ## Happy path
105
106
      ne <-
        new.env() ## new env to store RData content and avoid border effects
107
      if (!is.null(input$fileRData))
108
109
110
        load(input$fileRData$datapath, envir = ne)
      if (class(ne$data) == "phyloseq")
        return(ne$data)
111
      
112
      ## Unhappy paths: everything else
113
      return()
114
    }
115
    
116
    ## Default case
117
118
    load("demo/demo.RData")
    return(get(input$dataset))
119
    
120
  })
121
  
122
123
124
125
126
127
128
  data <- reactiveValues()
  {
    observe({
      if (!is.null(data16S()))
        isolate(data <<- data16S())
    })
  }
129
  
Midoux Cedric's avatar
Midoux Cedric committed
130
131
132
133
134
135
136
  scriptHead <- c(
    "# Loading packages",
    "source(\"https://raw.githubusercontent.com/mahendra-mariadassou/phyloseq-extended/master/R/load-extra-functions.R\")",
    "",
    "# Loading data",
    glue(
      "load(\"Easy16S-data.{Sys.Date()}.RData\") # if necessary, adapt the file path"
Midoux Cedric's avatar
Midoux Cedric committed
137
    ),
Midoux Cedric's avatar
Midoux Cedric committed
138
139
140
141
    "",
    "# View data",
    "data",
    ""
Midoux Cedric's avatar
Midoux Cedric committed
142
143
  )
  
144
145
146
147
148
149
150
151
152
153
  output$downloadData <- {
    downloadHandler(
      filename = function() {
        paste("Easy16S-data", Sys.Date(), "RData", sep = ".")
      },
      content = function(file) {
        save(data, file = file)
      }
    )
  }
154
  
155
  output$downloadUI <- renderUI({
156
157
158
    validate(need(data16S(), ""))
    tags$div(
      style = "text-align:center",
Midoux Cedric's avatar
Midoux Cedric committed
159
160
      title = "Download as RData",
      downloadButton("downloadData", "Download", style = "color: black; background-color: gray90")
161
162
    )
  })
163
  
164
165
166
167
  output$rarefactionMin <- renderText({
    validate(need(input$fileBiom, ""),
             need(input$dataset == "input", ""))
    paste("(min sample =", format(min(sample_sums(data16S(
168
      
169
170
    ))), big.mark = " "), "reads)")
  })
171
  
172
173
174
175
  output$phyloseqPrint <- renderPrint({
    validate(
      need(
        data16S(),
Midoux Cedric's avatar
Midoux Cedric committed
176
        "Firstly, you should select a demo dataset or upload an abundance BIOM file.\nFor example, with Galaxy, a BIOM file can be obtained at the end of FROGS workflow with the 'FROGS BIOM to std BIOM' tool. \nMake sure that the phyloseq object in the RData file is called 'data'."
177
178
179
180
      )
    )
    data16S()
  })
181
  
Midoux Cedric's avatar
Midoux Cedric committed
182
  output$sampledataTable <- renderUI({
Midoux Cedric's avatar
Midoux Cedric committed
183
    validate(need(sample_data(data16S(), errorIfNULL = FALSE), ""))
Midoux Cedric's avatar
Midoux Cedric committed
184
185
186
187
    collapsedBox(renderTable({
      (sapply(sample_data(data16S()), class))
    }, rownames = TRUE, colnames = FALSE),
    title = "Class of sample_data")
Midoux Cedric's avatar
Midoux Cedric committed
188
  })
Midoux Cedric's avatar
Midoux Cedric committed
189
  
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
  output$summaryTable <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Tables",
      width = NULL,
      status = "primary",
      tabsetPanel(
        tabPanel("otu_table",
                 beautifulTable(
                   data.frame(OTU = taxa_names(data16S()), otu_table(data16S()))
                 )),
        tabPanel("tax_table",
                 beautifulTable(
                   data.frame(OTU = taxa_names(data16S()), tax_table(data16S()))
                 )),
        tabPanel("sample_data",
                 #as.data.frame(sapply(sample_data(data16S()), class)),
                 beautifulTable(
                   data.frame(SAMPLE = sample_names(data16S()), sample_data(data16S()))
209
210
211
212
213
214
215
216
217
                 )),
        tabPanel(
          "agglomerate_taxa",
          radioButtons(
            "glomRank",
            label = "Taxonomic rank : ",
            choices = rank_names(data16S()),
            inline = TRUE
          ),
218
          DT::dataTableOutput("tableGlom")
219
        )
220
221
222
      )
    )
  })
223
  
224
  output$tableGlom <- DT::renderDataTable(server = FALSE, {
225
    Glom <- tax_glom(data16S(), input$glomRank, NArm=FALSE)
226
227
    taxTableGlom <- Glom %>%
      tax_table() %>%
Midoux Cedric's avatar
Midoux Cedric committed
228
      as.data.frame(stringsAsFactors = FALSE) %>%
229
      dplyr::select(input$glomRank:1) %>%
230
231
232
      tibble::rownames_to_column()
    otuTableGlom <- Glom %>%
      otu_table() %>%
Midoux Cedric's avatar
Midoux Cedric committed
233
      as.data.frame(stringsAsFactors = FALSE) %>%
234
235
236
237
      tibble::rownames_to_column()
    joinGlom <-
      dplyr::left_join(taxTableGlom, otuTableGlom, by = "rowname") %>%
      dplyr::select(-rowname)
238
239
    beautifulTable(joinGlom)
  })
240
  
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
  output$histUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : ",
      width = NULL,
      status = "primary",
      radioButtons(
        "barFill",
        label = "Taxonomic rank : ",
        choices = rank_names(data16S()),
        inline = TRUE
      ),
      textInput("barTitle",
                label = "Title : ",
                value = "OTU abundance barplot"),
      selectInput(
        "barGrid",
        label = "Subplot : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
260
      ),
261
262
263
264
      selectInput(
        "barX",
        label = "X : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
265
      ),
Midoux Cedric's avatar
Midoux Cedric committed
266
      collapsedBox(verbatimTextOutput("histScript"), title = "RCode")
267
268
    )
  })
Midoux Cedric's avatar
Midoux Cedric committed
269
  
Midoux Cedric's avatar
Midoux Cedric committed
270
  output$histScript <- renderText({
Midoux Cedric's avatar
Midoux Cedric committed
271
272
273
274
275
276
277
278
279
    scriptArgs <- c("physeq = data",
                    glue("fill = \"{input$barFill}\""))
    if (!is.null(checkNull(input$barX))) {
      scriptArgs <- c(scriptArgs, glue("x = \"{input$barX}\""))
    }
    if (!is.null(checkNull(input$barTitle))) {
      scriptArgs <- c(scriptArgs, glue("title = \"{input$barTitle}\""))
    }
    script <- c(
Midoux Cedric's avatar
Midoux Cedric committed
280
      scriptHead,
Midoux Cedric's avatar
Midoux Cedric committed
281
282
      "# Plot barplot",
      glue("p <- plot_bar({glue_collapse(scriptArgs, sep=', ')})")
283
    )
Midoux Cedric's avatar
Midoux Cedric committed
284
285
286
287
288
289
290
291
292
    if (!is.null(checkNull(input$barGrid))) {
      script <- c(script,
                  glue(
                    "p <- p + facet_grid(\". ~ {input$barGrid}\", scales = \"free_x\")"
                  ))
    }
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
293
  })
294
  
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
  output$histo <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    p <- plot_bar(
      physeq = data16S(),
      fill = input$barFill,
      x = ifelse(is.null(checkNull(input$barX)), "Sample", input$barX),
      title = checkNull(input$barTitle)
    )
    if (!is.null(checkNull(input$barGrid))) {
      p <-
        p + facet_grid(paste(".", "~", input$barGrid), scales = "free_x")
    }
    return(p)
  })
310
  
311
312
313
314
315
316
317
318
319
  output$histFocusUIfocusRank <- renderUI({
    validate(need(data16S(), ""))
    radioButtons(
      "focusRank",
      label = "Taxonomic rank : ",
      choices = rank_names(data16S())[-length(rank_names(data16S()))],
      inline = TRUE
    )
  })
320
  
321
  output$histFocusUIfocusTaxa <- renderUI({
Midoux Cedric's avatar
Midoux Cedric committed
322
323
    validate(need(data16S(), ""),
             need(input$focusRank, ""))
324
325
326
327
    selectInput(
      "focusTaxa",
      label = "Selected taxa : ",
      choices = unique(as.vector(tax_table(data16S(
328
        
329
330
331
332
      ))[, input$focusRank])),
      selected = TRUE
    )
  })
333
  
334
335
336
337
338
339
340
341
342
343
344
  output$histFocusUIfocusNbTaxa <- renderUI({
    validate(need(data16S(), ""))
    sliderInput(
      "focusNbTaxa",
      label = "Number of sub-taxa : ",
      min = 0,
      #max = sum(tax_table(tax_glom(data16S(), rank_names(data16S())[1+as.integer(input$focusRank)]))[, as.integer(input$focusRank)]==input$focusTaxa)
      max = 30,
      value = 10
    )
  })
Midoux Cedric's avatar
Midoux Cedric committed
345
  
346
347
348
349
350
351
  output$histFocusUIfocusGrid <- renderUI({
    validate(need(data16S(), ""))
    selectInput("focusGrid",
                label = "Subplot : ",
                choices = c("..." = 0, sample_variables(data16S())))
  })
Midoux Cedric's avatar
Midoux Cedric committed
352
  
353
354
355
356
357
358
  output$histFocusUIfocusX <- renderUI({
    validate(need(data16S(), ""))
    selectInput("focusX",
                label = "X : ",
                choices = c("..." = 0, sample_variables(data16S())))
  })
Midoux Cedric's avatar
Midoux Cedric committed
359
  
Midoux Cedric's avatar
Midoux Cedric committed
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
  output$histFocusUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : ",
      width = NULL,
      status = "primary",
      uiOutput("histFocusUIfocusRank"),
      uiOutput("histFocusUIfocusTaxa"),
      uiOutput("histFocusUIfocusNbTaxa"),
      uiOutput("histFocusUIfocusGrid"),
      uiOutput("histFocusUIfocusX"),
      collapsedBox(verbatimTextOutput("histFocusScript"), title = "RCode")
    )
  })
  
  output$histFocusScript <- renderText({
Midoux Cedric's avatar
Midoux Cedric committed
376
377
378
379
    scriptArgs <- c(
      "physeq = data",
      glue("taxaRank1 = \"{input$focusRank}\""),
      glue("taxaSet1 = \"{input$focusTaxa}\""),
Midoux Cedric's avatar
Midoux Cedric committed
380
      glue(
Midoux Cedric's avatar
Midoux Cedric committed
381
        "taxaRank2 = \"{rank_names(data16S())[which(rank_names(data16S()) == input$focusRank) + 1]}\""
Midoux Cedric's avatar
Midoux Cedric committed
382
      ),
Midoux Cedric's avatar
Midoux Cedric committed
383
      glue("numberOfTaxa = {input$focusNbTaxa}"),
Midoux Cedric's avatar
Midoux Cedric committed
384
      glue(
Midoux Cedric's avatar
Midoux Cedric committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
        "fill = \"{rank_names(data16S())[which(rank_names(data16S()) == input$focusRank) + 1]}\""
      )
    )
    if (!is.null(checkNull(input$focusX))) {
      scriptArgs <- c(scriptArgs, glue("x = \"{input$focusX}\""))
    }
    script <- c(
      scriptHead,
      "# Plot filtered barplot",
      glue(
        "p <- plot_composition({glue_collapse(scriptArgs, sep=', ')})"
      )
    )
    if (!is.null(checkNull(input$focusGrid))) {
      script <- c(
        script,
Midoux Cedric's avatar
Midoux Cedric committed
401
402
403
        glue(
          "p <- p + facet_grid(\". ~ {input$focusGrid}\", scales = \"free_x\")"
        )
Midoux Cedric's avatar
Midoux Cedric committed
404
405
406
407
408
      )
    }
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
Midoux Cedric's avatar
Midoux Cedric committed
409
410
411
412
413
414
415
416
417
  })
  
  output$histFocus <- renderPlot({
    validate(
      need(data16S(),
           "Requires an abundance dataset"),
      need(input$focusRank, ""),
      need(input$focusTaxa, "")
    )
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
    p <- plot_composition(
      physeq = data16S(),
      taxaRank1 = input$focusRank,
      taxaSet1 = input$focusTaxa,
      taxaRank2 = rank_names(data16S())[which(rank_names(data16S()) == input$focusRank) + 1],
      numberOfTaxa = input$focusNbTaxa,
      fill = rank_names(data16S())[which(rank_names(data16S()) == input$focusRank) + 1],
      x = ifelse(is.null(checkNull(input$focusX)), "Sample", input$focusX)
    )
    if (!is.null(checkNull(input$focusGrid))) {
      p <-
        p + facet_grid(paste(".", "~", input$focusGrid), scales = "free_x")
    }
    return(p)
  })
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
  output$clustUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      selectInput(
        "clustDist",
        label = "Distance : ",
        choices = list(
          "bray",
          "jaccard",
          "unifrac",
          "wunifrac",
          "dpcoa",
          "jsd",
          "euclidean"
        )
      ),
      selectInput(
        "clustMethod",
        label = "Method : ",
        choices = list(
          "ward.D2",
          "ward.D",
          "single",
          "complete",
          "average",
          "mcquitty",
          "median",
          "centroid"
        )
      ),
      selectInput(
        "clustCol",
        label = "Color : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
471
472
473
474
475
476
      ),
      collapsedBox(verbatimTextOutput("clustScript"), title = "RCode")
    )
  })
  
  output$clustScript <- renderText({
Midoux Cedric's avatar
Midoux Cedric committed
477
478
479
480
    scriptArgs <- c(
      "physeq = data",
      glue("dist = \"{input$clustDist}\""),
      glue("method = \"{input$clustMethod}\"")
481
    )
Midoux Cedric's avatar
Midoux Cedric committed
482
    if (!is.null(checkNull(input$clustCol))) {
Midoux Cedric's avatar
Midoux Cedric committed
483
      scriptArgs <- c(scriptArgs, glue("color = \"{input$clustCol}\""))
Midoux Cedric's avatar
Midoux Cedric committed
484
485
    }
    script <- c(
Midoux Cedric's avatar
Midoux Cedric committed
486
      scriptHead,
Midoux Cedric's avatar
Midoux Cedric committed
487
488
      "# Plot samples clustering",
      glue("p <- plot_clust({glue_collapse(scriptArgs, sep=', ')})")
489
    )
Midoux Cedric's avatar
Midoux Cedric committed
490
491
492
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
493
  })
494
  
495
496
497
498
499
500
501
502
503
504
  output$clust <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    plot_clust(
      physeq = data16S(),
      dist = input$clustDist,
      method = input$clustMethod,
      color = checkNull(input$clustCol)
    )
  })
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
  output$richnessAUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      checkboxGroupInput(
        "richnessMeasures",
        label = "Measures : ",
        choices = c(
          "Observed",
          "Chao1",
          "ACE",
          "Shannon",
          "Simpson",
          "InvSimpson",
          "Fisher"
        ),
        selected = c(
          "Observed",
          "Chao1",
          "ACE",
          "Shannon",
          "Simpson",
          "InvSimpson",
          "Fisher"
        ),
        inline = TRUE
      ),
      radioButtons(
        "richnessBoxplot",
        label = "Representation : ",
        choices = list(
          "Dots only" = 1,
          "Dots and boxplot" = 2,
          "Boxplot only" = 3
        ),
        selected = 2,
        inline = TRUE
      ),
      textInput("richnessTitle",
                label = "Title : ",
                value = "Alpha diversity graphics"),
      selectInput(
        "richnessX",
        label = "X : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "richnessColor",
        label = "Color : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "richnessShape",
        label = "Shape : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
563
564
565
566
567
568
      ),
      collapsedBox(verbatimTextOutput("richnessAScript"), title = "RCode")
    )
  })
  
  output$richnessAScript <- renderText({
Midoux Cedric's avatar
Midoux Cedric committed
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    if (!is.null(checkNull(input$richnessMeasures))) {
      measures <-
        glue("measures = c(\"{glue_collapse(input$richnessMeasures, sep='\", \"')}\")")
    } else {
      measures <- NULL
    }
    scriptArgs <- c("physeq = data", measures)
    if (!is.null(checkNull(input$richnessX))) {
      scriptArgs <- c(scriptArgs, glue("x = \"{input$richnessX}\""))
    }
    if (!is.null(checkNull(input$richnessColor))) {
      scriptArgs <-
        c(scriptArgs, glue("color = \"{input$richnessColor}\""))
    }
    if (!is.null(checkNull(input$richnessShape))) {
      scriptArgs <-
        c(scriptArgs, glue("shape = \"{input$richnessShape}\""))
    }
    if (!is.null(checkNull(input$richnessTitle))) {
      scriptArgs <-
        c(scriptArgs, glue("title = \"{input$richnessTitle}\""))
    }
    
    script <- c(
Midoux Cedric's avatar
Midoux Cedric committed
593
      scriptHead,
Midoux Cedric's avatar
Midoux Cedric committed
594
595
596
      "# Plot boxplot of alpha diversity",
      glue(
        "p <- plot_richness({glue_collapse(scriptArgs, sep=', ')})"
597
598
      )
    )
Midoux Cedric's avatar
Midoux Cedric committed
599
600
601
602
603
604
605
606
607
608
609
610
    if (input$richnessBoxplot >= 2) {
      script <- c(script,
                  "p <- p + geom_boxplot()")
    }
    if (input$richnessBoxplot <= 2) {
      script <- c(script,
                  "p <- p + geom_point()")
    }
    script <- c(script, "", "plot(p)")
    script <- c(script, "", "# Tables")
    script <- c(
      script,
Midoux Cedric's avatar
Midoux Cedric committed
611
612
613
614
615
      glue(
        "t <- estimate_richness({glue_collapse(c(\"data\", measures), sep=', ')})"
      ),
      "write.table(t, file = \"richness.tsv\", sep = \"\\t\", col.names = NA)"
    )
Midoux Cedric's avatar
Midoux Cedric committed
616
617
    
    return(glue_collapse(script, sep = "\n"))
618
  })
619
  
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
  output$richnessA <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    p <- plot_richness(
      physeq = data16S(),
      x = ifelse(is.null(checkNull(
        input$richnessX
      )), "samples", input$richnessX),
      color = checkNull(input$richnessColor),
      shape = checkNull(input$richnessShape),
      title = checkNull(input$richnessTitle),
      measures = checkNull(input$richnessMeasures)
    )
    if (input$richnessBoxplot >= 2) {
      p <- p + geom_boxplot()
    }
    if (input$richnessBoxplot <= 2) {
      p <- p + geom_point()
    }
    return(p)
  })
641
  
642
643
644
645
646
647
648
  output$richnessATable <- renderUI({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    p(beautifulTable(data.frame(
      SAMPLE = sample_names(data16S()), round(estimate_richness(data16S()), digits = 2)
    )))
  })
649
  
650
  output$richnessBUI <- renderUI({
Midoux Cedric's avatar
Midoux Cedric committed
651
    validate(need(data16S(), ""))
652
653
654
655
656
657
658
659
660
661
662
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      selectInput(
        "richnessBOrder",
        label = "Sorting sample : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      textInput("richnessBTitle",
                label = "Title : ",
Midoux Cedric's avatar
Midoux Cedric committed
663
664
                value = "Beta diversity heatmap"),
      collapsedBox(verbatimTextOutput("richnessBScript"), title = "RCode")
665
666
    )
  })
667
  
Midoux Cedric's avatar
Midoux Cedric committed
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
  output$richnessBScript <- renderText({
    script <- c(
      scriptHead,
      "# Plot heatmap of beta diversity",
      glue(
        "beta <- melt(as(distance(data, method = \"{input$richnessBDist}\"), \"matrix\"))"
      ),
      "colnames(beta) <- c(\"x\", \"y\", \"distance\")"
    )
    if (!is.null(checkNull(input$richnessBOrder))) {
      script <- c(
        script,
        glue(
          "new_factor = as.factor(get_variable(data, \"{input$richnessBOrder}\"))"
        ),
        glue(
          "variable_sort <- as.factor(get_variable(data, \"{input$richnessBOrder}\")[order(new_factor)])"
        ),
        "L = levels(reorder(sample_names(data), as.numeric(new_factor)))",
        "beta$x <- factor(beta$x, levels = L)",
        "beta$y <- factor(beta$y, levels = L)",
        "palette <- hue_pal()(length(levels(new_factor)))",
        "tipColor <- col_factor(palette, levels = levels(new_factor))(variable_sort)"
      )
    } else {
      script <- c(script, "tipColor <- NULL")
    }
    script <-
Midoux Cedric's avatar
Midoux Cedric committed
696
697
      c(
        script,
Midoux Cedric's avatar
Midoux Cedric committed
698
699
        "",
        "p1 <- ggplot(beta, aes(x = x, y = y, fill = distance))",
Midoux Cedric's avatar
Midoux Cedric committed
700
701
        "p1 <- p1 + geom_tile()"
      )
Midoux Cedric's avatar
Midoux Cedric committed
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
    if (!is.null(checkNull(input$richnessBTitle))) {
      script <- c(script,
                  glue("p1 <- p1 + ggtitle(\"{input$richnessBTitle}\")"))
    }
    script <- c(
      script,
      glue(
        "p1 <- p1 + theme(axis.text.x = element_text(angle = 90, hjust = 1, color = tipColor), axis.text.y = element_text(color = tipColor), axis.title.x = element_blank(), axis.title.y = element_blank())"
      )
    )
    script <- c(script, "", "plot(p1 + scale_fill_gradient2())")
    script <- c(script, "", "# Tables")
    script <- c(
      script,
      glue("t <- distance(data, method = \"{input$richnessBDist}\")"),
      "write.table(t, file = \"distance.tsv\", sep = \"\\t\", col.names = NA)"
    )
    
    return(glue_collapse(script, sep = "\n"))
  })
  
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
  output$richnessB <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    beta <-
      melt(as(distance(data16S(), method = input$richnessBDist), "matrix"))
    colnames(beta) <- c("x", "y", "distance")
    if (!is.null(checkNull(input$richnessBOrder)))
    {
      new_factor = as.factor(get_variable(data16S(), input$richnessBOrder))
      variable_sort <-
        as.factor(get_variable(data16S(), input$richnessBOrder)[order(new_factor)])
      L = levels(reorder(sample_names(data16S()), as.numeric(new_factor)))
      beta$x <- factor(beta$x, levels = L)
      beta$y <- factor(beta$y, levels = L)
      palette <- hue_pal()(length(levels(new_factor)))
      tipColor <-
        col_factor(palette, levels = levels(new_factor))(variable_sort)
    }
    p <-
      ggplot(beta, aes(x = x, y = y, fill = distance)) + geom_tile()
    p <- p + ggtitle(input$richnessBTitle) + theme(
      axis.text.x = element_text(
        angle = 90,
        hjust = 1,
        color = checkNull(tipColor)
      ),
      axis.text.y = element_text(color = checkNull(tipColor)),
      axis.title.x = element_blank(),
      axis.title.y = element_blank()
    )
    return(p + scale_fill_gradient2())
  })
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
  output$networkBUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      sliderInput(
        "netwMax",
        label = "Threshold : ",
        min = 0,
        max = 1,
        value = 0.7
      ),
      checkboxInput("netwOrphan",
                    label = "Keep orphans",
                    value = TRUE),
      textInput("netwTitle",
                label = "Title : ",
                value = "Beta diversity network"),
      selectInput(
        "netwCol",
        label = "Color : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "netwShape",
        label = "Shape : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "netwLabel",
        label = "Label : ",
        choices = c(
          "..." = 0,
          "Sample name" = "value",
          sample_variables(data16S())
        )
Midoux Cedric's avatar
Midoux Cedric committed
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
      ),
      collapsedBox(verbatimTextOutput("networkBScript"), title = "RCode")
    )
  })
  
  output$networkBScript <- renderText({
    scriptArgs <- c("g",
                    "physeq = data",
                    "hjust = 2")
    if (!is.null(checkNull(input$netwCol))) {
      scriptArgs <- c(scriptArgs, glue("color = \"{input$netwCol}\""))
    }
    if (!is.null(checkNull(input$netwShape))) {
      scriptArgs <- c(scriptArgs, glue("shape = \"{input$netwShape}\""))
    }
    if (!is.null(checkNull(input$netwLabel))) {
      scriptArgs <- c(scriptArgs, glue("label = \"{input$netwLabel}\""))
    }
    if (!is.null(checkNull(input$netwTitle))) {
      scriptArgs <- c(scriptArgs, glue("title = \"{input$netwTitle}\""))
    }
    script <- c(
      scriptHead,
      "# Plot samples network",
      glue(
        "g <- make_network(data, distance = \"{input$richnessBDist}\", max.dist = {input$netwMax}, keep.isolates = {input$netwOrphan})"
      ),
      glue("p <- plot_network({glue_collapse(scriptArgs, sep=', ')})")
821
    )
Midoux Cedric's avatar
Midoux Cedric committed
822
823
824
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
825
  })
826
  
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
  output$networkB <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    g <- make_network(
      data16S(),
      distance = input$richnessBDist,
      max.dist = input$netwMax,
      keep.isolates = input$netwOrphan
    )
    p <- plot_network(
      g,
      physeq = data16S(),
      color = checkNull(input$netwCol),
      shape = checkNull(input$netwShape),
      label = checkNull(input$netwLabel),
      hjust = 2,
      title = checkNull(input$netwTitle)
    )
    return(p)
  })
847
  
848
849
850
851
852
853
854
855
856
  output$richnessBTable <- renderUI({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    p(beautifulTable(data.frame(
      SAMPLE = sample_names(data16S()), round(as.matrix(
        distance(data16S(), method = input$richnessBDist)
      ), digits = 2)
    )))
  })
857
  
858
859
860
861
862
863
864
865
866
867
868
869
870
871
  output$rarefactionCurve <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    p <- ggrare(
      physeq = data16S(),
      step = 100,
      #step = input$rarefactionStep,
      color = checkNull(input$rarefactionColor),
      label = checkNull(input$rarefactionLabel),
      se = FALSE
    )
    if (!is.null(checkNull(input$rarefactionGrid))) {
      p <- p + facet_grid(paste(".", "~", input$rarefactionGrid))
    }
872
    
873
874
875
876
877
878
879
    if (input$rarefactionMin) {
      p <-
        p + geom_vline(xintercept = min(sample_sums(data16S())),
                       color = "gray60")
    }
    return(p + ggtitle(input$rarefactionTitle))
  })
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
  output$rarefactionCurveUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      # sliderInput(
      #   "rarefactionStep",
      #   label = "Etapes de calcul : ",
      #   min = 1,
      #   max = 1000,
      #   value = 100
      # ),
      checkboxInput("rarefactionMin", label = "Show min sample threshold", value = FALSE),
      textInput("rarefactionTitle",
                label = "Title : ",
                value = "Rarefaction curves"),
      selectInput(
        "rarefactionColor",
        label = "Color : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "rarefactionLabel",
        label = "Label : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "rarefactionGrid",
        label = "Subplot : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
912
913
      ),
      collapsedBox(verbatimTextOutput("rarefactionCurveScript"), title = "RCode")
914
915
    )
  })
916
  
Midoux Cedric's avatar
Midoux Cedric committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
  output$rarefactionCurveScript <- renderText({
    scriptArgs <- c("physeq = data",
                    "step = 100",
                    "se = FALSE")
    if (!is.null(checkNull(input$rarefactionColor))) {
      scriptArgs <-
        c(scriptArgs,
          glue("color = \"{input$rarefactionColor}\""))
    }
    if (!is.null(checkNull(input$rarefactionLabel))) {
      scriptArgs <-
        c(scriptArgs,
          glue("label = \"{input$rarefactionLabel}\""))
    }
    script <- c(
      scriptHead,
Midoux Cedric's avatar
Midoux Cedric committed
933
      "# Plot rarefaction curves",
Midoux Cedric's avatar
Midoux Cedric committed
934
      glue("p <- ggrare({glue_collapse(scriptArgs, sep=', ')})")
935
    )
Midoux Cedric's avatar
Midoux Cedric committed
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
    if (!is.null(checkNull(input$rarefactionGrid))) {
      script <- c(script,
                  glue("p <- p + facet_grid(\". ~ {input$rarefactionGrid}\")"))
    }
    if (input$rarefactionMin) {
      script = c(
        script,
        "p <- p + geom_vline(xintercept = min(sample_sums(data)), color = \"gray60\")"
      )
    }
    if (!is.null(checkNull(input$rarefactionTitle))) {
      script <- c(script,
                  glue("p <- p + ggtitle({input$rarefactionTitle})"))
    }
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
953
  })
Midoux Cedric's avatar
Midoux Cedric committed
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
  output$HeatmapUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      textInput("heatmapTitle",
                label = "Title : ",
                value = "Taxa heatmap by samples"),
      selectInput(
        "heatmapGrid",
        label = "Subplot : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "heatmapX",
        label = "X : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      sliderInput(
        "heatmapTopOtu",
        label = "Show the n most abundant OTU : ",
        min = 1,
        max = ntaxa(data16S()),
        value = 250
      ),
      selectInput(
        "heatmapDist",
        label = "Distance : ",
        selected = "bray",
        choices = list(
          "bray",
          "jaccard",
          "unifrac",
          "wunifrac",
          "dpcoa",
          "jsd",
          "euclidean"
        )
      ),
      selectInput(
        "heatmapMethod",
        label = "Method : ",
        selected = "NMDS",
        choices = list(
          "NMDS",
          "ward.D2",
          "ward.D",
          "single",
          "complete",
          "average",
          "mcquitty",
          "median",
          "centroid"
        )
Midoux Cedric's avatar
Midoux Cedric committed
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
      ),
      collapsedBox(verbatimTextOutput("heatmapScript"), title = "RCode")
    )
  })
  
  output$heatmapScript <- renderText({
    scriptArgs <-
      c(
        glue(
          "prune_taxa(names(sort(taxa_sums(data), decreasing = TRUE)[1:{input$heatmapTopOtu}]), data)"
        ),
        glue("distance = \"{input$heatmapDist}\""),
        glue("method = \"{input$heatmapMethod}\""),
        "low = \"yellow\"",
        "high = \"red\"",
        "na.value = \"white\""
1026
      )
Midoux Cedric's avatar
Midoux Cedric committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
    if (!is.null(checkNull(input$heatmapX))) {
      scriptArgs <-
        c(scriptArgs, glue("sample.order = \"{input$heatmapX}\""))
    }
    if (!is.null(checkNull(input$heatmapTitle))) {
      scriptArgs <-
        c(scriptArgs, glue("title = \"{input$heatmapTitle}\""))
    }
    
    script <- c(
      scriptHead,
      "# Plot heatmap",
      glue("p <- plot_heatmap({glue_collapse(scriptArgs, sep=', ')})")
1040
    )
Midoux Cedric's avatar
Midoux Cedric committed
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
    if (!is.null(checkNull(input$heatmapGrid))) {
      script <- c(
        script,
        glue(
          "p <- p + facet_grid(\". ~ {input$heatmapGrid}\", scales = \"free_x\")"
        )
      )
    }
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
1052
  })
1053
  
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
  output$Heatmap <- renderPlot({
    validate(need(data16S(),
                  "Requires an abundance dataset"))
    p <- plot_heatmap(
      physeq = prune_taxa(names(sort(
        taxa_sums(data16S()), decreasing = TRUE
      )[1:input$heatmapTopOtu]), data16S()),
      distance = input$heatmapDist,
      method = input$heatmapMethod,
      title = checkNull(input$heatmapTitle),
      sample.order = checkNull(input$heatmapX),
      low = "yellow",
      high = "red",
      na.value = "white"
    )
    if (!is.null(checkNull(input$heatmapGrid))) {
      p <-
        p + facet_grid(paste(".", "~", input$heatmapGrid), scales = "free_x")
    }
    return(p)
  })
1075
  
1076
  output$treeUI <- renderUI({
Midoux Cedric's avatar
Midoux Cedric committed
1077
    validate(need(phy_tree(data16S(), errorIfNULL = FALSE), ""))
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      radioButtons(
        "treeRank",
        label = "Taxonomic rank captioned : ",
        choices = c(aucun = "",
                    rank_names(data16S()),
                    OTU = "taxa_names"),
        inline = TRUE
      ),
      sliderInput(
        "treeTopOtu",
        label = "Show the n most abundant OTU : ",
        min = 1,
        max = ntaxa(data16S()),
        value = 20
      ),
      checkboxInput("treeRadial", label = "Radial tree", value = FALSE),
      checkboxInput("treeSample", label = "Show samples", value = TRUE),
      textInput("treeTitle",
                label = "Title : ",
                value = "Phylogenetic tree"),
      selectInput(
        "treeCol",
        label = "Color : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "treeShape",
        label = "Shape : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
1111
1112
1113
1114
1115
1116
1117
1118
1119
      ),
      collapsedBox(verbatimTextOutput("treeScript"), title = "RCode")
    )
  })
  
  output$treeScript <- renderText({
    scriptArgs <- c(
      glue(
        "physeq = prune_taxa(names(sort(taxa_sums(data), decreasing = TRUE)[1:{input$treeTopOtu}]), data)"
1120
1121
      )
    )
Midoux Cedric's avatar
Midoux Cedric committed
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
    if (input$treeSample) {
      scriptArgs <- c(scriptArgs, "method = \"sampledodge\"")
    } else {
      scriptArgs <- c(scriptArgs, "method = \"treeonly\"")
    }
    if (!is.null(checkNull(input$treeCol))) {
      scriptArgs <- c(scriptArgs, glue("color = \"{input$treeCol}\""))
    }
    if (!is.null(checkNull(input$treeShape))) {
      scriptArgs <- c(scriptArgs, glue("shape = \"{input$treeShape}\""))
    }
    scriptArgs <- c(scriptArgs, "size = \"abundance\"")
    if (!is.null(checkNull(input$treeRank))) {
      scriptArgs <-
        c(scriptArgs, glue("label.tips = \"{input$treeRank}\""))
    }
    scriptArgs <- c(scriptArgs,
                    "sizebase = 5",
                    "ladderize = \"left\"",
                    "plot.margin = 0")
    if (!is.null(checkNull(input$treeTitle))) {
      scriptArgs <- c(scriptArgs, glue("title = \"{input$treeTitle}\""))
    }
    script <- c(
      scriptHead,
      "# Plot phylogenetic tree",
      glue("p <- plot_tree({glue_collapse(scriptArgs, sep=', ')})")
    )
    if (input$treeRadial) {
      script <- c(script,
                  "p <- p + coord_polar(theta = \"y\")")
    }
    script <- c(script, "", "plot(p)")
    
    return(glue_collapse(script, sep = "\n"))
1157
  })
1158
  
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
  output$tree <- renderPlot({
    validate(
      need(data16S(), "Requires an abundance dataset"),
      need(
        phy_tree(data16S(), errorIfNULL = FALSE),
        "Requires a phylogenetic tree"
      )
    )
    p <- plot_tree(
      physeq = prune_taxa(names(sort(
        taxa_sums(data16S()), decreasing = TRUE
      )[1:input$treeTopOtu]), data16S()),
      method = ifelse(input$treeSample, "sampledodge", "treeonly"),
      color = checkNull(input$treeCol),
      shape = checkNull(input$treeShape),
      size = "abundance",
      label.tips = checkNull(input$treeRank),
      sizebase = 5,
      ladderize = "left",
      plot.margin = 0,
      title = checkNull(input$treeTitle)
    )
    if (checkNull(input$treeRadial)) {
      return(p + coord_polar(theta = "y"))
    } else {
      return(p)
    }
  })
1187
  
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
  output$acpUI <- renderUI({
    validate(need(data16S(), ""))
    box(
      title = "Setting : " ,
      width = NULL,
      status = "primary",
      checkboxGroupInput(
        "acpAxes",
        label = "Axes : ",
        choices = seq(10),
        selected = c(1, 2),
        inline = TRUE
      ),
      selectInput(
        "acpDist",
        label = "Distance : ",
        selected = "bray",
        choices = list(
          "bray",
          "jaccard",
          "unifrac",
          "wunifrac",
          "dpcoa",
          "jsd",
          "euclidean"
        )
      ),
      selectInput(
        "acpMethod",
        label = "Method : ",
        selected = "MDS",
        choices = list("DCA", "CCA", "RDA", "CAP", "DPCoA", "NMDS", "MDS", "PCoA")
      ),
      textInput("acpTitle",
                label = "Title : ",
                value = "Samples ordination graphic"),
      selectInput(
        "acpLabel",
        label = "Label : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "acpCol",
        label = "Color : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "acpShape",
        label = "Shape : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "acpEllipse",
        label = "Ellipses : ",
        choices = c("..." = 0, sample_variables(data16S()))
      ),
      selectInput(
        "acpRep",
        label = "Barycenters : ",
        choices = c("..." = 0, sample_variables(data16S()))
Midoux Cedric's avatar
Midoux Cedric committed
1248
      ),
Midoux Cedric's avatar
Midoux Cedric committed
1249
1250
      collapsedBox(verbatimTextOutput("acpScript"), title = "RCode"),
      actionButton("downloadSetting", label = "Download plot")
Midoux Cedric's avatar
Midoux Cedric committed
1251
1252
1253
    )
  })
  
Midoux Cedric's avatar
Midoux Cedric committed
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
  observeEvent(input$downloadSetting, {
    showModal(
      modalDialog(
        title = "Setting of downloading plot",
        textInput(
          "plotName",
          label = "Plot name : ",
          value = "Easy16S-plot"
          ),
        numericInput(
          "plotWidth",
          label = "Plot width (cm) : ",
          value = 20,
          min = 1,
          max = 100
        ),
        numericInput(
          "plotHeight",
          label = "Plot height (cm) : ",
          value = 20,
          min = 1,
          max = 100
        ),
        numericInput(
          "plotDPI",
          label = "Plot resolution : ",
          value = 300,
          min = 70,
          max = 500,
          step = 10
        ),
        selectInput(
          "plotDevice",
          label = "Plot device : ",
          choices = list("eps", "ps", "tex", "pdf", "jpeg", "tiff", "png", "bmp", "svg"),
          selected = "png"
        ),
        size = "s",
        easyClose = TRUE,
        footer = downloadButton(outputId = "downloadPlot", label = "Download the plot")
      )
    )
  })
  
  output$downloadPlot <- {
    downloadHandler(
      filename = function() {
        paste(input$plotName, input$plotDevice, sep = ".")
      },
      content = function(file) {
        ggsave(
          file,
          plot = plotInputACP(),
          device = input$plotDevice,
          units = "cm",
          width = input$plotWidth,
          height = input$plotHeight,
          dpi = input$plotDPI,
          limitsize = FALSE
        )
      }
    )
  }
  
  plotInputACP <- function()
    {
    p <- plot_samples(
      data16S(),
      ordination = ordinate(
        data16S(),
        method = input$acpMethod,
        distance = input$acpDist
      ),
      axes = as.numeric(input$acpAxes),
      title = checkNull(input$acpTitle),
      color = checkNull(input$acpCol),
      replicate = if (is.null(checkNull(input$acpRep))) {
        NULL
      } else {
        checkNull(input$acpRep)
      },
      shape = checkNull(input$acpShape),
      label = checkNull(input$acpLabel)
    )
    if (!is.null(checkNull(input$acpEllipse))) {
      p <- p + stat_ellipse(aes_string(group = input$acpEllipse))
    }
    return(p + theme_bw())
  }
  
Midoux Cedric's avatar
Midoux Cedric committed
1344
1345
1346
1347
1348
1349
1350
  output$acpScript <- renderText({
    scriptArgs <- c(
      "physeq = data",
      glue(
        "ordination = ordinate(data, method = \"{input$acpMethod}\", distance = \"{input$acpDist}\")"
      ),
      glue("axes = c({glue_collapse(input$acpAxes, sep = ', ')})")
1351
    )
Midoux Cedric's avatar
Midoux Cedric committed
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
    if (!is.null(checkNull(input$acpCol))) {
      scriptArgs <- c(scriptArgs, glue("color = \"{input$acpCol}\""))
    }
    if (!is.null(checkNull(input$acpShape))) {
      scriptArgs <- c(scriptArgs, glue("shape = \"{input$acpShape}\""))
    }
    if (!is.null(checkNull(input$acpRep))) {
      scriptArgs <- c(scriptArgs, glue("replicate = \"{input$acpRep}\""))
    } else {
      scriptArgs <- c(scriptArgs, glue("replicate = NULL"))
    }
    if (!is.null(checkNull(input$acpLabel))) {
      scriptArgs <- c(scriptArgs, glue("label = \"{input$acpLabel}\""))
    }
    if (!is.null(checkNull(input$acpTitle))) {
      scriptArgs <- c(scriptArgs, glue("title = \"{input$acpTitle}\""))
    }
    script <- c(
      scriptHead,
      "# MultiDimensional scaling",
      glue("p <- plot_samples({glue_collapse(scriptArgs, sep=', ')})")
1373
    )
Midoux Cedric's avatar
Midoux Cedric committed
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
    if (!is.null(checkNull(input$acpEllipse))) {
      script <- c(
        script,
        glue(
          "p <- p + stat_ellipse(aes_string(group = \"{input$acpEllipse}\"))"
        )
      )
    }
    script <- c(script, "", "plot(p + theme_bw())")
    
    return(glue_collapse(script, sep = "\n"))
1385
  })
1386
  
1387
1388
1389
1390
1391
  output$acp <- renderPlot({
    validate(
      need(data16S(), "Requires an abundance dataset"),
      need(length(input$acpAxes) == 2, "Requires two projections axes")
    )
Midoux Cedric's avatar
Midoux Cedric committed
1392
    plotInputACP()
1393
  })
Midoux Cedric's avatar
Midoux Cedric committed
1394
})