internal.R 73.4 KB
Newer Older
stevenn's avatar
stevenn 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

## 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)
}


Stevenn Volant's avatar
Stevenn Volant committed
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
78
79
80
81
82
## Function for the rdp format
getval <- function(annotation_rdp, interest, threshold_annot){
  annotation_rdp = unlist(strsplit(annotation_rdp,"\t"))
  annotation = c(annotation_rdp[1])
  for(level in interest){
    idlevel=which(annotation_rdp == level)
    if(length(idlevel)>0){
      if(as.numeric(annotation_rdp[idlevel+1]) >= threshold_annot){
        annotation = c(annotation, gsub("\"", "", annotation_rdp[idlevel-1]))
      }
      else annotation = c(annotation, "NA")
    }
    else annotation = c(annotation, "NA")  
  }
  return(annotation)
}

## Read rdp file
read_rdp <- function(filename, threshold_annot)
{
  interest=c("phylum", "class", "order", "family", "genus")
  conn <- file(filename,open="r")
  linn <-readLines(conn)
  tab=t(sapply(1:length(linn), function(i) getval(linn[i], interest, threshold_annot)))
  close(conn)
  
  if(!TRUE%in%duplicated(tab[,1])) rownames(tab)=tab[,1];tab=tab[,-1]
  colnames(tab) = c("Phylum","Class","Order","Family","Genus")
  
  return(tab)
}






CheckCountsTable <- function(counts)
  {
    Error = NULL
    Warning = NULL
    numTest = FALSE%in%sapply(counts,is.numeric)
    if(ncol(counts)<=1){Error = "The number of columns of the counts table must be at least 2" }
    if(nrow(counts)<=1){Error = "The number of rows of the counts table must be at least 2" }
    if(numTest){Error = "The counts table must contain only numeric values" }
    if(!numTest)
    {
      if(0%in%colSums(counts)){Error = "At least one of the column of the counts table is 0" }
      if(min(counts)<0){Error = "The counts table must contain only positive values" }
    }
    if(TRUE%in%sapply(counts,is.na)){Warning = "NA values are considered as 0 is the counts table"; counts[sapply(counts,is.na)]=0}
    
  
    return(list(Error=Error,Warning=Warning,counts=counts))
  }
  
svolant's avatar
svolant committed
83
  CheckTaxoTable <- function(taxo,counts)
stevenn's avatar
stevenn committed
84
  {
Stevenn Volant's avatar
Stevenn Volant committed
85
86
    Error = NULL
    Warning = NULL
svolant's avatar
svolant committed
87
    if(ncol(taxo)<1){Error = "The number of columns of the taxonomy table must be at least 1" }
Stevenn Volant's avatar
Stevenn Volant committed
88
89
90
91
92
93
94
95
96
    if(nrow(taxo)<=1){Error = "The number of rows if the taxonomy table must be at least 2" }
    if(TRUE%in%is.numeric(taxo)){Error = "The taxonomy table must contain only character" }

    for(i in 1:ncol(taxo))
    {
      level = levels(taxo[,i])
      nb = length(level)
      if(nb==1 && level=="NA"){ Error = "At least one column contains only NA"}
    }
stevenn's avatar
stevenn committed
97
    
svolant's avatar
svolant committed
98
99
100
    ## Annotated features without counts
    if(!any(rownames(taxo)%in%rownames(counts))){ Error = "Some annotated features are not in the count table"}
    
Stevenn Volant's avatar
Stevenn Volant committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    return(list(Error=Error,Warning=Warning))
  }
  
  PercentAnnot <- function(counts,taxo)
  {
    Error = NULL  
    tmp = table(rownames(counts)%in%rownames(taxo))
    Percent = tmp["TRUE"]/sum(tmp)
    if(is.na(Percent)) Percent = 0
    if(Percent==0){Error = "Counts table and annotation do not matched" }
       
    return(list(Error=Error,Percent=Percent))
  }
  
  
  GetDataFromBIOM <-function(dataBIOM)
  {
    ## Counts table
stevenn's avatar
stevenn committed
119
    counts = biom_data(dataBIOM)
stevenn's avatar
stevenn committed
120
121
    counts = as.matrix(counts)
    counts = as.data.frame(counts)
Stevenn Volant's avatar
Stevenn Volant committed
122
123
124
125
    CheckCounts = CheckCountsTable(counts)
    counts = CheckCounts$counts
    
    ## Taxonomy table
stevenn's avatar
stevenn committed
126
    taxo = as.data.frame(observation_metadata(dataBIOM))
127
128
129
130
131
132
133
    OTUnames = rownames(taxo)
    ## Modif taxo table (remove p__,... and change the colnames)
    taxo = as.data.frame(sapply(taxo,gsub,pattern="^.*__",replacement=""))
    colnames(taxo) = c("Kingdom", "Phylum","Class","Order","Family","Genus","Species")
    rownames(taxo) = OTUnames
    ## Remove empty row
    taxo[taxo==""] = NA
134
135
    taxo[taxo=="Unassigned"] = NA
    taxo=taxo[rowSums(is.na(taxo))!=dim(taxo)[2], ]
136
    
svolant's avatar
svolant committed
137
    CheckTaxo = CheckTaxoTable(taxo,counts)
Stevenn Volant's avatar
Stevenn Volant committed
138
139
140
141
142
    
    ## Pourcentage of annotation
    tmp = PercentAnnot(counts,taxo)
    
    return(list(counts=counts,taxo=taxo,CheckCounts=CheckCounts,CheckTaxo=CheckTaxo,Percent=tmp$Percent,CheckPercent=tmp$Error))
stevenn's avatar
stevenn committed
143
  }
