server.R 125 KB
Newer Older
stevenn's avatar
stevenn committed
1
shinyServer(function(input, output,session) {
svolant's avatar
svolant committed
2
3
4

  hide(id = "loading-content", anim = TRUE, animType = "fade",time=1.5)
  hide(id = "loading-content-bar", anim = TRUE, animType = "fade",time=1.5)
5
6
7
8
9
  #####################################################
  ##
  ##                    LOAD FILES
  ##
  #####################################################
stevenn's avatar
stevenn committed
10
  
11
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
  target = NULL
18
  
svolant's avatar
svolant committed
19
20
21
22
  
  ## JSON name for masque
  curdir  = getwd()
  json_name = tempfile(pattern = "file", tmpdir = paste(curdir,"www","masque","todo",sep= .Platform$file.sep),  fileext = ".json")
svolant's avatar
svolant committed
23

svolant's avatar
svolant committed
24
25
26
  ## Pass for MASQUE
  pass = gsub("file","",basename(file_path_sans_ext(json_name)))
  
svolant's avatar
svolant committed
27
  ## Popup messages
svolant's avatar
svolant committed
28
  observe(if(input$AddRegScatter) info("By adding the regression line, you will lose interactivity."))
29
  
30
  ## Reactive target
svolant's avatar
svolant committed
31
32
  values <- reactiveValues(TargetWorking = target,labeled=NULL,fastq_names_only=NULL,R1fastQ=NULL,R2fastQ=NULL,
                           json_name=json_name,num=0,pass=pass,login_email = NULL,is.valid =NULL,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
33
34
35
                           biom_masque = NULL,tree_masque=NULL, masque_key = NULL, count_table_masque = NULL, 
                           rdp_annot_masque = NULL, rdp_thres_masque = NULL,
                           paths_fastq_tmp=NULL,curdir=curdir, error_progress=FALSE)
36
  
stevenn's avatar
stevenn committed
37
  ## Counts file
stevenn's avatar
stevenn committed
38
  dataInputCounts <-reactive({ 
39
    
svolant's avatar
svolant committed
40
    data = NULL
stevenn's avatar
stevenn committed
41
    inFile <- input$fileCounts
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
42
43
    if (is.null(inFile) && is.null(values$count_table_masque)) return(NULL)
    #if (is.null(inFile)) return(NULL)
svolant's avatar
svolant committed
44

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
45
46
47
48
49
50
51
52
53
54
55
56
57
    if (!is.null(values$count_table_masque) && file.exists(values$count_table_masque)){
      tryCatch(read.csv(values$count_table_masque,sep="\t",header=TRUE,check.names=FALSE)->data,
               error=function(e) sendSweetAlert(messageId="ErrorCounts",
                                                title = "Oops",
                                                text=paste("The count file can not be read in SHAMAN.\n \n",e),type ="error"))
    }
    else{
      tryCatch(read.csv(inFile$datapath,sep=input$sepcount,header=TRUE,check.names=FALSE)->data,
               error=function(e) sendSweetAlert(messageId="ErrorCounts",
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
    }
    #print(data)
svolant's avatar
svolant committed
58
59
60
61
    if(!is.null(data)){
      colnames(data) = gsub("-",".",colnames(data))
      ## Rownames
      if(!TRUE%in%duplicated(data[,1])) rownames(data)=data[,1];data=data[,-1]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
62
      try(round(data, 0)->data, silent=T)
svolant's avatar
svolant committed
63
    }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
64

stevenn's avatar
stevenn committed
65
66
67
    return(as.data.frame(data))
  })
  
68
69
  
  
stevenn's avatar
stevenn committed
70
71
  ## Taxo File
  dataInputTaxo <-reactive({ 
stevenn's avatar
stevenn committed
72
    
stevenn's avatar
stevenn committed
73
    inFile <- input$fileTaxo
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
74
75
76
77
78

    if (is.null(inFile) && is.null(values$rdp_annot_masque)) return(NULL)
    #if (is.null(inFile)) return(NULL)

    if(input$TypeTaxo=="Table" && !is.null(inFile)) 
Stevenn Volant's avatar
Stevenn Volant committed
79
    {
svolant's avatar
svolant committed
80
81
82
83
      tryCatch(read.csv(inFile$datapath,sep=input$septaxo,header=TRUE)->data,
               error=function(e) sendSweetAlert(messageId="ErrorTaxo",
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
svolant's avatar
svolant committed
84
    
Stevenn Volant's avatar
Stevenn Volant committed
85
      ## Rownames
svolant's avatar
svolant committed
86
87
88
89
90
91
92
93
94
      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
        }
95
      }
Stevenn Volant's avatar
Stevenn Volant committed
96
    }
stevenn's avatar
stevenn committed
97
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
98
    if(input$TypeTaxo=="RDP" && !is.null(inFile) || !is.null(values$rdp_annot_masque)) 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
99
    {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
100
101
102
103
104
105
106
107
108
109
110
111
      if (!is.null(values$rdp_annot_masque) && file.exists(values$rdp_annot_masque)){
        tryCatch(read_rdp(values$rdp_annot_masque,values$rdp_thres_masque)->data,
                 error=function(e) sendSweetAlert(messageId="ErrorRDP",
                                                  title = "Oops",
                                                  text=paste("The annotation file can not be read in SHAMAN.\n \n",e),type ="error"))
      }
      else{
        tryCatch(read_rdp(inFile$datapath,input$RDP_th)->data,
                 error=function(e) sendSweetAlert(messageId="ErrorRDP",
                                                  title = "Oops",
                                                  text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
      }
svolant's avatar
svolant committed
112
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
113
    }
stevenn's avatar
stevenn committed
114
115
116
    
    ## Add NA
    data=as.matrix(data)
Stevenn Volant's avatar
Stevenn Volant committed
117
    indNa = which(data=="")
stevenn's avatar
stevenn committed
118
119
    data[indNa]=NA
    
stevenn's avatar
stevenn committed
120
    return(as.data.frame(data))
stevenn's avatar
stevenn committed
121
  })
122
123
  
  
stevenn's avatar
stevenn committed
124
125
  ## BIOM File
  dataInputBiom <-reactive({ 
stevenn's avatar
stevenn committed
126
    
svolant's avatar
svolant committed
127
    data = NULL
stevenn's avatar
stevenn committed
128
    inFile <- input$fileBiom
svolant's avatar
svolant committed
129

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
130
    if (!is.null(inFile) && is.null(values$biom_masque)){
svolant's avatar
svolant committed
131
132
133
134
      tryCatch(read_biom(inFile$datapath)->data,
               error=function(e) sendSweetAlert(messageId="ErrorBiom1",
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
stevenn's avatar
stevenn committed
135
    
svolant's avatar
svolant committed
136
137
138
139
140
141
142
      }
    if (!is.null(values$biom_masque) && file.exists(values$biom_masque)){ 
      tryCatch(read_biom(values$biom_masque)->data,
               error=function(e) sendSweetAlert(messageId="ErrorBiom2",
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
    }
stevenn's avatar
stevenn committed
143
    return(data)
stevenn's avatar
stevenn committed
144
  })
145
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
146
147
148
149
150
151
152
  observeEvent(input$fileCounts,{
    values$count_table_masque=NULL;
  })
  observeEvent(input$fileTaxo,{
    values$rdp_annot_masque=NULL;
    values$rdp_thres_masque=NULL;
  })
svolant's avatar
svolant committed
153
154
155
  observeEvent(input$fileBiom,{
    values$biom_masque=NULL;
  })
svolant's avatar
svolant committed
156

157
  
svolant's avatar
svolant committed
158
159
160
161
162
  ## Unifrac File (tree)
  dataInputTree <-reactive({ 
    
    data = NULL
    inFile <- input$fileTree
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
163

svolant's avatar
svolant committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
    if (!is.null(inFile) && is.null(values$tree_masque)) {
      try(read.tree(inFile$datapath)->data, silent=T)
      CheckTree = CheckTreeFile(data)
      data = CheckTree$tree
      try(readLines(inFile$datapath)->treeseq, silent=T)
      return(list(data=data, Error=CheckTree$Error, Warning=CheckTree$Warning, treeseq=treeseq))
    }
    
    if (!is.null(values$tree_masque) && file.exists(values$tree_masque)) {
      try(read.tree(values$tree_masque)->data, silent=T)
      CheckTree = CheckTreeFile(data)
      data = CheckTree$tree
      try(readLines(values$tree_masque)->treeseq, silent=T)
      return(list(data=data, Error=CheckTree$Error, Warning=CheckTree$Warning, treeseq=treeseq))
    }

  })
  
  
  observeEvent(input$fileTree,{
    values$tree_masque=NULL;
svolant's avatar
svolant committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
  })
  
  
  # Infobox Tree (Unifrac)
  output$InfoTreePhylo_box <- renderInfoBox({
    input$fileTree
    tree_tmp = isolate(dataInputTree())
    tree = tree_tmp$data
    
    res = infoBox(h6(strong("Phylogenetic tree")), subtitle = h6(strong("Load the phylogenetic tree (optional)")) ,color = "light-blue",width=NULL,fill=TRUE, icon = icon("upload"))
    if(!is.null(tree)){
      if(!is.null(isolate(input$fileTree))){
        res = infoBox(h6(strong("Phylogenetic tree")), subtitle = h6("The phylogenetic has been loaded") ,color = "green",width=NULL,fill=TRUE, icon = icon("thumbs-o-up"))
        if(!is.null(tree_tmp$Warning)){      
          res = infoBox(h6(strong("Phylogenetic tree")), subtitle = h6(tree_tmp$Warning) ,color = "orange",width=NULL,fill=TRUE, icon = icon("warning"))
        }
        if(!is.null(tree_tmp$Error)){      
          res = infoBox(h6(strong("Phylogenetic tree")), subtitle = h6(tree_tmp$Error),color = "red",width=NULL,fill=TRUE, icon = icon("thumbs-o-down"))
        }
      }
    } 
    return(res)
  })
208

209
  
stevenn's avatar
stevenn committed
210
211
  ## Input data
  dataInput <-reactive({ 
stevenn's avatar
stevenn committed
212
    
stevenn's avatar
stevenn committed
213
    data = NULL
Stevenn Volant's avatar
Stevenn Volant committed
214
215
    check = NULL
    percent = NULL
svolant's avatar
svolant committed
216
217
    Taxo = NULL
    Counts = NULL
svolant's avatar
svolant committed
218
219
    inputData = NULL
    
stevenn's avatar
stevenn committed
220
    if(input$FileFormat=="fileCounts")
stevenn's avatar
stevenn committed
221
    {
stevenn's avatar
stevenn committed
222
      Counts = dataInputCounts()
svolant's avatar
svolant committed
223
224
225
      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
226
227
      if(!is.null(Counts) && !is.null(Taxo))
      { 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
228
        tmp = GetDataFromCT(Counts,Taxo, ifelse(input$TypeTable=="MGS" && input$FileFormat!="fileBiom", TRUE, FALSE))
Stevenn Volant's avatar
Stevenn Volant committed
229
        data = list(counts=tmp$counts,taxo=tmp$taxo)
svolant's avatar
svolant committed
230
231
232
        ## Remove row with only O
        # data[["counts"]] = data[["counts"]][rowSums(data[["counts"]])>1,]
        
Stevenn Volant's avatar
Stevenn Volant committed
233
234
235
        check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
        percent = tmp$Percent
      }    
stevenn's avatar
stevenn committed
236
237
    }
    
stevenn's avatar
stevenn committed
238
    if(input$FileFormat=="fileBiom")
stevenn's avatar
stevenn committed
239
    {
stevenn's avatar
stevenn committed
240
      tmpBIOM = dataInputBiom()
Stevenn Volant's avatar
Stevenn Volant committed
241
242
243
244
      if(!is.null(tmpBIOM))
      {
        tmp = GetDataFromBIOM(tmpBIOM)
        data = list(counts=tmp$counts,taxo=tmp$taxo)
svolant's avatar
svolant committed
245
246
247
        ## Remove row with only O
        # data[["counts"]] = data[["counts"]][rowSums(data[["counts"]])>1,]
        
Stevenn Volant's avatar
Stevenn Volant committed
248
249
250
        check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
        percent = tmp$Percent
      }
stevenn's avatar
stevenn committed
251
252
    }
    
svolant's avatar
svolant committed
253
254
    

svolant's avatar
svolant committed
255
256
257
258
259
260
261
262
263
264
265
#     if(input$FileFormat=="fileRData")
#     {
#       inFile <- input$fileRData
#       load(inFile)
#       if(!is.null(inputData)){
#         data = inputData$data
#         check = inputData$check
#         percent = inputData$percent
#       }
#     }
    
Stevenn Volant's avatar
Stevenn Volant committed
266
    return(list(data=data,check=check,percent=percent))
stevenn's avatar
stevenn committed
267
268
269
  })
  
  
270
271
272
273
274
275
276
  ## Size factor file (optional)
  dataSizeFactors <-reactive({ 
    
    inFile <- input$fileSizeFactors
    
    if (is.null(inFile)) return(NULL)
    
svolant's avatar
svolant committed
277
278
279
280
    tryCatch(read.csv(inFile$datapath,sep=input$sepsize,header=TRUE)->data,
             error=function(e) sendSweetAlert(messageId="ErrorSizeFactor",
                                              title = "Oops",
                                              text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
    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}
302
      
303
304
305
306
307
308
309
310
311
312
313
      if(Check) normFactors = tmp
    }
    
    return(list(Check = Check,Error = Error,normFactors=normFactors))
  })
  
  
  
  
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
314
  ## Merge counts data
315
  dataMergeCounts <-reactive({
Stevenn Volant's avatar
Stevenn Volant committed
316
    input$RunDESeq
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
317
318
319
    
    counts = NULL
    CheckTarget = FALSE
320
    normFactors = NULL
Stevenn Volant's avatar
Stevenn Volant committed
321
    CT_noNorm = NULL
322
    CT_Norm = NULL
323
    ChTM = NULL
324
    data = isolate(dataInput()$data)
325
326
    target = isolate(values$TargetWorking)
    labeled= isolate(values$labeled)
327
    taxo = isolate(input$TaxoSelect)
328
    withProgress(
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
329
330
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0 && !is.null(taxo) && taxo!="..." && !is.null(target)) 
    {
svolant's avatar
svolant committed
331
      design = GetDesign(isolate(input),target)
332
333
      ChTM = CheckTargetModel(input,target,labeled,data$counts)$Error
      if(!is.null(design) && is.null(ChTM))
334
      {
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
        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
350
      }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
351
    }
352
    ,message="Merging the counts ...")
353
    return(list(counts=counts,CheckTarget=CheckTarget,normFactors=normFactors,CT_noNorm=CT_noNorm, CT_Norm=CT_Norm))
354
    #return(list(counts=counts,target=target,labeled=labeled,normFactors=normFactors,CT_noNorm=CT_noNorm))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
355
  })
356
357
  
  
Stevenn Volant's avatar
Stevenn Volant committed
358
359
360
361
362
363
364
  # Infobox Error counts
  output$InfoErrorCounts <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0)
365
    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
366
367
368
    
    if(cond)
    {
369
370
371
      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
372
373
374
375
    }
    
    return(res)
  })
376
  
Stevenn Volant's avatar
Stevenn Volant committed
377
378
379
380
381
382
383
  # 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
384
    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
385
386
387
388
389
390
391
392
    
    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
393
    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
394
395
    return(res)
  })
396
397
  
  
Stevenn Volant's avatar
Stevenn Volant committed
398
399
400
401
402
403
404
  # 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)
405
    res = shinydashboard::valueBox(paste0(0, "%"),h6(strong("Annotated features")), color = "light-blue",width=NULL,icon = icon("list"))
svolant's avatar
svolant committed
406

Stevenn Volant's avatar
Stevenn Volant committed
407
408
409
    if(cond)
    {
      percent = round(100*tmp$percent,2)
410
411
      if(percent==0) res = shinydashboard::valueBox(paste0(percent, "%"),h6(strong("Annotated features")), color = "red",width=NULL,icon = icon("list"))  
      if(percent!=0) res = shinydashboard::valueBox(paste0(percent, "%"),h6(strong("Annotated features")), color = "green",width=NULL,icon = icon("list"))  
Stevenn Volant's avatar
Stevenn Volant committed
412
413
414
415
416
      
    }
    
    return(res)
  })
stevenn's avatar
stevenn committed
417
  
418
  
419
420
421
422
423
424
425
426
  ####### Filtering the counts (sliders)
  
  output$ThAb <- renderUI({
    input$AddFilter
    
    res = NULL
    counts = isolate(dataMergeCounts()$counts)
    tot = rowSums(counts)
427
    #save(counts,tot,file="testFilter.RData")
428
    withProgress({tmp = SelectThreshAb(counts,lambda=max(round(sum(counts)/nrow(counts)*0.05),min(tot)+1),graph=FALSE)},message="Loading...")
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
    
    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")
  
456
  output$Plot_ThAb <- renderPlot({
457
458
459
460
461
462
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Abundance")
    
  })
    
463
  output$Plot_ThSamp <- renderPlot({
464
465
466
467
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Samples")
  })
468
  
469
470
471
472
473
  output$Plot_Scatter_Filter <- renderScatterD3({
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Scatter")
  })
474
475
476
477
478
  #####################################################
  ##
  ##                DYNAMIC MENU
  ##
  #####################################################
stevenn's avatar
stevenn committed
479
480
481
482
483
  
  
  
  output$dymMenu <- renderMenu({
    
Stevenn Volant's avatar
Stevenn Volant committed
484
485
486
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
stevenn's avatar
stevenn committed
487
    
Stevenn Volant's avatar
Stevenn Volant committed
488
489
490
    ## 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
491
    {
svolant's avatar
svolant committed
492

svolant's avatar
svolant committed
493
      sidebarMenu(id = "side",
stevenn's avatar
stevenn committed
494
495
        menuItem("Statistical analysis",
                 menuSubItem("Run differential analysis",tabName="RunDiff"),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
496
                 menuSubItem("Diagnostic plots",tabName="DiagPlotTab"),
stevenn's avatar
stevenn committed
497
                 menuSubItem("Tables",tabName="TableDiff"),
498
499
                 icon = icon("bar-chart-o"), tabName = "AnaStat"
        ),
500
501
502
        menuItem("Visualization",icon = icon("area-chart"),
                 menuSubItem("Global views",tabName="GlobVisu"),
                 menuSubItem("Comparison plots",tabName="CompPlot"),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
503
504
                 tabName = "Visu")
        #menuItem("Perspective plots", icon = icon("pie-chart"), tabName = "Krona")
stevenn's avatar
stevenn committed
505
      )
svolant's avatar
svolant committed
506
    } else{ sidebarMenu(id = "side",NULL)}
svolant's avatar
svolant committed
507

stevenn's avatar
stevenn committed
508
509
510
  })
  
  
511
  
stevenn's avatar
stevenn committed
512
513
514
515
516
517
518
  #####################################################
  ##
  ##                DATA TABLE
  ##
  #####################################################
  
  ## Counts Table
519
  output$DataCounts <- DT::renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
520
    dataInput()$data$counts, 
stevenn's avatar
stevenn committed
521
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
522
                   pageLength = 10,scrollX=TRUE, processing=FALSE
stevenn's avatar
stevenn committed
523
524
    ))
  
525
  ## Counts Table
526
527
528
529
530
531
532
  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')),
533
                    pageLength = 10,scrollX=TRUE, processing=FALSE
534
  ))
