dataInput.R 12.2 KB
Newer Older
Midoux Cedric's avatar
Midoux Cedric committed
1
### Upload Data ###
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
dataInput <- function(failed = FALSE) {
  modalDialog(
    title = "Select your data",
    
    if (failed)
    {
      div(
        "Invalide dataset. \n Please try again \n", 
        style = "font-weight: bold; color: red; text-align: center; white-space: pre-line"
        )
    }, 
    
    "Firstly, you should select a demo dataset or upload an abundance BIOM file. For example, with Galaxy, a BIOM file can be obtained at the end of FROGS workflow with the `FROGS BIOM to std BIOM` tool. Make sure that the phyloseq object in the RData file is called `data`.",
    
    radioButtons(
      inputId = "dataset",
      label = "Select dataset : ",
      inline = TRUE,
      choices = list(
        "Demo" = "demo",
        "Input data" = "input",
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
23
24
        "RData" = "rdata",
        "RDS" = "rds"
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
      ),
      selected = "demo"
    ),
    
    wellPanel(uiOutput("dataUI")),

    footer = tagList(modalButton("Cancel"),
                     actionButton(inputId = "okData", label = "OK"))
  )
}

output$dataUI <- renderUI({
  if (is.null(input$dataset))
    return()
  
  switch(
    input$dataset,
    "demo" = selectInput(
      inputId = "demo",
      label = "Select a demo dataset",
      choices = c("Chaillou et al., 2015" = "food",
      # "Mach et al., 2015" = "kinetic",
      # "Morton et al., 2017" = "soil",
      # "Ravel et al., 2011" = "ravel",
      # "biorare" = "biorare",
      "GlobalPatterns" = "GlobalPatterns")
    ),
    "input" = tags$div(
      tags$div(
        title = "Abundance BIOM file come from FROGS with 'FROGS BIOM to std BIOM', Qiime or another metagenomic tool.",
        fileInput(
          inputId = "fileBiom",
          label = "Abundance BIOM file : ",
          placeholder = "data.biom"
        )
      ),
      radioButtons(
        inputId = "biomFormat",
        label = NULL,
        inline = TRUE,
        choices = c("STD BIOM" = "std",
                    "FROGS BIOM" = "frogs"),
        selected = "std"
      ),
      # tags$div(
      # style = "text-align:center",
      # title = "Resample dataset such that all samples have the same library size. \nIt's using an random sampling without replacement.",
      checkboxInput(
        inputId = "rareData",
        label = "Rarefy dataset",
        value = TRUE
      ),
      # textOutput("rarefactionMin")
      # ),
      tags$div(
        title = "Metadata table with variables (in columns) and samples (in rows). \nMake sure you follow the exact spelling of the sample names (1st column). \nThe import of an excel table is possible but not recommended.",
        fileInput(
          inputId = "fileMeta",
          label = "Metadata table : ",
          placeholder = "data.csv"
        )
      ),
      radioButtons(
        inputId = "CSVsep",
        label = "CSV separator : ",
        inline = TRUE,
        choices = c("<tab>" = "\t",
                    "," = ",",
                    ";" = ";",
                    excel = "excel"
                    )
      ),
      fileInput(
        inputId = "fileTree",
        label = "Phylogenetic tree : ",
        placeholder = "data.nwk"),
      fileInput(
        inputId = "fileSeq",
        label = "Representative FASTA sequences of OTU : ",
        placeholder = "data.fasta"
      )
    ),
    "rdata" = fileInput(
      inputId = "fileRData",
      label = "RData where 'data' is a phyloseq object : ",
      placeholder = "data.RData"
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
111
112
113
114
115
    ),
    "rds" = fileInput(
      inputId = "fileRDS",
      label = "RDS with a phyloseq object : ",
      placeholder = "phyloseq.RDS"
116
    )
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
117
    
118
119
120
121
122
123
124
125
126
127
128
  )
})