stevenn's avatar
stevenn committed
144
145
  
  
stevenn's avatar
stevenn committed
146
147
148
  GetDataFromCT <-function(dataC,dataT)
  {
    
Stevenn Volant's avatar
Stevenn Volant committed
149
    ## Counts table
stevenn's avatar
stevenn committed
150
    counts = dataC
Stevenn Volant's avatar
Stevenn Volant committed
151
152
153
154
155
    CheckCounts = CheckCountsTable(counts)
    counts = CheckCounts$counts
    
    ## Taxonomy table
    taxo = as.data.frame(dataT)
svolant's avatar
svolant committed
156
    CheckTaxo = CheckTaxoTable(taxo,counts)
Stevenn Volant's avatar
Stevenn Volant committed
157
158
159
160
161
    
    ## Pourcentage of annotation
    tmp = PercentAnnot(counts,taxo)
    
    return(list(counts=counts,taxo=taxo,CheckCounts=CheckCounts,CheckTaxo=CheckTaxo,Percent=tmp$Percent,CheckPercent=tmp$Error))
stevenn's avatar
stevenn committed
162
163
164
  }
  
  GetInteraction2 <- function(target)
stevenn's avatar
stevenn committed
165
  { 
stevenn's avatar
stevenn committed
166
167
168
169
    res=c()
    namesTarget = colnames(target)[2:ncol(target)]
    k=1
    for(i in 1:(length(namesTarget)-1))
stevenn's avatar
stevenn committed
170
    { 
stevenn's avatar
stevenn committed
171
172
173
174
175
      for(j in (i+1):length(namesTarget))
      { 
        res[k] = paste(namesTarget[i],":",namesTarget[j],sep="")
        k = k+1
      }
stevenn's avatar
stevenn committed
176
    }
stevenn's avatar
stevenn committed
177
178
    
    return(res)
stevenn's avatar
stevenn committed
179
180
181
182
  }
  


Amine  GHOZLANE's avatar
Amine GHOZLANE committed
183
  ## Print the contrasts
stevenn's avatar
stevenn committed
184
185
186
187
188
189
190
191
192
193
  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)
194
      out = paste(out,paste("<b>",contnames[i], "</b> <br/>", paste(contrast[contrast != 0], coefs[contrast != 0], collapse = " ", sep = " ")),"<br/>")
stevenn's avatar
stevenn committed
195
196
197
198
    }
    return(out)
    
  }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
199

stevenn's avatar
stevenn committed
200
  ## Get the counts for the selected taxonomy
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
201
  GetCountsMerge <- function(input,dataInput,taxoSelect,target,design)
