server.R 70.5 KB
Newer Older
1
source('LoadPackages.R')
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
2

stevenn's avatar
stevenn committed
3
shinyServer(function(input, output,session) {
svolant's avatar
svolant committed
4
5
6

  hide(id = "loading-content", anim = TRUE, animType = "fade",time=1.5)
  hide(id = "loading-content-bar", anim = TRUE, animType = "fade",time=1.5)
7
8
9
10
11
  #####################################################
  ##
  ##                    LOAD FILES
  ##
  #####################################################
stevenn's avatar
stevenn committed
12
  
stevenn's avatar
stevenn committed
13
14
  ## Create base for contrast
  rand = floor(runif(1,0,1e9))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
15
  namesfile = tempfile(pattern = "BaseContrast", tmpdir = tempdir(), fileext = "")
stevenn's avatar
stevenn committed
16
  file.create(namesfile,showWarnings=FALSE)
17
  
svolant's avatar
svolant committed
18
  ## Popup messages
svolant's avatar
svolant committed
19
  observe(if(input$AddRegScatter) info("By adding the regression line, you will lose interactivity."))
20
  
svolant's avatar
svolant committed
21

stevenn's avatar
stevenn committed
22
  ## Counts file
stevenn's avatar
stevenn committed
23
  dataInputCounts <-reactive({ 
24
    
svolant's avatar
svolant committed
25
    data = NULL
stevenn's avatar
stevenn committed
26
    inFile <- input$fileCounts
27
    
stevenn's avatar
stevenn committed
28
    if (is.null(inFile)) return(NULL)
29
30
    
    
svolant's avatar
svolant committed
31
32
33
34
35
36
37
    try(read.csv(inFile$datapath,sep=input$sepcount,header=TRUE,check.names=FALSE)->data,silent=T)

    if(!is.null(data)){
      colnames(data) = gsub("-",".",colnames(data))
      ## Rownames
      if(!TRUE%in%duplicated(data[,1])) rownames(data)=data[,1];data=data[,-1]
    }
stevenn's avatar
stevenn committed
38
39
40
    return(as.data.frame(data))
  })
  
41
42
  
  
stevenn's avatar
stevenn committed
43
44
  ## Taxo File
  dataInputTaxo <-reactive({ 
stevenn's avatar
stevenn committed
45
    
stevenn's avatar
stevenn committed
46
    inFile <- input$fileTaxo
stevenn's avatar
stevenn committed
47
    
stevenn's avatar
stevenn committed
48
    if (is.null(inFile)) return(NULL)
49
    
Stevenn Volant's avatar
Stevenn Volant committed
50
51
    if(input$TypeTaxo=="Table") 
    {
svolant's avatar
svolant committed
52
53
      try(read.csv(inFile$datapath,sep=input$septaxo,header=TRUE)->data,silent=T)
    
Stevenn Volant's avatar
Stevenn Volant committed
54
      ## Rownames
svolant's avatar
svolant committed
55
56
57
58
59
60
61
62
63
      if(!is.null(data))
      {
        if(!TRUE%in%duplicated(data[,1])){ 
          DataNames=data[,1]
          colNames=colnames(data)[-1]
          data=as.matrix(data[,-1])
          rownames(data)=DataNames
          colnames(data) = colNames
        }
64
      }
Stevenn Volant's avatar
Stevenn Volant committed
65
    }
stevenn's avatar
stevenn committed
66
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
67
68
    if(input$TypeTaxo=="RDP") 
    {
Stevenn Volant's avatar
Stevenn Volant committed
69
      data = read_rdp(inFile$datapath,input$RDP_th)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
70
    }
stevenn's avatar
stevenn committed
71
72
73
    
    ## Add NA
    data=as.matrix(data)
Stevenn Volant's avatar
Stevenn Volant committed
74
    indNa = which(data=="")
stevenn's avatar
stevenn committed
75
76
    data[indNa]=NA
    
stevenn's avatar
stevenn committed
77
    return(as.data.frame(data))
stevenn's avatar
stevenn committed
78
  })
79
80
  
  
stevenn's avatar
stevenn committed
81
82
  ## BIOM File
  dataInputBiom <-reactive({ 
stevenn's avatar
stevenn committed
83
    
svolant's avatar
svolant committed
84
    data = NULL
stevenn's avatar
stevenn committed
85
    inFile <- input$fileBiom
stevenn's avatar
stevenn committed
86
    
stevenn's avatar
stevenn committed
87
    if (is.null(inFile)) return(NULL)
svolant's avatar
svolant committed
88
    try(read_biom(inFile$datapath)->data,silent=T)
stevenn's avatar
stevenn committed
89
    
stevenn's avatar
stevenn committed
90
    return(data)
stevenn's avatar
stevenn committed
91
  })
92
93
94
  
  
  
stevenn's avatar
stevenn committed
95
96
  ## Input data
  dataInput <-reactive({ 
stevenn's avatar
stevenn committed
97
    
stevenn's avatar
stevenn committed
98
    data = NULL
Stevenn Volant's avatar
Stevenn Volant committed
99
100
    check = NULL
    percent = NULL
svolant's avatar
svolant committed
101
102
    Taxo = NULL
    Counts = NULL
stevenn's avatar
stevenn committed
103
    if(input$FileFormat=="fileCounts")
stevenn's avatar
stevenn committed
104
    {
stevenn's avatar
stevenn committed
105
      Counts = dataInputCounts()
svolant's avatar
svolant committed
106
107
108
      if(!input$NoTaxoFile) Taxo = dataInputTaxo()
      if(!is.null(Counts) && input$NoTaxoFile) {Taxo = data.frame(rownames(Counts),row.names = rownames(Counts));names(Taxo)=NA}
      
Stevenn Volant's avatar
Stevenn Volant committed
109
110
111
112
113
114
115
      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
116
117
    }
    
stevenn's avatar
stevenn committed
118
    if(input$FileFormat=="fileBiom")
stevenn's avatar
stevenn committed
119
    {
stevenn's avatar
stevenn committed
120
      tmpBIOM = dataInputBiom()
Stevenn Volant's avatar
Stevenn Volant committed
121
122
123
124
125
126
127
      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
128
129
    }
    
Stevenn Volant's avatar
Stevenn Volant committed
130
    return(list(data=data,check=check,percent=percent))
stevenn's avatar
stevenn committed
131
132
133
  })
  
  
134
  
135
136
137
138
139
140
141
142
143
  
  
  ## Size factor file (optional)
  dataSizeFactors <-reactive({ 
    
    inFile <- input$fileSizeFactors
    
    if (is.null(inFile)) return(NULL)
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
144
    data = read.csv(inFile$datapath,sep=input$sepsize,header=TRUE)
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    return(as.data.frame(data))
  })
  
  
  ## Size factor file (optional)
  SizeFactors_fromFile <-reactive({ 
    
    Error = NULL
    Check = TRUE
    
    data = dataSizeFactors()
    normFactors = dataMergeCounts()$normFactors
    
    if(!is.null(data)){
      ## Check the format
      
      tmp = as.numeric(data)
      names(tmp) = colnames(data)
      
      if(length(tmp)!=length(normFactors)){Error = "The number of samples is not the same than in the target file, size factors will be estimated"; Check = FALSE}
      if(!identical(names(tmp),names(normFactors))){Error = "The names are not the same or in the same order than in the target file, size factors will be estimated"; Check = FALSE}
166
      
167
168
169
170
171
172
173
174
175
176
177
      if(Check) normFactors = tmp
    }
    
    return(list(Check = Check,Error = Error,normFactors=normFactors))
  })
  
  
  
  
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
178
  ## Merge counts data
179
  dataMergeCounts <-reactive({
Stevenn Volant's avatar
Stevenn Volant committed
180
    input$RunDESeq
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
181
182
183
    
    counts = NULL
    CheckTarget = FALSE
184
    normFactors = NULL
Stevenn Volant's avatar
Stevenn Volant committed
185
    CT_noNorm = NULL
186
    CT_Norm = NULL
187
    ChTM = NULL
188
    data = isolate(dataInput()$data)
189
    target = isolate(dataInputTarget()$target)
190
    labeled= isolate(dataInputTarget()$labeled)
191
    taxo = isolate(input$TaxoSelect)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
192
    
193
    withProgress(
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
194
195
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0 && !is.null(taxo) && taxo!="..." && !is.null(target)) 
    {
196
      design = GetDesign(isolate(input))
197
      ChTM = CheckTargetModel(input,target,labeled,data$counts)$Error
198
      
199
      if(!is.null(design) && is.null(ChTM))
200
      {
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
        tmp = isolate(GetCountsMerge(input,data,taxo,target,design))
        counts = tmp$counts
        
        ## Filtering the counts
        if(isolate(input$AddFilter) && !is.null(isolate(input$SliderThSamp)) && !is.null(isolate(input$SliderThAb)))
        {
          ind.filter =Filtered_feature(counts,isolate(input$SliderThSamp),isolate(input$SliderThAb))$ind
          counts = counts[-ind.filter,]
        }
        
        CheckTarget = tmp$CheckTarget
        #target = tmp$target
        #labeled = tmp$labeled
        normFactors = tmp$normFactors
        
        ## OTU table, norm and no norm
        CT_noNorm = tmp$CT_noNorm
        CT_Norm = tmp$CT_Norm
219
      }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
220
    }
221
    ,message="Merging the counts ...")
222
    return(list(counts=counts,CheckTarget=CheckTarget,normFactors=normFactors,CT_noNorm=CT_noNorm, CT_Norm=CT_Norm))
223
    #return(list(counts=counts,target=target,labeled=labeled,normFactors=normFactors,CT_noNorm=CT_noNorm))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
224
  })
225
226
  
  
Stevenn Volant's avatar
Stevenn Volant committed
227
228
229
230
231
232
233
  # Infobox Error counts
  output$InfoErrorCounts <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0)