observeEvent(input$okData, {
  physeq(NULL)
  try(
    physeq(
      switch(
        input$dataset,
        "demo" =
          {
Midoux Cedric's avatar
Midoux Cedric committed
129
            message <- as.character(input$demo)
130
131
132
133
134
135
            data(GlobalPatterns)
            load("demo/demo.RData")
            get(input$demo)
          },
        "input" =
          {
Midoux Cedric's avatar
Midoux Cedric committed
136
            message <- as.character(input$fileBiom$name)
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
            d <- .import_biom(input)
            ## Format tax table
            tax_table(d) <- .format_tax_table(tax_table(d))
      
            ## import metadata and store it in phyloseq object
            sample_data(d) <- .import_sample_data(input, d)
      
            ## Rarefy data
            if (input$rareData)
            {
              d <- rarefy_even_depth(
                d,
                replace = FALSE,
                rngseed = as.integer(Sys.time()),
                verbose = FALSE
              )
            }
            d
          },
        "rdata" =
          {
Midoux Cedric's avatar
Midoux Cedric committed
158
            message <- as.character(input$fileRData$name)
159
160
161
162
            ne <- new.env()
            if (!is.null(input$fileRData))
              {load(input$fileRData$datapath, envir = ne)}
            ne$data
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
163
164
165
166
167
168
          },
        "rds" = 
          {
            message <- as.character(input$fileRDS$name)
            if (!is.null(input$fileRDS))
              {readRDS(input$fileRDS$datapath)}
169
170
171
172
173
174
175
          }
        )
      ),
    silent = TRUE, 
    outFile = showModal(dataInput(failed = TRUE))
    )
  
Midoux Cedric's avatar
Midoux Cedric committed
176
  if (inherits(physeq(), "phyloseq")) {
Midoux Cedric's avatar
Midoux Cedric committed
177
    message(paste("[Easy16S] Correct upload with", input$dataset, "mode :", message))
178
179
180
181
182
    removeModal()
  } else {
    showModal(dataInput(failed = TRUE))
  }
})
Midoux Cedric's avatar
Midoux Cedric committed
183

Midoux Cedric's avatar
Midoux Cedric committed
184
### Filter ###
Midoux Cedric's avatar
Midoux Cedric committed
185
186
187
filterSample <- function() {
  modalDialog(
    title = "Select some sample",
Midoux Cedric's avatar
Midoux Cedric committed
188
189
190
191
192
193
194
195
196
197
198
199
    
    radioButtons(
      inputId = "filterCriteria",
      label = "Filter criteria : ",
      inline = TRUE,
      choices = c(
        "Sample" = "sample",
        sample_variables(physeq(), errorIfNULL = FALSE)
      ),
      selected = "sample"
    ),
    
Midoux Cedric's avatar
Midoux Cedric committed
200
201
    wellPanel(uiOutput("filterUI"), 
              actionLink(inputId = "selectAll", label = "(Un)select All")),
Midoux Cedric's avatar
Midoux Cedric committed
202
    
Midoux Cedric's avatar
Midoux Cedric committed
203
204
205
206
207
208
209
    footer = tagList(modalButton("Cancel"),
                     actionButton(inputId = "okData", label = "Refresh filter"),
                     actionButton(inputId = "selectData", label = "Select")
    )
  )
}

Midoux Cedric's avatar
Midoux Cedric committed
210
211
212
output$filterUI <- renderUI({
  if (is.null(input$filterCriteria))
    return()
Midoux Cedric's avatar
Midoux Cedric committed
213
  
Midoux Cedric's avatar
Midoux Cedric committed
214
215
216
  if (input$filterCriteria == "sample") {
    label <- "Sample to keep :"
    choices <- sample_names(physeq())
Midoux Cedric's avatar
Midoux Cedric committed
217
  } else {
Midoux Cedric's avatar
Midoux Cedric committed
218
219
220
    label <- "Variable to keep :"
    choices <- levels(get_variable(physeq(), input$filterCriteria))
  }
Midoux Cedric's avatar
Midoux Cedric committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
  
  observe({
    if(input$selectAll == 0) return(NULL)
    else if (input$selectAll%%2 == 0)
    {
      updateCheckboxGroupInput(session = session,
                               inputId = "filterCheck",
                               label = label,
                               choices = choices,
                               selected = choices,
                               inline = TRUE)
    } else {
      updateCheckboxGroupInput(session = session,
                               inputId = "filterCheck",
                               label = label,
                               choices = choices,
                               inline = TRUE)
    }
  })
  
Midoux Cedric's avatar
Midoux Cedric committed
241
242
243
244
245
246
247
248
249
250
  checkboxGroupInput(inputId = "filterCheck",
                     label = label,
                     choices = choices,
                     selected = choices,
                     inline = TRUE)
})