stevenn's avatar
stevenn committed
202
  {
203
    ## Init
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
204
205
    counts= NULL
    CheckTarget = FALSE
Stevenn Volant's avatar
Stevenn Volant committed
206
207
    CT_noNorm = NULL
    normFactors = NULL
208
209
    FeatureSize = NULL

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
210
    ## Counts and taxo tables
stevenn's avatar
stevenn committed
211
212
    CT = dataInput$counts
    taxo = dataInput$taxo
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
213

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
214
215
216
    ## Select cols in the target
    labels = target[,1]
    ind = which(colnames(CT)%in%labels)
217

svolant's avatar
svolant committed
218
219
220
    ## Get the normalization variable (normalization can be done according to this variable)
    VarNorm = input$VarNorm
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
221
222
    if(length(ind)==length(labels))
    { 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
      if(input$TypeTable == "MGS"){
        ## Get the feature size for the normalisation
        Size_indcol = which(toupper(colnames(CT))%in%"SIZE")
        if(length(Size_indcol)==1) FeatureSize = CT[,Size_indcol]
        else print("Size parameter is missing in the count matrix")
        # Consider only counts
        CT = CT[,ind]
        # Divide by gene length
        CT = CT / FeatureSize * 1000
        # Convert matrix as integer
        CT_int=t(apply(CT,1,as.integer))
        rownames(CT_int)=rownames(CT)
        colnames(CT_int)=colnames(CT)
        CT=CT_int
svolant's avatar
svolant committed
237
238
      } else CT = CT[,ind]
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
239
      ## Order CT according to the target
240
      CT = OrderCounts(counts=CT,labels=labels)$CountsOrder
Stevenn Volant's avatar
Stevenn Volant committed
241
      CT_noNorm = CT
242
      RowProd = sum(apply(CT_noNorm,1,prod))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
243
      
svolant's avatar
svolant committed
244
      ## Create the dds object
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
245
      dds <- DESeqDataSetFromMatrix(countData=CT, colData=target, design=design)
svolant's avatar
svolant committed
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
279
      
      if(is.null(VarNorm)){
        ## Counts normalisation
        ## Normalisation with or without 0
        if(input$AccountForNA || RowProd==0) dds = estimateSizeFactors(dds,locfunc=eval(as.name(input$locfunc)),geoMeans=GeoMeansCT(CT))
        if(!input$AccountForNA && RowProd!=0) dds = estimateSizeFactors(dds,locfunc=eval(as.name(input$locfunc)))
        normFactors = sizeFactors(dds)
        
      } else{
        group = as.data.frame(target[,VarNorm])
        group = apply(group,1,paste, collapse = "-")
        normFactors = c()
        mod = unique(group)
        ## At least 2 samples are needed for the normalization
        if(min(table(group))>1){
          for(i in unique(group))
          {
            indgrp = which(group==i) 
            CT_tmp = CT[,indgrp]
            CT_tmp = removeNulCounts(CT_tmp) 
            target_tmp = data.frame(labels = rownames(target)[indgrp])
            dds_tmp <- DESeqDataSetFromMatrix(countData=CT_tmp, colData=target_tmp, design=~labels)
            if(input$AccountForNA) dds_tmp = estimateSizeFactors(dds_tmp,locfunc=eval(as.name(input$locfunc)),geoMeans=GeoMeansCT(CT_tmp))
            if(!input$AccountForNA) dds_tmp = estimateSizeFactors(dds_tmp,locfunc=eval(as.name(input$locfunc)))
            normFactors[indgrp] = sizeFactors(dds_tmp)
          }
        } else{
            if(input$AccountForNA || RowProd==0) dds = estimateSizeFactors(dds,locfunc=eval(as.name(input$locfunc)),geoMeans=GeoMeansCT(CT))
            if(!input$AccountForNA && RowProd!=0) dds = estimateSizeFactors(dds,locfunc=eval(as.name(input$locfunc)))
            normFactors = sizeFactors(dds)
        }
        
        sizeFactors(dds) = normFactors
      }
280
281
282
283
      
      ## Keep normalized OTU table
      CT_Norm = counts(dds, normalized=TRUE)
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
284
285
286
287
288
289
      # Only interesting OTU
      merged_table = merge(CT, taxo[order(rownames(CT)),], by="row.names")
      CT = merged_table[,2: (dim(CT)[2]+1)]
      taxo = merged_table[,(dim(CT)[2]+2):dim(merged_table)[2]]
      rownames(CT) = merged_table[,1]
      rownames(taxo) = merged_table[,1]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
290
      #ordOTU = order(rownames(taxo))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
291
292
293
294
      counts_annot = CT
#       ordOTU = order(rownames(taxo))
#       indOTU_annot = which(rownames(CT)%in%rownames(taxo))
#       counts_annot = CT[indOTU_annot[ordOTU],]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
295
296
     ## Aggregate matrix
      if(taxoSelect=="OTU/Gene") counts = counts_annot
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
297
      else{
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
        if(input$TypeTable == "MGS"){
          taxoS = taxo[,input$TypeTable]
          counts = aggregate(counts_annot,by=list(Taxonomy = taxoS),mean)
          rownames(counts)=counts[,1]
          counts=counts[,-1]
          counts_int=t(apply(counts,1,as.integer))
          rownames(counts_int)=rownames(counts)
          colnames(counts_int)=colnames(counts)
          counts=counts_int
        }
        if(taxoSelect != "MGS"){
          #taxoS = taxo[ordOTU,taxoSelect]
          taxoS = taxo[,taxoSelect]
          counts = aggregate(counts_annot,by=list(Taxonomy = taxoS),sum)
          rownames(counts)=counts[,1];counts=counts[,-1]
        }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
314
315
316
      }
      
      ## Ordering the counts table according to the target labels 
317
318
319
      tmpOrder = OrderCounts(counts,normFactors,labels)
      counts = tmpOrder$CountsOrder
      normFactors = tmpOrder$normFactorsOrder
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
320
321
      CheckTarget = TRUE
    }
322
    return(list(counts=counts,CheckTarget=CheckTarget,normFactors=normFactors, CT_noNorm=CT_noNorm, CT_Norm =CT_Norm))
323
    #return(list(counts=counts,target=target[ind,],labeled=labeled,normFactors=normFactors, CT_noNorm=CT_noNorm))
stevenn's avatar
stevenn committed
324
  }
325
326
327
328
329
330
331
332
333
334
335
  
  ## Get the geometric mean of the counts (0 are replaced by NA values)
  GeoMeansCT <- function(CT)
  {
    CT=as.matrix(CT)
    CT[which(CT<1)]=NA
    gm = apply(CT,1,geometric.mean,na.rm=TRUE)
    return(gm)
  }
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
336
  ## Order the counts 
337
  OrderCounts <- function(counts,normFactors=NULL,labels)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
338
339
340
  {
    n = length(labels)
    CountsOrder = counts
341
    normFactorsOrder = normFactors
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
342
343
344
345
    for(i in 1:n)
    {
      ind = which(labels[i]==colnames(counts))
      CountsOrder[,i] = counts[,ind]
346
      if(!is.null(normFactors)) normFactorsOrder[i] = normFactors[ind]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
347
348
    }
    colnames(CountsOrder) = labels
349
    return(list(CountsOrder=CountsOrder,normFactorsOrder = normFactorsOrder))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
350
351
352
  }
  
  
stevenn's avatar
stevenn committed
353
  ## Get the dds object of DESeq2
354
  Get_dds_object <- function(input,counts,target,design,normFactorsOTU,CT_noNorm,CT_Norm)
