server.R 45.4 KB
Newer Older
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1
if (!require("Rcpp")){
2
3
  install.packages("Rcpp")
}
Stevenn Volant's avatar
Stevenn Volant committed
4

5
6
7
8
if(!require(shinydashboard)){
  install.packages('shinydashboard')
  library(shinydashboard)
}
Stevenn Volant's avatar
Stevenn Volant committed
9

10
11
12
if(!require(rjson)){
  install.packages('rjson')
}
Stevenn Volant's avatar
Stevenn Volant committed
13

14
15
if(!require(devtools)){
  install.packages('devtools')
stevenn's avatar
stevenn committed
16
}
17
18

#library(plotly)
Stevenn Volant's avatar
Stevenn Volant committed
19

stevenn's avatar
stevenn committed
20
21
22
23
if (!require(psych)) {
  install.packages('psych')
  library(psych)
}
Stevenn Volant's avatar
Stevenn Volant committed
24

stevenn's avatar
stevenn committed
25
26
27
28
if (!require(ggplot2)) {
  install.packages('ggplot2')
  library(ggplot2)
}
Stevenn Volant's avatar
Stevenn Volant committed
29

stevenn's avatar
stevenn committed
30
31
32
33
if (!require(vegan)) {
  install.packages('vegan')
  library(vegan)
}
Stevenn Volant's avatar
Stevenn Volant committed
34

stevenn's avatar
stevenn committed
35
36
37
38
if (!require(dendextend)) {
  install.packages('dendextend')
  library(dendextend)
}
Stevenn Volant's avatar
Stevenn Volant committed
39

stevenn's avatar
stevenn committed
40
41
42
43
if (!require(circlize)) {
  install.packages('circlize')
  library(circlize)
}
Stevenn Volant's avatar
Stevenn Volant committed
44

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
45
46
47
48
if (!require(d3heatmap)) {
  install.packages('d3heatmap')
  library(d3heatmap)
}
Stevenn Volant's avatar
Stevenn Volant committed
49

stevenn's avatar
stevenn committed
50
51
52
53
if (!require(biom)) {
  install.packages('biom')
  library(biom)
}
Stevenn Volant's avatar
Stevenn Volant committed
54

55
56
if (!require(devtools)) {
  install.packages('devtools')
svolant's avatar
svolant committed
57
58
59
60
61
62
  library(devtools)
}

if (!require(scatterD3)) {
  install.packages('scatterD3')
  library(scatterD3)
63
}
Stevenn Volant's avatar
Stevenn Volant committed
64

65
66
67
if (!require(rNVD3)) {
  library(devtools)
  install_github('rNVD3', 'ramnathv')
68
  library(rNVD3)
69
}
Stevenn Volant's avatar
Stevenn Volant committed
70

Stevenn Volant's avatar
Stevenn Volant committed
71
if (!require(genefilter)) {
72
73
  source("https://bioconductor.org/biocLite.R")
  biocLite("genefilter")
Stevenn Volant's avatar
Stevenn Volant committed
74
75
  library(genefilter)
}
svolant's avatar
svolant committed
76
library(shinyjs)
77
78
# Allow to upload 50M files
options(shiny.maxRequestSize=50*1024^2) 
stevenn's avatar
stevenn committed
79
80
81
82
83
source("internal.R")

renderDataTable <- DT::renderDataTable
dataTableOutput <- DT::dataTableOutput