234
    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
235
236
237
    
    if(cond)
    {
238
239
240
      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
241
242
243
244
    }
    
    return(res)
  })
245
  
Stevenn Volant's avatar
Stevenn Volant committed
246
247
248
249
250
251
252
  # Infobox Error counts
  output$InfoErrorTaxo <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$taxo) && nrow(data$taxo)>0)
svolant's avatar
svolant committed
253
    res = infoBox(h6(strong("Taxonomy table")), subtitle = h6("Load the taxonomy table") ,color = "light-blue",width=NULL,fill=TRUE, icon = icon("upload"))
Stevenn Volant's avatar
Stevenn Volant committed
254
255
256
257
258
259
260
261
    
    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)
    }
    
svolant's avatar
svolant committed
262
    if(input$NoTaxoFile && input$FileFormat=="fileCounts") res = infoBox(h6(strong("Taxonomy table")), subtitle = h6("No taxonomy table has been uploaded, the analysis can only be done at the OTU/gene level"), icon = icon("warning"),color = "orange",width=NULL,fill=TRUE)
Stevenn Volant's avatar
Stevenn Volant committed
263
264
    return(res)
  })
265
266
  
  
Stevenn Volant's avatar
Stevenn Volant committed
267
268
269
270
271
272
273
274
  # 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"))