535
536
  
  
stevenn's avatar
stevenn committed
537
  ## Taxonomy table
538
  output$DataTaxo <- DT::renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
539
    dataInput()$data$taxo, 
stevenn's avatar
stevenn committed
540
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
svolant's avatar
svolant committed
541
                   pageLength = 10,scrollX=TRUE, processing=FALSE
stevenn's avatar
stevenn committed
542
    ))
543
  
stevenn's avatar
stevenn committed
544
  
stevenn's avatar
stevenn committed
545
  ## Tab box for data visualisation
stevenn's avatar
stevenn committed
546
  output$TabBoxData <- renderUI({
547
    tree = dataInputTree()$data
Stevenn Volant's avatar
Stevenn Volant committed
548
    data=dataInput()$data
svolant's avatar
svolant committed
549
550
    res=NULL
    if(!is.null(tree))
551
    {
552
     res = tabBox(width = NULL, selected = "Count table",
553
554
555
556
557
             tabPanel("Count table",DT::dataTableOutput("DataCounts")),
             tabPanel("Taxonomy",DT::dataTableOutput("DataTaxo")),
             tabPanel("Summary",h5(strong("Percentage of annotation")),htmlOutput("SummaryView"),
                      br(),h5(strong("Number of features by level:")),plotOutput("SummaryViewBarplot",width = 1200,height=500)),
             tabPanel("Phylogeny", PhyloTreeMetaROutput('PhyloTreeMetaR'))
svolant's avatar
svolant committed
558
559
     )
            
560
    }
svolant's avatar
svolant committed
561
    else if(is.null(tree))
stevenn's avatar
stevenn committed
562
    {
563
     res = tabBox(width = NULL,selected = "Count table",
564
565
             tabPanel("Count table",DT::dataTableOutput("DataCounts")),
             tabPanel("Taxonomy",DT::dataTableOutput("DataTaxo")),
svolant's avatar
svolant committed
566
567
             tabPanel("Summary",h5(strong("Percentage of annotation")),htmlOutput("SummaryView"),
                      br(),h5(strong("Number of features by level:")),plotOutput("SummaryViewBarplot",width = 1200,height=500))
svolant's avatar
svolant committed
568
569
             )
      
stevenn's avatar
stevenn committed
570
    }
svolant's avatar
svolant committed
571
572
573
574
575
576
577
578
579
    return(res)
  })
  
  observe({
    data=dataInput()$data
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0)
    {
        showElement("tabboxdata_col",anim=TRUE)
    } else hideElement("tabboxdata_col",anim=TRUE)
stevenn's avatar
stevenn committed
580
    
stevenn's avatar
stevenn committed
581
  })
