VisuPlot.R 22.1 KB
Newer Older
svolant's avatar
svolant committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#@ This file contains all the functions for the 
#@ visualisation plots of SHAMAN


###########################
##        Barplot
###########################

Plot_Visu_Barplot <- function(input,resDiff)
{
  
  ## Get Input for BarPlot
  VarInt = input$VisuVarInt
  ind_taxo = input$selectTaxoPlot
  
  tmp_combined = GetDataToPlot(input,resDiff,VarInt,ind_taxo)
  counts_tmp_combined = tmp_combined$counts
  nbKept = length(ind_taxo)
  SamplesNames = tmp_combined$namesCounts
  
  if(nbKept>1) namesTax = colnames(counts_tmp_combined)
  if(nbKept==1) namesTax = ind_taxo
  
  dataNull = data.frame(x=c(0,0),y=c(1,2))
  plotd3 = nvd3Plot(x ~ y , data = dataNull, type = "multiBarChart", id = 'barplotTaxoNyll',height = input$heightVisu,width=input$widthVisu)
  gg = NULL
  
  if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0 && length(VarInt)>0)
  { 
    
    ## Create the data frame for the plot function
    dataBarPlot_mat = c()
    tmp_mat = matrix(0,ncol=3,nrow=nbKept)
    tmp_counts = c()
    
    for(i in 1:(nrow(counts_tmp_combined)))
    {
      ## Taxo
      tmp_mat[1:nbKept,1] = namesTax
      
      ## Counts
      
      tmpProp = counts_tmp_combined[i,]
      if(input$CountsOrProp=="prop")
      { 
        tmpProp = round(tmpProp/sum(tmpProp),3)
        tmpProp = as.numeric(tmpProp/sum(tmpProp) * 100)
      }
      tmp_counts = c(tmp_counts,tmpProp)      
      
      ## Meta data
      tmp_mat[1:nbKept,3] = as.character(rep(SamplesNames[i],nbKept))
      
      ## Conbined the sample
      dataBarPlot_mat = rbind(dataBarPlot_mat,tmp_mat)
    }
    
    
    ## Add numeric vector to the dataframe
    dataBarPlot_mat = as.data.frame(dataBarPlot_mat)
    
    colnames(dataBarPlot_mat) = c("Taxonomy","Proportions","AllVar")
    dataBarPlot_mat[,2] = tmp_counts
    if(input$SensPlotVisu == "Vertical") Sens = "multiBarChart"
    if(input$SensPlotVisu == "Horizontal") Sens = "multiBarHorizontalChart"
    
    plotd3 <- nvd3Plot(Proportions ~ AllVar | Taxonomy, data = dataBarPlot_mat, type = Sens, id = 'barplotTaxo',height = input$heightVisu,width=input$widthVisu)
    plotd3$chart(stacked = TRUE)
    
    ##################################
    ## Same plot in ggplot2 for export
    ##################################
    
    tax.colors=rep(c("#1f77b4","#aec7e8","#ff7f0e","#ffbb78", "#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b",
                     "#c49c94","#e377c2","#f7b6d2","#7f7f7f", "#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"),ceiling(nbKept/20))
    
    dataBarPlot_mat$Taxonomy = factor(dataBarPlot_mat$Taxonomy,levels = namesTax)
svolant's avatar
svolant committed
78
    dataBarPlot_mat$AllVar = factor(dataBarPlot_mat$AllVar,levels = unique(dataBarPlot_mat$AllVar))
svolant's avatar
svolant committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
    
    gg= ggplot(dataBarPlot_mat, aes(x=AllVar, y=Proportions, fill=Taxonomy)) 
    gg= gg + geom_bar(stat="identity")
    gg= gg + theme_bw()+ scale_fill_manual(values=tax.colors)
    gg = gg +theme(panel.grid.minor.x=element_blank(),panel.grid.major.x=element_blank()) 
    if(input$CountsOrProp=="prop") gg = gg+labs(y="Relative abundance (%)",x="")
    if(input$CountsOrProp=="counts") gg = gg+labs(y="Abundance",x="")
    if(input$SensPlotVisu == "Horizontal") gg = gg + coord_flip()
  } 
  return(list(plotd3=plotd3,gg=gg))
}