svolant's avatar
svolant committed
275

Stevenn Volant's avatar
Stevenn Volant committed
276
277
278
279
280
281
282
283
284
285
    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
286
  
287
  
288
289
290
291
292
293
294
295
  ####### Filtering the counts (sliders)
  
  output$ThAb <- renderUI({
    input$AddFilter
    
    res = NULL
    counts = isolate(dataMergeCounts()$counts)
    tot = rowSums(counts)
296
    #save(counts,tot,file="testFilter.RData")
297
    withProgress({tmp = SelectThreshAb(counts,lambda=max(round(sum(counts)/nrow(counts)*0.05),min(tot)+1),graph=FALSE)},message="Loading...")
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
    
    res = sliderInput("SliderThAb","Threshold on the total abundance (in log)",min=0,max=round(max(log(tot+1)),1),value = log(tmp+1))
    return(res)
  })
  
  
  output$ThSamp <- renderUI({
    input$AddFilter
    
    res = NULL
    counts = isolate(dataMergeCounts()$counts)
    counts.bin = as.matrix(counts)
    counts.bin[which(counts>0)] = 1
    nbSampByFeat = rowSums(counts.bin)
    
    ## Default value
    val = round(max(nbSampByFeat)*0.2)
    
    res = sliderInput("SliderThSamp","Threshold on the minimal number of samples",min=0,max=max(nbSampByFeat),value = val)
    return(res)
  })
  
  
  ## Plot for the filtering step$
  
  # plot_filter(counts,th.samp,th.abund,type="Scatter")
  
325
  output$Plot_ThAb <- renderPlot({
326
327
328
329
330
331
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Abundance")
    
  })
    
332
  output$Plot_ThSamp <- renderPlot({
333
334
335
336
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Samples")
  })
337
  
338
339
340
341
342
  output$Plot_Scatter_Filter <- renderScatterD3({
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Scatter")
  })
343
344
345
346
347
  #####################################################
  ##
  ##                DYNAMIC MENU
  ##
  #####################################################
stevenn's avatar
stevenn committed
348
349
350
351
352
  
  
  
  output$dymMenu <- renderMenu({
    
Stevenn Volant's avatar
Stevenn Volant committed
353
354
355
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
stevenn's avatar
stevenn committed
356
    
Stevenn Volant's avatar
Stevenn Volant committed
357
358
359
    ## 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
360
    {
svolant's avatar
svolant committed
361

svolant's avatar
svolant committed
362
      sidebarMenu(id = "side",
stevenn's avatar
stevenn committed
363
364
        menuItem("Statistical analysis",
                 menuSubItem("Run differential analysis",tabName="RunDiff"),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
365
                 menuSubItem("Diagnostic plots",tabName="DiagPlotTab"),
stevenn's avatar
stevenn committed
366
                 menuSubItem("Tables",tabName="TableDiff"),
367
368
                 icon = icon("bar-chart-o"), tabName = "AnaStat"
        ),
369
370
371
372
        menuItem("Visualization",icon = icon("area-chart"),
                 menuSubItem("Global views",tabName="GlobVisu"),
                 menuSubItem("Comparison plots",tabName="CompPlot"),
                 tabName = "Visu"),
Stevenn Volant's avatar
Stevenn Volant committed
373
        menuItem("Perspective plots", icon = icon("pie-chart"), tabName = "Krona")
stevenn's avatar
stevenn committed
374
      )
svolant's avatar
svolant committed
375
    } else{ sidebarMenu(id = "side",NULL)}
svolant's avatar
svolant committed
376

stevenn's avatar
stevenn committed
377
378
379
  })
  
  