stevenn's avatar
stevenn committed
355
356
  {
    dds <- DESeqDataSetFromMatrix(countData=counts, colData=target, design=design)
357
    sizeFactors(dds) = normFactorsOTU
stevenn's avatar
stevenn committed
358
    dds <- estimateDispersions(dds, fitType=input$fitType)
359
    if(as.numeric(R.Version()$major)+as.numeric(R.Version()$minor) >= 4.3){
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
360
      dds <- nbinomWaldTest(dds)
361
    }else{
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
362
      dds <- nbinomWaldTest(dds,modelMatrixType = "expanded")
363
    }
364
    countsNorm = counts(dds, normalized = TRUE)
365
366
367
    
    save(dds,file="dds.RData")
    return(list(dds = dds,raw_counts=counts,countsNorm=countsNorm,target=target,design=design,normFactors = normFactorsOTU,CT_noNorm=CT_noNorm,CT_Norm=CT_Norm))
stevenn's avatar
stevenn committed
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
  }

  ## 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= "+")))
    return(design)
  }
  


  ## Diagnostic Plots
  Plot_diag <- function(input,resDiff)
  {
Stevenn Volant's avatar
Stevenn Volant committed
385
    
stevenn's avatar
stevenn committed
386
387
    VarInt = input$VarInt
    dds = resDiff$dds
388
    counts = resDiff$raw_counts
389
    if(input$CountsType=="Normalized") counts = resDiff$countsNorm
stevenn's avatar
stevenn committed
390
    target = resDiff$target
391
    normFactors = resDiff$normFactors
392
393
394
395
396
    
    ## Counts at the OTU level
    CT = resDiff$CT_noNorm
    if(input$CountsType=="Normalized") CT = resDiff$CT_Norm
    
stevenn's avatar
stevenn committed
397
    group = as.data.frame(target[,VarInt])
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
398
    rownames(group) = rownames(target)
Stevenn Volant's avatar
Stevenn Volant committed
399
    res = NULL
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
400
    
Stevenn Volant's avatar
Stevenn Volant committed
401
402
    if(ncol(group)>0 && nrow(counts)>0)
    { 
Stevenn Volant's avatar
Stevenn Volant committed
403
404
      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(target)/20))
Stevenn Volant's avatar
Stevenn Volant committed
405
406
407
408
      
      if(input$DiagPlot=="barplotTot") res = barplotTot(input,counts,group = group, col=colors)
      if(input$DiagPlot=="barplotNul") res = barPlotNul(input,counts, group = group, col=colors)
      if(input$DiagPlot=="densityPlot") res = densityPlotTot(input,counts, group = group, col=colors)
409
      if(input$DiagPlot=="boxplotNorm") res = boxplotNorm(input,CT,group = group, col=colors)
410
      if(input$DiagPlot=="DispPlot") res = plotDispEsts(dds)
Stevenn Volant's avatar
Stevenn Volant committed
411
      if(input$DiagPlot=="MajTax") res = majTaxPlot(input,counts, group = group, col=colors)
412
      if(input$DiagPlot=="SfactorsVStot") res = diagSFactors(input,normFactors,resDiff$raw_counts) 
Stevenn Volant's avatar
Stevenn Volant committed
413
      if(input$DiagPlot=="pcaPlot") res = PCAPlot_meta(input,dds, group,  type.trans = input$TransType, col = colors)
Stevenn Volant's avatar
Stevenn Volant committed
414
      if(input$DiagPlot=="pcoaPlot") res = PCoAPlot_meta(input,dds, group, col = colors) 
415
      if(input$DiagPlot=="clustPlot") res = HCPlot(input,dds,group,type.trans=input$TransType,counts,col=colors)
Stevenn Volant's avatar
Stevenn Volant committed
416
    }
417
    
Stevenn Volant's avatar
Stevenn Volant committed
418
    return(res)
stevenn's avatar
stevenn committed
419
420
  }

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
421
  
