server.R 178 KB
Newer Older
stevenn's avatar
stevenn committed
1
shinyServer(function(input, output,session) {
2
  
svolant's avatar
svolant committed
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
  ###                                               ###
  ####                    LOAD FILES ####
  ###                                               ###
stevenn's avatar
stevenn committed
8
  
9
10
  
  
stevenn's avatar
stevenn committed
11
12
  ## Create base for contrast
  rand = floor(runif(1,0,1e9))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
13
  namesfile = tempfile(pattern = "BaseContrast", tmpdir = tempdir(), fileext = "")
stevenn's avatar
stevenn committed
14
  file.create(namesfile,showWarnings=FALSE)
15
  target = NULL
16
  taxo = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
17
  proxy = dataTableProxy('DataTaxo')
18
  
svolant's avatar
svolant committed
19
20
21
  ## JSON name for masque
  curdir  = getwd()
  json_name = tempfile(pattern = "file", tmpdir = paste(curdir,"www","masque","todo",sep= .Platform$file.sep),  fileext = ".json")
22
  
svolant's avatar
svolant committed
23
24
25
  ## Pass for MASQUE
  pass = gsub("file","",basename(file_path_sans_ext(json_name)))
  
svolant's avatar
svolant committed
26
  ## Popup messages
svolant's avatar
svolant committed
27
  observe(if(input$AddRegScatter) info("By adding the regression line, you will lose interactivity."))
28
  
29
  ## Reactive target
30
  values <- reactiveValues(TargetWorking = target, TaxoWorking = taxo, labeled=NULL,fastq_names_only=NULL,R1fastQ=NULL,R2fastQ=NULL,
svolant's avatar
svolant committed
31
                           json_name=json_name,num=0,pass=pass,login_email = NULL,is.valid =NULL,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
32
33
                           biom_masque = NULL,tree_masque=NULL, masque_key = NULL, count_table_masque = NULL, 
                           rdp_annot_masque = NULL, rdp_thres_masque = NULL,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
34
                           paths_fastq_tmp=NULL,curdir=curdir, error_progress=FALSE, visTarget=FALSE, colors_diag=NULL)
35
  
stevenn's avatar
stevenn committed
36
  ## Counts file
stevenn's avatar
stevenn committed
37
  dataInputCounts <-reactive({ 
38
    
svolant's avatar
svolant committed
39
    data = NULL
stevenn's avatar
stevenn committed
40
    inFile <- input$fileCounts
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
41
42
    if (is.null(inFile) && is.null(values$count_table_masque)) return(NULL)
    #if (is.null(inFile)) return(NULL)
43
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
44
45
    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,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
46
47
               #messageId="ErrorCounts",
               error=function(e) sendSweetAlert(session,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
48
49
50
51
52
                                                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,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
53
54
               #messageId="ErrorCounts",
               error=function(e) sendSweetAlert(session,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
55
56
57
58
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
    }
    #print(data)
svolant's avatar
svolant committed
59
    if(!is.null(data)){
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
60
      colnames(data) = gsub("-",".",colnames(data))
svolant's avatar
svolant committed
61
62
      ## Rownames
      if(!TRUE%in%duplicated(data[,1])) rownames(data)=data[,1];data=data[,-1]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
63
      try(round(data, 0)->data, silent=T)
svolant's avatar
svolant committed
64
    }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
65
    print(data)
stevenn's avatar
stevenn committed
66
67
68
    return(as.data.frame(data))
  })
  
69
70
  
  
stevenn's avatar
stevenn committed
71
72
73
  ## Taxo File
  dataInputTaxo <-reactive({ 
    inFile <- input$fileTaxo
74
    values$TaxoWorking = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
75
76
    if (is.null(inFile) && is.null(values$rdp_annot_masque)) return(NULL)
    #if (is.null(inFile)) return(NULL)
77
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
78
    if(input$TypeTaxo=="Table" && !is.null(inFile)) 
Stevenn Volant's avatar
Stevenn Volant committed
79
    {
svolant's avatar
svolant committed
80
      tryCatch(read.csv(inFile$datapath,sep=input$septaxo,header=TRUE)->data,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
81
82
               #messageId="ErrorTaxo",
               error=function(e) sendSweetAlert(session,
svolant's avatar
svolant committed
83
84
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
85
      
Stevenn Volant's avatar
Stevenn Volant committed
86
      ## Rownames
svolant's avatar
svolant committed
87
88
89
90
91
92
93
94
95
      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
        }
96
      }
Stevenn Volant's avatar
Stevenn Volant committed
97
    }
stevenn's avatar
stevenn committed
98
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
99
    if(input$TypeTaxo=="RDP" && !is.null(inFile) || !is.null(values$rdp_annot_masque)) 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
100
    {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
101
102
      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,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
103
104
                 #messageId="ErrorRDP",
                 error=function(e) sendSweetAlert(session,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
105
106
107
108
109
                                                  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,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
110
111
                 #messageId="ErrorRDP",
                 error=function(e) sendSweetAlert(session,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
112
113
114
                                                  title = "Oops",
                                                  text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
      }
svolant's avatar
svolant committed
115
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
116
    }
stevenn's avatar
stevenn committed
117
118
119
    
    ## Add NA
    data=as.matrix(data)
Stevenn Volant's avatar
Stevenn Volant committed
120
    indNa = which(data=="")
stevenn's avatar
stevenn committed
121
    data[indNa]=NA
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
122
    print(data)
stevenn's avatar
stevenn committed
123
    return(as.data.frame(data))
stevenn's avatar
stevenn committed
124
  })
125
126
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
  ## BIOM File
  dataInputEpi2me <-reactive({
    
    data = NULL
    inFile <- input$fileEpi2me
    
    if (!is.null(inFile) && is.null(values$biom_masque)){
      tryCatch(read.csv(inFile$datapath,sep=input$sepepi2me,header=TRUE)->data,
               #messageId="ErrorBiom1",
               error=function(e) sendSweetAlert(session,
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
      if(FALSE %in% c(c("accuracy", "barcode", "genus", "species") %in% colnames(data))){
        data = NULL
        sendSweetAlert(session, title = "Missing data",
                       text="Shaman looks for accuracy, barcode, genus and species colnames in Epi2me files\n \n",type ="error")
      }
    }
    return(data)
  })
  
stevenn's avatar
stevenn committed
148
149
  ## BIOM File
  dataInputBiom <-reactive({ 
stevenn's avatar
stevenn committed
150
    
svolant's avatar
svolant committed
151
    data = NULL
stevenn's avatar
stevenn committed
152
    inFile <- input$fileBiom
153
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
154
    if (!is.null(inFile) && is.null(values$biom_masque)){
svolant's avatar
svolant committed
155
      tryCatch(read_biom(inFile$datapath)->data,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
156
157
               #messageId="ErrorBiom1",
               error=function(e) sendSweetAlert(session,
svolant's avatar
svolant committed
158
159
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
160
161
      
    }
svolant's avatar
svolant committed
162
163
    if (!is.null(values$biom_masque) && file.exists(values$biom_masque)){ 
      tryCatch(read_biom(values$biom_masque)->data,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
164
165
               #messageId="ErrorBiom2",
               error=function(e) sendSweetAlert(session,
svolant's avatar
svolant committed
166
167
168
                                                title = "Oops",
                                                text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
    }
stevenn's avatar
stevenn committed
169
    return(data)
stevenn's avatar
stevenn committed
170
  })
171
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
172
173
174
175
176
177
178
  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
179
180
181
  observeEvent(input$fileBiom,{
    values$biom_masque=NULL;
  })
182
  
183
  
svolant's avatar
svolant committed
184
185
186
187
  ## Unifrac File (tree)
  dataInputTree <-reactive({ 
    
    data = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
188
189
    {inFile <- input$fileTree
    values$tree_masque}
190
    
svolant's avatar
svolant committed
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    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))
    }
206
    
svolant's avatar
svolant committed
207
208
209
210
211
  })
  
  
  observeEvent(input$fileTree,{
    values$tree_masque=NULL;
svolant's avatar
svolant committed
212
213
214
215
216
  })
  
  
  # Infobox Tree (Unifrac)
  output$InfoTreePhylo_box <- renderInfoBox({
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
217
218
    {input$fileTree
     values$tree_masque}
svolant's avatar
svolant committed
219
220
    tree_tmp = isolate(dataInputTree())
    tree = tree_tmp$data
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
221

svolant's avatar
svolant committed
222
223
    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)){
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
224
      #if(!is.null(isolate(input$fileTree))){
svolant's avatar
svolant committed
225
226
227
228
229
230
231
        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"))
        }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
232
      #}
svolant's avatar
svolant committed
233
234
235
    } 
    return(res)
  })
236
  
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
  observe({
    val <- input$annotationKingdomthreshold
    # Control the value, min, max, and step.
    # Step size is 2 when input value is even; 1 when value is odd.
    updateSliderInput(session, "annotationPhylumthreshold", value = input$annotationPhylumthreshold,
                      min = val, max = 1, step = 0.005)
  })
  observe({
    val <- input$annotationPhylumthreshold[2]
    # Control the value, min, max, and step.
    # Step size is 2 when input value is even; 1 when value is odd.
    updateSliderInput(session, "annotationClassthreshold", value = input$annotationClassthreshold,
                      min = val, max = 1, step = 0.005)
  })
  observe({
    val <- input$annotationClassthreshold[2]
    # Control the value, min, max, and step.
    # Step size is 2 when input value is even; 1 when value is odd.
    updateSliderInput(session, "annotationOrderthreshold", value = input$annotationOrderthreshold,
                      min = val, max = 1, step = 0.005)
  })
  observe({
    val <- input$annotationOrderthreshold[2]
    # Control the value, min, max, and step.
    # Step size is 2 when input value is even; 1 when value is odd.
    updateSliderInput(session, "annotationFamilythreshold", value = input$annotationFamilythreshold,
                      min = val, max = 1, step = 0.005)
  })
  observe({
    val <- input$annotationFamilythreshold[2]
    # Control the value, min, max, and step.
    # Step size is 2 when input value is even; 1 when value is odd.
    updateSliderInput(session, "annotationGenusthreshold", value = input$annotationGenusthreshold,
                      min = val, max = 1, step = 0.005)
  })
  observe({
    val <- input$annotationGenusthreshold[2]
    # Control the value, min, max, and step.
    # Step size is 2 when input value is even; 1 when value is odd.
    updateSliderInput(session, "annotationSpeciethreshold", value = input$annotationSpeciethreshold,
                      min = val, max = 1, step = 0.005)
  })
stevenn's avatar
stevenn committed
279
280
  ## Input data
  dataInput <-reactive({ 
stevenn's avatar
stevenn committed
281
    
stevenn's avatar
stevenn committed
282
    data = NULL
Stevenn Volant's avatar
Stevenn Volant committed
283
284
    check = NULL
    percent = NULL
285
    Taxo = values$TaxoWorking
svolant's avatar
svolant committed
286
    Counts = NULL
svolant's avatar
svolant committed
287
    inputData = NULL
288
    target = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
289
    
stevenn's avatar
stevenn committed
290
    if(input$FileFormat=="fileCounts")
stevenn's avatar
stevenn committed
291
    {
stevenn's avatar
stevenn committed
292
      Counts = dataInputCounts()
293
      if(!input$NoTaxoFile && is.null(Taxo)) Taxo = dataInputTaxo()
svolant's avatar
svolant committed
294
295
      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
296
297
      if(!is.null(Counts) && !is.null(Taxo))
      { 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
298
        tmp = GetDataFromCT(Counts,Taxo, ifelse(input$TypeTable=="MGS" && input$FileFormat!="fileBiom", TRUE, FALSE))
299
        data = list(counts=tmp$counts,taxo=tmp$taxo, taxo_biom=tmp$taxo_biom)
svolant's avatar
svolant committed
300
301
302
        ## Remove row with only O
        # data[["counts"]] = data[["counts"]][rowSums(data[["counts"]])>1,]
        
Stevenn Volant's avatar
Stevenn Volant committed
303
304
        check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
        percent = tmp$Percent
305
      }
stevenn's avatar
stevenn committed
306
307
    }
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
308
309
310
311
312
313
314
    if(input$FileFormat=="fileEpi2me")
    {
      tmpEpi2me = dataInputEpi2me()

      if(!is.null(tmpEpi2me) && is.null(data))
      {
        tmpEpi2me = tmpEpi2me[which(tmpEpi2me$accuracy >= as.numeric(input$Epi2me_th) & !is.na(tmpEpi2me$barcode) ),]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
315
316
        # remove missing levels
        tmpEpi2me = droplevels(tmpEpi2me)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
        tmp = plyr::count(tmpEpi2me,c("barcode", "genus", "species"))
        tmp$ids = paste(tmp$genus, tmp$species, sep="|")
        tmp$index = paste0("Seq_",match(tmp$ids, unique(tmp$ids)))
        Counts = as.data.frame.matrix(t(xtabs(freq~.,tmp[,c("freq", "barcode","index")])))
        Taxo = unique(tmp[,c("index", "genus", "species")])
        rownames(Taxo) = Taxo$index
        Taxo= Taxo[,c("genus","species")]
        names(Taxo)=c("Genus","Specie")

        if(!is.null(Counts) && !is.null(Taxo))
        { 
          tmp = GetDataFromCT(Counts,Taxo, FALSE)
          # print(tmp)
          data = list(counts=tmp$counts,taxo=tmp$taxo, taxo_biom=tmp$taxo_biom)
          ## Remove row with only O
          # data[["counts"]] = data[["counts"]][rowSums(data[["counts"]])>1,]
          
          check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
          # print(check)
          percent = tmp$Percent
        }
      ## Remove row with only O
      # data[["counts"]] = data[["counts"]][rowSums(data[["counts"]])>1,]
      }
    }
342
    
stevenn's avatar
stevenn committed
343
    if(input$FileFormat=="fileBiom")
stevenn's avatar
stevenn committed
344
    {
stevenn's avatar
stevenn committed
345
      tmpBIOM = dataInputBiom()
346
      if(!is.null(tmpBIOM) && is.null(data))
Stevenn Volant's avatar
Stevenn Volant committed
347
348
      {
        tmp = GetDataFromBIOM(tmpBIOM)
349
350
351
352
353
354
355
356
357
        if(!is.null(Taxo)){ 
          data = list(counts=tmp$counts,taxo=Taxo, target=tmp$target, taxo_biom=tmp$taxo_biom)
          tmp_check = CheckTaxoTable(Taxo,tmp$counts)
          tmp_annot = PercentAnnot(tmp$counts,Taxo)
          check = list(CheckCounts=tmp_check$CheckCounts,CheckTaxo=tmp_check$CheckTaxo,Percent=tmp_annot$Percent,CheckPercent=tmp_annot$Error)
          percent = tmp_annot$Percent
          }
        else{ 
          data = list(counts=tmp$counts,taxo=tmp$taxo, target=tmp$target, taxo_biom=tmp$taxo_biom)
svolant's avatar
svolant committed
358
359
360
        ## Remove row with only O
        # data[["counts"]] = data[["counts"]][rowSums(data[["counts"]])>1,]
        
361
362
          check = list(CheckCounts=tmp$CheckCounts,CheckTaxo=tmp$CheckTaxo,CheckPercent=tmp$CheckPercent)
          percent = tmp$Percent}
363
        #if(!is.null(data$target)) values$TargetWorking = data$target
Stevenn Volant's avatar
Stevenn Volant committed
364
      }
stevenn's avatar
stevenn committed
365
366
    }
    
svolant's avatar
svolant committed
367
    
368
369
370
371
372
373
374
375
376
377
378
    
    #     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
379
    return(list(data=data,check=check,percent=percent))
stevenn's avatar
stevenn committed
380
381
382
  })
  
  
383
384
385
386
387
388
389
  ## Size factor file (optional)
  dataSizeFactors <-reactive({ 
    
    inFile <- input$fileSizeFactors
    
    if (is.null(inFile)) return(NULL)
    
svolant's avatar
svolant committed
390
    tryCatch(read.csv(inFile$datapath,sep=input$sepsize,header=TRUE)->data,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
391
392
             #messageId="ErrorSizeFactor",
             error=function(e) sendSweetAlert(session,
svolant's avatar
svolant committed
393
394
                                              title = "Oops",
                                              text=paste("Your file can not be read in SHAMAN.\n \n",e),type ="error"))
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    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}
416
      
417
418
419
420
421
422
      if(Check) normFactors = tmp
    }
    
    return(list(Check = Check,Error = Error,normFactors=normFactors))
  })
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
423
  ## Merge counts data
424
  dataMergeCounts <-reactive({
Stevenn Volant's avatar
Stevenn Volant committed
425
    input$RunDESeq
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
426
427
428
    
    counts = NULL
    CheckTarget = FALSE
429
    normFactors = NULL
Stevenn Volant's avatar
Stevenn Volant committed
430
    CT_noNorm = NULL
431
    CT_Norm = NULL
432
    ChTM = NULL
433
    ChMC = NULL
434
    data = isolate(dataInput()$data)
435
436
    target = isolate(values$TargetWorking)
    labeled= isolate(values$labeled)
437
    taxo = isolate(input$TaxoSelect)
438
    withProgress(
439
      if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0 && !is.null(taxo) && taxo!="..." && !is.null(target)) 
440
      {
441
442
443
        design = GetDesign(isolate(input),target)
        ChTM = CheckTargetModel(input,target,labeled,data$counts)$Error
        if(!is.null(design) && is.null(ChTM))
444
        {
445
          tmp = isolate(GetCountsMerge(input,data,taxo,target,design))
446
447
448
          #ChMC = tmp$Error
          #if (!is.null(ChMC))
          #{
449
450
451
452
453
454
455
456
457
458
459
460
461
462
          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
463
          #}
464
        }
465
      }
466
467
      ,message="Merging the counts ...")
    return(list(counts=counts,CheckTarget=CheckTarget,normFactors=normFactors,CT_noNorm=CT_noNorm, CT_Norm=CT_Norm, Error = ChMC))
468
    #return(list(counts=counts,target=target,labeled=labeled,normFactors=normFactors,CT_noNorm=CT_noNorm))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
469
  })
470
471
  
  
Stevenn Volant's avatar
Stevenn Volant committed
472
473
474
475
476
477
478
  # Infobox Error counts
  output$InfoErrorCounts <- renderInfoBox({
    
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0)
479
    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
480
481
482
    
    if(cond)
    {
483
484
485
      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
486
487
488
489
    }
    
    return(res)
  })