380
  
stevenn's avatar
stevenn committed
381
382
383
384
385
386
387
  #####################################################
  ##
  ##                DATA TABLE
  ##
  #####################################################
  
  ## Counts Table
388
  output$DataCounts <- DT::renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
389
    dataInput()$data$counts, 
stevenn's avatar
stevenn committed
390
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
391
                   pageLength = 10,scrollX=TRUE, processing=FALSE
stevenn's avatar
stevenn committed
392
393
    ))
  
394
  ## Counts Table
395
396
397
398
399
400
401
  output$DataVenn<- DT::renderDataTable(#{
    #SelContrast = input$ContrastList_table_FC
    #resDiff = ResDiffAnal()
    #BaseContrast = read.table(namesfile,header=TRUE)
    GetData_venn(input,input$ContrastList_table_FC,read.table(namesfile,header=TRUE),ResDiffAnal())$df.tot,
  #}
   options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
402
                    pageLength = 10,scrollX=TRUE, processing=FALSE
403
  ))
404
405
  
  
stevenn's avatar
stevenn committed
406
  ## Taxonomy table
407
  output$DataTaxo <- DT::renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
408
    dataInput()$data$taxo, 
stevenn's avatar
stevenn committed
409
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
svolant's avatar
svolant committed
410
                   pageLength = 10,scrollX=TRUE, processing=FALSE
stevenn's avatar
stevenn committed
411
    ))
412
  
stevenn's avatar
stevenn committed
413
  
stevenn's avatar
stevenn committed
414
  ## Tab box for data visualisation
stevenn's avatar
stevenn committed
415
416
  output$TabBoxData <- renderUI({
    
Stevenn Volant's avatar
Stevenn Volant committed
417
    data=dataInput()$data
stevenn's avatar
stevenn committed
418
419
420
    
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0)
    {
421
      tabBox(width = NULL, selected = "Count table",
422
423
             tabPanel("Count table",DT::dataTableOutput("DataCounts")),
             tabPanel("Taxonomy",DT::dataTableOutput("DataTaxo")),
svolant's avatar
svolant committed
424
425
             tabPanel("Summary",h5(strong("Percentage of annotation")),htmlOutput("SummaryView"),
                      br(),h5(strong("Number of features by level:")),plotOutput("SummaryViewBarplot",width = 1200,height=500))
stevenn's avatar
stevenn committed
426
      )
stevenn's avatar
stevenn committed
427
    }
stevenn's avatar
stevenn committed
428
    
stevenn's avatar
stevenn committed
429
  })
430
  
svolant's avatar
svolant committed
431
432
433
434
435
436
437
  output$SummaryView <- renderGvis({
    data = dataInput()$data
    taxo = data$taxo
    counts = data$counts
    res = NULL
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0)
    {
svolant's avatar
svolant committed
438
      taxo = rbind(taxo,rep(NA,ncol(taxo)))
439
      tmpPercent = round(apply(is.na(taxo),2,table)["FALSE",]/(nrow(taxo)-1)*100,2)
440
      
441
      #print(tmpPercent)
svolant's avatar
svolant committed
442
      df <- data.frame(Label = colnames(taxo),Value = tmpPercent)
443
      
svolant's avatar
svolant committed
444
      res = gvisGauge(df,options=list(min=0, max=100, greenFrom=80,
445
446
                                      greenTo=100, yellowFrom=60, yellowTo=80,
                                      redFrom=0, redTo=60, width=1200, height=300))
svolant's avatar
svolant committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
    }
    return(res)
  })
  
  
  output$SummaryViewBarplot <- renderPlot({
    data = dataInput()$data
    taxo = data$taxo
    counts = data$counts
    res = NULL
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0)
    {
      colors=rep(c("#1f77b4","#aec7e8","#ff7f0e","#ffbb78", "#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b",
                   "#c49c94","#e377c2","#f7b6d2","#7f7f7f", "#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"),ceiling(ncol(taxo)/20))
      tmp = apply(taxo,2,unique)
      nbfeatures = as.numeric(lapply(tmp,length)) -as.numeric(lapply(lapply(tmp,is.na),any))
      df <- data.frame(Label = colnames(taxo),Count = nbfeatures)
      df$Label = factor(df$Label,levels =colnames(taxo) )
      res = ggplot(df,aes(x=Label,y=Count,fill=Label))+geom_bar(stat="identity")
      res = res + theme_bw() + xlab("Taxonomy") + scale_fill_manual(values=colors) + guides(fill=FALSE)
    }
    return(res)
  })
  
