internal.R 54.3 KB
Newer Older
Stevenn Volant's avatar
Stevenn Volant committed
1001
  Plot_Visu_Heatmap <- function(input,resDiff,export=FALSE){
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1002
  
1003
1004
  VarInt = input$VisuVarInt
  ind_taxo = input$selectTaxoPlot
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1005
  
1006
  counts_tmp_combined = GetDataToPlot(input,resDiff,VarInt,ind_taxo)$counts
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1007
1008
1009
1010
  
  if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0)
  { 
    ## Transform to log2
1011
    counts_tmp_combined = log2(GetDataToPlot(input,resDiff,VarInt,ind_taxo)$counts+1)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1012
1013
1014
1015
1016
1017
   
    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
1018
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1019
    ## Transpose matrix if Horizontal
1020
    if(input$SensPlotVisu=="Horizontal") counts_tmp_combined = t(as.matrix(counts_tmp_combined))
Stevenn Volant's avatar
Stevenn Volant committed
1021
1022
1023
1024
1025
    
    if(!export) plot = d3heatmap(counts_tmp_combined, dendrogram = "none", Rowv = NA, Colv = NA, na.rm = TRUE,width = input$widthVisu, height = input$heightVisu, show_grid = FALSE, colors = col, scale = input$scaleHeatmap,cexRow = 0.6)
    
    if(export) plot = heatmap.2(counts_tmp_combined, dendrogram = "none", Rowv = NA, Colv = NA, na.rm = TRUE, density.info="none", margins=c(12,8),trace="none",srtCol=45,col = col, scale = input$scaleHeatmap,cexRow = 0.6)
    return(plot)
stevenn's avatar
stevenn committed
1026
  }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1027

stevenn's avatar
stevenn committed
1028
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1029
1030
1031
1032
1033
1034
1035
1036
1037
  }

  ######################################################
  ##
  ##            BOXPLOT
  ##
  ######################################################
  
  
1038
  Plot_Visu_Boxplot <- function(input,resDiff,alpha=0.7){
stevenn's avatar
stevenn committed
1039
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1040
    gg = NULL
1041
1042
1043
1044
1045
    
    ## Colors
    colors = rep(c("#1f77b4","#aec7e8","#ff7f0e","#ffbb78", "#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b",
                   "#c49c94","#e377c2","#f7b6d2","#7f7f7f", "#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"),ceiling(nrow(resDiff$target)/20))
    
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1046
    ## Get Input for BoxPlot
1047
1048
    VarInt = input$VisuVarInt
    ind_taxo = input$selectTaxoPlot
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1049
    
1050
1051
    
    tmp_merge = GetDataToPlot(input,resDiff,VarInt,ind_taxo,aggregate=FALSE)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1052
    counts_tmp_combined = tmp_merge$counts
1053
    levelsMod = tmp_merge$levelsMod
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1054
1055
    nbKept = length(ind_taxo)
    
1056
    if(!is.null(counts_tmp_combined) && nrow(counts_tmp_combined)>0 && !is.null(levelsMod))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1057
1058
    { 
    
1059
1060
      if(input$typeDataBox == "Relative") counts_tmp_combined = tmp_merge$prop_all
      else counts_tmp_combined = log2(counts_tmp_combined+1)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1061
1062
1063
1064
1065
1066
      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
1067
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
      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
1084
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1085
1086
1087
1088
      dataBarPlot_mat = as.data.frame(dataBarPlot_mat)
      
      colnames(dataBarPlot_mat) = c("Taxonomy","Value","Samples")
      dataBarPlot_mat[,2] = tmp_counts
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098

      if(is.null(input$BoxColorBy) || length(VarInt)<=1){ dataBarPlot_mat$Colors = dataBarPlot_mat$Samples}
      if(!is.null(input$BoxColorBy) && length(VarInt)>1)
        { 
        tmp = strsplit(as.character(dataBarPlot_mat$Samples),"-")
        ind = which(VarInt%in%input$BoxColorBy)
        dataBarPlot_mat$Colors = rapply(tmp, function(x) paste(x[ind],collapse ="-"), how = "unlist")
      }
      # print(dataBarPlot_mat$Colors)
      dataBarPlot_mat$Samples = factor(dataBarPlot_mat$Samples,levels=levelsMod)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1099
      
1100
1101
1102
1103
      gg = ggplot(dataBarPlot_mat,aes(x=Samples,y=Value,fill=Colors))  + geom_boxplot(alpha=alpha) +theme_bw()
      gg = gg  +theme(axis.text=element_text(size=16,face="bold"),axis.title=element_text(size=18,face="bold"),panel.background = element_blank(),
                      panel.grid.major = element_blank(),panel.grid.minor = element_blank(), axis.title.x=element_blank(), axis.text.x = element_text(angle = 90, hjust = 1,vjust=0.5)) 
      gg = gg + ylab(paste(input$typeDataBox, "abundance")) +scale_fill_manual(values = colors) + guides(fill=FALSE)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1104
      if(input$CheckAddPointsBox) gg = gg + geom_point(position=position_jitterdodge(dodge.width=0.9))
1105
      if(input$SensPlotVisu=="Horizontal") gg = gg + coord_flip()
Stevenn Volant's avatar
Stevenn Volant committed
1106
      if(nbKept>1) gg = gg + facet_wrap(~ Taxonomy,scales = input$ScaleBoxplot)
stevenn's avatar
stevenn committed
1107
    }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1108
1109
1110
    
   return(gg)
    
stevenn's avatar
stevenn committed
1111
1112
1113
  }
  
  
