dataInput.R 11.8 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 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
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",
        "Rdata" = "rdata"
      ),
      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"
    )
  )
})

observeEvent(input$okData, {
  physeq(NULL)
  try(
    physeq(
      switch(
        input$dataset,
        "demo" =
          {
Midoux Cedric's avatar
Midoux Cedric committed
122
            message <- as.character(input$demo)
123 124 125 126 127 128
            data(GlobalPatterns)
            load("demo/demo.RData")
            get(input$demo)
          },
        "input" =
          {
Midoux Cedric's avatar
Midoux Cedric committed
129
            message <- as.character(input$fileBiom$name)
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
            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
151
            message <- as.character(input$fileRData$name)
152 153 154 155 156 157 158 159 160 161 162 163
            ne <- new.env()
            if (!is.null(input$fileRData))
              {load(input$fileRData$datapath, envir = ne)}
            ne$data
          }
        )
      ),
    silent = TRUE, 
    outFile = showModal(dataInput(failed = TRUE))
    )
  
  if (class(physeq()) == "phyloseq") {
Midoux Cedric's avatar
Midoux Cedric committed
164
    message(paste("[Easy16S] Correct upload with", input$dataset, "mode :", message))
165 166 167 168 169
    removeModal()
  } else {
    showModal(dataInput(failed = TRUE))
  }
})
Midoux Cedric's avatar
Midoux Cedric committed
170

Midoux Cedric's avatar
Midoux Cedric committed
171
### Filter ###
Midoux Cedric's avatar
Midoux Cedric committed
172 173 174
filterSample <- function() {
  modalDialog(
    title = "Select some sample",
Midoux Cedric's avatar
Midoux Cedric committed
175 176 177 178 179 180 181 182 183 184 185 186
    
    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
187 188
    wellPanel(uiOutput("filterUI"), 
              actionLink(inputId = "selectAll", label = "(Un)select All")),
Midoux Cedric's avatar
Midoux Cedric committed
189
    
Midoux Cedric's avatar
Midoux Cedric committed
190 191 192 193 194 195 196
    footer = tagList(modalButton("Cancel"),
                     actionButton(inputId = "okData", label = "Refresh filter"),
                     actionButton(inputId = "selectData", label = "Select")
    )
  )
}

Midoux Cedric's avatar
Midoux Cedric committed
197 198 199
output$filterUI <- renderUI({
  if (is.null(input$filterCriteria))
    return()
Midoux Cedric's avatar
Midoux Cedric committed
200
  
Midoux Cedric's avatar
Midoux Cedric committed
201 202 203
  if (input$filterCriteria == "sample") {
    label <- "Sample to keep :"
    choices <- sample_names(physeq())
Midoux Cedric's avatar
Midoux Cedric committed
204
  } else {
Midoux Cedric's avatar
Midoux Cedric committed
205 206 207
    label <- "Variable to keep :"
    choices <- levels(get_variable(physeq(), input$filterCriteria))
  }
Midoux Cedric's avatar
Midoux Cedric committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  
  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
228 229 230 231 232 233 234 235 236 237
  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
238
    showModal(dataInput(failed = TRUE))
Midoux Cedric's avatar
Midoux Cedric committed
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
  } 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)))
    
    if (class(physeq()) == "phyloseq") {
      removeModal()
    } else {
      showModal(dataInput(failed = TRUE))
    }    
Midoux Cedric's avatar
Midoux Cedric committed
256 257 258
  }
})

Midoux Cedric's avatar
Midoux Cedric committed
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
### 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) {",
                        "  exp(sum(log(x[x > 0 & !is.na(x)]), na.rm=na.rm) / length(x))",
                        "  }",
                        "clr <- function(x, base=2) {",
                        "  x <- log((x / gm_mean(x)), base)",
                        "  x[!is.finite(x) | is.na(x)] <- 0.0",
                        "  return(x)",
                        "}",
                        "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) {
                  exp(sum(log(x[x > 0 & !is.na(x)]), na.rm=na.rm) / length(x))
                }
                clr <- function(x, base=2) {
                  x <- log((x / gm_mean(x)), base)
                  x[!is.finite(x) | is.na(x)] <- 0.0
                  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))
    }    
  }
})
### Download Data ###
Midoux Cedric's avatar
Midoux Cedric committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
dataDownload <- function() {
  modalDialog(
    title = "Download data",
    size = "s",
    textInput("dataName", "File name : ", value = paste("Easy16S-data", Sys.Date(), sep = "-")),
    radioButtons("dataFormat", "File format : ", choices = c("RData", "biom"), selected = "RData", inline = TRUE),
    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
357 358
      data <- physeq()
      save(data, file = file)
Midoux Cedric's avatar
Midoux Cedric committed
359 360
    } else if (input$dataFormat == "biom") {
      write_phyloseq(physeq = physeq(), biom_file = file, biom_format = "frogs") #"standard"
Midoux Cedric's avatar
Midoux Cedric committed
361
    }
Midoux Cedric's avatar
Midoux Cedric committed
362 363
  }
)
Midoux Cedric's avatar
Midoux Cedric committed
364

Midoux Cedric's avatar
Midoux Cedric committed
365
### Download Plot ###
Midoux Cedric's avatar
Midoux Cedric committed
366 367 368 369 370 371 372 373
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
374
    radioButtons("plotFormat", "File format : ", choices = c("png", "pdf", "jpeg", "svg", "wmf"), selected = "png", inline = TRUE),
Midoux Cedric's avatar
Midoux Cedric committed
375 376 377 378 379 380 381 382 383
    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
384 385
)

Midoux Cedric's avatar
Midoux Cedric committed
386 387 388 389 390 391 392
# output$rarefactionMin <- renderText({
#   validate(need(input$fileBiom, ""),
#            need(input$dataset == "input", ""))
#   paste("(min sample =", format(min(sample_sums(data16S(
#     
#   ))), big.mark = " "), "reads)")
# })