422
  HCPlot <- function (input,dds,group,type.trans,counts,col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen")) 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
423
424
  {
    
Stevenn Volant's avatar
Stevenn Volant committed
425
426
    res = NULL
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
427
    ## Get the counts
428
429
    if (input$DistClust == "euclidean" && type.trans == "VST") counts <- assay(varianceStabilizingTransformation(dds))
    if (input$DistClust == "euclidean" && type.trans == "rlog") counts <- assay(rlogTransformation(dds))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
430
431
432
433
434
435
    
    ## Get the group of leaf
    group = apply(group,1,paste, collapse = "-")    
    nb = length(unique((group)))
    
    ## Get the dendrogram
Stevenn Volant's avatar
Stevenn Volant committed
436
437
438
439
    if(input$DistClust!="sere") dist = vegdist(t(counts), method = input$DistClust)
    if(input$DistClust=="sere") dist = as.dist(SEREcoef(counts))
    hc <- hclust(dist, method = "ward.D")
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
440
441
442
    dend = as.dendrogram(hc)
    
    ## Get the type of dendrogram
Stevenn Volant's avatar
Stevenn Volant committed
443
    type <- input$typeHculst
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
444
445
    
    dend <- set(dend, "labels_cex", input$cexLabelDiag)
446
    if(input$colorHC) labels_colors(dend)<-col[as.integer(as.factor(group))][order.dendrogram(dend)]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
447
448
    if(type=="hori") 
    { 
449
      par(cex=input$cexTitleDiag,mar=c(6,6,4,5))
Stevenn Volant's avatar
Stevenn Volant committed
450
      res = plot(dend, main = "Cluster dendrogram",xlab = paste(input$DistClust,"distance, Ward criterion",sep=" "),cex=input$cexLabelDiag)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
451
452
453
    }  
    if(type!="hori")
    {
454
      par(cex=input$cexTitleDiag,mar=c(6,6,4,5))
Stevenn Volant's avatar
Stevenn Volant committed
455
      res = circlize_dendrogram(dend, labels_track_height = 0.2, dend_track_height = .3, main = "Cluster dendrogram",xlab = paste(input$DistClust,"distance, Ward criterion",sep=" "))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
456
    }
Stevenn Volant's avatar
Stevenn Volant committed
457
    return(res)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
458
459
460
461
462
463
464
465
466
467
  }
  
  
  ## 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
468

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
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
    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") 
  }
  
  
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
  my.boxplot <- function(x, pol.col = 1, pol.density = NULL, pol.angle = 45,
                         bxp.pars = list(boxwex = 0.8, staplewex = 0.5, outwex = 0.5), ...){
    res <- boxplot(x, pars = bxp.pars, ...) # que boxplot se d�merde avec ses arguments
    n <- ncol(res$stats) # nombre de boxplots
    density <- if(is.null(pol.density)){NULL}else{rep(pol.density, length = n)}
    angle <- if(is.null(pol.angle)){NULL}else{rep(pol.angle, length = n)}
    col <- if(is.null(pol.col)){NULL}else{rep(pol.col, length = n)}
    # Ajout des textures
    ex <- bxp.pars$boxwex/2 # j'ai juste besoin de la largeur des bo�tes pass�e � bxp
    for(i in 1:n){
      polygon(c(i - ex, i - ex, i + ex, i + ex),
              c(res$stats[2, i], res$stats[4, i], res$stats[4, i], res$stats[2, i]),
              density = density[i], angle = angle[i], col = col[i])
      segments(i-ex,res$stats[3,i],i+ex,res$stats[3,i],lwd=3,col="black",lend=1)
    }
  }
  
  
  
  ## Boxplot for the counts normalized/no normalized
  boxplotNorm <- function(input,CT, group, col = c("lightblue","orange", "MediumVioletRed", "SpringGreen")) 
  {
    
    ncol1 <- ncol(group) == 1
    par(cex=input$cexTitleDiag,mar=c(12,6,4,5))
    if(input$RemoveNullValue) CT[CT==0] = NA
    
    ### Boxplots of the counts
    my.boxplot(log2(CT+1), las = 2, pol.col = col[as.integer(group[,1])],
               pol.density = if (ncol1) {NULL}
               else {15}, 
               pol.angle = if (ncol1) {NULL}
            else {seq(0,160,length.out =nlevels(group[, 2]))[as.integer(group[, 2])]},
            main = paste(input$CountsType, "counts distribution"), ylab = expression(log[2] ~ ( count + 1)))
    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 = seq(0,160,length.out =nlevels(group[, 2]))[1:nlevels(group[, 2])], bty = "n")
    
     }
  

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
546
  