svolant's avatar
svolant committed
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
  
  ######################################################
  ##
  ##            Scatter plot
  ##
  ######################################################
  
  
  Plot_Visu_Scatterplot<- function(input,resDiff,export=FALSE,lmEst = FALSE){
    
    plot = NULL
    regCoef = NULL
    Rsq = NULL
    dds = resDiff$dds
    counts = as.data.frame(round(counts(dds, normalized = TRUE)))
    target = as.data.frame(resDiff$target)
    data = cbind(target,log2(t(counts)+1))
    
    ## Get Input for ScatterPlot
    Xvar = input$Xscatter
    Yvar = input$Yscatter
    ColBy = input$ColorBy
    PchBy = input$PchBy
    PointSize = input$PointSize
    
    x_var = if (is.null(Xvar)) NULL else data[,Xvar]
    y_var = if (is.null(Yvar)) NULL else data[,Yvar]
    col_var = if (ColBy== "None" || is.null(ColBy)) NULL else data[,ColBy]
    symbol_var = if (PchBy == "None" || is.null(PchBy)) NULL else data[,PchBy]
    size_var = if (PointSize == "None" || is.null(PointSize))  NULL else data[,PointSize]
    
    if(!export && !input$AddRegScatter && !lmEst){
      plot = scatterD3(x = x_var,
                            y = y_var,
                            lab = rownames(data),
                            xlab = Xvar,
                            ylab = Yvar,
                            col_var = col_var,
                            col_lab = ColBy,
                            symbol_var = symbol_var,
                            symbol_lab = PchBy,
                            size_var = size_var,
                            size_lab = PointSize,
                            key_var = rownames(data),
                            height = input$heightVisu,
                            point_opacity = 0.7,
                            labels_size = input$SizeLabelScatter,
                            transitions = TRUE)
      return(plot)
    }

    if(export || input$AddRegScatter){
      if(!lmEst ){
        col_var = if (ColBy== "None" || is.null(ColBy)) 1 else data[,ColBy]
        symbol_var = if (PchBy == "None" || is.null(PchBy)) factor(rep(1,nrow(data))) else data[,PchBy]
        size_var = if (PointSize == "None" || is.null(PointSize))  1 else data[,PointSize]
        
        plot = ggplot(data, aes(x = x_var, y = y_var)) + geom_point(aes(color=col_var,size =size_var,shape = symbol_var),alpha=0.7) 
        if(input$SizeLabelScatter!=0) plot = plot + geom_text(aes(label=rownames(data),color=col_var,size=input$SizeLabelScatter/20),vjust = 0,nudge_y =0.05)
        plot = plot + xlab(Xvar) + ylab(Yvar)
        if(input$AddRegScatter) plot = plot + geom_smooth(method="lm")
      return(plot)
      }
    }
    if(lmEst)
    {
      res = lm(y_var~x_var)
      sumRes = summary(res)
      regCoef = sumRes$coefficients 
      rownames(regCoef) = c("Intercept",Xvar)
      Rsq = sumRes$r.squared
      return(list(regCoef=regCoef,Rsq = Rsq))
    }
  }
  
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1191
1192
1193
1194
1195
  ######################################################
  ##
  ##            GLOBAL VIEW
  ##
  ######################################################