##############################
##          HEATMAP
##############################
Plot_Visu_Heatmap <- function(input,resDiff,export=FALSE){
  
  VarInt = input$VisuVarInt
  ind_taxo = input$selectTaxoPlot
  
  counts_tmp_combined = GetDataToPlot(input,resDiff,VarInt,ind_taxo)$counts
  
  if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0)
  { 
    ## Transform to log2
    counts_tmp_combined = log2(GetDataToPlot(input,resDiff,VarInt,ind_taxo)$counts+1)
    
    col <- switch(input$colors,
                  "green-blue"=colorRampPalette(brewer.pal(9,"GnBu"))(200),
                  "blue-white-red"=colorRampPalette(rev(brewer.pal(9, "RdBu")))(200),
                  "purple-white-orange"=colorRampPalette(rev(brewer.pal(9, "PuOr")))(200),
                  "red-yellow-green"= colorRampPalette(rev(brewer.pal(9,"RdYlGn")))(200))
    
    ## Transpose matrix if Horizontal
    if(input$SensPlotVisu=="Horizontal") counts_tmp_combined = t(as.matrix(counts_tmp_combined))
    
    if(!export) plot = d3heatmap(counts_tmp_combined, dendrogram = "none", Rowv = NA, Colv = NA, na.rm = TRUE,width = input$widthVisu, height = input$heightVisu, show_grid = FALSE, colors = col, scale = input$scaleHeatmap,cexRow = 0.6)
    if(export) plot = heatmap.2(counts_tmp_combined, dendrogram = "none", Rowv = NA, Colv = NA, na.rm = TRUE, density.info="none", margins=c(12,8),trace="none",srtCol=45,col = col, scale = input$scaleHeatmap,cexRow = 0.6)
    return(plot)
  }
}



##############################
##          BOXPLOTS
##############################
Plot_Visu_Boxplot <- function(input,resDiff,alpha=0.7){
  
  gg = NULL
  
  ## Colors
  colors = rep(c("#1f77b4","#aec7e8","#ff7f0e","#ffbb78", "#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b",
                 "#c49c94","#e377c2","#f7b6d2","#7f7f7f", "#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"),ceiling(nrow(resDiff$target)/20))
  
  ## Get Input for BoxPlot
  VarInt = input$VisuVarInt
  ind_taxo = input$selectTaxoPlot
  
  
  tmp_merge = GetDataToPlot(input,resDiff,VarInt,ind_taxo,aggregate=FALSE)
  counts_tmp_combined = tmp_merge$counts
  levelsMod = tmp_merge$levelsMod
  nbKept = length(ind_taxo)
  
  if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0 && !is.null(levelsMod))
  { 
    
    if(input$typeDataBox == "Relative") counts_tmp_combined = tmp_merge$prop_all
    else counts_tmp_combined = log2(counts_tmp_combined+1)
    if(nbKept==1) colnames(counts_tmp_combined)=ind_taxo
    
    ## Create the data frame for the plot function
    dataBarPlot_mat = c()
    tmp_mat = matrix(0,ncol=3,nrow=nbKept)
    tmp_counts = c()
    
    for(i in 1:(nrow(counts_tmp_combined)))
    {
      ## Taxo
      tmp_mat[1:nbKept,1] = colnames(counts_tmp_combined)
      
      ## Counts        
      tmpProp = counts_tmp_combined[i,]
      tmp_counts = c(tmp_counts,tmpProp)      
      
      ## Meta data
      tmp_mat[1:nbKept,3] = as.character(rownames(counts_tmp_combined)[i],nbKept)
      
      ## Conbined the sample
      dataBarPlot_mat = rbind(dataBarPlot_mat,tmp_mat)
    }
    
    
    dataBarPlot_mat = as.data.frame(dataBarPlot_mat)
    
    colnames(dataBarPlot_mat) = c("Taxonomy","Value","Samples")
    dataBarPlot_mat[,2] = tmp_counts
    
    if(is.null(input$BoxColorBy) || length(VarInt)<=1){ dataBarPlot_mat$Colors = dataBarPlot_mat$Samples}
    if(!is.null(input$BoxColorBy) && length(VarInt)>1)
    { 
      tmp = strsplit(as.character(dataBarPlot_mat$Samples),"-")
      ind = which(VarInt%in%input$BoxColorBy)
      dataBarPlot_mat$Colors = rapply(tmp, function(x) paste(x[ind],collapse ="-"), how = "unlist")
    }
    
    dataBarPlot_mat$Samples = factor(dataBarPlot_mat$Samples,levels=levelsMod)
    
    gg = ggplot(dataBarPlot_mat,aes(x=Samples,y=Value,fill=Colors))  + geom_boxplot(alpha=alpha) +theme_bw()
    gg = gg  +theme(axis.text=element_text(size=16,face="bold"),axis.title=element_text(size=18,face="bold"),panel.background = element_blank(),
                    panel.grid.major = element_blank(),panel.grid.minor = element_blank(), axis.title.x=element_blank(), axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)) 
    gg = gg + ylab(paste(input$typeDataBox, "abundance")) +scale_fill_manual(values = colors) + guides(fill=FALSE)
    if(input$CheckAddPointsBox) gg = gg + geom_point(position=position_jitterdodge(dodge.width=0.9))
    if(input$SensPlotVisu=="Horizontal") gg = gg + coord_flip()
    if(nbKept>1) gg = gg + facet_wrap(~ Taxonomy,scales = input$ScaleBoxplot)
  }
  
  return(gg)
}