stevenn's avatar
stevenn committed
547
548

  ## barplot total
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
549
  barplotTot <- function(input,counts, group, cex.names = 1, col = c("lightblue","orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
550
  {
Stevenn Volant's avatar
Stevenn Volant committed
551

stevenn's avatar
stevenn committed
552
    ncol1 <- ncol(group) == 1
553
    par(cex=input$cexTitleDiag,mar=c(12,6,4,5))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
554
    barplot(colSums(counts), cex.names = cex.names, main = "Total mapped read count per sample", ylab = "Total mapped read count", 
stevenn's avatar
stevenn committed
555
556
557
            ylim = c(0, max(colSums(counts)) * 1.2), density = if (ncol1) {NULL}
            else {15}, 
            angle = if (ncol1) {NULL}
Stevenn Volant's avatar
Stevenn Volant committed
558
            else {seq(0,160,length.out =nlevels(group[, 2]))[as.integer(group[, 2])]}, col = col[as.integer(group[, 1])], las = 2)
stevenn's avatar
stevenn committed
559
    legend("topright", levels(group[, 1]), fill = col[1:nlevels(group[,1])], bty = "n")
Stevenn Volant's avatar
Stevenn Volant committed
560
    if (!ncol1)  legend("topleft", levels(group[, 2]), density = 15,col = 1, angle = seq(0,160,length.out =nlevels(group[, 2]))[1:nlevels(group[, 2])], bty = "n")
stevenn's avatar
stevenn committed
561
562
563
564
565
  
  }


  ## barplot Nul 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
566
  barPlotNul <-function (input,counts, group, cex.names = 1, col = c("lightblue","orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
567
568
569
  {
    
    percentage <- apply(counts, 2, function(x) {sum(x == 0)}) * 100/nrow(counts)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
570
    percentage.allNull <- (nrow(counts) - nrow(removeNulCounts(counts))) * 100/nrow(counts)
stevenn's avatar
stevenn committed
571
572
    ncol1 <- ncol(group) == 1
    
573
    par(cex=input$cexTitleDiag,mar=c(12,6,4,5))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
574

stevenn's avatar
stevenn committed
575
576
577
578
    barplot(percentage, las = 2, col = col[as.integer(group[,1])], 
            density = if (ncol1) {NULL}
            else {15}, 
            angle = if (ncol1) {NULL}
Stevenn Volant's avatar
Stevenn Volant committed
579
            else {seq(0,160,length.out =nlevels(group[, 2]))[as.integer(group[, 2])]},
stevenn's avatar
stevenn committed
580
581
582
583
584
585
            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")
Stevenn Volant's avatar
Stevenn Volant committed
586
    if (!ncol1) legend("topleft", levels(group[, 2]), density = 15, col = 1, angle = seq(0,160,length.out =nlevels(group[, 2]))[1:nlevels(group[, 2])], bty = "n")
stevenn's avatar
stevenn committed
587
588
589
590
  }


  ## Plot density
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
591
  densityPlotTot <-function (input,counts, group, col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
592
593
594
595
  {
    
    counts <- removeNulCounts(counts)
    ncol1 <- ncol(group) == 1
596
    par(cex=input$cexTitleDiag,mar=c(12,5,4,5))
stevenn's avatar
stevenn committed
597
598
    plot(density(log2(counts[, 1] + 1)), las = 1, lwd = 2, main = "Density of counts distribution", 
         xlab = expression(log[2] ~ (raw ~ count + 1)), 
599
         ylim = c(0, max(apply(counts, 2, function(x) {max(density(log2(x + 1))$y)})) * 1.05), 
stevenn's avatar
stevenn committed
600
         lty = if (ncol1) {1}
601
         else{rep(seq(1:6),ceiling(nlevels(group[, 2])/6))[as.integer(group[, 2])[1]]}, 
stevenn's avatar
stevenn committed
602
603
604
605
606
607
         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}
608
            else{rep(seq(1:6),ceiling(nlevels(group[, 2])/6))[as.integer(group[, 2])[i]]})
stevenn's avatar
stevenn committed
609
610
    }
    legend("topright", levels(group[, 1]), lty = 1, col = col[1:nlevels(group[,1])], lwd = 2, bty = "n")
611
    if (!ncol1) legend("topleft", levels(group[, 2]), lty = rep(seq(1:6),ceiling(nlevels(group[, 2])/6))[1:nlevels(group[, 2])], col = 1, lwd = 2, bty = "n")
stevenn's avatar
stevenn committed
612
613
614
615
616
    
  }


  ## Table of maj. taxo
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
617
  majTab <- function(input,counts,n)
stevenn's avatar
stevenn committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
  {
    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
633
  majTaxPlot <-function (input,counts, n = 3, group, cex.names = 1, col = c("lightblue",  "orange", "MediumVioletRed", "SpringGreen")) 
stevenn's avatar
stevenn committed
634
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
635
    p = majTab(input,counts,n)
stevenn's avatar
stevenn committed
636
637
638
    maj <- apply(p, 2, max)
    seqname <- rownames(p)[apply(p, 2, which.max)]
    ncol1 <- ncol(group) == 1
639
    par(cex=input$cexTitleDiag,mar=c(12,6,4,5))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
640
    x <- barplot(maj, col = col[as.integer(group[, 1])], main = "Proportion of mapped reads from\nmost expressed sequence",
stevenn's avatar
stevenn committed
641
                 ylim = c(0, max(maj) * 1.2), cex.main = 1, 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
642
                 cex.names = cex.names, las = 2, ylab = "Proportion of mapped reads", 
stevenn's avatar
stevenn committed
643
644
645
                 density = if (ncol1) {NULL}
                 else {15}, 
                 angle = if (ncol1) {NULL}
Stevenn Volant's avatar
Stevenn Volant committed
646
                 else {seq(0,160,length.out =nlevels(group[, 2]))[as.integer(group[, 2])]})
stevenn's avatar
stevenn committed
647
648
649
    
    legend("topright", levels(group[, 1]), fill = col[1:nlevels(group[,1])], bty = "n")
    if (!ncol1) legend("topleft", levels(group[, 2]), density = 15, col = 1, 
Stevenn Volant's avatar
Stevenn Volant committed
650
                       angle = seq(0,160,length.out =nlevels(group[, 2]))[1:nlevels(group[, 2])], bty = "n")
stevenn's avatar
stevenn committed
651
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
652
    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
653
654
655
656
  }
  

  ## plot SERE Coefs
Stevenn Volant's avatar
Stevenn Volant committed
657
658
659
660
661
662
663
#   SEREplot<-function(input,counts) 
#   {
#     sere = SEREcoef(counts)
#     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")
#     
#   }
stevenn's avatar
stevenn committed
664
665
666
667
668
  
  
  ## Get the SERE COEF
  SEREcoef<-function(counts)
  {
Stevenn Volant's avatar
Stevenn Volant committed
669
670
671
672
    counts = as.matrix(counts)
    sere <- matrix(0, ncol = ncol(counts), nrow = ncol(counts))
    for (i in 1:(ncol(counts)-1)) {
      for (j in (i+1):ncol(counts)) {
stevenn's avatar
stevenn committed
673
674
675
        sere[i, j] <- sigfun_Pearson_meta(counts[, c(i, j)])
      }
    }
Stevenn Volant's avatar
Stevenn Volant committed
676
    sere=sere+t(sere)
stevenn's avatar
stevenn committed
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
    colnames(sere) <- rownames(sere) <- colnames(counts)
    sere <- round(sere, digits = 3)
    
    return(sere) 
  }
  

  ## function for the SERE coef
  sigfun_Pearson_meta <- function(observed) {
    laneTotals <- colSums(observed)
    total <- sum(laneTotals)
    fullObserved <- observed[rowSums(observed) > 0, ]
    fullLambda <- rowSums(fullObserved)/total
    fullLhat <- fullLambda > 0
    fullExpected <- outer(fullLambda, laneTotals)
    fullKeep <- which(fullExpected > 0)
    oeFull <- (fullObserved[fullKeep] - fullExpected[fullKeep])^2/fullExpected[fullKeep]
    dfFull <- length(fullKeep) - sum(fullLhat != 0)
    sqrt(sum(oeFull)/dfFull)
  }
stevenn's avatar
stevenn committed
697
698


stevenn's avatar
stevenn committed
699
  ## Plots of size factors
700
  diagSFactors<-function (input,normFactors,counts) 
stevenn's avatar
stevenn committed
701
  {
Stevenn Volant's avatar
Stevenn Volant committed
702
703
    geomeans <- exp(rowMeans(log(counts)))
    samples <- colnames(counts)
Stevenn Volant's avatar
Stevenn Volant committed
704
705
      par(cex=input$cexTitleDiag,mar=c(6,6,4,5))
      plot(normFactors, colSums(counts), pch = 19, las = 1,cex = ifelse(input$addLabelSFact,0,input$cexLabelDiag),
stevenn's avatar
stevenn committed
706
707
           ylab = "Total number of reads", xlab = "Size factors", 
           main = "Diagnostic: size factors vs total number of reads")
Stevenn Volant's avatar
Stevenn Volant committed
708
      if(input$addLabelSFact) text(normFactors,colSums(counts),labels = samples,cex=input$cexLabelDiag)
Stevenn Volant's avatar
Stevenn Volant committed
709
      abline(lm(colSums(counts) ~ normFactors + 0), lty = 2, col = "grey")
stevenn's avatar
stevenn committed
710
  }
stevenn's avatar
stevenn committed
711

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
712
713
  
  ### PCoA
714
  PCoAPlot_meta <-function (input, dds, group_init, col = c("SpringGreen","dodgerblue","black","firebrick1"), plot = "pcoa") 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
715
716
  {
    cval=c()
Stevenn Volant's avatar
Stevenn Volant committed
717
    time_set = 0
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
718
719
    # Set of shape
    shape=c(19,17,15,18)
Stevenn Volant's avatar
Stevenn Volant committed
720
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
721
722
    ## Var of interest
    VarInt  = input$VarInt
Stevenn Volant's avatar
Stevenn Volant committed
723
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
    ## 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)
Stevenn Volant's avatar
Stevenn Volant committed
739
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
740
741
742
743
744
    ## Get the group corresponding to the modalities
    group = group[ind_kept]
    nb = length(unique((group)))
    group = as.factor(group)
    
Stevenn Volant's avatar
Stevenn Volant committed
745
746
747
    if(nlevels(group)!=0)
    { 
      ## Get the norm data
748
      counts.norm = as.data.frame(round(counts(dds)))
749
      if(input$CountsType=="Normalized") counts.norm = as.data.frame(round(counts(dds, normalized = TRUE)))
Stevenn Volant's avatar
Stevenn Volant committed
750
751
752
753
      # was removed
      counts.norm = counts.norm[,ind_kept]
  
      ## Get the distance
Stevenn Volant's avatar
Stevenn Volant committed
754
755
756
      if(input$DistClust!="sere") dist.counts.norm = vegdist(t(counts.norm), method = input$DistClust)
      if(input$DistClust=="sere") dist.counts.norm = as.dist(SEREcoef(counts.norm))
      
Stevenn Volant's avatar
Stevenn Volant committed
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
      ## 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))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
775
      }
Stevenn Volant's avatar
Stevenn Volant committed
776
777
778
779
780
781
782
783
784
785
786
      #else if(length(col)<length(condition_set) * length(time_set) && input$colorgroup){
      #  col = rep(col[1:length(condition_set)], length(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)
      }
      
      # to reactivate
      #pco.counts.norm$li = pco.counts.norm$li[ind_kept,]
      if (plot == "pcoa"){
Stevenn Volant's avatar
Stevenn Volant committed
787
        par(cex=input$cexTitleDiag,mar=c(6,6,4,5))
Stevenn Volant's avatar
Stevenn Volant committed
788
789
        ## 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),"%"),
Stevenn Volant's avatar
Stevenn Volant committed
790
             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",main='Principal Coordinates Analysis ')
Stevenn Volant's avatar
Stevenn Volant committed
791
792
793
794
795
796
797
798
799
        # Set different shapes
        if(input$labelPCOA == "Group"){
          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),
800
                        add.plot = TRUE, cpoint = input$cexpoint, cell=input$cexcircle, clabel=input$cexLabelDiag,  cstar = input$cexstar)
Stevenn Volant's avatar
Stevenn Volant committed
801
802
803
804
805
806
807
808
809
810
        }  
        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)
      }
  }
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
811
812
813
  }
  
  ### PCA