490
  
Stevenn Volant's avatar
Stevenn Volant committed
491
492
493
494
495
496
497
  # 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
498
    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
499
500
501
502
503
504
505
506
    
    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
507
    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
508
509
    return(res)
  })
510
511
  
  
Stevenn Volant's avatar
Stevenn Volant committed
512
513
  # Infobox Error counts
  output$valueErrorPercent <- renderInfoBox({
514
515
    {values$TaxoWorking
    tmp = dataInput()}
Stevenn Volant's avatar
Stevenn Volant committed
516
    data = tmp$data
517
    if(!is.null(values$TaxoWorking)) tmp = dataInput()
Stevenn Volant's avatar
Stevenn Volant committed
518
519
    check = tmp$check
    cond = (!is.null(data$counts) && nrow(data$counts)>0 && !is.null(data$taxo) && nrow(data$taxo)>0)
520
    res = shinydashboardshaman::valueBox(paste0(0, "%"),h6(strong("Annotated features")), color = "light-blue",width=NULL,icon = icon("list"))
521
    
Stevenn Volant's avatar
Stevenn Volant committed
522
523
524
    if(cond)
    {
      percent = round(100*tmp$percent,2)
525
526
      if(percent==0) res = shinydashboardshaman::valueBox(paste0(percent, "%"),h6(strong("Annotated features")), color = "red",width=NULL,icon = icon("list"))  
      if(percent!=0) res = shinydashboardshaman::valueBox(paste0(percent, "%"),h6(strong("Annotated features")), color = "green",width=NULL,icon = icon("list"))  
Stevenn Volant's avatar
Stevenn Volant committed
527
528
529
530
531
      
    }
    
    return(res)
  })