stevenn's avatar
stevenn committed
471
472
473
474
475
  #####################################################
  ##
  ##                TARGET FILE
  ##
  #####################################################
stevenn's avatar
stevenn committed
476
  
477
  
stevenn's avatar
stevenn committed
478
479
480
481
  ## Load target file
  dataInputTarget <-reactive({ 
    
    inFile <- input$fileTarget
Stevenn Volant's avatar
Stevenn Volant committed
482
    counts = dataInput()$data$counts
483
484
    
    
stevenn's avatar
stevenn committed
485
486
487
    if (is.null(inFile)) return(NULL)
    
    
488
    data = read.csv(inFile$datapath,sep=input$septarget,header=TRUE)
svolant's avatar
svolant committed
489
    data = as.data.frame(data)
svolant's avatar
svolant committed
490
491
492
493
494
495
496
497
498
    names = colnames(data)
    
    ## Change the rownames
    rownames(data) <- as.character(data[, 1])
    
    ## Keep only the row which are in the count table
    ind = which(rownames(data)%in%colnames(counts))
    data = as.data.frame(data[ind,])
    colnames(data) = names
svolant's avatar
svolant committed
499
    ## Replace "-" by "."
500
501
502
503
504
505
506
507
    if(ncol(data)>1 && nrow(data)>1){
      ind_num = which(sapply(as.data.frame(data[,-1]),is.numeric)) + 1
      if(length(ind_num)>0){
        data_tmp =cbind( as.data.frame(apply(as.data.frame(data[,-ind_num]),2,gsub,pattern = "-",replacement = ".")),data[,ind_num])
        colnames(data_tmp) = c(colnames(data)[-ind_num],colnames(data)[ind_num])
        data = data_tmp
      }
      if(length(ind_num)==0){data = as.data.frame(apply(data,2,gsub,pattern = "-",replacement = "."))}
svolant's avatar
svolant committed
508
    }
509
    target = as.data.frame(data)
svolant's avatar
svolant committed
510
511
    
    # target = as.data.frame(apply(target,2,gsub,pattern = "-",replacement = "."))
512
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
513
514
515
516
    #ord = order(rownames(data))
    #data = data[ord,]
    ### A SUPPRIMER 
    #rownames(data) <- colnames(counts)
517
518
    
    # Percent annotated
519
520
521
    #     print(ind)
    #     print(colnames(counts))
    #     print(rownames(data))
522
523
    labeled = length(ind)/length(colnames(counts))*100.0
    
524
    return(list(target = target, labeled=labeled))
stevenn's avatar
stevenn committed
525
  })
526
527
528
  
  
  
stevenn's avatar
stevenn committed
529
530
  ## Interest Variables
  output$SelectInterestVar <- renderUI({
531
    
532
    target=dataInputTarget()$target
stevenn's avatar
stevenn committed
533
534
535
    if(!is.null(target)) 
    {
      namesTarget = colnames(target)[2:ncol(target)]
Stevenn Volant's avatar
Stevenn Volant committed
536
      selectInput("InterestVar",h6(strong("Select the variables")),namesTarget,selected=namesTarget,multiple=TRUE)
stevenn's avatar
stevenn committed
537
    }
538
    
stevenn's avatar
stevenn committed
539
  })
540
  
stevenn's avatar
stevenn committed
541
542
  ## Interactions
  output$SelectInteraction2 <- renderUI({
543
    
544
    target = dataInputTarget()$target
545
546
547
    VarInt = input$InterestVar
    res = NULL
    if(!is.null(target) && length(input$InterestVar)>1) 
stevenn's avatar
stevenn committed
548
    {
549
550
      Interac = GetInteraction2(target,VarInt)
      res = selectInput("Interaction2",h6(strong("Add interactions")),Interac,selected=NULL,multiple=TRUE)
stevenn's avatar
stevenn committed
551
    }
552
    if(length(input$InterestVar)==1) res = NULL
stevenn's avatar
stevenn committed
553
    
554
    return(res)
stevenn's avatar
stevenn committed
555
556
557
  })


svolant's avatar
svolant committed
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
  ## Var for normalization
  output$SelectVarNorm <- renderUI({
    
    target=dataInputTarget()$target
    res = selectInput("VarNorm",h6(strong("Normalization by:")),NULL,multiple=TRUE)
    if(!is.null(target)) 
    {
      namesTarget = colnames(target)[2:ncol(target)]
      ind = which(apply(as.data.frame(target[,namesTarget]),2,is.numeric))
      if(length(ind)>=1) namesTarget = namesTarget[-ind]
      res = selectInput("VarNorm",h6(strong("Normalization by:")),c(NULL,namesTarget),multiple=TRUE)
    }
    return(res)
    
  })
  
  
  