582
  
583
584
585
586
  output$PhyloTreeMetaR <- renderPhyloTreeMetaR({
    PhyloTreeMetaR(dataInputTree()$treeseq,NULL)
  })
  
svolant's avatar
svolant committed
587
  output$SummaryView <- renderGvis({
svolant's avatar
svolant committed
588
589
    tmp = dataInput()
    data = tmp$data
svolant's avatar
svolant committed
590
591
    taxo = data$taxo
    counts = data$counts
svolant's avatar
svolant committed
592
593
594
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0 && !is.null(data$taxo) && nrow(data$taxo)>0 && is.null(check$CheckTaxo$Error) && is.null(check$CheckCounts$Error))
  
svolant's avatar
svolant committed
595
    res = NULL
svolant's avatar
svolant committed
596
    if(cond)
svolant's avatar
svolant committed
597
    {
svolant's avatar
svolant committed
598
      taxo = rbind(taxo,rep(NA,ncol(taxo)))
599
600
601
602
603
604
605
606
607
608
609
610
611
612
      #tmpPercent = round(apply(is.na(taxo),2,table)["FALSE",]/(nrow(taxo)-1)*100,2)
      
      tmp = apply(is.na(taxo),2,table)
      
      if (class(tmp) == "list") {
        tmp2 = sapply(tmp, function (x) {if (! "FALSE" %in% names(x)) {x["FALSE"] = 0} ; return(x["FALSE"])})
      }
      else
      {
        tmp2 = tmp["FALSE",]
      }
      
      tmpPercent = round(tmp2/(nrow(taxo)-1)*100,2)
      
613
      
svolant's avatar
svolant committed
614
      df <- data.frame(Label = colnames(taxo),Value = tmpPercent)
615
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
616
617
618
      # res = gvisGauge(df,options=list(min=0, max=100, greenFrom=80,
      #                                 greenTo=100, yellowFrom=60, yellowTo=80,
      #                                 redFrom=0, redTo=60, width=1200, height=300))
svolant's avatar
svolant committed
619
      res = gvisGauge(df,options=list(min=0, max=100, greenFrom=80,
620
                                      greenTo=100, yellowFrom=60, yellowTo=80,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
621
                                      redFrom=0, redTo=60, width=800, height=200))
svolant's avatar
svolant committed
622
623
624
625
626
627
    }
    return(res)
  })
  
  
  output$SummaryViewBarplot <- renderPlot({
svolant's avatar
svolant committed
628
629
    tmp = dataInput()
    data = tmp$data
svolant's avatar
svolant committed
630
631
    taxo = data$taxo
    counts = data$counts
svolant's avatar
svolant committed
632
633
634
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0 && !is.null(data$taxo) && nrow(data$taxo)>0 && is.null(check$CheckTaxo$Error) && is.null(check$CheckCounts$Error))

svolant's avatar
svolant committed
635
    res = NULL
svolant's avatar
svolant committed
636
    if(cond)
svolant's avatar
svolant committed
637
638
639
640
641
642
643
644
645
646
647
648
649
    {
      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
650
651
652
653
654
  #####################################################
  ##
  ##                TARGET FILE
  ##
  #####################################################
stevenn's avatar
stevenn committed
655
  
656
  
stevenn's avatar
stevenn committed
657
  ## Load target file
658
  observe({ 
stevenn's avatar
stevenn committed
659
660
    
    inFile <- input$fileTarget
Stevenn Volant's avatar
Stevenn Volant committed
661
    counts = dataInput()$data$counts
svolant's avatar
svolant committed
662
    labeled = 0
svolant's avatar
svolant committed
663
    data = NULL
664
    
stevenn's avatar
stevenn committed
665
666
    if (is.null(inFile)) return(NULL)
    
svolant's avatar
svolant committed
667
668
    ## Read the data
    try(read.csv(inFile$datapath,sep=input$septarget,header=TRUE)->data,silent=TRUE)
stevenn's avatar
stevenn committed
669
    
svolant's avatar
svolant committed
670
671
672
673
674
675
    if(!is.null(data))
    {
      data = as.data.frame(data)
      names = colnames(data)
      
      ## Change the rownames
svolant's avatar
svolant committed
676
      if(!TRUE%in%duplicated(data[,1])) rownames(data)=gsub(pattern = "-",replacement = ".",as.character(data[,1]))
svolant's avatar
svolant committed
677
678
679
680
681
      
      ## 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
682
683
      
      
svolant's avatar
svolant committed
684
685
686
687
688
689
690
691
692
      ## Replace "-" by "."
      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 = "."))}
693
      }
svolant's avatar
svolant committed
694
      
695
696
697
      values$TargetWorking = as.data.frame(data)
#       ind_sel = Target_selection()
#       if(length(ind))
svolant's avatar
svolant committed
698
699
700
701
702
703
704
705
706
707
708
      # target = as.data.frame(apply(target,2,gsub,pattern = "-",replacement = "."))
      
      #ord = order(rownames(data))
      #data = data[ord,]
      ### A SUPPRIMER 
      #rownames(data) <- colnames(counts)
      
      # Percent annotated
      #     print(ind)
      #     print(colnames(counts))
      #     print(rownames(data))
709
      values$labeled = length(ind)/length(colnames(counts))*100.0
svolant's avatar
svolant committed
710
    }