stevenn's avatar
stevenn committed
84
shinyServer(function(input, output,session) {
stevenn's avatar
stevenn committed
85
86
87
88
  
  
#####################################################
##
stevenn's avatar
stevenn committed
89
##                    LOAD FILES
stevenn's avatar
stevenn committed
90
91
##
#####################################################
stevenn's avatar
stevenn committed
92
  
stevenn's avatar
stevenn committed
93
94
  ## Create base for contrast
  rand = floor(runif(1,0,1e9))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
95
  namesfile = tempfile(pattern = "BaseContrast", tmpdir = tempdir(), fileext = "")
stevenn's avatar
stevenn committed
96
  file.create(namesfile,showWarnings=FALSE)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
97

svolant's avatar
svolant committed
98
99
  ## Popup messages
  observe(if(input$AddRegScatter) info("By adding the regression line, you will loose interactivity."))
stevenn's avatar
stevenn committed
100

stevenn's avatar
stevenn committed
101
  ## Counts file
stevenn's avatar
stevenn committed
102
103
104
105
106
  dataInputCounts <-reactive({ 
    
    inFile <- input$fileCounts
  
    if (is.null(inFile)) return(NULL)
Stevenn Volant's avatar
Stevenn Volant committed
107

stevenn's avatar
stevenn committed
108
    data = read.csv(inFile$datapath,sep="\t",header=TRUE)
stevenn's avatar
stevenn committed
109
110

    ## Rownames
Stevenn Volant's avatar
Stevenn Volant committed
111
112
    if(!TRUE%in%duplicated(data[,1])) rownames(data)=data[,1];data=data[,-1]

stevenn's avatar
stevenn committed
113
114
115
116
117
    return(as.data.frame(data))
  })
  


stevenn's avatar
stevenn committed
118
119
  ## Taxo File
  dataInputTaxo <-reactive({ 
stevenn's avatar
stevenn committed
120
    
stevenn's avatar
stevenn committed
121
    inFile <- input$fileTaxo
stevenn's avatar
stevenn committed
122
    
stevenn's avatar
stevenn committed
123
    if (is.null(inFile)) return(NULL)
stevenn's avatar
stevenn committed
124
    
Stevenn Volant's avatar
Stevenn Volant committed
125
126
127
    if(input$TypeTaxo=="Table") 
    {
      data = read.csv(inFile$datapath,sep="\t",header=TRUE)
svolant's avatar
svolant committed
128
      
Stevenn Volant's avatar
Stevenn Volant committed
129
      ## Rownames
svolant's avatar
svolant committed
130
131
132
133
134
135
136
      if(!TRUE%in%duplicated(data[,1])){ 
        DataNames=data[,1]
        colNames=colnames(data)[-1]
        data=as.matrix(data[,-1])
        rownames(data)=DataNames
        colnames(data) = colNames
        }
Stevenn Volant's avatar
Stevenn Volant committed
137
    }
stevenn's avatar
stevenn committed
138
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
139
140
    if(input$TypeTaxo=="RDP") 
    {
Stevenn Volant's avatar
Stevenn Volant committed
141
      data = read_rdp(inFile$datapath,input$RDP_th)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
142
    }
stevenn's avatar
stevenn committed
143
144
145
    
    ## Add NA
    data=as.matrix(data)
Stevenn Volant's avatar
Stevenn Volant committed
146
    indNa = which(data=="")
stevenn's avatar
stevenn committed
147
148
    data[indNa]=NA
    
stevenn's avatar
stevenn committed
149
    return(as.data.frame(data))
stevenn's avatar
stevenn committed
150
151
152
  })


stevenn's avatar
stevenn committed
153
154
  ## BIOM File
  dataInputBiom <-reactive({ 
stevenn's avatar
stevenn committed
155
    
stevenn's avatar
stevenn committed
156
    inFile <- input$fileBiom
stevenn's avatar
stevenn committed
157
    
stevenn's avatar
stevenn committed
158
    if (is.null(inFile)) return(NULL)
stevenn's avatar
stevenn committed
159
    data = read_biom(inFile$datapath)
stevenn's avatar
stevenn committed
160
    
stevenn's avatar
stevenn committed
161
    return(data)
stevenn's avatar
stevenn committed
162
163
164
  })


stevenn's avatar
stevenn committed
165
166
167

  ## Input data
  dataInput <-reactive({ 
stevenn's avatar
stevenn committed
168
    
stevenn's avatar
stevenn committed
169
    data = NULL
Stevenn Volant's avatar
Stevenn Volant committed
170
171
    check = NULL
    percent = NULL
stevenn's avatar
stevenn committed
172
    
stevenn's avatar
stevenn committed
173
    if(input$FileFormat=="fileCounts")
stevenn's avatar
stevenn committed
174
    {
stevenn's avatar
stevenn committed
175
176
      Counts = dataInputCounts()
      Taxo = dataInputTaxo()
Stevenn Volant's avatar
Stevenn Volant committed
177
178
179
180
181
182
183
      if(!is.null(Counts) && !is.null(Taxo))
      { 
        tmp = GetDataFromCT(Counts,Taxo)
        data = list(counts=tmp$counts,taxo=tmp$taxo)
        check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
        percent = tmp$Percent
      }    
stevenn's avatar
stevenn committed
184
185
    }
    
stevenn's avatar
stevenn committed
186
    if(input$FileFormat=="fileBiom")
stevenn's avatar
stevenn committed
187
    {
stevenn's avatar
stevenn committed
188
      tmpBIOM = dataInputBiom()
Stevenn Volant's avatar
Stevenn Volant committed
189
190
191
192
193
194
195
      if(!is.null(tmpBIOM))
      {
        tmp = GetDataFromBIOM(tmpBIOM)
        data = list(counts=tmp$counts,taxo=tmp$taxo)
        check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
        percent = tmp$Percent
      }
stevenn's avatar
stevenn committed
196
197
    }
    
Stevenn Volant's avatar
Stevenn Volant committed
198
    return(list(data=data,check=check,percent=percent))
stevenn's avatar
stevenn committed
199
200
201
  })
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
202
203
204

  ## Merge counts data
  dataMergeCounts <-reactive({ 
Stevenn Volant's avatar
Stevenn Volant committed
205
    input$RunDESeq
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
206
207
208
    
    counts = NULL
    CheckTarget = FALSE
209
    normFactors = NULL
Stevenn Volant's avatar
Stevenn Volant committed
210
    CT_noNorm = NULL
Stevenn Volant's avatar
Stevenn Volant committed
211
    data = dataInput()$data
212
213
    target = isolate(dataInputTarget())
    taxo = isolate(input$TaxoSelect)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
214
215
216
217
    
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0 && !is.null(taxo) && taxo!="..." && !is.null(target)) 
    {
      design = GetDesign(input)
218
      tmp = isolate(GetCountsMerge(input,data,taxo,target,design))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
219
220
      counts = tmp$counts
      CheckTarget = tmp$CheckTarget
221
      normFactors = tmp$normFactors
Stevenn Volant's avatar
Stevenn Volant committed
222
      CT_noNorm = tmp$CT_noNorm
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
223
    }
Stevenn Volant's avatar
Stevenn Volant committed
224
    return(list(counts=counts,CheckTarget=CheckTarget,normFactors=normFactors,CT_noNorm=CT_noNorm))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
225
226
227
  })


Stevenn Volant's avatar
Stevenn Volant committed
228
229
230
231
232
233
234
  # Infobox Error counts
  output$InfoErrorCounts <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0)