stevenn's avatar
stevenn committed
532
  
533
  
534
535
536
537
538
539
540
541
  ####### Filtering the counts (sliders)
  
  output$ThAb <- renderUI({
    input$AddFilter
    
    res = NULL
    counts = isolate(dataMergeCounts()$counts)
    tot = rowSums(counts)
542
    #save(counts,tot,file="testFilter.RData")
543
    withProgress({tmp = SelectThreshAb(counts,lambda=max(round(sum(counts)/nrow(counts)*0.05),min(tot)+1),graph=FALSE)},message="Loading...")
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
    
    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")
  
571
  output$Plot_ThAb <- renderPlot({
572
573
574
575
576
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Abundance")
    
  })
577
  
578
  output$Plot_ThSamp <- renderPlot({
579
580
581
582
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Samples")
  })
583
  
584
585
586
587
588
  output$Plot_Scatter_Filter <- renderScatterD3({
    counts = dataMergeCounts()$counts
    ## output of plot_filter is ggplot class
    plot_filter(counts,input$SliderThSamp,input$SliderThAb,type="Scatter")
  })
589
  ###                                               ###
590
  ##
591
  ##                DYNAMIC MENU ####
592
  ##
593
  ###                                               ###
stevenn's avatar
stevenn committed
594
595
596
597
598
  
  
  
  output$dymMenu <- renderMenu({
    
Stevenn Volant's avatar
Stevenn Volant committed
599
600
601
    tmp = dataInput()
    data = tmp$data
    check = tmp$check
stevenn's avatar
stevenn committed
602
    
Stevenn Volant's avatar
Stevenn Volant committed
603
604
605
    ## 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
606
    {
607
      
svolant's avatar
svolant committed
608
      sidebarMenu(id = "side",
609
610
611
612
613
614
615
616
617
618
619
                  menuItem("Statistical analysis",
                           menuSubItem("Run differential analysis",tabName="RunDiff"),
                           menuSubItem("Diagnostic plots",tabName="DiagPlotTab"),
                           menuSubItem("Tables",tabName="TableDiff"),
                           icon = icon("bar-chart-o"), tabName = "AnaStat"
                  ),
                  menuItem("Visualization",icon = icon("area-chart"),
                           menuSubItem("Global views",tabName="GlobVisu"),
                           menuSubItem("Comparison plots",tabName="CompPlot"),
                           tabName = "Visu")
                  #menuItem("Perspective plots", icon = icon("pie-chart"), tabName = "Krona")
stevenn's avatar
stevenn committed
620
      )
svolant's avatar
svolant committed
621
    } else{ sidebarMenu(id = "side",NULL)}
622
    
stevenn's avatar
stevenn committed
623
624
625
  })
  
  
626
  
627
  ###                                               ###
stevenn's avatar
stevenn committed
628
  ##
629
  ##                DATA TABLE ####
stevenn's avatar
stevenn committed
630
  ##
631
  ###                                               ###
stevenn's avatar
stevenn committed
632
633
  
  ## Counts Table
634
  output$DataCounts <- DT::renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
635
    dataInput()$data$counts, 
stevenn's avatar
stevenn committed
636
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
637
                   pageLength = 10,scrollX=TRUE, processing=FALSE
stevenn's avatar
stevenn committed
638
639
    ))
  
