server.R 35.1 KB
Newer Older
Dhanaprakash Jambulingam's avatar
Dhanaprakash Jambulingam committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
## Required libraries ##

library(shiny)
library(shinyBS)
library(plyr)
library(RColorBrewer)
library(readR)
library(medseqr)
library(heatmapGen2)
library(genefilter)
library(DT)
library(PAMhm)
library(coreheat)
library(digest)
options(shiny.maxRequestSize = 40 * 1024 ^ 2)#increase maximum upload size for fileInput() to 40 MB
#library(shinysky)


## Shiny server logic ##

shinyServer(function(input, output, session) {
  message("\n@@ Starting...\n")
  
  shinyjs::hide('doBiomart')
  shinyjs::hide('imgSize')
  shinyjs::hide('chooseSelType')
  shinyjs::hide('geneSelUI')
  shinyjs::hide('nSurrGenes')
  shinyjs::hide('addRect4genes')
  shinyjs::hide('addStars')
  shinyjs::hide('nvarUI')
  shinyjs::hide('textSize')
  shinyjs::hide('toggleAdv')
  shinyjs::hide('plotTitle')
  shinyjs::hide('sortPlotData')
  shinyjs::hide('toPlot')
  shinyjs::hide('toggleBMset')
  
  raw.data <- reactiveValues()
  plot.data <- reactiveValues()
  plot.data2 <- reactiveValues()
  plot.data3 <- reactiveValues()
  plot.data4 <- reactiveValues()
  adjPlot.data <- reactiveValues()
  cormat0.data <- reactiveValues()
  cormat1.data <- reactiveValues()
  cormat.data <- reactiveValues()
  filt.values.hash <- reactiveValues()
  dat.object.hash <- reactiveValues()
  hideall <- reactiveValues(v = FALSE)
  
  output$idColSelect <- renderUI({
    if (is.null(input$uploadData))
      return()
    ext <- sub(".+(\\.[a-z]{3,4}$)", "\\1", input$uploadData$name)
    if (!file.exists(paste(input$uploadData$datapath, ext, sep = ""))) {
      file.rename(input$uploadData$datapath,
                  paste(input$uploadData$datapath, ext, sep = ""))
    }
    cat("Reading raw data...\n")
    ds <-
      read.to.list(file.path(dirname(input$uploadData$datapath), dir(dirname(
        input$uploadData$datapath
      ))), stringsAsFactors = FALSE)
    ds <- ds[[1]]
    raw.data[["ds"]] <- ds
    id.choices <- c("<row names>", colnames(ds))
    cat("done\n")
    output$nvarUI <- renderUI({
      if (is.null(input$uploadData))
        return()
      if (is.null(input$IDcolName))
        return(NULL)
      if (is.null(input$columnSel))
        return(NULL)
      #									if (input$chooseSelType=="By gene symbol (using pre-selected number of genes)") return(NULL)
      cat("Creating gene # slider...\n")
      sliderInput('nvar',
                  "Number of Genes With Highest Variance",
                  50,
                  nrow(ds),
                  100,
                  50)
    })
    
    tags$html(
      tags$hr(),
      selectInput(
        'IDcolName',
        tags$label("Name of ID column", style = "font-size: 14px;"),
        id.choices,
        id.choices[2],
        FALSE
      )
    )
  })
  
  output$columnSelect <- renderUI({
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return()
    ds <- reactiveValuesToList(raw.data)[[1]]
    cat("Generating column selectizer...")
    if (input$IDcolName == "<row names>") {
      cat("<row names>\n")
      dat.cols <- c(1:ncol(ds))
    } else {
      cat("<ID column>\n")
      id.col <- which(colnames(ds) %in% input$IDcolName)
      dat.cols <- c(1:ncol(ds))[-id.col]
    }
    cat("done\n")
    shinyjs::show('doBiomart')
    shinyjs::show('toggleBMset')
    updateButton(session,
                 'sortPlotData',
                 "Sort Plot Data",
                 value = FALSE,
                 style = "info")
    selectizeInput(
      'columnSel',
      label = tags$label("Available Data Columns", style = "font-size: 14px;"),
      choices = names(ds)[dat.cols],
      selected = names(ds)[dat.cols],
      multiple = TRUE
    )
  })
  
  output$inputDT <- renderUI({
    if (is.null(input$uploadData))
      return(NULL)
    if (is.null(input$IDcolName))
      return(NULL)
    if (is.null(input$columnSel))
      return(NULL)
    ds <- reactiveValuesToList(raw.data)[[1]]
    selCols <- which(colnames(ds) %in% input$columnSel)
    if (input$IDcolName == "<row names>" &&
        ncol(ds[selCols]) > length(selCols))
      return(NULL)
    cat("Generating upload overview...\n")
    if (nrow(ds) > 12000) {
      createAlert(
        session,
        anchorId = 'alert_anchor1',
        alertId = "upload_nrow_alert",
        title = "NOTE!",
        content = paste(
          "The data set is very large (",
          nrow(ds),
          " rows). Processing may be slow!",
          sep = ""
        ),
        style = "info",
        append = FALSE
      )
    } else {
      closeAlert(session, 'upload_nrow_alert')
    }
    cat(" (Generating Plot Data...")
    if (input$IDcolName == "<row names>") {
      ds <- data.frame(ds[selCols], stringsAsFactors = FALSE)
    } else {
      id.col <- which(colnames(ds) %in% input$IDcolName)
      ds <-
        as.data.frame(ds[, c(id.col, selCols)], stringsAsFactors = FALSE)
    }
    cat("done)\n")
    if (length(selCols) < 2) {
      createAlert(
        session,
        anchorId = 'alert_anchor1',
        alertId = "hm_ncol_alert",
        title = "Warning!",
        content = "At least 2 data columns are needed for a heatmap! No plot data are generated.",
        style = "warning",
        append = FALSE
      )
    }
    else {
      closeAlert(session, 'hm_ncol_alert')
    }
    plot.data[["ds"]] <- ds
    cat(" Rendering input data...")
    closeAlert(session, 'upload_nrow_alert')
    shiny::withProgress({
      output$uploadTable <-
        DT::renderDataTable(ds, options = list(pageLength = 20))
    }, message = "Rendering data table...", detail = "(Input data)", value =
      0.5)
    shinyjs::show('doBiomart')
    cat("done\n")
    dataTabStyle <-
      "max-height: 1024px; max-width: 99%; border-bottom-left-radius: 1.9%; font-size: 90%; "
    tags$div(DT::dataTableOutput('uploadTable'), style = dataTabStyle)
  })
  
  observeEvent(input$doBiomart, {
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return(NULL)
    ds <- reactiveValuesToList(raw.data)
    if (length(ds) == 0)
      return()
    ds <- isolate(ds[[1]])
    cat("Annotating data...\n ")
    createAlert(
      session,
      anchorId = 'alert_anchor1',
      alertId = "biomart_query_alert1",
      title = "NOTE!",
      content = paste(
        "Querying biomart for HGNC Gene Symbols. Depending on your network bandwidth and server workload processing may be slow!\n",
        "You will be automatically redirected to the 'Plot Data' tab.",
        sep = ""
      ),
      style = "info",
      append = FALSE
    )
    createAlert(
      session,
      anchorId = 'alert_anchor2',
      alertId = "biomart_query_alert2",
      title = "NOTE!",
      content = paste(
        "Querying biomart for HGNC Gene Symbols. Depending on your network bandwidth and server workload processing may be slow!",
        sep = ""
      ),
      style = "info",
      append = FALSE
    )
    if (input$IDcolName == "<row names>") {
      id.col <- "row.names"
      hgnc.col <- "ID"
    } else {
      id.col <- hgnc.col <- input$IDcolName
    }
    shiny::withProgress({
      ds <-
        try(convert.bm(
          ds,
          id.col,
          host = input$biomHost,
          biom.filter = input$biomFilt,
          biom.attributes = c("ensembl_gene_id", "hgnc_symbol"),
          rm.dups = FALSE
        ))
    }, message = "Getting information from Biomart...", detail = "This may take a short while...", value =
      0.5)
    if (is(ds, "try-error")) {
      aaid <- switch(
        input$mainNavbarPage,
        "Data Table" = 'alert_anchor1',
        "Plot Data" = 'alert_anchor2',
        "Correlation Heatmap" = 'alert_anchor3'
      )
      aid <- switch(
        input$mainNavbarPage,
        "Data Table" = "bm_fail1",
        "Plot Data" = "bm_fail2",
        "Correlation Heatmap" = "bm_fail3"
      )
      createAlert(
        session,
        anchorId = aaid,
        alertId = aid,
        title = "Warning!",
        content = "The biomart query failed!!'.",
        style = "warning",
        append = FALSE
      )
      return(NULL)
    }
    closeAlert(session, 'biomart_query_alert1')
    closeAlert(session, 'biomart_query_alert2')
    rownames(ds) <- make.unique(ds[, "ensembl_gene_id"])
    ds <- ds[,-which(colnames(ds) %in% "ensembl_gene_id")]
    colnames(ds)[which(colnames(ds) == "hgnc_symbol")] <- hgnc.col
    cat("done\n")
    if (input$mainNavbarPage == "Data Table") {
      updateNavbarPage(session, "mainNavbarPage", "Plot Data")
    }
    #						shinyjs::hide('doBiomart')
    #						shinyjs::hide('toggleBMset')
    #						shinyjs::hide('biomHost')
    #						shinyjs::hide('biomFilt')
    cat("updatting button\n")
    updateButton(session,
                 'sortPlotData',
                 "Unsort Plot Data",
                 style = "success",
                 value = TRUE)
    updateCheckboxInput(session, 'addRect4genes', value = FALSE)
    plot.data[["ds"]] <- ds
  })
  
  observe({
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return(NULL)
    if (is.null(input$columnSel))
      return(NULL)
    ds <- reactiveValuesToList(plot.data)
    if (length(ds) == 0)
      return()
    cat("Plot data filtering...")
    ds <- isolate(ds[["ds"]])
    selCols <- which(colnames(ds) %in% input$columnSel)
    if (input$IDcolName == "<row names>") {
      cat("using <row names>...")
      if ("ID" %in% colnames(ds)) {
        cat("and ID column...")
        id.col <- which(colnames(ds) %in% "ID")
        ds <-
          as.data.frame(ds[, c(id.col, selCols)], stringsAsFactors = FALSE)
      } else {
        ds <- data.frame(ds[selCols], stringsAsFactors = FALSE)
      }
    } else {
      id.col <- which(colnames(ds) %in% input$IDcolName)
      ds <-
        as.data.frame(ds[, c(id.col, selCols)], stringsAsFactors = FALSE)
    }
    nvar <- input$nvar
    if (is.null(nvar)) {
      nvar <- 100
    }
    if ((input$IDcolName != "<row names>" &&
         ncol(ds) < 3) || (input$IDcolName == "<row names>" &&
                           ncol(ds) < 2)) {
      d <- ds[, ncol(ds)]
      z <-
        try((d - median(d, na.rm = TRUE)) / (mad(d - median(d, na.rm = TRUE))), silent =
              TRUE)
      if (is(z, "try-error"))
        return(NULL)
      select <-
        order(abs(z), decreasing = TRUE)[seq_len(min(nvar, length(z)))]
    } else {
      if (input$IDcolName == "<row names>") {
        if ("ID" %in% colnames(ds)) {
          Pvars <- try(genefilter::rowVars(ds[, 2:ncol(ds)]), silent = TRUE)
          if (is(Pvars, "try-error"))
            return(NULL)
        } else {
          Pvars <- try(genefilter::rowVars(ds[, 1:ncol(ds)]), silent = TRUE)
          if (is(Pvars, "try-error"))
            return(NULL)
        }
      } else {
        Pvars <- try(genefilter::rowVars(ds[, 2:ncol(ds)]), silent = TRUE)
        if (is(Pvars, "try-error"))
          return(NULL)
      }
      select <-
        order(Pvars, decreasing = TRUE)[seq_len(min(nvar, length(Pvars)))]
    }
    ds.filt <- ds[select, , drop = FALSE]
    plot.data2[["ds2"]] <- ds.filt
    cat("done\n")
  })
  
  observeEvent(input$toPlot, {
    updateNavbarPage(session, "mainNavbarPage", "Correlation Heatmap")
  })
  
  output$geneSelUI <- renderUI({
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return()
    if (input$chooseSelType == "By number of genes")
      return()
    ds <- reactiveValuesToList(plot.data2)
    if (length(ds) == 0)
      return()
    ds.filt <- isolate(ds[["ds2"]])
    if (input$IDcolName == "<row names>") {
      if ("ID" %in% colnames(ds.filt)) {
        choices <- ds.filt$ID
      } else {
        choices <- rownames(ds.filt)
      }
    } else {
      choices <- ds.filt[[input$IDcolName]]
    }
    sel <- sort(choices[!choices %in% ""])[1]
    selectInput(
      'geneSel',
      "Select gene to display",
      choices = sort(choices),
      selected = sel,
      TRUE
    )
  })
  
  observe({
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return()
    ds <- reactiveValuesToList(plot.data2)
    if (length(ds) == 0)
      return()
    ds.filt <- ds[["ds2"]]
    if (input$chooseSelType == "By number of genes") {
      cat("  Filtering by number of genes...\n")
      updateCheckboxInput(session, 'addRect4genes', value = FALSE)
      select <- 1:nrow(ds.filt)
    } else if (input$chooseSelType == "By gene symbol (using pre-selected number of genes)") {
      cat("  Filtering by gene symbol...\n")
      syms <- input$geneSel
      if (input$IDcolName == "<row names>") {
        if ("ID" %in% colnames(ds.filt)) {
          dat <- as.matrix(ds.filt[,-which(colnames(ds.filt) %in% "ID")])
          lab <- ds.filt["ID"]
        } else {
          dat <- as.matrix(ds.filt)
          lab <-
            data.frame(ID = rownames(ds.filt),
                       stringsAsFactors = FALSE)
          rownames(lab) <- rownames(ds.filt)
        }
      } else {
        dat <-
          as.matrix(ds.filt[,-which(colnames(ds.filt) %in% input$IDcolName)])
        lab <- ds.filt[input$IDcolName]
      }
      # Create a Progress object
      progress <- shiny::Progress$new()
      progress$set(message = "Generating correlation matrix for filtering...", value = 0)
      # Close the progress when this reactive exits (even if there's an error)
      on.exit(progress$close())
      updateProgress <- function(value = NULL,
                                 detail = NULL) {
        if (is.null(value)) {
          value <- progress$getValue()
          value <- value + (progress$getMax() - value) / 5
        }
        progress$set(value = value, detail = detail)
      }
      cat("    Calling 'cormap2' for gene selection...\n")
      cm0 <- isolate(reactiveValuesToList(cormat0.data))
      if (length(cm0) != 0) {
        cat("  Existing correlation values...\n")
        cm0 <- cm0[[1]]
        if (nrow(dat) != nrow(cm0)) {
          cat("    Input data has changed. Recalculating correlation matrix...\n")
          if (nrow(dat) > 8000) {
            createAlert(
              session,
              anchorId = 'alert_anchor2',
              alertId = "cormat_nrow_alert",
              title = "WARNING!",
              content = paste(
                "Calculating correlation map for",
                nrow(dat),
                "genes. Processing may be slow!"
              ),
              style = "warning",
              append = FALSE
            )
          }
          cormat <-
            cormap2(
              dat,
              biomart = FALSE,
              doPlot = FALSE,
              updateProgress = updateProgress
            )
          cormat0.data[["cm0"]] <- cormat
        } else {
          cat("   Using existing matrix...\n")
          cormat <- cm0
        }
      } else {
        cat("    Calculating correlation matrix for the first time...\n")
        if (nrow(dat) > 8000) {
          createAlert(
            session,
            anchorId = 'alert_anchor2',
            alertId = "cormat_nrow_alert",
            title = "WARNING!",
            content = paste(
              "Calculating correlation map for",
              nrow(dat),
              "genes. Processing may be slow!"
            ),
            style = "warning",
            append = FALSE
          )
        }
        cormat <-
          cormap2(
            dat,
            biomart = FALSE,
            doPlot = FALSE,
            updateProgress = updateProgress
          )
        cormat0.data[["cm0"]] <- cormat
      }
      closeAlert(session, 'cormat_nrow_alert')
      cat("  Starting ID selection...\n")
      cormat <- cormat[nrow(cormat):1,]
      rn <- rownames(cormat)
      symSel <- plyr::llply(syms, function(x) {
        id <- rownames(lab)[lab[, 1] %in% x]
        plyr::llply(id, function(y) {
          rns <- which(rn %in% y)
          if (length(syms) > 2 && input$nSurrGenes == 0) {
            rns
          } else {
            if (rns < input$nSurrGenes) {
              rns1 <- 1:(rns - 1)
            } else {
              rns1 <- (rns - input$nSurrGenes):(rns - 1)
            }
            if (rns > (length(rn) - input$nSurrGenes)) {
              rns2 <- (rns + 1):length(rn)
            } else {
              rns2 <- (rns + 1):(rns + input$nSurrGenes)
            }
            c(rns1, rns, rns2)
          }
        })
      })
      symSel <- unique(unlist(symSel))
      select <- which(rownames(ds.filt) %in% rn[symSel])
    }
    cat("   Setting filtered plot data...\n")
    plot.data3[["ds3"]] <- ds.filt[select, , drop = FALSE]
  })
  
  observe({
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return(NULL)
    ds <- reactiveValuesToList(plot.data3)
    if (length(ds) == 0)
      return()
    cat("  Triggering sorting...\n")
    ds.filt <- isolate(ds[["ds3"]])
    if (input$sortPlotData) {
      cat("    Sorting...\n")
      plot.data4[["ds4"]] <-
        ds.filt[order(rownames(ds.filt)), , drop = FALSE]
      updateButton(session, 'sortPlotData', "Unsort Plot Data", style =
                     "success")
    } else {
      cat("    Not sorting\n")
      plot.data4[["ds4"]] <- ds.filt
      updateButton(session, 'sortPlotData', "Sort Plot Data", style = "info")
    }
  })
  
  output$plotDT <- renderUI({
    shinyjs::hide('nvarUI')
    shinyjs::hide('geneSelUI')
    shinyjs::hide('nSurrGenes')
    shinyjs::hide('sortPlotData')
    shinyjs::hide('chooseSelType')
    shinyjs::hide('toPlot')
    if (is.null(input$uploadData))
      return()
    if (is.null(input$IDcolName))
      return(NULL)
    ds <- reactiveValuesToList(plot.data4)
    if (length(ds) == 0)
      return()
    ds.filt <- isolate(ds[["ds4"]])
    if (ncol(ds.filt) < 2)
      return(NULL)
    cat("Rendering plot data...")
    shinyjs::hide('noplotdata')
    if (input$IDcolName != "<row names>" && ncol(ds.filt) < 3) {
      createAlert(
        session,
        anchorId = 'alert_anchor2',
        alertId = "hm_ncol_alert2",
        title = "Warning!",
        content = "At least 2 data columns are needed for a heatmap!",
        style = "warning",
        append = FALSE
      )
    }
    else {
      closeAlert(session, 'hm_ncol_alert2')
    }
    shiny::withProgress({
      output$plotTable <-
        renderDataTable(ds.filt, options = list(pageLength = 20))
    }, message = "Rendering data table...", detail = "(Plot data)", value =
      0.5)
    shinyjs::show('nvarUI')
    shinyjs::show('geneSelUI')
    shinyjs::show('nSurrGenes')
    tabStyle <-
      "max-height: 1024px; max-width: 99%; border-bottom-left-radius: 1.9%; font-size: 90%; "
    cat("done\n\n")
    shinyjs::show('sortPlotData')
    shinyjs::show('chooseSelType')
    shinyjs::show('toPlot')
    tags$div(dataTableOutput('plotTable'), style = tabStyle)
  })
  
  
  
612
  observeEvent(input$showEx, {
Dhanaprakash Jambulingam's avatar
Dhanaprakash Jambulingam committed
613
614
615
    showModal(
      modalDialog(
        title = "Example expression file",
Dhanaprakash Jambulingam's avatar
Dhanaprakash Jambulingam committed
616
        "Formatted example datasets from the GEO database can be obatined from <https://gitlab.utu.fi/dhajam/biocpr/tree/master/Data>",
617
        easyClose = TRUE
Dhanaprakash Jambulingam's avatar
Dhanaprakash Jambulingam committed
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
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
889
890
891
892
893
894
895
896
897
898
899
900
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
      )
    )
  })
  
  
  
  observe({
    if (is.null(input$uploadData))
      return()
    if (input$mainNavbarPage != "Correlation Heatmap")
      return(NULL)
    ds <- reactiveValuesToList(plot.data4)
    if (length(ds) == 0)
      return()
    cat("Getting plot adjustments...\n")
    ds.filt <- isolate(ds[["ds4"]])
    if (input$IDcolName == "<row names>") {
      cat("  IDs in <row names>\n")
      cat("   using <row names>...\n")
      if ("ID" %in% colnames(ds.filt)) {
        cat("  ...and ID column...\n")
        dat <-
          as.matrix(ds.filt[,-which(colnames(ds.filt) %in% "ID"), drop = FALSE])
      } else {
        dat <- as.matrix(ds.filt)
      }
    } else {
      cat("  IDs in ID column\n")
      dat <-
        as.matrix(ds.filt[,-which(colnames(ds.filt) %in% input$IDcolName), drop =
                            FALSE])
    }
    if (ncol(dat) < 2) {
      cat("  break1\n\n")
      hideall[[1]] <- as.logical(TRUE)
      return(NULL)
    }
    if (nrow(dat) == 0) {
      cat("  break2\n\n")
      hideall[[1]] <- as.logical(TRUE)
      return(NULL)
    }
    adj.l <- plotAdjust(dat)
    cex <- round(adj.l$r.cex * 2.1, 1)
    lw <- adj.l$labelwidth * 8 ^ log10(cex)
    adjPlot.data[["pdf.w"]] <- adj.l$pdf.width
    adjPlot.data[["cex"]] <- cex
    adjPlot.data[["lw"]] <- lw
    cat("done\n")
    updateSliderInput(session, 'textSize', value = cex)
  })
  
  observeEvent(input$textSize, {
    if (input$mainNavbarPage != "Correlation Heatmap")
      return(NULL)
    cex <- isolate(reactiveValuesToList(adjPlot.data))[["cex"]]
    if (input$textSize == cex)
      return(NULL)
    cat("Adjusting plot width...\n")
    adj.l.lw <- isolate(reactiveValuesToList(adjPlot.data))[["lw"]]
    labelwidth <- (adj.l.lw) * 8 ^ log10(input$textSize)
    adjPlot.data[["lw2"]] <- labelwidth
  })
  
  output$main_plot_ui <- renderUI({
    shinyjs::hide('toggleAdv')
    shinyjs::hide('imgSize')
    shinyjs::hide('textSize')
    shinyjs::hide('plotTitle')
    shinyjs::hide('chooseSelType')
    shinyjs::hide('addStars')
    shinyjs::hide('addRect4genes')
    shinyjs::hide('downlButID')
    if (is.null(input$uploadData))
      return()
    ds <- reactiveValuesToList(plot.data4)
    if (length(ds) == 0)
      return()
    if (is.null(input$nvar))
      return()
    shinyjs::hide('nohmdata')
    cat("\nPlotting...\n")
    ds.filt <- isolate(ds[["ds4"]])
    if (input$IDcolName == "<row names>") {
      cat("using <row names>...\n")
      if ("ID" %in% colnames(ds.filt)) {
        cat("  ...and ID column...\n")
        dat <-
          as.matrix(ds.filt[,-which(colnames(ds.filt) %in% "ID"), drop = FALSE])
        lab <- ds.filt["ID"]
      } else {
        dat <- as.matrix(ds.filt)
        lab <-
          data.frame(ID = rownames(ds.filt), stringsAsFactors = FALSE)
        rownames(lab) <- rownames(ds.filt)
      }
    } else {
      dat <-
        as.matrix(ds.filt[,-which(colnames(ds.filt) %in% input$IDcolName), drop =
                            FALSE])
      lab <- ds.filt[input$IDcolName]
    }
    if (ncol(dat) < 2) {
      createAlert(
        session,
        anchorId = 'alert_anchor3',
        alertId = "hm_ncol_alert3",
        title = "Warning!",
        content = "At least 2 data columns are needed for a heatmap!",
        style = "warning",
        append = FALSE
      )
      return(NULL)
    } else {
      closeAlert(session, 'hm_ncol_alert3')
    }
    
    # dat hash
    cat("  Generating hash sum of dat object...")
    dat.hash <- isolate(reactiveValuesToList(dat.object.hash))
    dat.hash1 <- digest::sha1(dat)
    cat("done\n")
    if (length(dat.hash) == 0) {
      cat ("   No saved dat hash sum. Saving...\n")
      dat.object.hash[["dh1"]] <- dat.hash1
    } else {
      dat.hash <- isolate(dat.hash[[1]])
    }
    
    # Plot adjustments
    cat("  Loading plot adjustments...\n")
    if (length(reactiveValuesToList(adjPlot.data)[["lw2"]]) == 0) {
      cat("    Using standard adjustments...\n")
      labelwidth <-
        isolate(reactiveValuesToList(adjPlot.data))[["lw"]]
    } else {
      cat("    Using modified adjustments...\n")
      labelwidth <-
        isolate(reactiveValuesToList(adjPlot.data))[["lw2"]]
    }
    width <- height <- 1024 * input$imgSize / 100
    if (isolate(input$imgSize) == 100) {
      hmStyle <- "overflow-y: hidden; overflow-x: hidden; "
    } else {
      hmStyle <- "overflow: scroll; "
    }
    
    # Filters
    corThr <- input$corThr
    cutThr <- input$cutThr
    if (!input$doCorFilt) {
      corThr <- NULL
    }
    if (!input$doCutFilt) {
      cutThr <- NULL
    }
    cat("  Generating filters list...\n")
    filt.hash <- isolate(reactiveValuesToList(filt.values.hash))
    filt.l1 <- list(
      doClust = input$doClust,
      naFrac = input$naFrac,
      corThr = corThr,
      corMar = input$corMar,
      cutThr = cutThr,
      cut.size = input$cutSize
    )
    filt.hash1 <- digest::sha1(filt.l1)
    if (length(filt.hash) == 0) {
      cat ("   No saved filters. Saving...\n")
      filt.values.hash[["fvh"]] <- filt.hash1
    } else {
      filt.hash <- isolate(filt.hash[[1]])
    }
    cat("    Calling 'cormap2' for heatmap...\n     First without plotting...\n")
    # Create a Progress object
    progress0 <- shiny::Progress$new()
    progress0$set(message = "Generating heatmap...", value = 0)
    # Close the progress when this reactive exits (even if there's an error)
    on.exit(progress0$close())
    updateProgress <- function(value = NULL, detail = NULL) {
      if (is.null(value)) {
        value <- progress0$getValue()
        value <- value + (progress0$getMax() - value) / 5
      }
      progress0$set(value = value, detail = detail)
    }
    
    # Correlation matrix
    cm1 <- isolate(reactiveValuesToList(cormat1.data))
    if (length(cm1) != 0) {
      cat("  Existing plot correlation values...\n")
      cm1 <- cm1[[1]]
      if (dat.hash != dat.hash1 || filt.hash != filt.hash1) {
        if (dat.hash != dat.hash1) {
          cat("    Plot data has changed.\n")
        }
        if (filt.hash != filt.hash1) {
          cat("    Plot filters were modified.\n")
        }
        cat("     Recalculating plot data correlation matrix and saving changes...\n")
        if (nrow(dat) > 8000) {
          createAlert(
            session,
            anchorId = 'alert_anchor2',
            alertId = "cormat_nrow_alert",
            title = "WARNING!",
            content = paste(
              "Calculating correlation map for",
              nrow(dat),
              "genes. Processing may be slow!"
            ),
            style = "warning",
            append = FALSE
          )
        }
        cormat <-
          cormap2(
            dat,
            biomart = FALSE,
            cluster_correlations = filt.l1$doClust,
            minfrac = filt.l1$naFrac,
            cor.thr = filt.l1$corThr,
            cor.mar = filt.l1$corMar,
            cut.thr = filt.l1$cutThr,
            cut.size = filt.l1$cutSize,
            doPlot = FALSE,
            updateProgress = updateProgress
          )
        cormat1.data[["cm1"]] <- cormat
        dat.object.hash[["dh1"]] <- dat.hash1
        filt.values.hash[["fvh"]] <- filt.hash1
      } else {
        cat("   Using existing plot data correlation matrix...\n")
        cormat <- cm1
      }
    } else {
      cat("    Calculating plot data correlation matrix for the first time...\n")
      if (nrow(dat) > 8000) {
        createAlert(
          session,
          anchorId = 'alert_anchor2',
          alertId = "cormat_nrow_alert",
          title = "WARNING!",
          content = paste(
            "Calculating correlation map for",
            nrow(dat),
            "genes. Processing may be slow!"
          ),
          style = "warning",
          append = FALSE
        )
      }
      cormat <-
        cormap2(
          dat,
          biomart = FALSE,
          cluster_correlations = filt.l1$doClust,
          minfrac = filt.l1$naFrac,
          cor.thr = filt.l1$corThr,
          cor.mar = filt.l1$corMar,
          cut.thr = filt.l1$cutThr,
          cut.size = filt.l1$cutSize,
          doPlot = FALSE,
          updateProgress = updateProgress
        )
      cat("    Saving correlation matrix...")
      cormat1.data[["cm1"]] <- cormat
      cat("done\n")
    }
    closeAlert(session, 'cormat_nrow_alert')
    output$main_plot <- renderPlot({
      cat("  Starting plot...\n")
      # Create a Progress object
      progress <- shiny::Progress$new()
      progress$set(message = "Generating heatmap...", value = 0)
      # Close the progress when this reactive exits (even if there's an error)
      on.exit(progress$close())
      updateProgress <- function(value = NULL,
                                 detail = NULL) {
        if (is.null(value)) {
          value <- progress$getValue()
          value <- value + (progress$getMax() - value) / 5
        }
        progress$set(value = value, detail = detail)
      }
      cat("    Calling 'cormap2' for heatmap...\n     Now with plotting...\n")
      genes2highl <- NULL
      if (input$addRect4genes &&
          input$chooseSelType == "By gene symbol (using pre-selected number of genes)") {
        cat("   -> Highlighting genes:\n    ")
        genes2highl <- input$geneSel
        print(genes2highl)
      }
      cormat <- cormat[nrow(cormat):1,]
      cm <-
        cormap2(
          dat,
          cormat = cormat,
          lab = lab,
          biomart = FALSE,
          main = input$plotTitle,
          cluster_correlations = FALSE,
          cex = isolate(input$textSize),
          labelheight = labelwidth,
          labelwidth = labelwidth,
          add.sig = input$addStars,
          genes2highl = genes2highl,
          updateProgress = updateProgress
        )
      cat("  done\n\n")
      cormat.data[["cm"]] <- cm
      #									if (is(cm, "try-error")) return(NULL)
    }, width, height)
    shinyjs::show('toggleAdv')
    shinyjs::show('imgSize')
    shinyjs::show('textSize')
    shinyjs::show('plotTitle')
    shinyjs::show('chooseSelType')
    shinyjs::show('addStars')
    shinyjs::show('downlButID')
    if (isolate(input$chooseSelType) == "By gene symbol (using pre-selected number of genes)") {
      shinyjs::show('addRect4genes')
    } else if (isolate(input$chooseSelType) == "By number of genes") {
      shinyjs::hide('addRect4genes')
    }
    tags$div(style = hmStyle, plotOutput('main_plot', height = 1024))
  })
  
  output$cormatUI <- renderUI({
    if (is.null(input$uploadData))
      return()
    if (input$mainNavbarPage != "Correlation Matrix")
      return(NULL)
    cm <- isolate(reactiveValuesToList(cormat.data))
    if (length(cm) == 0)
      return()
    shinyjs::hide('nocmdata')
    cat("Rendering correlation matrix data table...\n")
    cm <- isolate(cm[["cm"]])
    tabStyle <-
      "max-height: 1024px; max-width: 99%; border-bottom-left-radius: 1.9%; font-size: 90%; overflow-x: scroll; "
    shiny::withProgress({
      output$cormatDT <-
        renderDataTable(
          format(
            round(cm, 2),
            width = 12,
            digits = 1,
            scientific = FALSE
          ),
          options = list(pageLength = 20)
        )
    }, message = "Rendering data table...", detail = "(Correlation matrix)", value =
      0.5)
    tags$div(dataTableOutput('cormatDT'), style = tabStyle)
  })
  
  output$downloadPlot <-
    downloadHandler(
      filename = "correlationHeatmap.pdf",
      content = function(file) {
        if (is.null(input$uploadData))
          return()
        if (input$mainNavbarPage != "Correlation Heatmap")
          return(NULL)
        ds <-
          reactiveValuesToList(plot.data4)
        if (length(ds) == 0)
          return()
        cat("DOWNLOADING PLOT\n")
        ds.filt <-
          isolate(ds[["ds4"]])
        if (input$IDcolName == "<row names>") {
          cat("  using <row names>...\n")
          if ("ID" %in% colnames(ds.filt)) {
            cat("  ...and ID column...\n")
            dat <-
              as.matrix(ds.filt[,-which(colnames(ds.filt) %in% "ID")])
          } else {
            dat <- as.matrix(ds.filt)
          }
        } else {
          dat <-
For faster browsing, not all history is shown. View entire blame