internal.R 54 KB
Newer Older
stevenn's avatar
stevenn committed
1
2
3



stevenn's avatar
stevenn committed
4
5
6
7
8
9
10
  GetDataFromBIOM <-function(dataBIOM)
  {
    
    counts = biom_data(dataBIOM)
    taxo = observation_metadata(dataBIOM)
    return(list(counts=counts,taxo=taxo))
  }
stevenn's avatar
stevenn committed
11
12
  
  
stevenn's avatar
stevenn committed
13
14
15
16
17
18
19
20
21
  GetDataFromCT <-function(dataC,dataT)
  {
    
    counts = dataC
    taxo = dataT
    return(list(counts=counts,taxo=taxo))
  }
  
  GetInteraction2 <- function(target)
stevenn's avatar
stevenn committed
22
  { 
stevenn's avatar
stevenn committed
23
24
25
26
    res=c()
    namesTarget = colnames(target)[2:ncol(target)]
    k=1
    for(i in 1:(length(namesTarget)-1))
stevenn's avatar
stevenn committed
27
    { 
stevenn's avatar
stevenn committed
28
29
30
31
32
      for(j in (i+1):length(namesTarget))
      { 
        res[k] = paste(namesTarget[i],":",namesTarget[j],sep="")
        k = k+1
      }
stevenn's avatar
stevenn committed
33
    }
stevenn's avatar
stevenn committed
34
35
    
    return(res)
stevenn's avatar
stevenn committed
36
37
38
39
  }
  


Amine  GHOZLANE's avatar
Amine GHOZLANE committed
40
  ## Print the contrasts
stevenn's avatar
stevenn committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  PrintContrasts <- function (coefs, contrasts,contnames) 
  {
    contrasts = as.matrix(contrasts)
    out <-""
    
    for (i in 1:ncol(contrasts)) 
    {
      contrast <- contrasts[,i]
      contrast <- paste(ifelse(contrast > 0, "+ ", ""), contrast, sep = "")
      contrast <- gsub("( 1)|(1)", "", contrast)
      out = paste(out,paste("<b>",contnames[i], ":</b> <br/>", paste(contrast[contrast != 0], coefs[contrast != 0], collapse = " ", sep = " ")),"<br/>")
    }
    return(out)
    
  }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
56
57

  
stevenn's avatar
stevenn committed
58
59
  
  ## Get the counts for the selected taxonomy
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
60
  GetCountsMerge <- function(input,dataInput,taxoSelect,target,design)
stevenn's avatar
stevenn committed
61
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
62
63
    counts= NULL
    CheckTarget = FALSE
stevenn's avatar
stevenn committed
64
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
65
    ## Counts and taxo tables
stevenn's avatar
stevenn committed
66
67
    CT = dataInput$counts
    taxo = dataInput$taxo
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
68
69
70
71
        
    ## Select cols in the target
    labels = target[,1]
    ind = which(colnames(CT)%in%labels)
stevenn's avatar
stevenn committed
72
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    if(length(ind)==length(labels))
    { 
      CT = CT[,ind]
      
      ## Order CT according to the target
      CT = OrderCounts(CT,labels)
#       ind0 = which(rowSums(CT)==0)
#       if(length(ind0)>0) CT = CT[-ind0,]
      
      ## Counts normalisation
      dds <- DESeqDataSetFromMatrix(countData=CT, colData=target, design=design)
      dds <- estimateSizeFactors(dds,locfunc=eval(as.name(input$locfunc)))

      CT = as.data.frame(round(counts(dds, normalized = TRUE)))
      ordOTU = order(rownames(taxo))
      indOTU_annot = which(rownames(CT)%in%rownames(taxo))
      counts_annot = CT[indOTU_annot[ordOTU],]
      
      if(taxoSelect=="OTU") counts = counts_annot
      else{
      taxoS = taxo[ordOTU,taxoSelect]
      counts = aggregate(counts_annot,by=list(Taxonomy = taxoS),sum)
      rownames(counts)=counts[,1];counts=counts[,-1]
      }
      
      ## Ordering the counts table according to the target labels 
      counts = OrderCounts(counts,labels)
      CheckTarget = TRUE
    }
    return(list(counts=counts,CheckTarget=CheckTarget))
stevenn's avatar
stevenn committed
103
104
  }

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
105
106
107
108
109
  ## Order the counts 
  OrderCounts <- function(counts,labels)
  {
    n = length(labels)
    CountsOrder = counts
stevenn's avatar
stevenn committed
110

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
111
112
113
114
115
116
117
118
119
120
121
    for(i in 1:n)
    {
      
      ind = which(labels[i]==colnames(counts))
      CountsOrder[,i] = counts[,ind]
    }
    colnames(CountsOrder) = labels
    return(CountsOrder)
  }
  
  
stevenn's avatar
stevenn committed
122
123
124
  ## Get the dds object of DESeq2
  Get_dds_object <- function(input,counts,target,design)
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
125
    
stevenn's avatar
stevenn committed
126
    dds <- DESeqDataSetFromMatrix(countData=counts, colData=target, design=design)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
127
    normFactors = rep(1,nrow(target))
stevenn's avatar
stevenn committed
128
    ## Size factor estimation
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
129
130
131
    #dds <- estimateSizeFactors(dds,locfunc=eval(as.name(input$locfunc)))
    #normalizationFactors(dds) <- normFactors
    sizeFactors(dds)<- normFactors