##############################
##      SCATTER PLOT
##############################
Plot_Visu_Scatterplot<- function(input,resDiff,export=FALSE,lmEst = FALSE,CorEst=FALSE){
  
  plot = NULL
  regCoef = NULL
  Rsq = NULL
  cor.est = NULL
  cor.pvalue = NULL
  div = NULL
  dds = resDiff$dds
  counts = as.data.frame(round(counts(dds, normalized = TRUE)))
  target = as.data.frame(resDiff$target)
  ## Get the diversity values
  tmp_div = Plot_Visu_Diversity(input,resDiff,ForScatter=TRUE)$dataDiv
  
  if(!is.null(tmp_div)){
    div = cbind(round(tmp_div$value[tmp_div$diversity =="Alpha"],3),
                round(tmp_div$value[tmp_div$diversity =="Shannon"],3),
                round(tmp_div$value[tmp_div$diversity =="Inv.Simpson"],3),
                round(tmp_div$value[tmp_div$diversity =="Simpson"],3))
    colnames(div) = c("Alpha div","Shannon div","Inv.Simpson div","Simpson div")
  }
  if(input$TransDataScatter =="log2") data = cbind(target,log2(t(counts)+1),div)
  if(input$TransDataScatter =="none") data = cbind(target,t(counts),div)
  
  
  ## Get Input for ScatterPlot
  Xvar = input$Xscatter
  Yvar = input$Yscatter
  ColBy = input$ColorBy
  PchBy = input$PchBy
  PointSize = input$PointSize
  
  x_var = if (is.null(Xvar)) NULL else data[,Xvar]
  y_var = if (is.null(Yvar)) NULL else data[,Yvar]
  col_var = if (ColBy== "None" || is.null(ColBy)) NULL else data[,ColBy]
  symbol_var = if (PchBy == "None" || is.null(PchBy)) NULL else data[,PchBy]
  size_var = if (PointSize == "None" || is.null(PointSize))  NULL else data[,PointSize]
  
  if(!export && !input$AddRegScatter && !lmEst && !CorEst && !is.null(x_var) && !is.null(y_var)){
    plot = scatterD3(x = x_var,
                     y = y_var,
                     lab = rownames(data),
                     xlab = Xvar,
                     ylab = Yvar,
                     col_var = col_var,
                     col_lab = ColBy,
                     symbol_var = symbol_var,
                     symbol_lab = PchBy,
                     size_var = size_var,
                     size_lab = PointSize,
                     key_var = rownames(data),
                     height = input$heightVisu,
                     point_opacity = 0.7,
                     labels_size = input$SizeLabelScatter,
                     transitions = TRUE)
    return(plot)
  }
  
  if(export || input$AddRegScatter){
    if(!lmEst && !CorEst){
      col_var = if (ColBy== "None" || is.null(ColBy)) 1 else data[,ColBy]
      symbol_var = if (PchBy == "None" || is.null(PchBy)) factor(rep(1,nrow(data))) else data[,PchBy]
      size_var = if (PointSize == "None" || is.null(PointSize))  1 else data[,PointSize]
      
      plot = ggplot(data, aes(x = x_var, y = y_var)) + geom_point(aes(color=col_var,size =size_var,shape = symbol_var),alpha=0.7) +theme_bw()
272
      if(input$AddRegScatter) plot = plot + geom_smooth(method="lm")
svolant's avatar
svolant committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
      if(input$SizeLabelScatter!=0) plot = plot + geom_text(aes(label=rownames(data),color=col_var,size=as.numeric(input$SizeLabelScatter)/10),vjust = 0,nudge_y =0.05)
      plot = plot + xlab(Xvar) + ylab(Yvar)
      
      return(plot)
    }
  }
  if(lmEst && !CorEst)
  {
    res = lm(y_var~x_var)
    sumRes = summary(res)
    regCoef = sumRes$coefficients 
    rownames(regCoef) = c("Intercept",Xvar)
    Rsq = sumRes$r.squared
    return(list(regCoef=regCoef,Rsq = Rsq))
  }
  if(CorEst)
  {
    typesTarget = sapply(target,class)
    numInd = (typesTarget=="numeric")[1:ncol(target)]
    
    if(any(numInd)) data = cbind(target[,numInd],log2(t(counts)+1),div)
    if(!any(numInd)) data = cbind(log2(t(counts)+1),div)
    
296
    cor.est = round(cor(as.matrix(data),method = input$CorMeth),3)
svolant's avatar
svolant committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
    #cor.pvalue = cor.test(data,method = input$CorMeth)
    return(list(cor.est=cor.est))
  }
}