235
    res =infoBox(h6(strong("Count table")), subtitle = h6("Load the count table") ,color = "light-blue",width=NULL,fill=TRUE, icon = icon("upload"))
Stevenn Volant's avatar
Stevenn Volant committed
236
237
238
    
    if(cond)
    {
239
240
241
      if(!is.null(check$CheckCounts$Warning)) res = infoBox(h6(strong("Count table")), subtitle = h6(check$CheckCounts$Warning), icon = icon("warning"),color = "orange",width=NULL,fill=TRUE)
      if(!is.null(check$CheckCounts$Error)) res = infoBox(h6(strong("Count table")), subtitle = h6(check$CheckCounts$Error), icon = icon("thumbs-o-down"),color = "red",width=NULL,fill=TRUE)
      if(is.null(check$CheckCounts$Error) && is.null(check$CheckCounts$Warning)) res = infoBox(h6(strong("Count table")), subtitle = h6(paste("Format of the count table seems to be OK")), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
Stevenn Volant's avatar
Stevenn Volant committed
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
    }
    
    return(res)
  })

  # Infobox Error counts
  output$InfoErrorTaxo <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$taxo) && nrow(data$taxo)>0)
    res =infoBox(h6(strong("Taxonomy table")), subtitle = h6("Load the taxonomy table") ,color = "light-blue",width=NULL,fill=TRUE, icon = icon("upload"))
    
    if(cond)
    {
      if(!is.null(check$CheckTaxo$Warning)) res = infoBox(h6(strong("Taxonomy table")), subtitle = h6(check$CheckTaxo$Warning), icon = icon("warning"),color = "orange",width=NULL,fill=TRUE)
      if(!is.null(check$CheckTaxo$Error)) res = infoBox(h6(strong("Taxonomy table")), subtitle = h6(check$CheckTaxo$Error), icon = icon("thumbs-o-down"),color = "red",width=NULL,fill=TRUE)
      if(is.null(check$CheckTaxo$Error) && is.null(check$CheckTaxo$Warning)) res = infoBox(h6(strong("Taxonomy table")), subtitle = h6(paste("Format of the taxonomy table seems to be OK")), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
    }
    
    return(res)
  })


  # Infobox Error counts
  output$valueErrorPercent <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0 && !is.null(data$taxo) && nrow(data$taxo)>0)
    res = valueBox(paste0(0, "%"),h6(strong("Annotated features")), color = "light-blue",width=NULL,icon = icon("list"))
    
    if(cond)
    {
      percent = round(100*tmp$percent,2)
      if(percent==0) res = valueBox(paste0(percent, "%"),h6(strong("Annotated features")), color = "red",width=NULL,icon = icon("list"))  
      if(percent!=0) res = valueBox(paste0(percent, "%"),h6(strong("Annotated features")), color = "green",width=NULL,icon = icon("list"))  
      
    }
    
    return(res)
  })


stevenn's avatar
stevenn committed
288
  
stevenn's avatar
stevenn committed
289
290
291
292
293
#####################################################
##
##                DYNAMIC MENU
##
#####################################################
stevenn's avatar
stevenn committed
294
295
296
297
298
  
  
  
  output$dymMenu <- renderMenu({
    
Stevenn Volant's avatar
Stevenn Volant committed
299
300
301
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
stevenn's avatar
stevenn committed
302
    
Stevenn Volant's avatar
Stevenn Volant committed
303
304
305
306
    ## Check error in the counts and taxonomy table 
    CheckOK = (is.null(check$CheckCounts$Error) && is.null(check$CheckTaxo$Error)  && is.null(check$CheckPercent))

    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0 && CheckOK)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
307
    {
stevenn's avatar
stevenn committed
308
      sidebarMenu(
stevenn's avatar
stevenn committed
309
310
        menuItem("Statistical analysis",
                 menuSubItem("Run differential analysis",tabName="RunDiff"),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
311
                 menuSubItem("Diagnostic plots",tabName="DiagPlotTab"),
stevenn's avatar
stevenn committed
312
                 menuSubItem("Tables",tabName="TableDiff"),
313
314
315
                 icon = icon("bar-chart-o"), tabName = "AnaStat"
        ),
        menuItem("Visualization",icon = icon("area-chart"), tabName = "Visu"),
Stevenn Volant's avatar
Stevenn Volant committed
316
        menuItem("Perspective plots", icon = icon("pie-chart"), tabName = "Krona")
stevenn's avatar
stevenn committed
317

stevenn's avatar
stevenn committed
318
      )
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
319
     }
Stevenn Volant's avatar
Stevenn Volant committed
320
    else{
321
      sidebarMenu()
Stevenn Volant's avatar
Stevenn Volant committed
322
323
    }
    
stevenn's avatar
stevenn committed
324
325
326
327
328
329
330
331
332
333
334
335
  })
  
  

  #####################################################
  ##
  ##                DATA TABLE
  ##
  #####################################################
  
  ## Counts Table
  output$DataCounts <- renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
336
    dataInput()$data$counts, 
stevenn's avatar
stevenn committed
337
338
339
340
341
342
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
                   pageLength = 10,scrollX=TRUE
    ))
  
  ## Taxonomy table
  output$DataTaxo <- renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