stevenn's avatar
stevenn committed
132
133
134
135
136
137
138
139
140
141
142
143
    dds <- estimateDispersions(dds, fitType=input$fitType)
    dds <- nbinomWaldTest(dds)
    return(list(dds = dds,counts=counts,target=target,design=design))
  }

  ## Get the design according to the input
  GetDesign <- function(input)
  {
    InterVar = input$InterestVar
    Interaction = input$Interaction2
    alltmp = c(InterVar,Interaction)
    design = as.formula(paste("~", paste0(alltmp, collapse= "+")))
stevenn's avatar
stevenn committed
144

stevenn's avatar
stevenn committed
145
146
147
148
149
150
151
152
    return(design)
  }
  


  ## Diagnostic Plots
  Plot_diag <- function(input,resDiff)
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
153
154
    #colors = c("dodgerblue","firebrick1","MediumVioletRed","SpringGreen")
    colors = c("SpringGreen","dodgerblue","black","firebrick1")
stevenn's avatar
stevenn committed
155
156
157
158
159
    VarInt = input$VarInt
    dds = resDiff$dds
    counts = resDiff$counts
    target = resDiff$target
    group = as.data.frame(target[,VarInt])
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
160
161
162
163
164
165
    rownames(group) = rownames(target)
    
    ## If more than 4 levels for one factor
    if(length(VarInt)>1)  maxFact =max(sapply(group,FUN=function(x) length(levels(x))))
    else maxFact = length(levels(group))
    if(maxFact>=4) colors = rainbow(maxFact) 
stevenn's avatar
stevenn committed
166
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
167
168
169
170
171
    if(input$DiagPlot=="barplotTot") barplotTot(input,counts,group = group, col=colors)
    if(input$DiagPlot=="barplotNul") barPlotNul(input,counts, group = group, col=colors)
    if(input$DiagPlot=="densityPlot") densityPlotTot(input,counts, group = group, col=colors)
    if(input$DiagPlot=="MajTax") majTaxPlot(input,counts, group = group, col=colors)
    if(input$DiagPlot=="SERE") SEREplot(input,counts)
stevenn's avatar
stevenn committed
172
173
    if(input$DiagPlot=="Sfactors") diagSFactors(input,dds,frame=1) 
    if(input$DiagPlot=="SfactorsVStot") diagSFactors(input,dds,frame=2) 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
174
175
176
    if(input$DiagPlot=="pcaPlot") PCAPlot_meta(input,dds, group,  type.trans = input$TransType, col = colors)
    if(input$DiagPlot=="pcoaPlot") PCoAPlot_meta(input,dds, group) 
    if(input$DiagPlot=="clustPlot") HCPlot(input,dds,group,type.trans=input$TransType)
stevenn's avatar
stevenn committed
177
178
  }

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
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
  