observeEvent(input$selectData, {
  if (is.null(input$filterCheck)) 
  {
Midoux Cedric's avatar
Midoux Cedric committed
251
    showModal(dataInput(failed = TRUE))
Midoux Cedric's avatar
Midoux Cedric committed
252
253
254
255
256
257
258
259
260
261
262
263
  } else {
    try(
      if (input$filterCriteria == "sample") {
        physeq(prune_samples(samples = input$filterCheck, physeq()))
      } else {
        criteria <<- input$filterCriteria
        check <<- input$filterCheck
        physeq(subset_samples(physeq(), eval(parse(text = criteria)) %in% check))
        },
      silent = TRUE,
      outFile = showModal(dataInput(failed = TRUE)))
    
Midoux Cedric's avatar
Midoux Cedric committed
264
    if (inherits(physeq(), "phyloseq")) {
Midoux Cedric's avatar
Midoux Cedric committed
265
266
267
268
      removeModal()
    } else {
      showModal(dataInput(failed = TRUE))
    }    
Midoux Cedric's avatar
Midoux Cedric committed
269
270
271
  }
})

Midoux Cedric's avatar
Midoux Cedric committed
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
### Transformation ###
transformSample <- function() {
  modalDialog(
    title = "Transform abundance data",
    
    radioButtons(
      inputId = "transformFun",
      label = "Transform function : ",
      selected = character(0),
      choices = c("Proportional Transformation" = "prop", 
                  "Square Root Transformation" = "sqrt", 
                  "Centered Log-Ratio (CLR) Transformation" = "clr")
    ),
    
    wellPanel(verbatimTextOutput("transformFun")),
    
    footer = tagList(modalButton("Cancel"),
                     actionButton(inputId = "okData", label = "Refresh transformation"),
                     actionButton(inputId = "transformData", label = "Transforme")
    )
  )
}

output$transformFun <- renderText({
  validate(need(input$transformFun, ""))
  switch (input$transformFun,
          "prop" = paste("count_to_prop <- function(x) {return( x / sum(x) )}", 
                         "data_prop <- transform_sample_counts(data, count_to_prop)",
                         sep = "\n"),
          "sqrt" = "data_sqrt <- transform_sample_counts(data, sqrt)",
          "clr" = paste("gm_mean <- function(x, na.rm=TRUE) {",
Midoux Cedric's avatar
Midoux Cedric committed
303
                        "  return(exp(mean(log(x), na.rm=na.rm)))",
Midoux Cedric's avatar
Midoux Cedric committed
304
                        "}",
Midoux Cedric's avatar
Midoux Cedric committed
305
306
307
308
309
                        "clr <- function(x, base=exp(1)) {",
                        "  x <- x+1",
                        "  x <- log(x/gm_mean(x), base)",
                        "  return(x)",
                        "}", 
Midoux Cedric's avatar
Midoux Cedric committed
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
                        "data_clr <- transform_sample_counts(data, clr)",
                        sep = "\n")
          )
})