343
    dataInput()$data$taxo, 
stevenn's avatar
stevenn committed
344
345
346
347
348
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
                   pageLength = 10,scrollX=TRUE
    ))

  
stevenn's avatar
stevenn committed
349
  ## Tab box for data visualisation
stevenn's avatar
stevenn committed
350
351
  output$TabBoxData <- renderUI({
    
Stevenn Volant's avatar
Stevenn Volant committed
352
    data=dataInput()$data
stevenn's avatar
stevenn committed
353
354
355
    
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0)
    {
356
357
      tabBox(width = NULL, selected = "Count table",
             tabPanel("Count table",dataTableOutput("DataCounts")),
stevenn's avatar
stevenn committed
358
359
             tabPanel("Taxonomy",dataTableOutput("DataTaxo"))  
      )
stevenn's avatar
stevenn committed
360
    }
stevenn's avatar
stevenn committed
361
    
stevenn's avatar
stevenn committed
362
  })
stevenn's avatar
stevenn committed
363
364
365
366
367
368
369


  #####################################################
  ##
  ##                TARGET FILE
  ##
  #####################################################
stevenn's avatar
stevenn committed
370
  
stevenn's avatar
stevenn committed
371
372
373
374
375

  ## Load target file
  dataInputTarget <-reactive({ 
    
    inFile <- input$fileTarget
Stevenn Volant's avatar
Stevenn Volant committed
376
    counts = dataInput()$data$counts
stevenn's avatar
stevenn committed
377
378
379
380
    if (is.null(inFile)) return(NULL)
    
    
    data = read.csv(inFile$datapath,sep="\t",header=TRUE)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
381
382
383
384
385
    rownames(data) <- as.character(data[, 1])
    #ord = order(rownames(data))
    #data = data[ord,]
    ### A SUPPRIMER 
    #rownames(data) <- colnames(counts)
stevenn's avatar
stevenn committed
386
    return((data))
stevenn's avatar
stevenn committed
387
388
389
390
391
392
393
394
395
396
397
398
  })



  ## Interest Variables
  output$SelectInterestVar <- renderUI({
        
    target=dataInputTarget()
    
    if(!is.null(target)) 
    {
      namesTarget = colnames(target)[2:ncol(target)]
Stevenn Volant's avatar
Stevenn Volant committed
399
      selectInput("InterestVar",h6(strong("Select the variables")),namesTarget,selected=namesTarget,multiple=TRUE)
stevenn's avatar
stevenn committed
400
    }
stevenn's avatar
stevenn committed
401
  
stevenn's avatar
stevenn committed
402
  })
stevenn's avatar
stevenn committed
403

stevenn's avatar
stevenn committed
404
405
406
407
408
409
410
411
412
413
414

  ## Interactions
  output$SelectInteraction2 <- renderUI({
        
    target = dataInputTarget()

    if(!is.null(target)) 
    {
      Interac = GetInteraction2(target)
      selectInput("Interaction2",h6(strong("Add interactions")),Interac,selected=NULL,multiple=TRUE)
    }
stevenn's avatar
stevenn committed
415
    
stevenn's avatar
stevenn committed
416
417
418
419
420
  })


  ## Reference radio buttons
  output$RefSelect <- renderUI({
stevenn's avatar
stevenn committed
421
    
stevenn's avatar
stevenn committed
422
423
424
    target = dataInputTarget()
    RB=list()
    if(!is.null(target)) 
stevenn's avatar
stevenn committed
425
    {
stevenn's avatar
stevenn committed
426
427
428
429
430
431
432
433
434
435
      InterVar = input$InterestVar
      if(length(InterVar)>0)
      {
        names = paste0("Ref",InterVar)
          for(i in 1:length(names))
          {
            val = unique(target[,InterVar[i]])
            RB[[i]] = selectInput(names[i],paste("Reference for",InterVar[i]),as.vector(val))
          }
      }
stevenn's avatar
stevenn committed
436
    }
stevenn's avatar
stevenn committed
437
    return(RB)
stevenn's avatar
stevenn committed
438
    
stevenn's avatar
stevenn committed
439
440
441
  })


stevenn's avatar
stevenn committed
442
443
444
445
446
447
448
449
450
451
  # Infobox design
  output$RowTarget <- renderInfoBox({
    
    target = dataInputTarget()
    
    if(!is.null(target)) 
    {
      #### Ajout fontion check target
      infoBox(h6(strong("Target file")), subtitle = h6("Your target file is OK"), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
    }
452
    else infoBox(h6(strong("Target file")), subtitle = h6("Label of the target file must correspond to count table column names") ,color = "light-blue",width=NULL,fill=TRUE, icon = icon("warning"))
stevenn's avatar
stevenn committed
453
454
455
456
457
  })




Amine  GHOZLANE's avatar
Amine GHOZLANE committed
458
  ## target table
stevenn's avatar
stevenn committed
459
460
461
462
463
464
  output$DataTarget <- renderDataTable(
  dataInputTarget(),
  options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
                 pageLength = 10,scrollX=TRUE
  ))

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
465
466
  ## Counts table for the selected taxonomy level
  output$CountsMerge <- renderDataTable(
467
    round(counts(ResDiffAnal()$dds,normalized=TRUE)),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
468
469
470
471
472
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
                   pageLength = 10,scrollX=TRUE
    ))