#   HCPlot <- function (input,dds,group,type.trans,col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen")) 
#   {
#     counts = as.data.frame(round(counts(dds, normalized = TRUE)))
#     if (type.trans == "VST") counts.trans <- assay(varianceStabilizingTransformation(dds))
#     if (type.trans == "rlog") counts.trans <- assay(rlogTransformation(dds))
#     
#     hc <- hclust(dist(t(counts.trans)), method = "ward.D")
#     
#     type <- switch(input$typeHculst,
#                   "radial"="radial",
#                   "fan"="fan",
#                   "triangle"="cladogram",,
#                   "hori"= "hori",
#                   "verti"=NULL)
#     
#     par(cex=input$cexLabelDiag,mar=c(12,5,8,5))
#     if(input$colorHC && type=="hori") 
#     {
#       hc = dendrapply(as.dendrogram(hc),colLabdendo,group) 
#       plot(hc, xlab = "Euclidean distance, Ward criterion", main = "Cluster dendrogram")
#     }
#     
#     if(!input$colorHC && type=="hori") 
#     {
#       plot(hc, xlab = "Euclidean distance, Ward criterion", main = "Cluster dendrogram",hang=-1)
#     }
#     
#     if(type!="hori") 
#     { 
#       group = apply(group,1,paste, collapse = "-")
#       nb = length(unique(group))
#       plot(as.phylo(hc), type= type,label.offset = 1, tip.color = ifelse(input$colorHC, rainbow(nb)[as.integer(as.factor(group))], rep(1,nb)))
#     }
#     dev.off() 
#   }
  
  HCPlot <- function (input,dds,group,type.trans,col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen")) 
  {
    
    ## Get the counts
    counts = as.data.frame(round(counts(dds, normalized = TRUE)))
    if (type.trans == "VST") counts.trans <- assay(varianceStabilizingTransformation(dds))
    if (type.trans == "rlog") counts.trans <- assay(rlogTransformation(dds))
    
    ## Get the group of leaf
    group = apply(group,1,paste, collapse = "-")    
    nb = length(unique((group)))
    
    ## Get the dendrogram
    hc <- hclust(dist(t(counts.trans)), method = "ward.D")
    dend = as.dendrogram(hc)
    
    ## Get the type of dendrogram
    type <- switch(input$typeHculst,
                   "fan"="fan",
                   "hori"= "hori")
    
    dend <- set(dend, "labels_cex", input$cexLabelDiag)
    if(input$colorHC) labels_colors(dend)<-rainbow(nb)[as.integer(as.factor(group))][order.dendrogram(dend)]
    
    if(type=="hori") 
    { 
      par(mar = c(8,4,4,2))
      plot(dend, main = "Cluster dendrogram")
    }  
    if(type!="hori")
    {
      par(mar = c(0.3,2,0.3,2))
      circlize_dendrogram(dend, labels_track_height = 0.2, dend_track_height = .3, main = "Cluster dendrogram")
    }
  }
  
  
  ## Color for the horizontal dendro
  colLabdendo <- function(n,group) {
    
    group = apply(group,1,paste, collapse = "-")
    
    nb = length(unique((group)))
    namesGrp = names(group)
stevenn's avatar
stevenn committed
260

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    if (is.leaf(n)) {
      a <- attributes(n)
      labCol <- rainbow(nb)[as.integer(as.factor(group))[which(namesGrp == a$label)]]
      attr(n, "nodePar") <- c(a$nodePar, lab.col = labCol)
    }
    return(n)
  }
  
  ## Diagnostic Plots Eigen value
  Plot_diag_Eigen <- function(input,resDiff)
  {
    colors = c("dodgerblue","firebrick1","MediumVioletRed","SpringGreen")
    VarInt = input$VarInt
    dds = resDiff$dds
    counts = resDiff$counts
    target = resDiff$target
    group = as.data.frame(target[,VarInt])
    
    ## If more than 4 levels for one factor
    maxFact =max(sapply(group,FUN=function(x) length(levels(x))))
    if(maxFact>=4) colors = rainbow(maxFact) 
    
    PCAPlot_meta(input,dds, group,  type.trans = input$TransType, col = colors, plot = "eigen") 
  }
  
  Plot_diag_pcoaEigen = function(input,resDiff)
  {
    colors = c("SpringGreen","dodgerblue","black","firebrick1")
    VarInt = input$VarInt
    dds = resDiff$dds
    target = resDiff$target
    group = as.data.frame(target[,VarInt])
    rownames(group) = rownames(target)
    PCoAPlot_meta(input,dds, group, col = colors, plot = "eigen") 
  }
  
  
  
stevenn's avatar
stevenn committed
299
300

  ## barplot total
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
301
  barplotTot <- function(input,counts, group, cex.names = 1, col = c("lightblue","orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
302
303
  {
    ncol1 <- ncol(group) == 1
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
304
305
    par(cex=input$cexLabelDiag,mar=c(12,5,4,5))
    barplot(colSums(counts), cex.names = cex.names, main = "Total mapped read count per sample", ylab = "Total mapped read count", 
stevenn's avatar
stevenn committed
306
307
308
309
310
311
312
313
314
315
316
            ylim = c(0, max(colSums(counts)) * 1.2), density = if (ncol1) {NULL}
            else {15}, 
            angle = if (ncol1) {NULL}
            else {c(-45, 0, 45, 90)[as.integer(group[, 2])]}, col = col[as.integer(group[, 1])], las = 2)
    legend("topright", levels(group[, 1]), fill = col[1:nlevels(group[,1])], bty = "n")
    if (!ncol1)  legend("topleft", levels(group[, 2]), density = 15,col = 1, angle = c(-45, 0, 45, 90)[1:nlevels(group[, 2])], bty = "n")
  
  }


  ## barplot Nul 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
317
  barPlotNul <-function (input,counts, group, cex.names = 1, col = c("lightblue","orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
318
319
320
  {
    
    percentage <- apply(counts, 2, function(x) {sum(x == 0)}) * 100/nrow(counts)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
321
    percentage.allNull <- (nrow(counts) - nrow(removeNulCounts(counts))) * 100/nrow(counts)
stevenn's avatar
stevenn committed
322
323
    ncol1 <- ncol(group) == 1
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
324
325
    par(cex=input$cexLabelDiag,mar=c(12,5,4,5))

stevenn's avatar
stevenn committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
    barplot(percentage, las = 2, col = col[as.integer(group[,1])], 
            density = if (ncol1) {NULL}
            else {15}, 
            angle = if (ncol1) {NULL}
            else {c(-45, 0, 45, 90)[as.integer(group[, 2])]},
            cex.names = cex.names, ylab = "Proportion of null counts", 
            main = "Proportion of null counts per sample", 
            ylim = c(0, 1.2 * ifelse(max(percentage) == 0, 1, max(percentage))))
    
    abline(h = percentage.allNull, lty = 2, lwd = 2)
    legend("topright", levels(group[, 1]), fill = col[1:nlevels(group[,1])], bty = "n")
    if (!ncol1) legend("topleft", levels(group[, 2]), density = 15, col = 1, angle = c(-45, 0, 45, 90)[1:nlevels(group[, 2])], bty = "n")
  }


  ## Plot density
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
342
  densityPlotTot <-function (input,counts, group, col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
343
344
345
346
  {
    
    counts <- removeNulCounts(counts)
    ncol1 <- ncol(group) == 1
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
347
    par(cex=input$cexLabelDiag,mar=c(8,5,4,5))
stevenn's avatar
stevenn committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    plot(density(log2(counts[, 1] + 1)), las = 1, lwd = 2, main = "Density of counts distribution", 
         xlab = expression(log[2] ~ (raw ~ count + 1)), 
         ylim = c(0, max(apply(counts, 2, function(x) {max(density(log2(x + 1))$y)})) * 1.05), 
         lty = if (ncol1) {1}
         else{c(1, 2, 3, 4)[as.integer(group[, 2])[1]]}, 
         col = col[as.integer(group[, 1])[1]])
    
    for (i in 2:ncol(counts)) 
    {
      lines(density(log2(counts[, i] + 1)), col = col[as.integer(group[,1])[i]], lwd = 2, 
            lty = if (ncol1) {1}
            else {c(1, 2, 3, 4)[as.integer(group[, 2])[i]]})
    }
    legend("topright", levels(group[, 1]), lty = 1, col = col[1:nlevels(group[,1])], lwd = 2, bty = "n")
    if (!ncol1) legend("topleft", levels(group[, 2]), lty = c(1, 2, 3, 4)[1:nlevels(group[, 2])], col = 1, lwd = 2, bty = "n")
    
  }


  ## Table of maj. taxo
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
368
  majTab <- function(input,counts,n)
stevenn's avatar
stevenn committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
  {
    seqnames <- apply(counts, 2, function(x) {
      x <- sort(x, decreasing = TRUE)
      names(x)[1:n]
    })
    seqnames <- unique(unlist(as.character(seqnames)))
    sum <- apply(counts, 2, sum)
    counts <- counts[seqnames, ]
    sum <- matrix(sum, nrow(counts), ncol(counts), byrow = TRUE)
    p <- round(100 * counts/sum, digits = 3)
    return(p)
  }


  ## Plot maj. taxo
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
384
  majTaxPlot <-function (input,counts, n = 3, group, cex.names = 1, col = c("lightblue",  "orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
385
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
386
    p = majTab(input,counts,n)
stevenn's avatar
stevenn committed
387
388
389
    maj <- apply(p, 2, max)
    seqname <- rownames(p)[apply(p, 2, which.max)]
    ncol1 <- ncol(group) == 1
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
390
391

    x <- barplot(maj, col = col[as.integer(group[, 1])], main = "Proportion of mapped reads from\nmost expressed sequence",
stevenn's avatar
stevenn committed
392
                 ylim = c(0, max(maj) * 1.2), cex.main = 1, 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
393
                 cex.names = cex.names, las = 2, ylab = "Proportion of mapped reads", 
stevenn's avatar
stevenn committed
394
395
396
397
398
399
400
401
402
                 density = if (ncol1) {NULL}
                 else {15}, 
                 angle = if (ncol1) {NULL}
                 else {c(-45, 0, 45, 90)[as.integer(group[, 2])]})
    
    legend("topright", levels(group[, 1]), fill = col[1:nlevels(group[,1])], bty = "n")
    if (!ncol1) legend("topleft", levels(group[, 2]), density = 15, col = 1, 
                       angle = c(-45, 0, 45, 90)[1:nlevels(group[, 2])], bty = "n")
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
403
    for (i in 1:length(seqname)) text(x[i], maj[i]/2, seqname[i], cex=input$cexLabelDiag, srt = 90, adj = 0)
stevenn's avatar
stevenn committed
404
405
406
407
  }
  

  ## plot SERE Coefs
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
408
  SEREplot<-function(input,counts) 
stevenn's avatar
stevenn committed
409
410
  {
    sere = SEREcoef(counts)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
411
    print(sere)
stevenn's avatar
stevenn committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
    hc <- hclust(as.dist(sere), method = "ward.D")
    plot(hc, las = 2, hang = -1, xlab = "SERE distance, Ward criterion",main = "Cluster dendrogram\non SERE values")
    
  }
  
  
  ## Get the SERE COEF
  SEREcoef<-function(counts)
  {
    sere <- matrix(NA, ncol = ncol(counts), nrow = ncol(counts))
    for (i in 1:ncol(counts)) {
      for (j in 1:ncol(counts)) {
        sere[i, j] <- sigfun_Pearson_meta(counts[, c(i, j)])
      }
    }
    colnames(sere) <- rownames(sere) <- colnames(counts)
    sere <- round(sere, digits = 3)
    
    return(sere) 
  }
  

  ## function for the SERE coef
  sigfun_Pearson_meta <- function(observed) {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
436
    print("OK1")
stevenn's avatar
stevenn committed
437
438
    laneTotals <- colSums(observed)
    total <- sum(laneTotals)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
439
    print("OK2")
stevenn's avatar
stevenn committed
440
441
442
    fullObserved <- observed[rowSums(observed) > 0, ]
    fullLambda <- rowSums(fullObserved)/total
    fullLhat <- fullLambda > 0
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
443
    print("OK3")
stevenn's avatar
stevenn committed
444
445
    fullExpected <- outer(fullLambda, laneTotals)
    fullKeep <- which(fullExpected > 0)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
446
447
    print(fullKeep)
    print(fullExpected)
stevenn's avatar
stevenn committed
448
    oeFull <- (fullObserved[fullKeep] - fullExpected[fullKeep])^2/fullExpected[fullKeep]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
449
    print(oeFull)
stevenn's avatar
stevenn committed
450
    dfFull <- length(fullKeep) - sum(fullLhat != 0)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
451
    print(dfFull)
stevenn's avatar
stevenn committed
452
453
    sqrt(sum(oeFull)/dfFull)
  }
stevenn's avatar
stevenn committed
454
455


stevenn's avatar
stevenn committed
456
457
458
459
460
461
462
463
464
465
466
467
468
  ## Plots of size factors
  diagSFactors<-function (input,dds,frame=1) 
  {
    geomeans <- exp(rowMeans(log(counts(dds))))
    samples <- colnames(counts(dds))
    counts.trans <- log2(counts(dds)/geomeans)
    xmin <- min(counts.trans[is.finite(counts.trans)], na.rm = TRUE)
    xmax <- max(counts.trans[is.finite(counts.trans)], na.rm = TRUE)
    
    if(!is.na(input$NbcolSfactors)) parCols = as.numeric(input$NbcolSfactors)
    else parCols = ceiling(ncol(counts.trans)/3)
    
    parRows = ceiling(ncol(counts.trans)/parCols)
stevenn's avatar
stevenn committed
469

stevenn's avatar
stevenn committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
    if(frame==1)
    {
      par(mfrow=c(parRows,parCols))
      for (j in 1:ncol(dds)) {
        hist(log2(counts(dds)[, j]/geomeans), nclass = 100, 
             xlab = expression(log[2] ~ (counts/geometric ~ mean)), las = 1, xlim = c(xmin, xmax), 
             main = paste("Size factors diagnostic - Sample ",samples[j], sep = ""), col = "skyblue")
        
        abline(v = log2(sizeFactors(dds)[j]), col = "red", lwd = 1.5)
      }
    }
    
    if(frame==2)
    {
      plot(sizeFactors(dds), colSums(counts(dds)), pch = 19, las = 1, 
           ylab = "Total number of reads", xlab = "Size factors", 
           main = "Diagnostic: size factors vs total number of reads")
      abline(lm(colSums(counts(dds)) ~ sizeFactors(dds) + 0), lty = 2, col = "grey")
    }
  }
stevenn's avatar
stevenn committed
490

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
  
  ### PCoA
  PCoAPlot_meta <-function (input,dds, group_init,col = c("SpringGreen","dodgerblue","black","firebrick1"), plot = "pcoa") 
  {
    cval=c()
    # Set of shape
    shape=c(19,17,15,18)
    ## Var of interest
    VarInt  = input$VarInt
    ## Group
    group = as.character(apply(group_init,1,paste, collapse = "-"))
    
    ## Keep only some sample 
    val = c()
    for(i in 1:length(VarInt))
    { 
      Tinput = paste("input$","Mod",VarInt[i],sep="")
      expr=parse(text=Tinput)
      ## All the modalities for all the var of interest
      val = c(val,eval(expr))
    }
    if(length(VarInt)>1) Kval = apply(expand.grid(val,val),1,paste, collapse = "-")
    else Kval = val
    ind_kept = which(as.character(group)%in%Kval)
    ## Get the group corresponding to the modalities
    group = group[ind_kept]
    nb = length(unique((group)))
    group = as.factor(group)
    
    ## Get the norm data
    counts.norm = as.data.frame(round(counts(dds, normalized = TRUE)))
    
    # was removed
    counts.norm = counts.norm[,ind_kept]
    
    ## Get the distance
    dist.counts.norm = vegdist(t(counts.norm), method = input$DistPCOA)
    
    ## Do PCoA
    pco.counts.norm = dudi.pco(d = dist.counts.norm, scannf = FALSE,nf=3)
    
    ## Get eigen values
    eigen=(pco.counts.norm$eig/sum(pco.counts.norm$eig))*100
    
    
    ## xlim and ylim of the plot
    min = min(pco.counts.norm$li)
    max = max(pco.counts.norm$li)
    
    ## get condition set
    condition_set=val[which(val %in% unique(group_init$condition))]
    time_set=val[which(val %in% unique(group_init$time))]
    
    ## Colors
    if(length(col)<length(condition_set) * length(time_set))# && !input$colorgroup)
    {
      col = rainbow(length(condition_set) * length(time_set))
    }
    #else if(length(col)<length(condition_set) * length(time_set) && input$colorgroup){
    #  col = rep(col[1:length(condition_set)], length(time_set))
    #}
    print(condition_set)
    print(time_set)
    if (length(time_set) == 1 && length(condition_set) <= 4){
      cval = apply(expand.grid(condition_set,time_set),1,paste, collapse = "-")
      cval = sort(cval)
    }
    print(col)
    # to reactivate
    #pco.counts.norm$li = pco.counts.norm$li[ind_kept,]
    if (plot == "pcoa"){
      ## Plot axis, label and circles
      plot(pco.counts.norm$li[1:2], xlab=paste("PC1 : ",round(eigen[1],1),"%") , ylab=paste("PC2 : ",round(eigen[2],1),"%"),
           xlim=c(min+0.25*min,max+0.25*max), ylim=c(min-0.1,max+0.1), cex.axis=1, cex.lab=1,lwd=2, type="n")
      # Set different shapes
      if(input$labelPCOA == "Group"){
        print(cval)
        print(length(cval))
        if(!is.null(cval)){
          for (i in 1:length(cval)){
            points(pco.counts.norm$li[which(group==cval[i]),1:2],pch=shape[i],col=col[i], cex=input$cexpoint)
          }
          s.class(dfxy = pco.counts.norm$li, fac = group, col = col, label = levels(group),
                  add.plot = TRUE, cpoint = 0, cell=input$cexcircle, clabel=input$cexLabelDiag,  cstar = input$cexstar)
        }else s.class(dfxy = pco.counts.norm$li, fac = group, col = col, label = levels(group),
                      add.plot = TRUE, cpoint = input$cexpoint, cell=input$cexcircle, clabel=input$cexLabelDiag,  cstar = input$cexstar)
      }  
      else{
        s.label(pco.counts.norm$li, clabel = input$cexLabelDiag,boxes=FALSE, add.plot = TRUE)
        s.class(dfxy = pco.counts.norm$li, fac = group, col = col, label = levels(group), add.plot = TRUE, cpoint = 0, clabel = 0, cstar = input$cexstar, cell=input$cexcircle)
      }
    }else{
      barplot(eigen[1:7], xlab="Dimensions", ylab="Eigenvalues (%)", names.arg = 1:7, col = c(rep("black", 2), rep("grey", 5)), ylim=c(0,max(eigen)+5), cex.axis=1.2, cex.lab=1.4,cex.names=1.2)
    }
   
  }
  
  ### PCA
  PCAPlot_meta <-function (input,dds, group, n = min(500, nrow(counts(dds))), type.trans = c("VST", "rlog"), 
                           col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen"),plot="pca") 
  {
    type.trans <- type.trans[1]
    
    if (type.trans == "VST") counts.trans <- assay(varianceStabilizingTransformation(dds))
    else counts.trans <- assay(rlogTransformation(dds))
    
    rv = apply(counts.trans, 1, var, na.rm = TRUE)
    pca = prcomp(t(counts.trans[order(rv, decreasing = TRUE),][1:n, ]))
    
   
    
    
    
    if(plot=="pca")
    { 
      prp <- pca$sdev^2 * 100/sum(pca$sdev^2)
      prp <- round(prp, 2)
      ncol1 <- ncol(group) == 1
      
      par(mfrow = c(1, 2))
      
      abs = range(pca$x[, 1])
      abs = abs(abs[2] - abs[1])/25
      ord = range(pca$x[, 2])
      ord = abs(ord[2] - ord[1])/25
      
      par(mar=c(8,5,4,5))
      plot(pca$x[, 1], pca$x[, 2], las = 1, cex = 2, col = col[as.integer(group[,1])], 
           pch = if (ncol1) {16}
           else {c(16:18, 25)[as.integer(group[, 2])]},
           xlab = paste0("PC1 (", prp[1], "%)"),
           ylab = paste0("PC2 (", prp[2], "%)"), 
           main = "Principal Component Analysis",
            )
      abline(h = 0, v = 0, lty = 2, col = "lightgray")
      text(pca$x[, 1] - ifelse(pca$x[, 1] > 0, abs, -abs), pca$x[,2] - ifelse(pca$x[, 2] > 0, ord, -ord), colnames(counts.trans), col = col[as.integer(group[, 1])])
      abs = range(pca$x[, 1])
      abs = abs(abs[2] - abs[1])/25
      ord = range(pca$x[, 3])
      ord = abs(ord[2] - ord[1])/25
      plot(pca$x[, 1], pca$x[, 3], las = 1, cex = 2, col = col[as.integer(group[, 1])], 
           pch = if (ncol1) {16}
           else {c(16:18, 25)[as.integer(group[, 2])]}, 
           xlab = paste0("PC1 (", prp[1], "%)"), 
           ylab = paste0("PC3 (", prp[3], "%)"), 
           main = "Principal Component Analysis")
      abline(h = 0, v = 0, lty = 2, col = "lightgray")
      text(pca$x[, 1] - ifelse(pca$x[, 1] > 0, abs, -abs), pca$x[,3] - ifelse(pca$x[, 3] > 0, ord, -ord), colnames(counts.trans), col = col[as.integer(group[, 1])],cex=input$cexLabelDiag)
    }
    
    if(plot=="eigen") barplot(pca$sdev^2, main = "Eigen values of the PCA", names.arg = 1:length(pca$sdev), xlab = "Axes")
  }
  
  
  
stevenn's avatar
stevenn committed
646

stevenn's avatar
stevenn committed
647
648
649
650
651
  ############################################################
  ##
  ##              CREATE THE CONTRAST DATABASE
  ##
  ############################################################
stevenn's avatar
stevenn committed
652

stevenn's avatar
stevenn committed
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
  
  BaseContrast <- function(input,names,namesfile)
  {  

    v_tmp = c()
    filesize = file.info(namesfile)[,"size"]
    
    for(i in 1:length(names))
    {  
      Tinput = paste("input$",names[i],sep="")
      expr=parse(text=Tinput)
      val = eval(expr) 
      v_tmp[i] = as.numeric(val)
    }
    
    if(filesize!=0)
    { 
      oldContrast = read.table(namesfile,header=TRUE)
      colnamesTmp = c(colnames(oldContrast),input$ContrastName)
      mat = cbind(oldContrast,v_tmp)
    }
    else{ colnamesTmp = input$ContrastName; mat = v_tmp}
    
    write.table(mat,namesfile,row.names=FALSE,col.names = colnamesTmp)
  }
  
  
  ## Remove nul counts
  removeNulCounts <-function (counts) 
  {
    return(counts[rowSums(counts) > 0, ])
  }
stevenn's avatar
stevenn committed
685
686

  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
687
688
689
690
691
  ############################################################
  ##
  ##              VISUALISATION PLOTS
  ##
  ############################################################
stevenn's avatar
stevenn committed
692
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
693
694
695
696
697
698
699
700
701
702
703
  GetDataToPlot <- function(resDiff,VarInt,ind_taxo,aggregate=TRUE)
  {
    dds = resDiff$dds
    counts = as.data.frame(round(counts(dds, normalized = TRUE)))
    target = resDiff$target
    counts_tmp_combined = NULL
    prop_tmp_combined = NULL
    targetInt = NULL
    ## Select a subset within the taxonomy level (default is the 12 most abundant)
    nbKept = length(ind_taxo)
    Taxonomy = rownames(counts)
stevenn's avatar
stevenn committed
704
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
705
706
707
708
709
710
711
712
713
714
    if (length(VarInt)>0 && nbKept>0)
    { 
      ## Create the variable to plot
      targetInt = as.data.frame(target[,VarInt])
      rownames(targetInt)=target[,1]  
      if(length(VarInt)>1) targetInt$AllVar = apply(targetInt,1,paste, collapse = "-")
      if(length(VarInt)<=1)  targetInt$AllVar = target[,VarInt]
      colnames(targetInt) = c(VarInt,"AllVar")
      ## Create the counts matrix only for the selected subset
      counts_tmp = counts[Taxonomy%in%ind_taxo,]
stevenn's avatar
stevenn committed
715

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
      ## Be careful transposition !
      if(aggregate)
      { 
        counts_tmp_combined = aggregate(t(counts_tmp),by=list(targetInt$AllVar),sum)
        rownames(counts_tmp_combined) = counts_tmp_combined$Group.1
        counts_tmp_combined = as.matrix(counts_tmp_combined[,-1])
      }
      if(!aggregate)
      {  
        counts_tmp_combined = t(counts_tmp)
        prop_tmp_combined = counts_tmp_combined/colSums(counts)
        rownames(counts_tmp_combined) = targetInt$AllVar
        rownames(prop_tmp_combined) = targetInt$AllVar
      }
      ## Ordering the counts
      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])
    }
    
      return(list(counts = counts_tmp_combined,targetInt=targetInt,prop=prop_tmp_combined))
    
    
  }
stevenn's avatar
stevenn committed
741
742
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
743
744
745
746
747
748
  
  ###########################
  ## Plots for visualisation
  ###########################
  
  Plot_Visu_Barplot <- function(input,resDiff)
stevenn's avatar
stevenn committed
749
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
750
751
752
753

    ## Get Input for BarPlot
    VarInt = input$VisuVarIntBP
    ind_taxo = input$selectTaxoPlotBP
stevenn's avatar
stevenn committed
754
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
755
756
    counts_tmp_combined = GetDataToPlot(resDiff,VarInt,ind_taxo)$counts
    nbKept = length(ind_taxo)
stevenn's avatar
stevenn committed
757
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
758
759
760
761
762
763
764
765
    if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0)
    { 
      counts_tmp_combined = GetDataToPlot(resDiff,VarInt,ind_taxo)$counts
      Taxonomy = rownames(counts_tmp_combined)
      ## Create the data frame for the plot function
      dataBarPlot_mat = c()
      tmp_mat = matrix(0,ncol=3,nrow=nbKept)
      tmp_counts = c()
stevenn's avatar
stevenn committed
766
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
        for(i in 1:(nrow(counts_tmp_combined)))
        {
          ## Taxo
          tmp_mat[1:nbKept,1] = colnames(counts_tmp_combined)
          
          ## 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(rownames(counts_tmp_combined)[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
  
        plotd3 <- nvd3Plot(Proportions ~ AllVar | Taxonomy, data = dataBarPlot_mat, type = input$SensPlotVisuBP, id = 'barplotTaxo',height = input$heightVisu,width=input$widthVisu)
        plotd3$chart(stacked = TRUE)
    } 
    else{ 
      ## Pb affichage quand data NULL
      dataNull = data.frame(x=c(1,2),y=c(1,2))
      plotd3 = nvd3Plot(x ~ y , data = dataNull, type = "multiBarChart", id = 'barplotTaxoNyll',height = input$heightVisu,width=input$widthVisu)
stevenn's avatar
stevenn committed
803
    }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
804
805
806
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
    return(plotd3)
  }
  
  
  
######################################################
##
##            HEATMAP
##
######################################################
  
  
  Plot_Visu_Heatmap <- function(input,resDiff){
  
  VarInt = input$VisuVarIntHM
  ind_taxo = input$selectTaxoPlotHM
  
  counts_tmp_combined = GetDataToPlot(resDiff,VarInt,ind_taxo)$counts
  
  if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0)
  { 
    ## Transform to log2
    counts_tmp_combined = log2(GetDataToPlot(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))
stevenn's avatar
stevenn committed
833
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
834
835
836
837
838
839
840
841
    ## Transpose matrix if Horizontal
    if(input$SensPlotVisuHM=="Horizontal") counts_tmp_combined = t(as.matrix(counts_tmp_combined))
         #print(counts_tmp_combined)
    return(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.4,cexCol = 0.4))
#     return(d3heatmap(counts_tmp_combined, dendrogram = "none", Rowv = NA, Colv = NA, na.rm = TRUE, 
#                      width = 1500, height = 1000, show_grid = FALSE, colors = col, scale = input$scaleHeatmap,
#                      cexRow = 0.6))
stevenn's avatar
stevenn committed
842
  }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
843

stevenn's avatar
stevenn committed
844
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
845
846
847
848
849
850
851
852
853
854
  }

  ######################################################
  ##
  ##            BOXPLOT
  ##
  ######################################################
  
  
  Plot_Visu_Boxplot <- function(input,resDiff){
stevenn's avatar
stevenn committed
855
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
    gg = NULL
    ## Get Input for BoxPlot
    VarInt = input$VisuVarIntBoxP
    ind_taxo = input$selectTaxoPlotBoxP
    
    tmp_merge = GetDataToPlot(resDiff,VarInt,ind_taxo,aggregate=FALSE)
    counts_tmp_combined = tmp_merge$counts

    nbKept = length(ind_taxo)
    
    if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0)
    { 
      Taxonomy = rownames(counts_tmp_combined)
    
      if(input$typeDataBox == "Relative") 
      { 
        counts_tmp_combined = tmp_merge$prop
      }
      if(input$typeDataBox == "Log2") counts_tmp_combined = log2(counts_tmp_combined+1)
stevenn's avatar
stevenn committed
875
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
876
877
878
879
880
881
882
      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()
stevenn's avatar
stevenn committed
883
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
      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)
      }
    
stevenn's avatar
stevenn committed
900
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
901
902
903
904
905
906
907
908
909
910
      dataBarPlot_mat = as.data.frame(dataBarPlot_mat)
      
      colnames(dataBarPlot_mat) = c("Taxonomy","Value","Samples")
      dataBarPlot_mat[,2] = tmp_counts
      
      gg = ggplot(dataBarPlot_mat,aes(x=Samples,y=Value,fill=Samples))  + geom_boxplot(alpha=0.7) + theme_bw()  + theme(axis.text.x = element_text(angle = 90, hjust = 1))
      gg = gg + ylab(input$typeDataBox)
      if(input$CheckAddPointsBox) gg = gg + geom_point(position=position_jitterdodge(dodge.width=0.9))
      if(input$SensPlotVisuBoxP=="Horizontal") gg = gg + coord_flip()
      if(nbKept>1) gg = gg + facet_wrap(~ Taxonomy)
stevenn's avatar
stevenn committed
911
    }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
912
913
914
    
   return(gg)
    
stevenn's avatar
stevenn committed
915
916
917
  }
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
918
919
920
921
922
  ######################################################
  ##
  ##            GLOBAL VIEW
  ##
  ######################################################