##############################
##      Diversity
##############################
Plot_Visu_Diversity <- function(input,resDiff,ForScatter=FALSE){
  gg = NULL
  dataTmp = NULL
  dds = resDiff$dds
  counts = round(counts(dds, normalized = TRUE))
  
  ## Get Input for the plot
  if(!ForScatter)
  {
    VarInt = input$VisuVarInt
    VarIntBoxDiv = input$VarBoxDiv 
    VarIntDivCol = input$VarDivCol
    ind_taxo = rownames(counts)
    tmp = GetDataToPlot(input,resDiff,VarInt,ind_taxo,aggregate=FALSE,rarefy = TRUE)
    counts_tmp_combined = tmp$counts
    targetInt = tmp$targetInt
    levelsMod = tmp$levelsMod
  }
  if(ForScatter)
  {
    counts_tmp_combined = t(counts)
    targetInt = resDiff$target
    targetInt$AllVar = targetInt[,1]
    levelsMod = NULL
  }
  
  if(nrow(counts_tmp_combined)>0 && !is.null(counts_tmp_combined) && !is.null(targetInt))
  { 
    sqrt.nb = sqrt(table(targetInt$AllVar))
336
    # save(counts_tmp_combined,targetInt,file = "testDiv.RData")
svolant's avatar
svolant committed
337
    alpha <- tapply(TaxoNumber(counts_tmp_combined), targetInt$AllVar, mean)
338
339
    ci.alpha.down = pmax(alpha - 1.96*tapply(TaxoNumber(counts_tmp_combined), targetInt$AllVar, sd)/sqrt.nb,0)
    ci.alpha.up = alpha + 1.96*tapply(TaxoNumber(counts_tmp_combined), targetInt$AllVar, sd)/sqrt.nb
svolant's avatar
svolant committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
    
    shan <- tapply(diversity(counts_tmp_combined, index = "shannon"), targetInt$AllVar, mean)
    ci.shan.down = pmax(shan - 1.96*tapply(diversity(counts_tmp_combined, index = "shannon"), targetInt$AllVar, sd)/sqrt.nb,0)
    ci.shan.up = shan + 1.96*tapply(diversity(counts_tmp_combined, index = "shannon"), targetInt$AllVar, sd)/sqrt.nb
    
    simpson <- tapply(diversity(counts_tmp_combined, index = "simpson"), targetInt$AllVar, mean)
    ci.simpson.down = pmax(simpson - 1.96*tapply(diversity(counts_tmp_combined, index = "simpson"), targetInt$AllVar, sd)/sqrt.nb,0)
    ci.simpson.up = simpson + 1.96*tapply(diversity(counts_tmp_combined, index = "simpson"), targetInt$AllVar, sd)/sqrt.nb
    
    invsimpson <- tapply(diversity(counts_tmp_combined, index = "invsimpson"), targetInt$AllVar, mean)
    ci.invsimpson.down = pmax(invsimpson - 1.96*tapply(diversity(counts_tmp_combined, index = "invsimpson"), targetInt$AllVar, sd)/sqrt.nb,0)
    ci.invsimpson.up = invsimpson + 1.96*tapply(diversity(counts_tmp_combined, index = "invsimpson"), targetInt$AllVar, sd)/sqrt.nb
    
    gamma <- TaxoNumber(counts_tmp_combined, targetInt$AllVar)
    beta = gamma/alpha - 1
    nb = length(alpha)
    
    dataTmp = data.frame(value=c(alpha,beta,gamma,shan,simpson,invsimpson),
                         ci.down=c(ci.alpha.down,beta,gamma,ci.shan.down,ci.simpson.down,ci.invsimpson.down),
                         ci.up=c(ci.alpha.up,beta,gamma,ci.shan.up,ci.simpson.up,ci.invsimpson.up),
                         diversity = c(rep("Alpha",nb),rep("Beta",nb),rep("Gamma",nb),rep("Shannon",nb),rep("Simpson",nb),rep("Inv.Simpson",nb)),
                         Var = as.character(rep(names(alpha),6)))
    
    if(!ForScatter)
    {                  
      dataTmp = dataTmp[dataTmp$diversity%in%input$WhichDiv,]
      
      ## Order of the modalities
      dataTmp$Var = factor(dataTmp$Var,levels = levelsMod)
      
      tmp.mat = matrix(unlist((lapply(as.matrix(as.character(dataTmp$Var)),strsplit,"-"))),ncol=length(VarInt),byrow = T)
      tmp.level = matrix(unlist((lapply(as.matrix(as.character(levelsMod)),strsplit,"-"))),ncol=length(VarInt),byrow = T)
      
      indVar = VarInt%in%VarIntBoxDiv
      if(length(which(indVar))>=1){
        if(length(which(indVar))>=2){
          tmp.levelX = apply(tmp.level[,which(indVar)],1,paste,collapse = "-")
          dataTmp$VarX = factor(apply(tmp.mat[,which(indVar)],1,paste,collapse = "-"),levels = unique(tmp.levelX))
        }
        if(length(which(indVar))==1){
          tmp.levelX = tmp.level[,which(indVar)]
          dataTmp$VarX = factor(tmp.mat[,which(indVar)],levels = unique(tmp.levelX))
        }
      }
      
      if(is.null(VarIntBoxDiv)) dataTmp$VarX = tmp.mat[,1]
      dataTmp$VarCol = dataTmp$VarX
      
      if(length(which(!indVar))>=1){
        if(length(which(!indVar))>=2){
          tmp.levelCol = apply(tmp.level[,which(!indVar)],1,paste,collapse = "-")
          dataTmp$VarCol = factor(apply(tmp.mat[,which(!indVar)],1,paste,collapse = "-"),levels = unique(tmp.levelCol))
        }
        if(length(which(!indVar))==1){ 
          tmp.levelCol = tmp.level[,which(!indVar)]
          dataTmp$VarCol = factor(tmp.mat[,which(!indVar)],levels = unique(tmp.levelCol))
        }
      }
      
      
      colors = rep(c("#1f77b4","#aec7e8","#ff7f0e","#ffbb78", "#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b",
                     "#c49c94","#e377c2","#f7b6d2","#7f7f7f", "#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"),ceiling(nrow(targetInt)/20))
      
      gg = ggplot(dataTmp, aes(x=VarX, y=value, fill=VarCol)) 
      gg = gg + theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5), legend.title=element_blank())
      gg = gg + geom_bar(stat = "identity",width=0.4,position = position_dodge(width=0.5),alpha=0.8) 
      if(input$DivAddError=="Add") gg = gg + geom_errorbar(aes(ymin=ci.down, ymax=ci.up,color=VarCol,width=.2),position = position_dodge(width=0.5))
      if(input$SensPlotVisu=="Horizontal") gg = gg + coord_flip() + facet_wrap(~ diversity,scales="fixed")
      if(input$SensPlotVisu=="Vertical") gg = gg + facet_wrap(~ diversity,scales=input$DivScale)
      gg = gg + xlab(paste(VarIntBoxDiv,collapse ="-"))+ ylab("Diversity")
      gg = gg + scale_fill_manual(values = colors[1:length(unique(dataTmp[,7]))]) + scale_color_manual(values = colors[1:length(unique(dataTmp[,7]))])
    }
    
    ## Get interactivity
    #ff = ggplotly(gg)
  }