stevenn's avatar
stevenn committed
576
577
  ## Reference radio buttons
  output$RefSelect <- renderUI({
stevenn's avatar
stevenn committed
578
    
579
    target = dataInputTarget()$target
stevenn's avatar
stevenn committed
580
581
    RB=list()
    if(!is.null(target)) 
stevenn's avatar
stevenn committed
582
    {
stevenn's avatar
stevenn committed
583
584
585
586
      InterVar = input$InterestVar
      if(length(InterVar)>0)
      {
        names = paste0("Ref",InterVar)
587
588
589
590
591
        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
592
      }
stevenn's avatar
stevenn committed
593
    }
stevenn's avatar
stevenn committed
594
    return(RB)
stevenn's avatar
stevenn committed
595
    
stevenn's avatar
stevenn committed
596
  })
597
598
  
  
stevenn's avatar
stevenn committed
599
600
  # Infobox design
  output$RowTarget <- renderInfoBox({
601
602
603
604
    #target = dataInputTarget()
    #labeled = dataMergeCounts()$labeled
    labeled = dataInputTarget()$labeled
    if(!is.null(labeled)) 
stevenn's avatar
stevenn committed
605
606
    {
      #### Ajout fontion check target
607
608
609
610
      #infoBox(h6(strong("Target file")), subtitle = h6("Your target file is OK"), icon = icon("thumbs-o-up"),color = "green",width=NULL,fill=TRUE)
      labeled = round(labeled,2)
      if(labeled>0) res = valueBox(paste0(labeled, "%"),h6(strong("Labeled features")), color = "green",width=NULL,icon = icon("list"))
      else res = valueBox(paste0(labeled, "%"),h6(strong("Labeled features")), color = "red",width=NULL,icon = icon("list"))  
stevenn's avatar
stevenn committed
611
    }
612
613
614
615
616
    #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"))
    else res = valueBox(paste0(0, "%"),h6(strong("Labeled features")), color = "light-blue",width=NULL,icon = icon("list"))
    return(res)
  }
  )
617
618
619
620
  
  
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
621
  ## target table
622
  output$DataTarget <- DT::renderDataTable(
623
624
    dataInputTarget()$target,
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
625
                   pageLength = 10,scrollX=TRUE, processing=FALSE
626
627
    ))
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
628
  ## Counts table for the selected taxonomy level
629
  output$CountsMerge <- DT::renderDataTable(
630
    round(counts(ResDiffAnal()$dds,normalized=TRUE)),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
631
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
632
                   pageLength = 10,scrollX=TRUE, processing=FALSE
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
633
    ))
634
635
  
  
Stevenn Volant's avatar
Stevenn Volant committed
636
  ## Box for merged counts
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
637
  output$BoxCountsMerge <- renderUI({
638
639
    input$RunDESeq
    counts = isolate(dataMergeCounts()$counts)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
640
641
642
643
    taxo = input$TaxoSelect
    
    if(!is.null(counts) && taxo != "...")
    {
644
      box(title=paste("Count table (",taxo,")",sep=""),width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = TRUE,
645
          DT::dataTableOutput("CountsMerge"),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
646
647
648
649
650
651
          downloadButton('ExportCounts', 'Export normalised counts'),
          downloadButton('ExportRelative', 'Export relative abundance')
      )  
    }
    
  })
652
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
653
654
  ## Export in .csv
  output$ExportCounts <- downloadHandler(
Stevenn Volant's avatar
Stevenn Volant committed
655
656
    filename = function() { 'NormCounts.csv' },
    content = function(file){write.csv(dataMergeCounts()$counts, file)}
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
657
  )
658
  
stevenn's avatar
stevenn committed
659
660
661
  ## Export in .csv
  output$ExportRelative <- downloadHandler(
    filename = function() { 'RelativeAb.csv' },
Stevenn Volant's avatar
Stevenn Volant committed
662
    content = function(file){write.csv(dataMergeCounts()$counts/colSums(dataMergeCounts()$counts), file)}
stevenn's avatar
stevenn committed
663
  )
664
  
665
666
  ## Export size factors
  output$ExportSizeFactor <- downloadHandler(
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
667
668
    filename = function() { if (input$sepsizef == "\t") 'SHAMAN_sizefactors.tsv' else 'SHAMAN_sizefactors.csv' },
    content = function(file){write.table(SizeFactor_table(), file,quote=FALSE,row.names = FALSE,sep=input$sepsizef)}
669
670
671
  )
  
  
stevenn's avatar
stevenn committed
672
673
674
  ## Box for target visualisation
  output$BoxTarget <- renderUI({
    
675
    target = dataInputTarget()$target
676
    
stevenn's avatar
stevenn committed
677
678
679
    if(!is.null(target) &&  nrow(target)>0)
    {
      box(title="Target file overview",width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = TRUE,
680
          DT::dataTableOutput("DataTarget")
stevenn's avatar
stevenn committed
681
682
683
684
      )  
    }
    
  })
