a b/server.R
1
shinyServer(function(input, output, session) {
2
    options(shiny.maxRequestSize=500*1024^2) 
3
    library(edgeR)
4
    library(limma)
5
    library(DESeq2)
6
    library(caret)
7
    library(kernlab)
8
    library(randomForest)
9
    library(sSeq)
10
    library(plyr)
11
    library(pamr)
12
    library(sfsmisc)
13
    library(foreach)
14
    library(digest)
15
    library(RColorBrewer)
16
    library(gplots)
17
    library(d3heatmap)
18
    library(igraph)
19
    library(DT)
20
    library(miRNAtap)
21
    library(topGO)
22
    library(org.Hs.eg.db)
23
24
    
25
    source("allFunctions.R")
26
    
27
    ## Source codes of PLDA (Witten et. al.)
28
    source("Classify.cv.R")
29
    source("Classify.R")
30
    source("CountDataSet.R")
31
    source("FindBestTransform.R")
32
    source("Functions.R")
33
    source("NullModel.R")
34
    source("NullModelTest.R")
35
    source("PoissonDistance.R")
36
    
37
    ## Source codes of NBLDA
38
    source("classnb.R")
39
    source("CountDataSet1.R")
40
    source("GetDnb.R")
41
    
42
    ## Source codes of voom classifiers
43
    source("voomGSD.R")
44
    source("weighted.stats.R")
45
    source("voomNSC.train.R")
46
    source("predict.voomNSC.R")
47
    source("voomDDA.train.R")
48
    source("predict.voomDDA.R")
49
    
50
    observe({
51
        if (input$varF){
52
            dat = t(dataM())
53
            nZ = nearZeroVar(dat,saveMetrics = FALSE)
54
            updateTextInput(session, inputId = "maxVar", label = "Number of genes with maximum variance", value = as.character(ncol(dat) - length(nZ)))
55
        } 
56
    })
57
    
58
    
59
    dataM <- reactive({  ## Data input.
60
        if(input$dataInput==1){  ## Load example data.
61
            
62
            if(input$sampleData==1){
63
                data <- read.table("cervical_train.txt", header=TRUE)
64
            }
65
            
66
            else if(input$sampleData==2){
67
                data <- read.table("lung_train.txt", header=TRUE)
68
            }
69
        } 
70
        
71
        else if(input$dataInput==2){  ## Upload data. Train
72
            
73
            inFile <- input$uploadTrain
74
            mySep <- switch(input$fileSepDF, '1'=",",'2'="\t",'3'=";", '4'="")
75
            
76
            if (is.null(input$uploadTrain))  {return(NULL)}
77
            
78
            if (file.info(inFile$datapath)$size <= 10485800){
79
                data <- read.table(inFile$datapath, sep=mySep, header=TRUE, fill=TRUE, na.strings = c("", "NA","."))
80
            }
81
            
82
            else print("File is bigger than 10MB and will not be uploaded.")
83
        } 
84
        return(data)
85
    })
86
    
87
    dataC <- reactive({  ## Data input. Conditions
88
        if(input$dataInput==1){  ## Load example data.
89
            
90
            if(input$sampleData==1){
91
                data <- read.table("cervical_cond.txt", header=FALSE, sep="\t")
92
            }
93
            
94
            else if(input$sampleData==2){
95
                data <- read.table("lung_cond.txt", header=FALSE, sep="\t")
96
            }
97
        }
98
        
99
        if(input$dataInput==2){  ## Upload data.
100
            
101
            inFile <- input$uploadCond
102
            mySep <- switch(input$fileSepDF, '1'=",",'2'="\t",'3'=";", '4'="")
103
            
104
            if (is.null(input$uploadCond))  {return(NULL)}
105
            
106
            if (file.info(inFile$datapath)$size <= 10485800){
107
                data <- read.table(inFile$datapath, sep=mySep, header=FALSE, fill=TRUE, na.strings = c("", "NA","."), 
108
                                   stringsAsFactors = TRUE, colClasses = "character")
109
            }
110
            
111
            else print("File is bigger than 10MB and will not be uploaded.")
112
        } 
113
        return(data)
114
    })
115
116
    dataT <- reactive({  ## Data input.
117
        
118
        if(input$dataInput==1){  ## Load example data.
119
            
120
            if(input$sampleData==1){
121
                data <- read.table("cervical_test.txt", header=TRUE)
122
            }
123
            
124
            else if(input$sampleData==2){
125
                data <- read.table("lung_test.txt", header=TRUE)
126
            }
127
        } 
128
        
129
        if(input$dataInput==2){  ## Upload data.
130
            
131
            inFile <- input$uploadTest
132
            mySep <- switch(input$fileSepDF, '1'=",",'2'="\t",'3'=";", '4'="")
133
            
134
            if (is.null(input$uploadTest))  {return(NULL)}
135
            
136
            if (file.info(inFile$datapath)$size <= 10485800){
137
                data <- read.table(inFile$datapath, sep=mySep, header=TRUE, fill=TRUE, na.strings = c("", "NA","."))
138
            }
139
            
140
            else print("File is bigger than 10MB and will not be uploaded.")
141
        } 
142
        return(data)
143
    })
144
145
    
146
    output$RawDataTrain <- DT::renderDataTable({
147
        dataTrain <- dataM()
148
        conditions <- dataC()[,1]
149
        dataTrain <- dataTrain[order(rownames(dataTrain)),]
150
        
151
        col_dots = rep("...", 10)
152
        row_dots = rep("...", 15)
153
        
154
        ## Buraya data wiev için bir fonsiyon yazılacak.
155
        rawTrain = rbind(data.frame(dataTrain[1:8, c(1:12)], col_dots = rep("...", 8), 
156
                         dataTrain[1:8, c(dim(dataTrain)[2]-1, dim(dataTrain)[2])]), 
157
              row_dots, cbind(dataTrain[c(dim(dataTrain)[1]-1,dim(dataTrain)[1]), 1:12], col_dots = c("...","..."), 
158
                              dataTrain[c(dim(dataTrain)[1]-1,dim(dataTrain)[1]), c(dim(dataTrain)[2]-1, 
159
                                                                                    dim(dataTrain)[2])]))
160
        return(rawTrain)
161
        
162
        
163
        
164
    })
165
    
166
    
167
    output$RawDataTest <- DT::renderDataTable({
168
        dataTest <- dataT()
169
        dataTest <- dataTest[order(rownames(dataTest)),]
170
        
171
        return(dataTest)
172
        
173
        
174
        
175
    })
176
    
177
    
178
    output$trainConsole <- renderPrint({
179
        
180
        if(input$runVoomDDA){ 
181
        dataTrain <- dataM()
182
        conditions <- as.factor(dataC()[,1])
183
        dataTest <- dataT()
184
        dataTrain <- dataTrain[order(rownames(dataTrain)),]
185
        dataTest <- dataTest[order(rownames(dataTest)),]
186
        
187
        ## Control steps
188
        trGenes <- sort(rownames(dataTrain))
189
        tsGenes <- sort(rownames(dataTest))
190
        
191
        if (!identical(trGenes, tsGenes)) stop(warning("Gene names should be identical for both training and test data sets."))
192
        if (ncol(dataTrain) != length(conditions)) stop(warning("Number of conditions and sample size do not match."))
193
        
194
        ## Filtering
195
        
196
        if (input$nearZeroF){
197
            nZ = nearZeroVar(t(dataTrain),saveMetrics = FALSE)
198
            if(length(nZ) != 0){
199
                dataTrain = dataTrain[-nZ,]
200
                dataTest = dataTest[-nZ,]      
201
            }
202
        }
203
        
204
        if (input$varF){
205
            ## Variance Filtering
206
            vars = apply(log(dataTrain+1),1,var)
207
            idx = order(vars, decreasing = TRUE)
208
            dataTrain <- dataTrain[idx[1:input$maxVar],]
209
            dataTest <- dataTest[rownames(dataTrain),]
210
        }
211
        
212
        ###
213
        if (input$models == "vDLDA") model = voomDDA.train(counts = dataTrain, conditions = conditions, normalization = input$normMeth, TRUE)
214
        if (input$models == "vDQDA") model = voomDDA.train(counts = dataTrain, conditions = conditions, normalization = input$normMeth, FALSE)
215
        if (input$models == "vNSC") model = voomNSC.train(counts = dataTrain, conditions = conditions, normalization = input$normMeth)
216
        
217
        cat("Model Summary:", "\n")
218
        cat("-----------------------------------------","\n")
219
        cat(paste("Raw Data"),"\n")
220
        cat(paste("   Data includes the read counts of ", dim(dataM())[1], " genes belong to ", dim(dataM())[2], " observations.", sep=""),"\n\n")
221
        
222
        if (input$nearZeroF){
223
            cat(paste("Near-zero filtering"), "\n")
224
            cat(paste("   ", length(nZ), " out of ", dim(dataM())[1]," genes are filtered.", sep=""), "\n\n")
225
        }
226
        
227
        if (input$varF){
228
            cat(paste("Variance filtering"), "\n")
229
            cat(paste("   ", input$maxVar, " genes are selected based on their maximum variance.",sep=""), "\n")
230
        }
231
        cat("-----------------------------------------","\n\n")
232
        
233
        
234
        if ("trSummary" %in% input$advOpts){
235
            if (input$models != "vNSC") trainSummary <- caret::confusionMatrix(table(Actual = conditions, Predicted = predict.voomDDA(model, dataTrain)))
236
            if (input$models == "vNSC") trainSummary <- caret::confusionMatrix(table(Actual = conditions, Predicted = predict.voomNSC(model, dataTrain)))
237
            
238
            cat("Training Summary:","\n")
239
            cat("-----------------------------------------","\n")
240
            caret:::print.confusionMatrix(trainSummary)
241
            cat("-----------------------------------------","\n\n")
242
        }
243
244
        if (input$models != "vNSC") Predicted = predict.voomDDA(model, dataTest)
245
        if (input$models == "vNSC") Predicted = predict.voomNSC(model, dataTest)
246
        
247
        cat("Predictions:","\n")
248
        cat("-----------------------------------------","\n")
249
        cat(paste(c("  ", as.character(Predicted)), sep=""), "\n\n")
250
        
251
        if ("selGenes" %in% input$advOpts){
252
        if (input$models == "vNSC"){
253
            selectedGenes <- model$SelectedGenes[[which(model$threshold == model$opt.threshold)]]
254
            cat(paste("Selected Genes (voomNSC): ", length(selectedGenes), " out of ", dim(dataTrain)[1], " genes are selected", sep=""),"\n")
255
            cat("-----------------------------------------","\n")
256
            cat(paste(selectedGenes,"\n"))
257
        }}
258
259
260
        heatMapData <- reactive({
261
262
263
                if (input$models == "vNSC"){
264
                    nSelFeat <- length(selectedGenes)
265
                    if (nSelFeat < 2) stop(warning("At least 2 features should be selected in the model. Heatmap can not be drawn with 1 feature."))
266
                }
267
268
                dataTrain_HM <- dataM()
269
                HM_data <- t(log2(t(dataTrain_HM + 0.5)/(apply(dataTrain_HM, 2, sum) + 1) * 1e+06))
270
                
271
                if (input$models == "vNSC") HM_data <- HM_data[selectedGenes,]
272
                if (input$models != "vNSC") HM_data <- HM_data[rownames(dataTrain),]
273
                
274
                if (input$centerHeat) HM_data <- scale(as.matrix(HM_data), scale = FALSE)
275
                hmcol = colorRampPalette(brewer.pal(8, "GnBu"))(250)
276
277
            
278
                    return(HM_data)
279
        })
280
        
281
282
283
284
285
        output$heatMap <- renderD3heatmap({
286
            if ((input$runHeatMap)){
287
                
288
                #heatmap.2(HM_data, col = hmcol, trace="none", margin=c(10, 6))
289
                if(input$darkTheme){
290
                    d3heatmap(heatMapData(), theme = "dark", color = input$colorsHM, width = "800px", height = "1800px")
291
                }else{
292
293
                    d3heatmap(heatMapData(), theme = "", color = input$colorsHM, width = "800px", height = "1800px")
294
295
                }
296
            }
297
            
298
        })#,  height = 800, width = 800)  
299
300
301
        output$newtwork <- renderPlot({
302
303
            if ((input$runNetwork)){
304
                cor_mat = cor = cor(t(heatMapData()))
305
                diag(cor_mat)<-0
306
                graph<-graph.adjacency(cor_mat,weighted=TRUE,mode="upper")
307
                E(graph)[ weight>0.7 ]$color <- "green" 
308
                E(graph)[ weight < -0.7 ]$color <- "red" 
309
                E(graph)[ weight>0.6 & weight < 0.7 ]$color <- "black" 
310
                E(graph)[ weight< -0.6 & weight > -0.7 ]$color <- "black" 
311
                plot(graph)
312
            }
313
314
        }, height = 650, width = 650)
315
316
317
318
       if(input$models == "vNSC"){
319
            observe({
320
                     updateSelectInput(session, "showResults", choices = selectedGenes[3:length(selectedGenes)], selected = selectedGenes[3:length(selectedGenes)][1])
321
            })
322
        }
323
324
            observe({
325
                if(input$goAlgorithm == "classic" || input$goAlgorithm == "elim" || input$goAlgorithm == "weight01" || input$goAlgorithm == "lea"){
326
327
                     updateSelectInput(session, "goStatistic", choices = c("ks"="ks", "fisher"="fisher", "t"="t", "ks.ties"="ks.ties"), selected = "ks")
328
                }else {
329
330
                     updateSelectInput(session, "goStatistic", choices = c("fisher"="fisher"), selected = "fisher")
331
                }
332
            })
333
334
335
            observe({
336
                if(input$goGeneAlgorithm == "classic" || input$goGeneAlgorithm == "elim" || input$goGeneAlgorithm == "weight01" || input$goGeneAlgorithm == "lea"){
337
338
                     updateSelectInput(session, "goGeneStatistic", choices = c("ks"="ks", "fisher"="fisher", "t"="t", "ks.ties"="ks.ties"), selected = "ks")
339
                }else {
340
341
                     updateSelectInput(session, "goGeneStatistic", choices = c("fisher"="fisher"), selected = "fisher")
342
                }
343
            })
344
345
        geneOntology <- reactive({
346
347
            if(input$runRNAGO && input$miRNAorGene == 1){  
348
                        mir = input$showResults
349
                        predictions = getPredictedTargets(mir, species = 'hsa', method = 'geom', min_src = 2)
350
                        rankedGenes = predictions[,'rank_product']
351
                        selection = function(x) TRUE 
352
                        allGO2genes = annFUN.org(whichOnto=input$ontology, feasibleGenes = NULL, mapping="org.Hs.eg.db", ID = "entrez")
353
                        GOdata =  new('topGOdata', ontology = input$ontology, allGenes = rankedGenes, 
354
                                                annot = annFUN.GO2genes, GO2genes = allGO2genes, 
355
                                                geneSel = selection, nodeSize=10)
356
                        results = runTest(GOdata, algorithm = input$goAlgorithm, statistic = input$goStatistic)
357
                        allRes = GenTable(GOdata, statistic = results, orderBy = "statistic", topNodes = input$topRNAs)
358
                        allRes = allRes[,c('GO.ID','Term','statistic')]
359
                        colnames(allRes)[1] = "GO ID"
360
                        colnames(allRes)[3] = input$goStatistic
361
                        return(allRes)
362
363
364
              }
365
                if(input$runGeneGO && input$miRNAorGene == 2){  
366
                    data = dataM()
367
                    condition = as.factor(dataC()[,1])
368
                    design = model.matrix(~condition)
369
370
                    dge = DGEList(counts=as.matrix(data), group = condition)
371
                    dge = calcNormFactors(dge, method = input$normMeth) #webtool'da var. RLE dediği deseq, TMM dediği TMM, none dediği none
372
                    v = voom(dge,design, plot=F) 
373
                    fit = lmFit(v, design)
374
                    fit = eBayes(fit)
375
                    res = topTable(fit, coef=ncol(design), number = dim(data)[1])
376
                    geneList = res$adj.P.Val #voomNSC tarafından seçilen genler
377
                    names(geneList) = rownames(res) #voomNSC tarafından seçilen genler
378
                    biomarkers = selectedGenes #voomNSC tarafından seçilen genler
379
   
380
                    truefalse = function(allScore) {  
381
                      truefalse = is.element(names(geneList), biomarkers)
382
                      return(truefalse)
383
                    }
384
385
                    allGO2genes = annFUN.org(whichOnto=input$ontologyGene, feasibleGenes = NULL,
386
                                             mapping="org.Hs.eg.db", ID = "symbol")
387
388
                    GOdata =  new('topGOdata', ontology = input$ontologyGene, allGenes = geneList, 
389
                                  annot = annFUN.GO2genes, GO2genes = allGO2genes, 
390
                                  geneSel = truefalse, nodeSize=10)
391
392
                    results = runTest(GOdata, algorithm = input$goGeneAlgorithm, statistic = input$goGeneStatistic)
393
394
                    allRes = GenTable(GOdata, statistic = results, orderBy = "statistic", topNodes = input$topGenes)
395
                    allRes = allRes[,c('GO.ID','Term','statistic')]
396
                    colnames(allRes)[1] = "GO ID"
397
                    colnames(allRes)[3] = input$goGeneStatistic
398
                    return(allRes)
399
400
              }
401
                else{
402
                    return(allRes = NULL)
403
                }
404
            
405
        })
406
407
408
409
        geneOntologyPlot <- reactive({
410
411
            if(input$runVoomDDA){
412
                if(input$miRNAorGene == 1){  
413
                        mir = input$showResults
414
                        predictions = getPredictedTargets(mir, species = 'hsa', method = 'geom', min_src = 2)
415
                        rankedGenes = predictions[,'rank_product']
416
                        selection = function(x) TRUE 
417
                        allGO2genes = annFUN.org(whichOnto=input$ontology, feasibleGenes = NULL, mapping="org.Hs.eg.db", ID = "entrez")
418
                        GOdata =  new('topGOdata', ontology = input$ontology, allGenes = rankedGenes, 
419
                                                annot = annFUN.GO2genes, GO2genes = allGO2genes, 
420
                                                geneSel = selection, nodeSize=10)
421
                        results = runTest(GOdata, algorithm = input$goAlgorithm, statistic = input$goStatistic)
422
                        showSigOfNodes(GOdata, score(results), firstSigNodes = 5, useInfo = 'all')
423
                       
424
425
426
              }
427
                if(input$miRNAorGene == 2){  
428
                    data = dataM()
429
                    condition = as.factor(dataC()[,1])
430
                    design = model.matrix(~condition)
431
432
                    dge = DGEList(counts=as.matrix(data), group = condition)
433
                    dge = calcNormFactors(dge, method = input$normMeth) #webtool'da var. RLE dediği deseq, TMM dediği TMM, none dediği none
434
                    v = voom(dge,design, plot=F) 
435
                    fit = lmFit(v, design)
436
                    fit = eBayes(fit)
437
                    res = topTable(fit, coef=ncol(design), number = dim(data)[1])
438
                    geneList = res$adj.P.Val #voomNSC tarafından seçilen genler
439
                    names(geneList) = rownames(res) #voomNSC tarafından seçilen genler
440
                    biomarkers = selectedGenes #voomNSC tarafından seçilen genler
441
   
442
                    truefalse = function(allScore) {  
443
                      truefalse = is.element(names(geneList), biomarkers)
444
                      return(truefalse)
445
                    }
446
447
                    allGO2genes = annFUN.org(whichOnto=input$ontologyGene, feasibleGenes = NULL,
448
                                             mapping="org.Hs.eg.db", ID = "symbol")
449
450
                    GOdata =  new('topGOdata', ontology = input$ontologyGene, allGenes = geneList, 
451
                                  annot = annFUN.GO2genes, GO2genes = allGO2genes, 
452
                                  geneSel = truefalse, nodeSize=10)
453
454
                    results = runTest(GOdata, algorithm = input$goGeneAlgorithm, statistic = input$goGeneStatistic)
455
                    showSigOfNodes(GOdata, score(results), firstSigNodes = 5, useInfo = 'all')
456
457
              }
458
459
          }
460
            
461
        })
462
463
464
        output$geneOntologyTable <- DT::renderDataTable({
465
466
            if(input$runRNAGO || input$runGeneGO){
467
468
469
                  datatable(geneOntology(), extensions = c('Buttons','KeyTable', 'Responsive'), options = list(
470
                  dom = 'Bfrtip',
471
                  buttons = c('copy', 'csv', 'excel', 'pdf', 'print'), keys = FALSE, pageLength = 20
472
                  ))
473
474
475
            }else{return(NULL)}
476
477
        }) 
478
479
        #output$geneOntologyPlot <- renderPlot({
480
481
        #if(input$includePlot){
482
        #    geneOntologyPlot()         
483
        #       
484
        #   }
485
        #})
486
487
488
        output$downloadGoPlot <- downloadHandler(
489
    
490
            filename <- function() { paste('GOplot.pdf') },
491
            content <- function(file) {
492
                pdf(file)
493
                if(input$runVoomDDA == 0){stop('First, run voomDDA')}
494
                else{
495
                    geneOntologyPlot()
496
            }
497
                dev.off()
498
            },
499
            contentType = 'application/pdf'
500
        )
501
        
502
        }   
503
    })
504
505
})
506
507
508
509
510