711
    
712
713
714
    # return(list(target = target, labeled=labeled))
  })
  
svolant's avatar
svolant committed
715

svolant's avatar
svolant committed
716
717
718
719
720
721
722
723
724
  
  
  #############################################################
  ##
  ##                        MASQUE
  ##
  #############################################################
  
  
svolant's avatar
svolant committed
725
  
svolant's avatar
svolant committed
726
727
728
  observeEvent(input$dir,{
    
    inFiles <- input$dir
svolant's avatar
svolant committed
729
    
svolant's avatar
svolant committed
730
731
732
733
734
    if (!is.null(inFiles)){
    # values$fastq_names_only = unique(paste(values$fastq_names_only,inFiles$name))
    values$paths_fastq_tmp = rbind(isolate(values$paths_fastq_tmp),inFiles)
    values$fastq_names_only = isolate(unique(values$paths_fastq_tmp[,"name"]))
    }
svolant's avatar
svolant committed
735
736
  })
  
svolant's avatar
svolant committed
737

svolant's avatar
svolant committed
738
  
svolant's avatar
svolant committed
739
  ## Create a fasta file containing the contaminant
svolant's avatar
svolant committed
740
741
742
743
744
745
746
747
748
749
750
  CreateFasta <- reactive({
    seq = NULL
    tmp = tempdir()
    fastaName = paste(tmp,paste(basename(file_path_sans_ext(json_name)),"_contaminant.fasta",sep=""),sep = .Platform$file.sep)
    
    if(!file.exists(fastaName)) file.create(fastaName,showWarnings=FALSE)
    if(input$PairedOrNot=="y"){seq =paste("#Seq1\n",input$R1primer,"\n \n","#Seq2\n",input$R2primer,sep="")}
    if(input$PairedOrNot=="n"){seq =input$primerSingle}
    if(!is.null(seq))  write(seq, file=fastaName)
    
  })