stevenn's avatar
stevenn committed
923
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
  
  Plot_Visu_Diversity <- function(input,resDiff,type="point"){
    
    gg = NULL
    dds = resDiff$dds
    counts = round(counts(dds, normalized = TRUE))
    #target = resDiff$target
    
    ## Get Input for the plot
    VarInt = input$VisuVarIntDiv
    VarIntBoxDiv = input$VarBoxDiv 
    ind_taxo = rownames(counts)
    
    tmp = GetDataToPlot(resDiff,VarInt,ind_taxo,aggregate=FALSE)
    counts_tmp_combined = tmp$counts
    targetInt = tmp$targetInt
stevenn's avatar
stevenn committed
940

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
    if(nrow(counts_tmp_combined)>0 && !is.null(counts_tmp_combined) && !is.null(targetInt))
    { 
      alpha <- tapply(TaxoNumber(counts_tmp_combined), targetInt$AllVar, mean)
      gamma <- TaxoNumber(counts_tmp_combined, targetInt$AllVar)
      beta = gamma/alpha - 1
      nb = length(alpha)
      dataTmp = data.frame(value=c(alpha,beta,gamma),
                           diversity = c(rep("Alpha",nb),rep("Beta",nb),rep("Gamma",nb)),
                           Var = as.character(rep(names(alpha),3)), X = as.character(rep(targetInt[,VarIntBoxDiv],3)))
     
      ## Merge targetInt et dataTmp par rapport à Var
#       VectX = c()
#       for(i in 1:nb)
#       {
#         ## If duplicated, take only one row
#         tmpX = which(targetInt$AllVar%in%names(alpha)[i])[1]
#         VectX = c(VectX,targetInt[tmpX,VarIntBoxDiv]) 
#       }
#       print(VectX)
#       dataTmp$X =  as.character(rep(VectX,3))
                               
      dataTmp = dataTmp[dataTmp$diversity%in%input$WhichDiv,]

      if(type=="point")
      { 
        gg = ggplot(dataTmp, aes(x=Var, y=value, color=diversity)) + theme_bw() + theme(axis.text.x = element_text(angle = 90, hjust = 1))
        gg = gg + geom_point(size=input$sizePointGlobal) 
        if(input$SensPlotVisuGlobal=="Horizontal") gg = gg + coord_flip()
        if(input$SplitVisuGlobal==TRUE) gg = gg + facet_wrap(~ diversity)
      }
#       if(type=="box")
#       { 
#         gg = ggplot(dataTmp,aes(x=X,y=value,fill=diversity))  + geom_boxplot(alpha=0.7) + theme_bw()  + theme(axis.text.x = element_text(angle = 90, hjust = 1))
#         gg = gg + geom_point(size=input$sizePointGlobal) 
#         gg = gg + geom_point(position=position_jitterdodge(dodge.width=0.9))
#         if(input$SensPlotVisuGlobal=="Horizontal") gg = gg + coord_flip()
#         if(input$SplitVisuGlobal==TRUE) gg = gg + facet_wrap(~ diversity) 
#       }
      
#       nvd3Plot(value ~ Var | diversity, data = dataTmp, id = 'Scachart', type = 'lineChart',height = 1000,width=1000)
#       p1$xAxis(axisLabel = 'Variable of interest')
    }
    return(gg)
    
  }
stevenn's avatar
stevenn committed
986
987
988

  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
989
990
991
992
993
994
995
996
997
998
999
1000
  ## 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))
For faster browsing, not all history is shown. View entire blame