814
  PCAPlot_meta <-function(input,dds, group_init, n = min(500, nrow(counts(dds))), type.trans = c("VST", "rlog"), 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
815
816
                           col = c("lightblue", "orange", "MediumVioletRed", "SpringGreen"),plot="pca") 
  {
817
818
    ## Var of interest
    VarInt  = input$VarInt
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
819
    
820
821
    group = as.character(apply(group_init,1,paste, collapse = "-"))
    group_init = group
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
822
    
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
    ## 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)
    
    ## To select the colors
    indgrp =as.integer(as.factor(group_init))[ind_kept]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
843
    
844
845
    
    if(nlevels(group)!=0)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
846
    { 
847
      type.trans <- type.trans[1]
Stevenn Volant's avatar
Stevenn Volant committed
848
      
849
850
851
      if (type.trans == "VST") counts.trans <- assay(varianceStabilizingTransformation(dds))
      else counts.trans <- assay(rlogTransformation(dds))
      counts.trans = counts.trans[,ind_kept]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
852
      
853
854
      rv = apply(counts.trans, 1, var, na.rm = TRUE)
      pca = prcomp(t(counts.trans[order(rv, decreasing = TRUE),][1:n, ]))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
855
      
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
      if(plot=="pca")
      { 
        prp <- pca$sdev^2 * 100/sum(pca$sdev^2)
        prp <- round(prp, 2)
        ncol1 <- ncol(group) == 1
        
        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(mfrow = c(1, 2),cex=input$cexTitleDiag,mar=c(6,6,4,5))
        plot(pca$x[, 1], pca$x[, 2], las = 1, cex = input$cexTitleDiag, col = col[indgrp], 
             pch = 16,
             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[indgrp],cex=input$cexLabelDiag)
        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 = input$cexTitleDiag, col = col[indgrp], 
             pch = 16,
             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[indgrp],cex=input$cexLabelDiag)
      }
      if(plot=="eigen"){eigen = pca$sdev[1:min(7,ncol(counts.trans))]^2; barplot(eigen, xlab="Dimensions", ylab="Eigenvalues (%)", names.arg = 1:min(7,ncol(counts.trans)), col = c(rep("black", 3), rep("grey", 4)), ylim=c(0,max(eigen)+5), cex.axis=1.2, cex.lab=1.4,cex.names=1.2)}
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
889
890
891
892
893
    }
  }
  
  
  