stevenn's avatar
stevenn committed
1196
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1197
1198
1199
1200
1201
1202
1203
1204
1205
  
  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
1206
1207
    VarInt = input$VisuVarInt
    #VarIntBoxDiv = input$VarBoxDiv 
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1208
1209
    ind_taxo = rownames(counts)
    
1210
    tmp = GetDataToPlot(input,resDiff,VarInt,ind_taxo,aggregate=FALSE)
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1211
1212
    counts_tmp_combined = tmp$counts
    targetInt = tmp$targetInt
stevenn's avatar
stevenn committed
1213

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1214
1215
1216
1217
1218
1219
    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)
Stevenn Volant's avatar
Stevenn Volant committed
1220
1221
1222
1223
#       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)))
1224
      dataTmp = data.frame(value=c(alpha,beta,gamma),
Stevenn Volant's avatar
Stevenn Volant committed
1225
1226
                     diversity = c(rep("Alpha",nb),rep("Beta",nb),rep("Gamma",nb)),
                     Var = as.character(rep(names(alpha),3)))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
     
      ## 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) 
1245
        if(input$SensPlotVisu=="Horizontal") gg = gg + coord_flip()
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
        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
1263
1264
1265

  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
  ## Rarefaction
  Plot_Visu_Rarefaction <- function(input,resDiff,xlim,ylim,ylab="Species"){
    
    PlotRare = NULL
    dds = resDiff$dds
    
    ## Taxo in columns
    counts = t(round(counts(dds, normalized = TRUE)))
    
    if(nrow(counts)>0 && !is.null(counts))
    { 
      max <- max(rowSums(counts))
      raremax <- min(rowSums(counts))
      #PlotRare = rarefaction_curve(counts, step = 10, taxo = "Taxonomy level") 
      options(warn=-1)
      PlotRare = rarecurve(counts, step = max(1,ceiling(max/60)),sample=raremax, col = "blue", cex = 0.9,xlim=xlim,ylim=ylim, ylab=ylab) 
      options(warn=0)
    }
    return(PlotRare)
  }
stevenn's avatar
stevenn committed
1286
1287
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1288
1289
1290
  
  ## Get the non-zero taxo by sample  
  TaxoNumber <-  function (x, groups, mar = 1) 
stevenn's avatar
stevenn committed
1291
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1292
1293
1294
1295
1296
1297
1298
1299
    if (!missing(groups)) 
    {
      if (length(groups) == 1) groups = rep(groups, nrow(x))
      x = aggregate(x, list(groups), max)
      rownames(x) = x[, 1]; x = x[, -1]
    }
    if (length(dim(x)) > 1) res = apply(x > 0, mar, sum)
    else res = sum(x > 0)
stevenn's avatar
stevenn committed
1300
1301
1302
  }
  
  
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1303
  rarefaction_curve <- function (x, step = 1, taxo ="Species") 