416
  
svolant's avatar
svolant committed
417
418
419
420
421
422
423
424
425
426
427
428
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
  return(list(plot=gg,dataDiv = dataTmp))
  
}


##############################
##       RAREFACTION
##############################
Plot_Visu_Rarefaction <- function(input,resDiff,xlim,ylim,ylab="Species"){
  
  PlotRare = NULL
  dds = resDiff$dds
  
  ## Taxo in columns
  counts = t(round(counts(dds, normalized = TRUE)))
  
  if(nrow(counts)>0 && !is.null(counts))
  { 
    max <- max(rowSums(counts))
    raremax <- min(rowSums(counts))
    #PlotRare = rarefaction_curve(counts, step = 10, taxo = "Taxonomy level") 
    options(warn=-1)
    PlotRare = rarecurve(counts, step = max(1,ceiling(max/60)),sample=raremax, col = "blue", cex = 0.9,xlim=xlim,ylim=ylim, ylab=ylab) 
    options(warn=0)
  }
  return(PlotRare)
}




##############################################################
##
##          Useful functions
##
##############################################################

## Get the non-zero taxo by sample  
TaxoNumber <-  function (x, groups, mar = 1) 
{
  if (!missing(groups)) 
  {
    if (length(groups) == 1) groups = rep(groups, nrow(x))
    x = aggregate(x, list(groups), max)
    rownames(x) = x[, 1]; x = x[, -1]
  }
  if (length(dim(x)) > 1) res = apply(x > 0, mar, sum)
  else res = sum(x > 0)
}