Stevenn Volant's avatar
Stevenn Volant committed
473
  ## Box for merged counts
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
474
475
476
477
478
479
480
  output$BoxCountsMerge <- renderUI({
    
    counts = dataMergeCounts()$counts
    taxo = input$TaxoSelect
    
    if(!is.null(counts) && taxo != "...")
    {
481
      box(title=paste("Count table (",taxo,")",sep=""),width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = TRUE,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
482
483
484
485
486
487
488
489
490
491
          dataTableOutput("CountsMerge"),
          downloadButton('ExportCounts', 'Export normalised counts'),
          downloadButton('ExportRelative', 'Export relative abundance')
      )  
    }
    
  })

  ## Export in .csv
  output$ExportCounts <- downloadHandler(
Stevenn Volant's avatar
Stevenn Volant committed
492
493
    filename = function() { 'NormCounts.csv' },
    content = function(file){write.csv(dataMergeCounts()$counts, file)}
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
494
  )
stevenn's avatar
stevenn committed
495
496
497
498

  ## Export in .csv
  output$ExportRelative <- downloadHandler(
    filename = function() { 'RelativeAb.csv' },
Stevenn Volant's avatar
Stevenn Volant committed
499
    content = function(file){write.csv(dataMergeCounts()$counts/colSums(dataMergeCounts()$counts), file)}
stevenn's avatar
stevenn committed
500
  )
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
501
502


stevenn's avatar
stevenn committed
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
  ## Box for target visualisation
  output$BoxTarget <- renderUI({
    
    target = dataInputTarget()
    
    if(!is.null(target) &&  nrow(target)>0)
    {
      box(title="Target file overview",width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = TRUE,
          dataTableOutput("DataTarget")
      )  
    }
    
  })


stevenn's avatar
stevenn committed
518
519
520
521
522
523
524
525
526

#####################################################
##
##            DEFINE CONTRAST
##
#####################################################
  
  output$contrastMat <- renderUI({
    
stevenn's avatar
stevenn committed
527
528
529
530
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)

stevenn's avatar
stevenn committed
531
532
    Contrast=list()
    
533
    for(i in 1:length(names)){Contrast[[i]] = numericInput(names[i],names[i],0,step=1,min=-1,max=1)}
stevenn's avatar
stevenn committed
534
535
536
537
538
539
  
    return(Contrast)
    
  })


stevenn's avatar
stevenn committed
540
541
542
543
544
  output$ContrastOverview <- renderPrint({
    
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)
stevenn's avatar
stevenn committed
545
546
    
    cont = input$ContrastList
stevenn's avatar
stevenn committed
547
    filesize = file.info(namesfile)[,"size"]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
548
    if(is.na(filesize)){filesize=0}
stevenn's avatar
stevenn committed
549
550
551
552
553
554
    if(filesize!=0)
    { 
      ContrastBase = read.table(namesfile,header=TRUE)
      ind = which(colnames(ContrastBase)%in%cont)
      div(HTML(PrintContrasts(names,sapply(ContrastBase[,ind],as.numeric),cont)))
    }
stevenn's avatar
stevenn committed
555
556
557
  })


stevenn's avatar
stevenn committed
558
559
560
561
562
563
  ## Add contrast function
  AddCont <-eventReactive(input$AddContrast,{
    
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)
Stevenn Volant's avatar
Stevenn Volant committed
564

stevenn's avatar
stevenn committed
565
    BaseContrast(input,names,namesfile)
Stevenn Volant's avatar
Stevenn Volant committed
566
567
568
    filesize = file.info(namesfile)[,"size"]
    if(is.na(filesize)){filesize=0}
    if(filesize!=0) tmp = read.table(namesfile,header=TRUE)
stevenn's avatar
stevenn committed
569
570
    Contrast = colnames(as.matrix(tmp))
    updateSelectInput(session, "ContrastList","Contrasts",Contrast)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
571
    updateSelectInput(session, "ContrastList_table","Contrasts",Contrast)
572
573
    updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",Contrast)
    updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",Contrast)
stevenn's avatar
stevenn committed
574
  })
stevenn's avatar
stevenn committed
575

stevenn's avatar
stevenn committed
576
577
  ## Add contrast 
  observeEvent(input$AddContrast,{  
stevenn's avatar
stevenn committed
578
    
stevenn's avatar
stevenn committed
579
    AddCont()
stevenn's avatar
stevenn committed
580
    
Stevenn Volant's avatar
Stevenn Volant committed
581
  },priority=1)
stevenn's avatar
stevenn committed
582

583
584
585
586
587
588
589
590
591
592
593
594
595

  ## Add contrast function
  AddContEasy <-eventReactive(input$AddContrastEasy,{
    
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)
#     
#     BaseContrast(input,names,namesfile)
#     tmp = read.table(namesfile,header=TRUE)
#     Contrast = colnames(as.matrix(tmp))
    updateSelectInput(session, "ContrastList","Contrasts",Contrast)
    updateSelectInput(session, "ContrastList_table","Contrasts",Contrast)
596
597
    updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",Contrast)
    updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",Contrast)
598
  })
stevenn's avatar
stevenn committed
599
  