stevenn's avatar
stevenn committed
1304
  {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
    
    tot = rowSums(x)
    S = TaxoNumber(x)
    if (any(S <= 0)) {
      x <- x[S > 0, , drop = FALSE]
      tot <- tot[S > 0]
      S <- S[S > 0]
    }
    nr <- nrow(x)

    out <- lapply(seq_len(nr), function(i) {
      n <- seq(1, tot[i], by = step)
      if (n[length(n)] != tot[i]) n <- c(n, tot[i])
      drop(rarefy(x[i, ], n))
    })
    
    
    df = data.frame()
    
    for(i in 1: length(out))
stevenn's avatar
stevenn committed
1325
    {
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
      dftmp = data.frame(x=attr(out[[i]], "Subsample"),y=out[[i]],samples=rep(rownames(x)[i],length(out[[i]])))
      df = rbind(df,dftmp)
    }
    
    Nmax = sapply(out, function(x) max(attr(x, "Subsample")))
    Smax = sapply(out, max)
    
#     plot =  nvd3Plot(y ~ x | samples, data = df, id = 'chart', type = 'lineChart',height=600)
#     plot$xAxis(axisLabel = 'Sample size')
    
    plot =  ggplot(df,aes=c(x=x,y=y,  group=samples, colour=samples)) + geom_line()+xlab('Sample size') 
    plot = plot + theme_bw() + theme(legend.position="bottom")

    return(plot)
  }
  
  
  TableDiff_print <- function(input,BaseContrast,resDiff, info = NULL) 
  {
    VarInt = input$VarInt
    dds = resDiff$dds
    counts = resDiff$counts
    target = resDiff$target
    group = ""
    if(length(VarInt)>1) for(i in VarInt){ group = paste(group,target[,i], sep="-") }
    else group = target[,VarInt]
    conds = unique(group)
    
    result = list()
    alpha = input$AlphaVal
    cooksCutoff = ifelse(input$CooksCutOff!='Auto',ifelse(input$CooksCutOff!=Inf,input$CutOffVal,Inf),TRUE)
    result[[input$ContrastList_table]] <- results(dds,contrast=BaseContrast[,input$ContrastList_table],pAdjustMethod=input$AdjMeth,
                                                  cooksCutoff=cooksCutoff,
                                                  independentFiltering=input$IndFiltering,alpha=alpha)
    
    #names(result) <- gsub("_", " ", names(result))
    if (is.null(info))  info <- data.frame(Id = rownames(result[[1]]))
    else names(info)[1] <- "Id"
    if (any(duplicated(info[, 1]))) stop("Duplicated IDs in the annotations")
    counts <- data.frame(Id = rownames(counts(dds)), counts(dds), round(counts(dds, normalized = TRUE)))
    colnames(counts) <- c("Id", colnames(counts(dds)), paste0("norm.", colnames(counts(dds))))
    bm <- data.frame(Id = rownames(result[[1]]), baseMean = round(result[[1]][,"baseMean"], 2))
    base <- merge(merge(info, counts, by = "Id", all.y = TRUE), bm, by = "Id")
    tmp <- base[, paste("norm", colnames(counts(dds)), sep = ".")]
    for (cond in conds) {
      base[, cond] <- round(apply(as.data.frame(tmp[, group == cond]), 1, mean), 0)
    }
    complete.complete <- base
    complete <- vector("list", length(result))
    names(complete) <- names(result)
    for (name in names(result)) {
      complete.name <- base
stevenn's avatar
stevenn committed
1378
      
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1379
1380
1381
1382
1383
1384
1385
      ### ??????????
      conds.supp <- setdiff(conds, gsub("\\(|\\)", "", unlist(strsplit(name, " vs "))))
      if (length(conds.supp) > 0) {
        complete.name <- complete.name[, -which(names(complete.name) %in% conds.supp)]
        samples.supp <- colnames(counts(dds))[group %in% conds.supp]
        col.supp <- c(samples.supp, paste("norm", samples.supp, sep = "."))
        complete.name <- complete.name[, -which(names(complete.name) %in% col.supp)]
stevenn's avatar
stevenn committed
1386
      }
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
      ### ??????????

      res.name <- data.frame(Id = rownames(result[[name]]), 
                             FC = round(2^(result[[name]][, "log2FoldChange"]), 3),
                             log2FoldChange = round(result[[name]][, "log2FoldChange"], 3),
                             pvalue = result[[name]][, "pvalue"], 
                             padj = result[[name]][, "padj"])
      complete.name <- merge(complete.name, res.name, by = "Id")
      mcols.add <- data.frame(Id = rownames(counts(dds)), 
                              dispGeneEst = mcols(dds)$dispGeneEst, dispFit = mcols(dds)$dispFit, 
                              dispMAP = mcols(dds)$dispMAP, dispersion = mcols(dds)$dispersion, 
                              betaConv = mcols(dds)$betaConv, maxCooks = mcols(dds)$maxCooks)
Stevenn Volant's avatar
Stevenn Volant committed
1399
      if (is.null(cooksCutoff)){
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1400
1401
1402
1403
1404
1405
1406
        m <- nrow(attr(dds, "modelMatrix"))
        p <- ncol(attr(dds, "modelMatrix"))
        cooksCutoff <- qf(0.99, p, m - p)
      }
      mcols.add$outlier <- ifelse(mcols(dds)$maxCooks > cooksCutoff, "Yes", "No")
      complete.name <- merge(complete.name, mcols.add, by = "Id")
      complete[[name]] <- complete.name
Stevenn Volant's avatar
Stevenn Volant committed
1407
      up.name <- complete.name[which(complete.name$padj <= alpha & complete.name$betaConv & complete.name$log2FoldChange>=0), ]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1408
      up.name <- up.name[order(up.name$padj), ]
Stevenn Volant's avatar
Stevenn Volant committed
1409
      down.name <- complete.name[which(complete.name$padj<=alpha & complete.name$betaConv & complete.name$log2FoldChange<=0), ]
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1410
      down.name <- down.name[order(down.name$padj), ]
Stevenn Volant's avatar
Stevenn Volant committed
1411

Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1412
      name <- gsub(" ", "", name)
Stevenn Volant's avatar
Stevenn Volant committed
1413
      keep <- c("Id","baseMean","FC","log2FoldChange","padj")
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1414
1415
1416
#       complete.complete[, paste(name, keep, sep = ".")] <- complete.name[, keep]
    }
    #return(list(complete=complete.name,up=up.name,down=down.name))
Stevenn Volant's avatar
Stevenn Volant committed
1417
    return(list(complete=complete.name[,keep],up=up.name[,keep],down=down.name[,keep]))
Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1418
1419
1420
  }
  
  