stevenn's avatar
stevenn committed
894

stevenn's avatar
stevenn committed
895
896
897
898
899
  ############################################################
  ##
  ##              CREATE THE CONTRAST DATABASE
  ##
  ############################################################
stevenn's avatar
stevenn committed
900

stevenn's avatar
stevenn committed
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
  
  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)
  }
  
  
928
929
930
931
  BaseContrastEasy <- function(input,names,namesfile,target)
  {  
    
    v_tmp = rep(0,length(names))
svolant's avatar
svolant committed
932
    print(names)
933
934
935
936
937
938
939
    filesize = file.info(namesfile)[,"size"]
    F1 = NULL
    nameContrast = ""
    
    ## Get the selected modalities
    M1 = input$Select1_contrast
    M2 = input$Select2_contrast
svolant's avatar
svolant committed
940
941
    print(M1)
    print(M2)
942
943
944
945
946
947
948
949
950
951
952
    
    if(length(input$Interaction2)>0) F1 = input$Select3_contrast
    ## Get the name of the parameter corresponding to the modalities
    InterVar = input$InterestVar
    Sel_Var = InterVar[which(unlist(lapply(target[,InterVar],FUN = function(x){M1%in%x})))]
    names1dds = paste(Sel_Var,M1,sep="")
    names2dds = paste(Sel_Var,M2,sep="")
    
    ## fill the vector
    ind1 = which(names%in%names1dds)
    ind2 = which(names%in%names2dds)
svolant's avatar
svolant committed
953
954
    print(ind1)
    print(ind2)
955
956
    if(length(ind1)>0) v_tmp[ind1] = 1
    if(length(ind2)>0) v_tmp[ind2] = -1
svolant's avatar
svolant committed
957
    print(v_tmp)
958
959
960
961
962
963
964
965
966
967
968
969
    
    nameContrast = paste(M1,"_vs_",M2,sep="")
    
    if(F1!="All" && !is.null(F1)){
      Sel_Var_For = InterVar[which(unlist(lapply(target[,InterVar],FUN = function(x){F1%in%x})))]
      ## Depends on the interation
      namesfor1 = paste(Sel_Var,M1,".",Sel_Var_For,F1,sep="")
      namesfor1.1 = paste(Sel_Var_For,F1,".",Sel_Var,M1,sep="")
      namesfor2 = paste(Sel_Var,M2,".",Sel_Var_For,F1,sep="")
      namesfor2.1 = paste(Sel_Var_For,F1,".",Sel_Var,M2,sep="")
      ind1.for = which(names%in%c(namesfor1,namesfor1.1))
      ind2.for = which(names%in%c(namesfor2,namesfor2.1))
970
971
      if(length(ind1.for)>0) v_tmp[ind1.for] = 1
      if(length(ind2.for)>0) v_tmp[ind2.for] = -1
972
973
      nameContrast = paste(nameContrast,"_for_",F1,sep="")
    }
svolant's avatar
svolant committed
974
    print(v_tmp)
975
976
977
978
    
    if(filesize!=0)
    { 
      oldContrast = read.table(namesfile,header=TRUE)
svolant's avatar
svolant committed
979
      print(oldContrast)
980
981
982
983
984
985
986
987
988
      colnamesTmp = c(colnames(oldContrast),nameContrast)
      mat = cbind(oldContrast,v_tmp)
    }
    else{ colnamesTmp = nameContrast; mat = v_tmp}
    
    write.table(mat,namesfile,row.names=FALSE,col.names = colnamesTmp)
  }
  
  
stevenn's avatar
stevenn committed
989
990
991
992
993
  ## Remove nul counts
  removeNulCounts <-function (counts) 
  {
    return(counts[rowSums(counts) > 0, ])
  }
stevenn's avatar
stevenn committed
994
995

  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
996
997
998
999
1000
  ############################################################
  ##
  ##              VISUALISATION PLOTS
  ##
  ############################################################