## Modified version of expand.grid
expand.grid2.list <- function(listInput)
{
  n = length(listInput)
  if(is.list(listInput) && n>1)
  {
    l1 = listInput[[1]]
    l2 = listInput[[2]]
    res = c()
    
    for(i in l1){
      for(j in l2){ 
        res = rbind(res,paste(i,j,sep = "-"))
      }
    }
    listInput[[1]] = res
    listInput = listInput[-2]
    if(length(listInput)>1 && is.list(listInput)) res = expand.grid2.list(listInput)
  }
  else res = listInput
  return(res)
}


## Put the data in the right format to be plot
GetDataToPlot <- function(input,resDiff,VarInt,ind_taxo,aggregate=TRUE,rarefy=FALSE)
{
  dds = resDiff$dds
  val = c()
  list.val = list()
  counts = as.data.frame(round(counts(dds, normalized = TRUE)))
  if(rarefy) {set.seed(1234); counts = t(rrarefy(t(counts), min(colSums(counts))))}
  
  target = resDiff$target
  counts_tmp_combined = NULL
  prop_tmp_combined = NULL
  targetInt = NULL
  namesCounts = NULL
  levelsMod = NULL
  prop_all=NULL
  ## Select a subset within the taxonomy level (default is the 12 most abundant)
  nbKept = length(ind_taxo)
  Taxonomy = rownames(counts)
  
  if (length(VarInt)>0 && nbKept>0)
  { 
    
    ## Get the modalities to keep
    for(i in 1:length(VarInt))
    { 
      ## Replace "-" by "." 
      target[,VarInt[i]] =  gsub("-",".",target[,VarInt[i]])
      
      Tinput = paste("input$","ModVisu",VarInt[i],sep="")
      expr=parse(text=Tinput)
      ## All the modalities for all the var of interest
      val = c(val,eval(expr))
      list.val[[i]] = eval(expr)
    }
    if (!is.null(val) && !is.null(list.val))
    {
      
      ## Create the variable to plot
      targetInt = as.data.frame(target[,VarInt])
      rownames(targetInt)=target[,1]  
      ## Combining the Varint
      if(length(VarInt)>1){targetInt$AllVar = apply(targetInt,1,paste, collapse = "-"); targetInt$AllVar = factor(targetInt$AllVar,levels =  expand.grid2.list(list.val))}
      if(length(VarInt)<=1){targetInt$AllVar = target[,VarInt]; targetInt$AllVar = factor(targetInt$AllVar,levels = val)}
      colnames(targetInt) = c(VarInt,"AllVar")
      
      ## Keep only the selected modalities
      ind_kept = which(!is.na(targetInt$AllVar))
      targetInt = targetInt[ind_kept,]
      
      levelsMod = levels(targetInt$AllVar)
      
      ## Create the counts matrix only for the selected subset
      counts_tmp = counts[Taxonomy%in%ind_taxo,]
      counts_tmp = counts_tmp[,colnames(counts_tmp)%in%rownames(targetInt)]
      
      ## Proportions over all the taxonomies
      prop_all = t(counts)/rowSums(t(counts))
      prop_all = as.data.frame(prop_all[,Taxonomy%in%ind_taxo])
      prop_all = as.matrix(prop_all[rownames(prop_all)%in%rownames(targetInt),])
      rownames(prop_all) = targetInt$AllVar
      
      ## Be careful transposition !
      if(aggregate && nrow(counts_tmp)>0 && nrow(targetInt)>0)
      { 
        counts_tmp_combined = aggregate(t(counts_tmp),by=list(targetInt$AllVar),mean)
        rownames(counts_tmp_combined) = counts_tmp_combined$Group.1
        namesCounts = counts_tmp_combined$Group.1
        counts_tmp_combined = as.matrix(counts_tmp_combined[,-1])
      }
      if(!aggregate && nrow(counts_tmp)>0 && nrow(targetInt)>0)
      {  
        counts_tmp_combined = t(counts_tmp)
        prop_tmp_combined = counts_tmp_combined/colSums(counts_tmp)
        rownames(counts_tmp_combined) = targetInt$AllVar
        namesCounts = targetInt$AllVar
        rownames(prop_tmp_combined) = targetInt$AllVar
      }
      
      ## Ordering the counts
      if(!is.null(counts_tmp_combined))
      {
        MeanCounts = apply(counts_tmp_combined,2,mean)
        ord = order(MeanCounts,decreasing=TRUE)
        counts_tmp_combined = as.matrix(counts_tmp_combined[,ord])
        if(!aggregate) prop_tmp_combined = as.matrix(prop_tmp_combined[,ord])
        prop_all = as.matrix(prop_all[,ord])
      }
    }
  }
  
  return(list(counts = counts_tmp_combined,targetInt=targetInt,prop=prop_tmp_combined,namesCounts=namesCounts,levelsMod=levelsMod,prop_all=prop_all))
  
  
}