1421
  Get_log2FC_padj <-function(input,BaseContrast,resDiff, info = NULL)
Stevenn Volant's avatar
Stevenn Volant committed
1422
  {
1423
1424
    log2FC = NULL
    padj = NULL
Stevenn Volant's avatar
Stevenn Volant committed
1425
1426
1427
1428
    VarInt = input$VarInt
    dds = resDiff$dds
    counts = resDiff$counts
    target = resDiff$target
1429
    SelContrast = colnames(BaseContrast)
Stevenn Volant's avatar
Stevenn Volant committed
1430
1431
1432
1433
    nbCont = length(SelContrast)
    result = list()
    alpha = input$AlphaVal
    cooksCutoff = ifelse(input$CooksCutOff!='Auto',ifelse(input$CooksCutOff!=Inf,input$CutOffVal,Inf),TRUE)
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444

      for(i in 1:nbCont)
      { 
        cont = as.character(SelContrast[i])
        result[[cont]] <- results(dds,contrast=BaseContrast[,cont],pAdjustMethod=input$AdjMeth,
                                  cooksCutoff=cooksCutoff,
                                  independentFiltering=input$IndFiltering,alpha=alpha)
      }
      log2FC = as.matrix(round(result[[SelContrast[1]]][, "log2FoldChange"], 3))
      padj = as.matrix(round(result[[SelContrast[1]]][, "padj"], 3))
      if(nbCont>1)
Stevenn Volant's avatar
Stevenn Volant committed
1445
      {
1446
1447
1448
1449
1450
1451
1452
        for(i in 2:nbCont)
        {
          log2FC = cbind(log2FC,round(result[[SelContrast[i]]][, "log2FoldChange"], 3))
          padj = cbind(padj,round(result[[SelContrast[i]]][, "padj"], 7))
        }
        colnames(log2FC) = names(result)
        colnames(padj) = names(result)
Stevenn Volant's avatar
Stevenn Volant committed
1453
      }
1454
1455
1456
      rownames(log2FC) = rownames(result[[SelContrast[1]]])
      rownames(padj) = rownames(result[[SelContrast[1]]])

Stevenn Volant's avatar
Stevenn Volant committed
1457
    return(list(log2FC=as.data.frame(log2FC),padj=padj))
Stevenn Volant's avatar
Stevenn Volant committed
1458
1459
1460
  }
  
  