640
641
642
643
644
645
646
647
648
649
  ## Counts Table
  output$DataUpSet<- DT::renderDataTable({
    resDiff = ResDiffAnal()
    BaseContrast = read.table(namesfile,header=TRUE)
    datatable(Plot_UpSet(input,BaseContrast, resDiff, ContrastListDebounce)$table,
              options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
                   pageLength = 10,scrollX=TRUE, processing=FALSE)
              )
    })
  
650
  ## Counts Table
651
  output$DataVenn<- DT::renderDataTable({
652
    SelContrast = ContrastListVennDebounce()
653
    #SelContrast = input$ContrastList_table_FC
654
    resDiff = ResDiffAnal()
655
    #BaseContrast = read.table(namesfile,header=TRUE)
656
657
    datatable(GetData_venn(input,SelContrast,read.table(namesfile,header=TRUE),resDiff)$df.tot,
              options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
658
659
660
                             pageLength = 10,scrollX=TRUE, processing=FALSE)
    )
  })
661
662
663
664
665
666
667
668
669
670
  
  # 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')),
  #                  pageLength = 10,scrollX=TRUE, processing=FALSE
  #   ))
671
672
  
  
stevenn's avatar
stevenn committed
673
  ## Taxonomy table
674
  output$DataTaxo <- DT::renderDataTable(
Stevenn Volant's avatar
Stevenn Volant committed
675
    dataInput()$data$taxo, 
676
    editable=T, 
stevenn's avatar
stevenn committed
677
    options = list(lengthMenu = list(c(10, 50, -1), c('10', '50', 'All')),
678
679
                                     pageLength = 10,scrollX=TRUE, processing=FALSE)
)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
680