600
601
602
603
604
605
606
607
608
609
610
611
612
  ## Add contrast 
  observeEvent(input$AddContrastEasy,{  
    
    AddContEasy()
    
  })


  AddContFromFile <-eventReactive(input$fileContrast,{ 
    
    res = ReadContrastFile()
    createdCont = NULL
    filesize = file.info(namesfile)[,"size"]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
613
    if(is.na(filesize)){filesize=0}
614
615
616
617
618
619
620
    if(filesize!=0){ createdCont = read.table(namesfile,header=TRUE) }
      
    if(!is.null(res))
    { 
      if(!is.null(createdCont)) res = cbind(res,createdCont)
      updateSelectInput(session, "ContrastList","Contrasts",colnames(res))
      updateSelectInput(session, "ContrastList_table","Contrasts",colnames(res))
621
622
      updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",colnames(res))
      updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",colnames(res))
623
624
625
626
627
628
629
      write.table(res,namesfile,row.names=FALSE)
    }
  })
 
 observeEvent(input$fileContrast,{ 
    
   AddContFromFile()
Stevenn Volant's avatar
Stevenn Volant committed
630
  },priority=1)
631
632


stevenn's avatar
stevenn committed
633
634
635
636
637
  ## Remove contrast function
  RemoveCont <-eventReactive(input$RemoveContrast,{
    
    ## get the size of the contrast base file
    filesize = file.info(namesfile)[,"size"]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
638
    if(is.na(filesize)){filesize=0}
stevenn's avatar
stevenn committed
639
640
641
642
643
644
    if(filesize!=0)
    { 
      tmp = read.table(namesfile,header=TRUE)
      ind = which(colnames(tmp)%in%input$ContrastList)
      matKept = as.matrix(tmp[,-ind])
      ContrastKept = colnames(tmp)[-ind]
stevenn's avatar
stevenn committed
645
      
stevenn's avatar
stevenn committed
646
647
648
      if(ncol(matKept)>0) write.table(matKept,namesfile,row.names=FALSE,col.names = ContrastKept)
      else file.create(namesfile,showWarnings=FALSE)
      updateSelectInput(session, "ContrastList","Contrasts",ContrastKept)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
649
      updateSelectInput(session, "ContrastList_table","Contrasts",ContrastKept)
650
651
      updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",ContrastKept)
      updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",ContrastKept)
stevenn's avatar
stevenn committed
652
    }
stevenn's avatar
stevenn committed
653
654
655
656
657
658
659
660
661
  })
  
  
  
  ## Remove contrast
  observeEvent(input$RemoveContrast,{  
    
    RemoveCont()
    
Stevenn Volant's avatar
Stevenn Volant committed
662
  },priority=1)
stevenn's avatar
stevenn committed
663

Stevenn Volant's avatar
Stevenn Volant committed
664
665
666
667
668
669
670
671
672
  ## Remove all contrasts
  RemoveAllCont <-eventReactive(input$RunDESeq,{
    
      file.create(namesfile,showWarnings=FALSE)
      updateSelectInput(session, "ContrastList","Contrasts",NULL)
      updateSelectInput(session, "ContrastList_table","Contrasts",NULL)
      updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",NULL)
      updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",NULL)
  })
stevenn's avatar
stevenn committed
673

Stevenn Volant's avatar
Stevenn Volant committed
674
675
  ## Remove all contrast
  observeEvent(input$RunDESeq,{  
stevenn's avatar
stevenn committed
676
    
Stevenn Volant's avatar
Stevenn Volant committed
677
    RemoveAllCont()
stevenn's avatar
stevenn committed
678
    
Stevenn Volant's avatar
Stevenn Volant committed
679
680
681
682
  })