observeEvent(input$transformData, {
  if (is.null(input$transformData)) 
  {
    removeModal()
  } else {
    try(
      switch (input$transformFun,
              "prop" = {
                count_to_prop <- function(x) {return( x / sum(x) )}
                physeq(transform_sample_counts(physeq(), count_to_prop))
              },
              "sqrt" = {
                physeq(transform_sample_counts(physeq(), sqrt))
              },
              "clr" = {
                gm_mean <- function(x, na.rm=TRUE) {
Midoux Cedric's avatar
Midoux Cedric committed
331
                  return(exp(mean(log(x), na.rm=na.rm)))
Midoux Cedric's avatar
Midoux Cedric committed
332
                }
Midoux Cedric's avatar
Midoux Cedric committed
333
334
335
                clr <- function(x, base=exp(1)) {
                  x <- x+1
                  x <- log(x/gm_mean(x), base)
Midoux Cedric's avatar
Midoux Cedric committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
                  return(x)
                }
                physeq(transform_sample_counts(physeq(), clr))
              }
      ),
      silent = TRUE,
      outFile = showModal(dataInput(failed = TRUE)))
    
    if (class(physeq()) == "phyloseq") {
      removeModal()
    } else {
      showModal(dataInput(failed = TRUE))
    }    
  }
})
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
351

Midoux Cedric's avatar
Midoux Cedric committed
352
### Download Data ###
Midoux Cedric's avatar
Midoux Cedric committed
353
354
355
356
357
dataDownload <- function() {
  modalDialog(
    title = "Download data",
    size = "s",
    textInput("dataName", "File name : ", value = paste("Easy16S-data", Sys.Date(), sep = "-")),
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
358
    radioButtons("dataFormat", "File format : ", choices = c("RData", "RDS", "biom"), selected = "RData", inline = TRUE),
Midoux Cedric's avatar
Midoux Cedric committed
359
360
361
362
363
364
365
366
367
368
369
370
    footer = tagList(modalButton("Cancel"),
                     downloadButton("okDownload", "Download")
    )
  )
}

output$okDownload <- downloadHandler(
  filename = function() {
    paste(input$dataName, input$dataFormat, sep = ".")
  },
  content = function(file) {
    if (input$dataFormat == "RData") {
Midoux Cedric's avatar
Midoux Cedric committed
371
372
      data <- physeq()
      save(data, file = file)
Midoux Cedric's avatar
RDS    
Midoux Cedric committed
373
374
    } else if (input$dataFormat == "RDS") {
      saveRDS(physeq(), file = file)
Midoux Cedric's avatar
Midoux Cedric committed
375
376
    } else if (input$dataFormat == "biom") {
      write_phyloseq(physeq = physeq(), biom_file = file, biom_format = "frogs") #"standard"
Midoux Cedric's avatar
Midoux Cedric committed
377
    }
Midoux Cedric's avatar
Midoux Cedric committed
378
379
  }
)
Midoux Cedric's avatar
Midoux Cedric committed
380

Midoux Cedric's avatar
Midoux Cedric committed
381
### Download Plot ###
Midoux Cedric's avatar
Midoux Cedric committed
382
383
384
385
386
387
388
389
plotDownload <- function() {
  modalDialog(
    title = "Download last modified plot",
    size = "s",
    textInput("plotName", "File name : ", value = "plot"),
    numericInput("plotWidth", "Width : ", value = 7),
    numericInput("plotHeight", "Height : ", value = 7),
    numericInput("plotDPI", "DPI : ", value = 300),
Midoux Cedric's avatar
Midoux Cedric committed
390
    radioButtons("plotFormat", "File format : ", choices = c("png", "pdf", "jpeg", "svg", "wmf"), selected = "png", inline = TRUE),
Midoux Cedric's avatar
Midoux Cedric committed
391
392
393
394
395
396
397
398
399
    footer = tagList(modalButton("Cancel"),
                     downloadButton("okPlot", "Download")
                     )
  )
}

output$okPlot <- downloadHandler(
  filename = function() {paste(input$plotName, input$plotFormat, sep = ".")},
  content = function(file) {ggsave(file, width = input$plotWidth, height = input$plotHeight, dpi = input$plotDPI)}
Midoux Cedric's avatar
Midoux Cedric committed
400
401
)

Midoux Cedric's avatar
Midoux Cedric committed
402
403
404
405
406
407
408
# output$rarefactionMin <- renderText({
#   validate(need(input$fileBiom, ""),
#            need(input$dataset == "input", ""))
#   paste("(min sample =", format(min(sample_sums(data16S(
#     
#   ))), big.mark = " "), "reads)")
# })