681
682
683
684
685
686
687
688
689
690
691
  observeEvent(input$DataTaxo_cell_edit, {
    info = input$DataTaxo_cell_edit
    str(info)
    i = info$row
    j = info$col
    v = info$value
    tmp=as.matrix(dataInput()$data$taxo)
    tmp[i,j] = v
    values$TaxoWorking = as.data.frame(tmp)
    replaceData(proxy, values$TaxoWorking, resetPaging = FALSE)
  })
stevenn's avatar
stevenn committed
692
  ## Tab box for data visualisation
stevenn's avatar
stevenn committed
693
  output$TabBoxData <- renderUI({
694
    tree = dataInputTree()$data
Stevenn Volant's avatar
Stevenn Volant committed
695
    data=dataInput()$data
svolant's avatar
svolant committed
696
697
    res=NULL
    if(!is.null(tree))
698
    {
699
      res = tabBox(width = NULL, selected = "Count table",
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
700
701
                   tabPanel("Count table",DT::dataTableOutput("DataCounts"),
                            downloadButton('ExportRawCounts', 'Export count table file')),
702
                   tabPanel("Taxonomy",DT::dataTableOutput("DataTaxo"), 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
703
                            actionButton("deleteTaxo", "Delete annotation"),
704
                            downloadButton('ExportTaxo', 'Export taxonomy file')),
705
706
                   tabPanel("Summary",h5(strong("Percentage of annotation")),htmlOutput("SummaryView"),
                            br(),h5(strong("Number of features by level:")),plotOutput("SummaryViewBarplot",width = 1200,height=500)),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
707
708
                   tabPanel("Phylogeny", PhyloTreeMetaROutput('PhyloTreeMetaR'),
                            downloadButton('ExportPhylo', 'Export phylogeny file'))
709
710
      )
      
711
    }
712
    else
stevenn's avatar
stevenn committed
713
    {
714
      res = tabBox(width = NULL,selected = "Count table",
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
715
716
                   tabPanel("Count table",DT::dataTableOutput("DataCounts"),
                            downloadButton('ExportRawCounts', 'Export count table file')),
717
                   tabPanel("Taxonomy",DT::dataTableOutput("DataTaxo"),
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
718
                            actionButton("deleteTaxo", "Delete annotation"),
719
                            downloadButton('ExportTaxo', 'Export taxonomy file')),
720
721
722
                   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
723
    }
svolant's avatar
svolant committed
724
725
726
727
728
729
730
    return(res)
  })
  
  observe({
    data=dataInput()$data
    if(!is.null(data$counts) && !is.null(data$taxo) && nrow(data$counts)>0 && nrow(data$taxo)>0)
    {
731
      showElement("tabboxdata_col",anim=TRUE)
svolant's avatar
svolant committed
732
    } else hideElement("tabboxdata_col",anim=TRUE)
stevenn's avatar
stevenn committed
733
    
stevenn's avatar
stevenn committed
734
  })
735
  
736
737
738
739
  output$PhyloTreeMetaR <- renderPhyloTreeMetaR({
    PhyloTreeMetaR(dataInputTree()$treeseq,NULL)
  })
  
svolant's avatar
svolant committed
740
  output$SummaryView <- renderGvis({
svolant's avatar
svolant committed
741
742
    tmp = dataInput()
    data = tmp$data
svolant's avatar
svolant committed
743
744
    taxo = data$taxo
    counts = data$counts
svolant's avatar
svolant committed
745
746
    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))
747
    
svolant's avatar
svolant committed
748
    res = NULL
svolant's avatar
svolant committed
749
    if(cond)
svolant's avatar
svolant committed
750
    {
svolant's avatar
svolant committed
751
      taxo = rbind(taxo,rep(NA,ncol(taxo)))
752
753
754
755
756
757
758
759
760
761
762
763
764
765
      #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)
      
766
      
svolant's avatar
svolant committed
767
      df <- data.frame(Label = colnames(taxo),Value = tmpPercent)
768
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
769
770
771
      # 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
772
      res = gvisGauge(df,options=list(min=0, max=100, greenFrom=80,
773
                                      greenTo=100, yellowFrom=60, yellowTo=80,
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
774
                                      redFrom=0, redTo=60, width=800, height=200))
svolant's avatar
svolant committed
775
776
777
778
779
780
    }
    return(res)
  })
  
  
  output$SummaryViewBarplot <- renderPlot({
svolant's avatar
svolant committed
781
782
    tmp = dataInput()
    data = tmp$data
svolant's avatar
svolant committed
783
784
    taxo = data$taxo
    counts = data$counts
svolant's avatar
svolant committed
785
786
    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))