# Infobox Contrast
output$InfoContrast <- renderInfoBox({
683
  input$RunDESeq
Stevenn Volant's avatar
Stevenn Volant committed
684
685
686
  input$AddContrast
  input$RemoveContrast
  input$fileContrast
687
688
689
  resDiff = ResDiffAnal()
  res=NULL
  if(!is.null(resDiff)){
Stevenn Volant's avatar
Stevenn Volant committed
690
  
svolant's avatar
svolant committed
691
692
693
694
695
696
697
698
699
700
701
702
    res = infoBox("Contrasts", subtitle = h6("At least one contrast (non null) must be defined"), icon = icon("warning"),color = "light-blue",width=NULL,fill=TRUE)
    test = FALSE
    filesize = isolate(file.info(namesfile)[,"size"])
    
    if(is.na(filesize)){filesize=0}
    if(filesize!=0) 
    {
      tmp = read.table(namesfile,header=TRUE)
      if(any(as.vector(tmp)!=0)) test = TRUE
    }
    
    if(test) res = infoBox("Contrasts", subtitle = h6("Contrasts OK"), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
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
    return(res)
  })


  
  output$contrastBox <- renderUI({
    
    resDiff = ResDiffAnal()
    int = input$Interaction2
    target = resDiff$target
    
    InterVar = input$InterestVar
    ModInterestAll = unique(target[,InterVar])
    test = c()
    for(i in 1:length(InterVar)){ test =c(test,input$Select1_contrast%in%target[,InterVar[i]]) }
    
    ModInterestCond = unique(target[,which(test)])
    #alltmp = c(InterVar,Interaction)
    
    if(!is.null(resDiff))
    { 
      box(title="Contrasts",width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = FALSE,
          fluidRow(
            column(width=3,selectInput("Select1_contrast",label=h6(strong("Compare")),ModInterestAll)),
            column(width=3,selectInput("Select2_contrast",label=h6(strong("To")),ModInterestCond)),
            if(length(int)>=1) column(width=3,selectInput("Select3_contrast",label=h6(strong("For")),c("All","WT","Delta"))),
            column(width=3,br(),br(),actionButton("AddContrastEasy","Add",icon = icon("plus")))
          )
      )
    }
    
  })


  output$contrastBoxAdvanced <- renderUI({
    
    resDiff = ResDiffAnal()
    
    if(!is.null(resDiff))
    { 
Stevenn Volant's avatar
Stevenn Volant committed
744
      box(title="Contrasts (advanced user)",width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = FALSE,
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
          fluidRow(
            column(width=12,
                   fileInput('fileContrast', h6(strong('Select a file of contrasts')),width="60%")
            ),
            hr(),
            column(width=12,h6(strong("Define contrasts by yourself"))),
            column(width=6,textInput("ContrastName",label = NULL,value = "Contrast name")),
            column(width=6,actionButton("AddContrast","Add contrast",icon = icon("plus")))
          ),
          fluidRow(column(width=12,uiOutput("contrastMat")))
      )
    }
    
  })


  output$contrastDefined <- renderUI({
    resDiff = ResDiffAnal()
    
    if(!is.null(resDiff))
    { 
      box(title="Defined contrasts",width = NULL, status = "primary", solidHeader = TRUE,collapsible = FALSE,collapsed = FALSE,
          fluidRow(
            column(width=11,
                   selectInput("ContrastList","Contrasts","",multiple=TRUE,size=4,selectize=FALSE,width = '100%'),
                   fluidRow(
                      column(width=6,actionButton("RemoveContrast","Remove",icon = icon("remove"))),
                      column(width=6,downloadButton("exportContrast", "Export"))
                   ),
                   htmlOutput("ContrastOverview")
            )
            
          )
      )
stevenn's avatar
stevenn committed
779
    }
stevenn's avatar
stevenn committed
780
781
  })

stevenn's avatar
stevenn committed
782

783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
  ReadContrastFile <-reactive({ 
    
    inFile <- input$fileContrast
    
    if (is.null(inFile)) return(NULL)
    
    res = read.csv(inFile$datapath,sep=" ",header=TRUE)
    
    return(res)
  })
  

  output$exportContrast <- downloadHandler(
    filename <- function() {"Contrasts.txt"},
    content <- function(file) {
      file.copy(namesfile,file)
    }
  )



stevenn's avatar
stevenn committed
804
805
806
807
808
809
810
811
812
813
814

#####################################################
##
##                DESEQ2 run
##
#####################################################



  # Infobox Contrast
  output$InfoDESeq <- renderInfoBox({
815
      input$RunDESeq
816
817
818
819
820
      
      resDiff = ResDiffAnal()
      if(!is.null(resDiff)){
        infoBox(h6(strong("Statistical analysis")), subtitle = h6("Differential analysis is done !"), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
      }
stevenn's avatar
stevenn committed
821

stevenn's avatar
stevenn committed
822
823
    
  })
stevenn's avatar
stevenn committed
824
  
stevenn's avatar
stevenn committed
825

stevenn's avatar
stevenn committed
826
827
828
  ## Get the results from DESeq2
  ResDiffAnal <-eventReactive(input$RunDESeq,{
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
829
    counts = dataMergeCounts()$counts
Stevenn Volant's avatar
Stevenn Volant committed
830
    CT_noNorm = dataMergeCounts()$CT_noNorm
831
    normFactors = dataMergeCounts()$normFactors
stevenn's avatar
stevenn committed
832
833
834
    target = dataInputTarget()
    design = GetDesign(input)
   
Stevenn Volant's avatar
Stevenn Volant committed
835
    Get_dds_object(input,counts,target,design,normFactors,CT_noNorm)
stevenn's avatar
stevenn committed
836
837
838

    
  })
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
839
840


stevenn's avatar
stevenn committed
841
  ## Run DESeq2 via RunDESeq button
842
  observeEvent(input$RunDESeq,{
Stevenn Volant's avatar
Stevenn Volant committed
843
    withProgress(message="Analysis in progress...",ResDiffAnal())
stevenn's avatar
stevenn committed
844
  })
stevenn's avatar
stevenn committed
845

stevenn's avatar
stevenn committed
846
  
stevenn's avatar
stevenn committed
847
848
849
850
851
#####################################################
##
##                Taxonomy
##
#####################################################
stevenn's avatar
stevenn committed
852
853
  
  
stevenn's avatar
stevenn committed
854
855
  # Infobox Contrast
  output$SelectTaxo <- renderUI({
stevenn's avatar
stevenn committed
856
    
Stevenn Volant's avatar
Stevenn Volant committed
857
    data = dataInput()$data
stevenn's avatar
stevenn committed
858
859
860
    if(!is.null(data$taxo) && nrow(data$taxo)>0)
    { 
      tmp = colnames(data$taxo)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
861
      selectInput("TaxoSelect",h6(strong("Select the taxonomy level")),c("...",tmp,"OTU"))
stevenn's avatar
stevenn committed
862
    }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
863
    else selectInput("TaxoSelect",h6(strong("Select the taxonomy level")),c("..."))
stevenn's avatar
stevenn committed
864
865
866
867
868
869
870
871
872

  })
  


  
  # Infobox taxo
  output$InfoTaxo <- renderInfoBox({
  
Stevenn Volant's avatar
Stevenn Volant committed
873
    data = dataInput()$data
stevenn's avatar
stevenn committed
874
    taxo = input$TaxoSelect
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
875
876
    
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0 && !is.null(taxo) && taxo!="...") 
stevenn's avatar
stevenn committed
877
    {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
878
879
880
      counts = dataMergeCounts()$counts
      nfeature = nrow(counts)
      infoBox(h6(strong("Taxonomy")), subtitle = h6(paste(taxo, ", nb features: ",nfeature,sep="")), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
stevenn's avatar
stevenn committed
881
    }
882
    else infoBox(h6(strong("Taxonomy")), subtitle = h6("Select the taxonomy for the analysis") ,color = "light-blue",width=NULL,fill=TRUE, icon = icon("warning"))
stevenn's avatar
stevenn committed
883
884
885
886
887
888
889
890
891
892
893
894
  })



#####################################################
##
##                Diagnostic plots
##
#####################################################


  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
895
  output$VarIntDiag <- renderUI({
stevenn's avatar
stevenn committed
896
    
897
    target=dataInputTarget()
stevenn's avatar
stevenn committed
898
    
899
900
901
902
903
    if(!is.null(target)) 
    {
      namesTarget = colnames(target)[2:ncol(target)]
      selectizeInput("VarInt",h6(strong("Select the variables of interest (max 2)")),namesTarget, selected = namesTarget[1],multiple = TRUE,options = list(maxItems = 2))
    }
stevenn's avatar
stevenn committed
904
905
906
907
908
    
  })
  
  
  output$PlotDiag <- renderPlot({
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
909
    input$RunDESeq
stevenn's avatar
stevenn committed
910
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
911
    resDiff = isolate(ResDiffAnal())
stevenn's avatar
stevenn committed
912
    Plot_diag(input,resDiff)
Stevenn Volant's avatar
Stevenn Volant committed
913
914
915
  },height = reactive(input$heightDiag))


stevenn's avatar
stevenn committed
916

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
917
918
919
920
  output$PlotpcoaEigen <- renderPlot({
    
    resDiff = ResDiffAnal()
    Plot_diag_pcoaEigen(input,resDiff)
Stevenn Volant's avatar
Stevenn Volant committed
921
  },height = 400)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
922
923
924
925
926

  output$PlotEigen <- renderPlot({
    
    resDiff = ResDiffAnal()
    Plot_diag_Eigen(input,resDiff)
Stevenn Volant's avatar
Stevenn Volant committed
927
  },height =400)
stevenn's avatar
stevenn committed
928
929
930

  SizeFactor_table <-reactive({ 
    res = ResDiffAnal()
931
    return(t(data.frame(Factor=res$normFactors)))
stevenn's avatar
stevenn committed
932
933
934
    
  })

stevenn's avatar
stevenn committed
935
936
937
938
939
  output$SizeFactTable <- renderDataTable(
    SizeFactor_table(),
    options = list(scrollX=TRUE,searching = FALSE
  ))

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
940

941
  ## Select Modality DiagPlot
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957

  output$ModMat <- renderUI({
    
    VarInt = input$VarInt
    target = dataInputTarget()
    
    Mod = list()
    
    for(i in 1:length(VarInt)){
      value = as.character(unique(as.factor(target[,VarInt[i]])))
      Mod[[i]] = selectizeInput(paste("Mod",VarInt[i],sep=""),VarInt[i],value,selected=value, multiple = TRUE)
    }
  
    return(Mod)
    
  })
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
  
  
  ## Select Modality VisuPlot
  
  output$ModVisu <- renderUI({
    Mod = NULL
    
    VisuVarInt = input$VisuVarInt
    target = dataInputTarget()
    if(!is.null(VisuVarInt))
    {
      Mod = list()
      
      for(i in 1:length(VisuVarInt)){
        value = as.character(unique(as.factor(target[,VisuVarInt[i]])))
        Mod[[i]] = selectizeInput(paste("ModVisu",VisuVarInt[i],sep=""),VisuVarInt[i],value,selected=value, multiple = TRUE)
      }
    }
    return(Mod)
    
  })
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
981

stevenn's avatar
stevenn committed
982
983
#####################################################
##
stevenn's avatar
stevenn committed
984
##                EXPORT DIAG GRAPH
stevenn's avatar
stevenn committed
985
986
987
##
#####################################################

stevenn's avatar
stevenn committed
988
989
  #### Export Diag
  output$exportdiag <- downloadHandler(
Stevenn Volant's avatar
Stevenn Volant committed
990
    filename <- function() { paste(input$DiagPlot,paste('SHAMAN',input$Exp_format,sep="."),sep="_") },
stevenn's avatar
stevenn committed
991
    content <- function(file) {
stevenn's avatar
stevenn committed
992
993
994
995
996
      if(input$Exp_format=="png") png(file, width = input$widthDiagExport, height = input$heightDiagExport)
      if(input$Exp_format=="pdf") pdf(file, width = input$widthDiagExport/96, height = input$heightDiagExport/96)
      if(input$Exp_format=="eps") postscript(file, width = input$widthDiagExport/96, height = input$heightDiagExport/96)
      if(input$Exp_format=="svg") svg(file, width = input$widthDiagExport/96, height = input$heightDiagExport/96)
      
stevenn's avatar
stevenn committed
997
998
999
1000
      print(Plot_diag(input,ResDiffAnal()))
      dev.off()
    }
  )