685
686
687
688
689
690
691
692
  
  
  
  #####################################################
  ##
  ##            DEFINE CONTRAST
  ##
  #####################################################
stevenn's avatar
stevenn committed
693
694
695
  
  output$contrastMat <- renderUI({
    
stevenn's avatar
stevenn committed
696
697
698
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)
699
    
stevenn's avatar
stevenn committed
700
701
    Contrast=list()
    
702
    for(i in 1:length(names)){Contrast[[i]] = numericInput(names[i],names[i],0,step=1,min=-1,max=1)}
703
    
stevenn's avatar
stevenn committed
704
705
706
    return(Contrast)
    
  })
707
708
  
  
stevenn's avatar
stevenn committed
709
710
711
712
713
  output$ContrastOverview <- renderPrint({
    
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)
stevenn's avatar
stevenn committed
714
715
    
    cont = input$ContrastList
stevenn's avatar
stevenn committed
716
    filesize = file.info(namesfile)[,"size"]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
717
    if(is.na(filesize)){filesize=0}
stevenn's avatar
stevenn committed
718
719
720
721
722
723
    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
724
  })
725
726
  
  
stevenn's avatar
stevenn committed
727
728
729
730
731
732
  ## Add contrast function
  AddCont <-eventReactive(input$AddContrast,{
    
    resDiff = ResDiffAnal()
    dds = resDiff$dds
    names = resultsNames(dds)
733
    
stevenn's avatar
stevenn committed
734
    BaseContrast(input,names,namesfile)
Stevenn Volant's avatar
Stevenn Volant committed
735
736
737
    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
738
739
    Contrast = colnames(as.matrix(tmp))
    updateSelectInput(session, "ContrastList","Contrasts",Contrast)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
740
    updateSelectInput(session, "ContrastList_table","Contrasts",Contrast)
741
    updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",Contrast)
742
    updateSelectInput(session, "ContrastList_table_VisuComp","For which contrasts",Contrast)
743
    updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",Contrast)
stevenn's avatar
stevenn committed
744
  })
745
  
stevenn's avatar
stevenn committed
746
747
  ## Add contrast 
  observeEvent(input$AddContrast,{  
stevenn's avatar
stevenn committed
748
    
stevenn's avatar
stevenn committed
749
    AddCont()
stevenn's avatar
stevenn committed
750
    
Stevenn Volant's avatar
Stevenn Volant committed
751
  },priority=1)
752
753
  
  
754
755
756
757
758
  ## Add contrast function
  AddContEasy <-eventReactive(input$AddContrastEasy,{
    
    resDiff = ResDiffAnal()
    dds = resDiff$dds
759
    target = resDiff$target
760
    names = resultsNames(dds)
761
762
763
764
765
766
767
    
    BaseContrastEasy(input,names,namesfile,target)
    filesize = file.info(namesfile)[,"size"]
    if(is.na(filesize)){filesize=0}
    if(filesize!=0) tmp = read.table(namesfile,header=TRUE)
    Contrast = colnames(as.matrix(tmp))
    
768
769
    updateSelectInput(session, "ContrastList","Contrasts",Contrast)
    updateSelectInput(session, "ContrastList_table","Contrasts",Contrast)
770
    updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",Contrast)
771
    updateSelectInput(session, "ContrastList_table_VisuComp","For which contrasts",Contrast)
772
    updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",Contrast)
773
  })
stevenn's avatar
stevenn committed
774
  
775
776
777
778
779
  ## Add contrast 
  observeEvent(input$AddContrastEasy,{  
    
    AddContEasy()
    
svolant's avatar
svolant committed
780
  },priority=1)
781
782
  
  
783
784
785
786
787
  AddContFromFile <-eventReactive(input$fileContrast,{ 
    
    res = ReadContrastFile()
    createdCont = NULL
    filesize = file.info(namesfile)[,"size"]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
788
    if(is.na(filesize)){filesize=0}
789
    if(filesize!=0){ createdCont = read.table(namesfile,header=TRUE) }
790
    
791
792
793
794
795
    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))
796
      updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",colnames(res))
797
      updateSelectInput(session, "ContrastList_table_VisuComp","For which contrasts",colnames(res))
798
      updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",colnames(res))
799
800
801
      write.table(res,namesfile,row.names=FALSE)
    }
  })
802
803
  
  observeEvent(input$fileContrast,{ 
804
    
805
    AddContFromFile()
Stevenn Volant's avatar
Stevenn Volant committed
806
  },priority=1)
807
808
  
  
stevenn's avatar
stevenn committed
809
810
811
812
813
  ## 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
814
    if(is.na(filesize)){filesize=0}