787
    
svolant's avatar
svolant committed
788
    res = NULL
svolant's avatar
svolant committed
789
    if(cond)
svolant's avatar
svolant committed
790
791
792
793
794
795
796
797
798
799
800
801
802
    {
      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)
  })
  
803
  ###                                               ###
stevenn's avatar
stevenn committed
804
  ##
805
806
  ##                TARGET FILE ####
  ###                                               ###
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
  observe({
    counts = dataInput()$data$counts
    data = dataInput()$data$target

    if(!is.null(data) && !is.null(counts))
    {
      names = colnames(data)
      ## 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
      
      ## 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])
          #data_tmp =cbind( as.data.frame(as.data.frame(data[,-ind_num])),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 = "."))}
      }
      values$TargetWorking = data
      values$labeled = length(ind)/length(colnames(counts))*100.0
    }
  })
834
  
stevenn's avatar
stevenn committed
835
  ## Load target file
836
  observe({ 
stevenn's avatar
stevenn committed
837
    inFile <- input$fileTarget
838
    #values$TargetWorking = NULL
839

Stevenn Volant's avatar
Stevenn Volant committed
840
    counts = dataInput()$data$counts
svolant's avatar
svolant committed
841
    labeled = 0
svolant's avatar
svolant committed
842
    data = NULL
843
    
stevenn's avatar
stevenn committed
844
845
    if (is.null(inFile)) return(NULL)
    
svolant's avatar
svolant committed
846
847
    ## Read the data
    try(read.csv(inFile$datapath,sep=input$septarget,header=TRUE)->data,silent=TRUE)
848
    
svolant's avatar
svolant committed
849
850
851
852
853
854
    if(!is.null(data))
    {
      data = as.data.frame(data)
      names = colnames(data)
      
      ## Change the rownames
svolant's avatar
svolant committed
855
      if(!TRUE%in%duplicated(data[,1])) rownames(data)=gsub(pattern = "-",replacement = ".",as.character(data[,1]))
svolant's avatar
svolant committed
856
857
858
859
860
      
      ## 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
861
862
      
      
svolant's avatar
svolant committed
863
864
865
866
867
      ## 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])
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
868
          #data_tmp =cbind( as.data.frame(as.data.frame(data[,-ind_num])),data[,ind_num])
svolant's avatar
svolant committed
869
870
871
872
          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 = "."))}