svolant's avatar
svolant committed
751
  
svolant's avatar
svolant committed
752
753
754
  
  ## Action with submit button
  MasqueSubmit <- eventReactive(input$submit,{
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
755
756
    #activate check_mail
    CMP = CheckMasque(input, values,check_mail = TRUE)
svolant's avatar
svolant committed
757
    Error = CMP$Error
svolant's avatar
svolant committed
758

svolant's avatar
svolant committed
759
    isJSONalreadyExist = file.exists(paste(values$curdir,"www","masque","doing",basename(json_name),sep= .Platform$file.sep))
svolant's avatar
svolant committed
760

svolant's avatar
json    
svolant committed
761
    if(is.null(Error) && !isJSONalreadyExist)
svolant's avatar
svolant committed
762
    {
svolant's avatar
svolant committed
763
764
      CreateFasta()
      values$num = 1
svolant's avatar
svolant committed
765
      tmp = tempdir()
svolant's avatar
svolant committed
766
      # home <- normalizePath("~")
svolant's avatar
svolant committed
767
      home <- ""
svolant's avatar
svolant committed
768
      # path_glob = file.path(home, paste(unlist(dir()$path[-1]), collapse = .Platform$file.sep))
svolant's avatar
svolant committed
769
770
771
772
773
774
775
776
777
778
779
780
781
    
    
      ## Paired-end
      if(input$PairedOrNot=="y"){
        cmp = 0
        nfiles = length(values$R1fastQ)+length(values$R2fastQ)
        
        withProgress(message = 'Uploading files...', value = 0, {
          pathToR1 = paste(tmp,"Masque_files_R1",sep=.Platform$file.sep)
          pathToR2 = paste(tmp,"Masque_files_R2",sep=.Platform$file.sep)
          
          if(dir.exists(pathToR1)){file.remove(list.files(pathToR1,full.names =TRUE))} else dir.create(pathToR1)
          if(dir.exists(pathToR2)){file.remove(list.files(pathToR2,full.names =TRUE))} else dir.create(pathToR2)
svolant's avatar
svolant committed
782
783
        for(i in values$R1fastQ){
          ind=which(i==values$paths_fastq_tmp[,"name"])[1]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
784
          file.rename(from=values$paths_fastq_tmp[,"datapath"][ind], to=paste(tmp,"Masque_files_R1",i,sep= .Platform$file.sep))
svolant's avatar
svolant committed
785
786
787
788
789
          cmp = cmp +1
          incProgress(cmp/nfiles, detail = "Forward fastq files...")
        }
          for(i in values$R2fastQ){
            ind=which(i==values$paths_fastq_tmp[,"name"])[1]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
790
            file.rename(from=values$paths_fastq_tmp[,"datapath"][ind], to=paste(tmp,"Masque_files_R2",i,sep= .Platform$file.sep))
svolant's avatar
svolant committed
791
792
793
            cmp = cmp +1
            incProgress(cmp/nfiles, detail = "Reverse fastq files...")
          }
svolant's avatar
svolant committed
794
        })
795
        
svolant's avatar
svolant committed
796
      } else{
797
        
svolant's avatar
svolant committed
798
799
800
801
802
803
804
805
806
        cmp = 0
        nfiles = length(values$fastq_names_only)
        
        withProgress(message = 'Uploading files...', value = 0, {
            
          pathTo = paste(tmp,"Masque_files",sep=.Platform$file.sep)
          
          if(dir.exists(pathTo)){file.remove(list.files(pathTo,full.names =TRUE))} else dir.create(pathTo)
          
svolant's avatar
svolant committed
807
808
          for(i in values$fastq_names_only){
            ind=which(i==values$paths_fastq_tmp[,"name"])[1]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
809
            file.rename(from=values$paths_fastq_tmp[,"datapath"][ind], to=paste(tmp,"Masque_files",i,sep= .Platform$file.sep));cmp = cmp +1;incProgress(cmp/nfiles)}
svolant's avatar
svolant committed
810
        })
811
      }
svolant's avatar
svolant committed
812
813
      
      ## Create JSON file
svolant's avatar
svolant committed
814
815
      withProgress(message = 'Creating JSON file...',{CreateJSON(input,values)})
      if(file.exists(values$json_name)) values$num = 1
svolant's avatar
svolant committed
816
817
818
819
820
821
822
823
824
825
      sendSweetAlert(messageId="SuccessMasque",
                     title = "Success",
                     text = paste("Your data have been submitted. You will receive an e-mail once the computation over. <br /> This can take few hours.
                                  <br /> 
                                  <br /> 
                                  <br /> 
                                  <em> Remind: You can close shaman and use your key to check the progression and get your results: </em>",values$pass),
                     type = "success",
                     html=TRUE
                     )
svolant's avatar
svolant committed
826
827
    }
    
svolant's avatar
svolant committed
828
829
830
831
832
833
834
835
836
837
838
  })
  
  
  observeEvent(input$submit,{  
    
    tryCatch(MasqueSubmit(),
             error=function(e) sendSweetAlert(messageId="ErrorMasque",
                                              title = "Oops",
                                              text=paste("Something wrong when submitting.\n \n",e),type ="error"))
    
    
svolant's avatar
svolant committed
839
  },priority = 1)
svolant's avatar
svolant committed
840
  
svolant's avatar
svolant committed
841
  
svolant's avatar
svolant committed
842
843
  ## FastQ list
  output$FastQList_out <- renderUI({
svolant's avatar
svolant committed
844
845
846
847
848
849
850
851
852
853
854
    res = NULL
    if(!is.null(input$dir)){
      NullBox = h3(strong("0 FastQ file detected"),style="color:red;  text-align: center")
      res = NullBox
      
      if(length(values$fastq_names_only)>0)
      {
        res =list(selectInput("FastQList",label = "List of the fastq files in the selected directory",isolate(values$fastq_names_only),multiple =TRUE,selectize=FALSE,size = 6),
                  actionButton("RemoveFastQbut",'Remove file(s)',icon=icon("remove")))
      } else res = NullBox
    }
svolant's avatar
svolant committed
855
856
857
    return(res)
  })
  
svolant's avatar
svolant committed
858

svolant's avatar
svolant committed
859
860
861
862
863
864
865
866
867


  ## Remove FastQ function
  RemoveFastQ <-eventReactive(input$RemoveFastQbut,{
    
    if(length(input$FastQList)>0)
    {
      ind = which(values$fastq_names_only%in% input$FastQList)
      values$fastq_names_only = values$fastq_names_only[-ind]
svolant's avatar
svolant committed
868
      values$paths_fastq_tmp = values$paths_fastq_tmp[-ind,]
svolant's avatar
svolant committed
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
      updateSelectInput(session, "FastQList","List of the fastq files in the selected directory",values$fastq_names_only)
    }
  })
  
  
  
  
  
  ## Remove FastQ
  observeEvent(input$RemoveFastQbut,{  
    
    RemoveFastQ()
    if(input$MatchFiles_button>=1) MatchFiles()
    
  },priority=1)
  
  
  
  ## Update R1 and R2 lists
  MatchFiles <-reactive({
    
    if(length(values$fastq_names_only)>0 && input$PairedOrNot=='y')
    {
      indR1 = grep(input$R1files,values$fastq_names_only)
      indR2 = grep(input$R2files,values$fastq_names_only)
      
      ## If some are R1 and R2, removed from both list
      b12 = intersect(indR1,indR2)
      if(length(b12)>0) {indR1 = indR1[-which(indR1%in%b12)]; indR2 = indR2[-which(indR2%in%b12)]}
      
      
      if(length(indR1)>0 && length(indR2)>0){
        
        values$R1fastQ = values$fastq_names_only[indR1]
        values$R2fastQ = values$fastq_names_only[indR2]
        
        ## If some are only R1 or R2
        tmpR1 = gsub(input$R1files,x=values$R1fastQ,""); tmpR2 = gsub(input$R2files,x=values$R2fastQ,"")
        values$R1fastQ = values$R1fastQ[tmpR1%in%tmpR2];values$R2fastQ = values$R2fastQ[tmpR2%in%tmpR1]

        ## Update the files lists
        updateSelectInput(session, "R1filesList","",values$R1fastQ); updateSelectInput(session, "R2filesList","",values$R2fastQ)
      } else{updateSelectInput(session, "R1filesList","","");updateSelectInput(session, "R2filesList","","")}
    } else{updateSelectInput(session, "R1filesList","","");updateSelectInput(session, "R2filesList","","")}
  })
  
  
  observeEvent(input$MatchFiles_button,{  
    
    MatchFiles()
    
  },priority=1)
  
  
  
  ## Remove FastQ function directly from R1, R2
  RemoveFastQ_R1R2 <-eventReactive(input$RemoveFastQbut_R1R2,{
    
    if(length(input$R1filesList)>0)
    {
      ind = which(values$R1fastQ%in% input$R1filesList)
      values$R1fastQ = values$R1fastQ[-ind]
      updateSelectInput(session, "R1filesList","",values$R1fastQ)
    }
    
    if(length(input$R2filesList)>0)
    {
      ind = which(values$R2fastQ%in% input$R2filesList)
      values$R2fastQ = values$R2fastQ[-ind]
      updateSelectInput(session, "R2filesList","",values$R2fastQ)
939
    }
svolant's avatar
svolant committed
940
941
942
943
    
    
  })
  
svolant's avatar
svolant committed
944
945
946
947
948
949
950
951
952
953
954
  
  
  RemoveFastQ_R1R2_all <-eventReactive(input$LoadFiles,{
    
      values$R1fastQ = NULL
      updateSelectInput(session, "R1filesList","","")
      values$R2fastQ = NULL
      updateSelectInput(session, "R2filesList","","")
    
  })
  
svolant's avatar
svolant committed
955
956
957
958
959
960
961
962
  ## Remove FastQ from R1, R2
  observeEvent(input$RemoveFastQbut_R1R2,{  
    
    RemoveFastQ_R1R2()
    
  },priority=1)
  
  
svolant's avatar
svolant committed
963
964
965
966
967
968
969
970
971
  ## Remove FastQ from R1, R2 (load button)
  observeEvent(input$LoadFiles,{  
    
    RemoveFastQ_R1R2_all()
    
  },priority=1)
  
  
  
svolant's avatar
svolant committed
972
973
974
975
976
977
978
979
980
981
982
983
  # observe({
  #   CMP = CheckMasque(input, values)
  #   toggleState("submit",condition = is.null(CMP$Error))
  # })
  
  observe({
    toggleState("box-match",condition = (input$PairedOrNot=="y"))
  })
  

  output$InfoMasque<- renderUI({
    input$submit
svolant's avatar
svolant committed
984

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
985
    CMP = isolate(CheckMasque(input, values, check_mail = FALSE))
svolant's avatar
svolant committed
986
    
svolant's avatar
svolant committed
987
    if(!is.null(CMP$Error) && input$submit>0) {
svolant's avatar
svolant committed
988
989
990
      toastr_error(title="Error",message=HTML(CMP$Error),closeButton = TRUE,position ="bottom-right",preventDuplicates = TRUE,newestOnTop = TRUE,
                   progressBar = FALSE,showDuration = 300,showMethod="show",timeOut = 10000)
    }
svolant's avatar
svolant committed
991
992

  })
svolant's avatar
svolant committed
993
994


svolant's avatar
svolant committed
995
996
  output$InfoMasqueHowTo<- renderUI({
    input$submit
svolant's avatar
svolant committed
997

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
998
    CMP = isolate(CheckMasque(input, values, check_mail = FALSE))
svolant's avatar
svolant committed
999

svolant's avatar
svolant committed
1000
    if(!is.null(CMP$HowTo) && input$submit>0) {
svolant's avatar
svolant committed
1001
1002
1003
1004
      toastr_success(title="How to",message=HTML(CMP$HowTo),closeButton = TRUE,position ="bottom-right",preventDuplicates = TRUE,newestOnTop = TRUE,
                     progressBar = FALSE,showDuration = 300,showMethod="show",timeOut = 10000)
    }

svolant's avatar
svolant committed
1005
  })
svolant's avatar
svolant committed
1006

svolant's avatar
svolant committed
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071

  
  # observeEvent(input$submit,{
  #   
  #   CMP = isolate(CheckMasque(input, values))
  #   if(!is.null(CMP$HowTo)) { 
  #     toastr_success(title="How to",message=HTML(CMP$HowTo),closeButton = TRUE,position ="bottom-right",preventDuplicates = TRUE,newestOnTop = TRUE,
  #                  progressBar = FALSE,showDuration = 300,showMethod="show",timeOut = 10000)
  #   }
  #   
  # })
  # 
  # 
  # observeEvent(input$submit,{
  #   
  #   CMP = isolate(CheckMasque(input, values))
  #   if(!is.null(CMP$Error)) { 
  #     toastr_error(title="Error",message=HTML(CMP$Error),closeButton = TRUE,position ="bottom-right",preventDuplicates = TRUE,newestOnTop = TRUE,
  #                  progressBar = FALSE,showDuration = 300,showMethod="show",timeOut = 10000)
  #   }
  #   
  # })
  
 #########    ICONS   ################ 
  
  
  output$spinner_anim <- renderUI(
    htmltools::HTML('<i class="fa fa-spinner fa-pulse fa-fw" style="color:white" ></i><span class="sr-only">Loading...</span>')
  )
  
  
  output$spinner_icon <- renderUI(
    htmltools::HTML('<i class="fa fa-spinner" aria-hidden="true" style="color:white" ></i><span class="sr-only">Loading...</span>')
  )
  
  output$pause_icon <- renderUI(
    htmltools::HTML('<i class="fa fa-pause" aria-hidden="true" style="color:white" ></i><span class="sr-only">Loading...</span>')
  )
  
  output$check_icon <- renderUI(
    htmltools::HTML('<i class="fa fa-check" style="color:white" ></i><span class="sr-only">Loading...</span>')
  )
  
  
  output$key_icon <- renderUI(
    htmltools::HTML('<i class="fa fa-key" style="color:white" ></i><span class="sr-only">Loading...</span>')
  )
  
  output$test_icon <- renderUI(
    htmltools::HTML('<img src="icon.png" alt="dna" style="width:80px;height:80px;">')
  )
  
  output$amplicon_icon <- renderUI(
    htmltools::HTML('<img src="icons/amplicon.png" alt="dna" style="width:80px;height:80px;">')
  )
  output$dereplication_icon <- renderUI(
    htmltools::HTML('<img src="icons/dereplication.png" alt="dna" style="width:80px;height:80px;">')
  )
  
  output$singleton_icon <- renderUI(
    htmltools::HTML('<img src="icons/singleton.png" alt="dna" style="width:80px;height:80px;">')
  )
  output$chimera_icon <- renderUI(
    htmltools::HTML('<img src="icons/chimera.png" alt="dna" style="width:80px;height:80px;">')
  )
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
  output$otu_icon <- renderUI(
    htmltools::HTML('<img src="icons/otu.png" alt="dna" style="width:80px;height:80px;">')
  )
  output$silva_icon <- renderUI(
    htmltools::HTML('<img src="icons/silva.png" alt="dna" style="width:199px;height:80px;">')
  )
  output$greengenes_icon <- renderUI(
    htmltools::HTML('<img src="icons/greengenes.png" alt="dna" style="width:143px;height:80px;">')
  )
  output$rdp_icon <- renderUI(
    htmltools::HTML('<img src="icons/rdp.png" alt="dna" style="width:107px;height:80px;">')
  )
  output$findley_icon <- renderUI(
    htmltools::HTML('<img src="icons/findley.png" alt="dna" style="width:131px;height:80px;">')
  )
  output$unite_icon <- renderUI(
    htmltools::HTML('<img src="icons/unite.png" alt="dna" style="width:163px;height:80px;">')
  )
  output$underhill_icon <- renderUI(
    htmltools::HTML('<img src="icons/underhill.png" alt="dna" style="width:80px;height:80px;">')
  )

svolant's avatar
svolant committed
1094
1095
1096
1097
1098
1099
  #####################################
  
  
  
  output$progressBoxMasque <- renderValueBox({
    res = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1100
    error_progress = values$error_progress
svolant's avatar
json    
svolant committed
1101
    num = round(as.numeric(values$num),1)
1102
    res = shinydashboard::valueBox("0 %",h6(strong("Waiting for the data...")), color = "light-blue",width=NULL,icon = uiOutput("spinner_icon"))  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1103
    CMP = isolate(CheckMasque(input, values, check_mail=FALSE))
svolant's avatar
svolant committed
1104
    Error = CMP$Error
1105
    if(num>=100) res = shinydashboard::valueBox(paste("100 %"),h6(strong("Analysis completed ! Check your mail.")), color = "green",width=NULL,icon =  uiOutput("check_icon"))