stevenn's avatar
stevenn committed
815
816
817
818
819
820
    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
821
      
stevenn's avatar
stevenn committed
822
823
824
      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
825
      updateSelectInput(session, "ContrastList_table","Contrasts",ContrastKept)
826
      updateSelectInput(session, "ContrastList_table_Visu","For which contrasts",ContrastKept)
827
      updateSelectInput(session, "ContrastList_table_VisuComp","For which contrasts",ContrastKept)
828
      updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",ContrastKept)
stevenn's avatar
stevenn committed
829
    }
stevenn's avatar
stevenn committed
830
831
832
833
834
835
836
837
838
  })
  
  
  
  ## Remove contrast
  observeEvent(input$RemoveContrast,{  
    
    RemoveCont()
    
Stevenn Volant's avatar
Stevenn Volant committed
839
  },priority=1)
840
  
Stevenn Volant's avatar
Stevenn Volant committed
841
842
843
  ## Remove all contrasts
  RemoveAllCont <-eventReactive(input$RunDESeq,{
    
844
845
846
847
848
849
    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_VisuComp","For which contrasts",NULL)
    updateSelectInput(session, "ContrastList_table_FC","Contrasts (Min = 2)",NULL)
Stevenn Volant's avatar
Stevenn Volant committed
850
  })
851
  
Stevenn Volant's avatar
Stevenn Volant committed
852
853
  ## Remove all contrast
  observeEvent(input$RunDESeq,{  
stevenn's avatar
stevenn committed
854
    
Stevenn Volant's avatar
Stevenn Volant committed
855
    RemoveAllCont()
stevenn's avatar
stevenn committed
856
    
Stevenn Volant's avatar
Stevenn Volant committed
857
  })
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
  
  # Infobox Contrast
  output$InfoContrast <- renderInfoBox({
    input$RunDESeq
    input$AddContrast
    input$AddContrastEasy
    input$RemoveContrast
    input$fileContrast
    resDiff = ResDiffAnal()
    res=NULL
    if(!is.null(resDiff)){
      
      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)
svolant's avatar
svolant committed
882
    }
883
884
    return(res)
  })
885
886
  
  
887
888
889
890
891
892
893
894
  
  output$contrastBox <- renderUI({
    
    resDiff = ResDiffAnal()
    int = input$Interaction2
    
    if(!is.null(resDiff))
    { 
895
896
897
898
899
900
901
902
903
904
905
      ## Check the R version
      if(as.numeric(R.Version()$major)<=3 && as.numeric(R.Version()$minor) <=1.2){
        box(title="Contrasts (New)",width = NULL, status = "primary", solidHeader = TRUE,collapsible = TRUE,collapsed = FALSE,
            fluidRow(
              column(width=3,selectInput("Select1_contrast","Compare","")),
              column(width=3,selectInput("Select2_contrast","To","")),
              if(length(int)>=1) column(width=3,selectInput("Select3_contrast",label=h6(strong("For")),"")),
              column(width=3,br(),actionButton("AddContrastEasy","Add",icon = icon("plus")))
            )
        )
      }
906
907
    }
    
908
909
    
    
910
  })
911
912
  
  ModifMod_ContEasy <-eventReactive(input$Select1_contrast,{
svolant's avatar
svolant committed
913
    input$RunDESeq
914
915
916
917
918
919
    resDiff = ResDiffAnal()
    int = input$Interaction2
    target = as.data.frame(resDiff$target)
    
    InterVar = input$InterestVar
    
svolant's avatar
svolant committed
920
    
svolant's avatar
svolant committed
921
    
922
    ## Get the selected variable from the selected modality
svolant's avatar
svolant committed
923
    Sel_Var = InterVar[which(unlist(lapply(as.data.frame(target[,InterVar]),FUN = function(x){input$Select1_contrast%in%x})))]
924
    
svolant's avatar
svolant committed
925
    ModInterestCond = levels(sapply(target[,Sel_Var],as.factor))
926
927
928
929
930
    ModInterestCond = ModInterestCond[-which(ModInterestCond==input$Select1_contrast)]
    
    updateSelectInput(session,"Select2_contrast","To",ModInterestCond)
  })
  
931
  
932
933
934
935
936
937
938
939
940
941
942
943
944
  observeEvent(input$Select1_contrast,{ 
    
    ModifMod_ContEasy()
  })
  
  
  ModifMod_ContEasyFrom <-eventReactive(input$RunDESeq,{
    
    resDiff = ResDiffAnal()
    int = input$Interaction2
    target = as.data.frame(resDiff$target)
    
    InterVar = input$InterestVar
svolant's avatar
svolant committed
945
    
946
    ## Remove numeric variable
svolant's avatar
svolant committed
947
    ind = unlist(lapply(as.data.frame(target[,InterVar]),is.numeric))
948
    InterVar = InterVar[!ind]