873
      }
874
      values$TargetWorking = as.data.frame(data)
875
      values$visTarget = FALSE
876
877
      #       ind_sel = Target_selection()
      #       if(length(ind))
svolant's avatar
svolant committed
878
879
880
881
      # target = as.data.frame(apply(target,2,gsub,pattern = "-",replacement = "."))
      
      #ord = order(rownames(data))
      #data = data[ord,]
882
883
      ### A SUqPPRIMER 
      #rownamQes(data) <- colnames(counts)
svolant's avatar
svolant committed
884
885
886
887
888
      
      # Percent annotated
      #     print(ind)
      #     print(colnames(counts))
      #     print(rownames(data))
889
      values$labeled = length(ind)/length(colnames(counts))*100.0
svolant's avatar
svolant committed
890
    }
891
    
892
893
894
    # return(list(target = target, labeled=labeled))
  })
  
895
  
svolant's avatar
svolant committed
896
897
  
  
898
  ###                                               ###
svolant's avatar
svolant committed
899
  ##
900
  ##                        MASQUE ####
svolant's avatar
svolant committed
901
  ##
902
  ###                                               ###
svolant's avatar
svolant committed
903
904
  
  
svolant's avatar
svolant committed
905
  
svolant's avatar
svolant committed
906
907
908
  observeEvent(input$dir,{
    
    inFiles <- input$dir
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
909
    
svolant's avatar
svolant committed
910
    if (!is.null(inFiles)){
911
912
913
      # 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
914
    }
svolant's avatar
svolant committed
915
916
  })
  
917
  
svolant's avatar
svolant committed
918
  
svolant's avatar
svolant committed
919
  ## Create a fasta file containing the contaminant
svolant's avatar
svolant committed
920
921
922
923
924
925
926
927
928
929
930
  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
931
  
svolant's avatar
svolant committed
932
933
934
  
  ## Action with submit button
  MasqueSubmit <- eventReactive(input$submit,{
935
936
    galaxyAlertfile=paste(values$curdir,"www","galaxy_pasteur_alert.txt",sep= .Platform$file.sep)
    galaxyAlert = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
937
938
    #activate check_mail
    CMP = CheckMasque(input, values,check_mail = TRUE)
svolant's avatar
svolant committed
939
    Error = CMP$Error
940
    
svolant's avatar
svolant committed
941
    isJSONalreadyExist = file.exists(paste(values$curdir,"www","masque","doing",basename(json_name),sep= .Platform$file.sep))
942