Stevenn Volant's avatar
Stevenn Volant committed
1461
  Plot_Visu_Heatmap_FC <- function(input,BaseContrast,resDiff,export=FALSE){
Stevenn Volant's avatar
Stevenn Volant committed
1462
    
1463
1464
1465
    res = NULL
    SelContrast = input$ContrastList_table_FC
    log2FC = Get_log2FC_padj(input,BaseContrast,resDiff, info = NULL)$log2FC
Stevenn Volant's avatar
Stevenn Volant committed
1466

Stevenn Volant's avatar
Stevenn Volant committed
1467
    
Stevenn Volant's avatar
Stevenn Volant committed
1468
    if(!is.null(log2FC) && length(SelContrast)>=2)
1469
    { 
Stevenn Volant's avatar
Stevenn Volant committed
1470
1471
      cont = which(colnames(log2FC)%in%SelContrast)
      log2FC = log2FC[,SelContrast] 
1472
1473
1474
1475
1476
1477
1478
1479
      ind_taxo = input$selectTaxoPlot
      ind = rownames(log2FC)%in%ind_taxo
      log2FC = log2FC[ind,]
      
      
      col <- c(colorRampPalette(c("royalblue4","royalblue3","royalblue2","royalblue1","white"))(n = 100),colorRampPalette(c("white",  "firebrick1", "firebrick2", "firebrick3", "firebrick4"))(n = 100))
      ## Transpose matrix if Horizontal
      if(input$SensPlotVisu=="Horizontal") log2FC = t(as.matrix(log2FC))
Stevenn Volant's avatar
Stevenn Volant committed
1480
1481
1482
1483
1484
      
      if(!export) res = d3heatmap(log2FC, dendrogram = "row", Rowv = TRUE, Colv = NA, na.rm = TRUE, width = input$widthVisu, height = input$heightVisu, show_grid = FALSE, colors = col, scale = input$scaleHeatmap,cexRow = input$LabelSizeHeatmap,cexCol =input$LabelSizeHeatmap, offsetCol=input$LabelColOffsetHeatmap,offsetRow=input$LabelRowOffsetHeatmap)
    
      
      if(export) res = heatmap.2(log2FC, dendrogram = "row", Rowv = TRUE, Colv = NA, na.rm = TRUE, width = input$widthVisu, height = input$heightVisu, show_grid = FALSE, colors = col, scale = input$scaleHeatmap,cexRow = input$LabelSizeHeatmap,cexCol =input$LabelSizeHeatmap, offsetCol=input$LabelColOffsetHeatmap,offsetRow=input$LabelRowOffsetHeatmap)
1485
1486
1487

    }
    return(res)
Stevenn Volant's avatar
Stevenn Volant committed
1488
1489
1490
  }


Amine  GHOZLANE's avatar
Amine GHOZLANE committed
1491