Upgrade to new Gitlab Version 13.9 on Saturday 19th April 20:00. Expect an interruption of about 30 to 60 minutes

tabClBay.R 10.2 KB
Newer Older
dmattek's avatar
dmattek 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
# RShiny module for performing Bayesian  clustering using bclust
# Use:
# in ui.R
# tabPanel(
#  'Hierarchical',
#  clustBayUI('TabClustBay'))
#
# in server.R
# callModule(clustBay, 'TabClustBay', dataMod)
# where dataMod is the output from a reactive function that returns dataset ready for clustering


require(gplots) # heatmap.2
require(dendextend) # color_branches
require(RColorBrewer) # brewer.pal
require(d3heatmap) # interactive heatmap
require(bclust) # Bayesian clustering


l.col.pal = list(
  "Spectral" = 'Spectral',
  "White-Orange-Red" = 'OrRd',
  "Yellow-Orange-Red" = 'YlOrRd',
  "Reds" = "Reds",
  "Oranges" = "Oranges",
  "Greens" = "Greens",
  "Blues" = "Blues"
)

# UI
clustBayUI <- function(id, label = "Sparse Hierarchical CLustering") {
  ns <- NS(id)
  
  tagList(
    h4(
      "Bayesian clustering using ",
      a("bclust", href = "https://cran.r-project.org/web/packages/bclust/index.html")
    ),
    p('The algorithm does not deal with missing values. Use conversion to zeroes in the right panel.'),
    p(
      'Column labels in the heat-map are additionally labeled according to their Bayes weight (\"importance\"):'
    ),
    tags$ol(
      tags$li("Blue with \"-\" - variable not likely to participate in optimal clustering (negative weight)"),
      tags$li("Black - low importance (weight factor in 1st quartile)"),
      tags$li("Green with \"*\" - medium importance (weight factor in 2nd quartile)"),
      tags$li("Orange with \"**\" - high importance (weight factor in 3rd quartile)"),
      tags$li("Red with \"***\" - very high importance (weight factor in 4th quartile)")
    ),
    
    br(),
    fluidRow(
      column(6,
             selectInput(
               ns("selectPlotBayHmPalette"),
               label = "Select colour palette:",
               choices = l.col.pal,
               selected = 'Spctral'
             ),
             checkboxInput(ns('inPlotBayHmRevPalette'), 'Reverse colour palette', TRUE),
             checkboxInput(ns('selectPlotBayDend'),
                           'Plot dendrogram and re-order samples', TRUE),
             checkboxInput(ns('selectPlotBayKey'), 'Plot colour key', TRUE)
             
      ),
      column(6,
             uiOutput(ns('inPlotBayHmNclustSlider')),
             sliderInput(
               ns('inPlotBayHmGridColor'),
               'Shade of grey for grid lines (0 - black, 1 - white)',
               min = 0,
               max = 1,
               value = 0.6,
               step = .1,
               ticks = TRUE
             )
      )
    ),
    
    fluidRow(
      column(
        2,
        numericInput(
          ns('inPlotBayHmMarginX'),
          'Margin below x-axis',
          10,
          min = 1,
          width = 100
        )
      ),
      column(
        2,
        numericInput(
          ns('inPlotBayHmMarginY'),
          'Margin right of y-axis',
          10,
          min = 1,
          width = 100
        )
      ),
      column(
        2,
        numericInput(
          ns('inPlotBayHmFontX'),
          'Font size row labels',
          1,
          min = 0,
          width = 100,
          step = 0.1
        )
      ),
      column(
        2,
        numericInput(
          ns('inPlotBayHmFontY'),
          'Font size column labels',
          1,
          min = 0,
          width = 100,
          step = 0.1
        )
      ),
      column(2,
             numericInput(
               ns('inPlotHeight'),
               'Display plot height',
               value = 1000,
               min = 100,
               step = 100
             )
      )
    ),
    br(),
    
    downPlotUI(ns('downPlotBayHM')),
    
    
    br(),
    checkboxInput(ns('inPlotBayInteractive'), 'Interactive Plot?',  value = FALSE),
    uiOutput(ns("plotBayInt_ui"))
    
  )
}

# SERVER
clustBay <- function(input, output, session, dataMod) {
  userFitBclus <- reactive({
    cat(file = stderr(), 'userFitBclus \n')
    
    loc.dm = dataMod()
    if (is.null(loc.dm))
      return(NULL)
    

    bclust(loc.dm, transformed.par = c(0, -50, log(16), 0, 0, 0))
  })
  
  userDendBclus <- reactive({
    cat(file = stderr(), 'userDendBclus \n')
    
    d.bclus = userFitBclus()
    if (is.null(d.bclus))
      return(NULL)
    
    dend <- as.dendrogram(d.bclus)
    #    dend <- color_branches(dend, k = d.bclus$optim.clustno)
    dend <- color_branches(dend, k = input$inPlotBayHmNclust)
    #    browser()
  })
  
  userVarImpBclus <- reactive({
    cat(file = stderr(), 'userVarImpBclus \n')
    
    d.bclus = userFitBclus()
    if (is.null(d.bclus))
      return(NULL)
    
    return(imp(d.bclus)$var)
  })
  
  
  output$inPlotBayHmNclustSlider = renderUI({
    ns <- session$ns
    
    loc.dm = dataMod()
    if (is.null(loc.dm))
      return(NULL)
    
    loc.d.bclus = userFitBclus()
    if (is.null(loc.d.bclus))
      return(NULL)
    
    sliderInput(
      ns('inPlotBayHmNclust'),
      '#clusters to colour (default: optimal # from bclust)',
      min = 1,
      max = nrow(loc.dm),
      value = loc.d.bclus$optim.clustno,
      step = 1,
      ticks = TRUE,
      round = TRUE
    )
  })
  
  
  plotBayHm <- function() {
    cat(file = stderr(), 'plotBayHm \n')
    
    loc.dm = dataMod()
    if (is.null(loc.dm))
      return(NULL)
    
    loc.dend = userDendBclus()
    if (is.null(loc.dend))
      return(NULL)
    
    loc.var.imp = imp(userFitBclus())$var
    if (is.null(loc.var.imp))
      return(NULL)
    
    col_labels <- get_leaves_branches_col(loc.dend)
    col_labels <- col_labels[order(order.dendrogram(loc.dend))]
    
    if (input$inPlotBayHmRevPalette)
      my_palette <-
      rev(colorRampPalette(brewer.pal(9, input$selectPlotBayHmPalette))(n = 99))
    else
      my_palette <-
      colorRampPalette(brewer.pal(9, input$selectPlotBayHmPalette))(n = 99)
    
    if (input$selectPlotBayDend) {
      assign("var.tmp.1", loc.dend)
      var.tmp.2 = "row"
    } else {
      assign("var.tmp.1", FALSE)
      var.tmp.2 = "none"
    }
    
    loc.colnames = paste0(ifelse(loc.var.imp < 0, "- ",
                                 ifelse(
                                   loc.var.imp < quantile(loc.var.imp, 0.25), "",
                                   ifelse(loc.var.imp < quantile(loc.var.imp, 0.5), "* ", 
                                          ifelse(loc.var.imp < quantile(loc.var.imp, 0.75), "** ", "*** "))
                                 )), colnames(loc.dm))
    
    loc.colcol   = ifelse(loc.var.imp < 0, "blue",
                          ifelse(
                            loc.var.imp < quantile(loc.var.imp, 0.25), "black",
                            ifelse(loc.var.imp < quantile(loc.var.imp, 0.5), "green", 
                                   ifelse(loc.var.imp < quantile(loc.var.imp, 0.75), "orange", "red"))
                          ))
    
    
    heatmap.2(
      loc.dm,
      Colv = "NA",
      Rowv = var.tmp.1,
      srtCol = 90,
      dendrogram = var.tmp.2,
      trace = "none",
      key = input$selectPlotBayKey,
      margins = c(input$inPlotBayHmMarginX, input$inPlotBayHmMarginY),
      col = my_palette,
      na.col = grey(input$inPlotBayHmNAcolor),
      denscol = "black",
      density.info = "density",
      RowSideColors = col_labels,
      colRow = col_labels,
      colCol = loc.colcol,
      labCol = loc.colnames,
      sepcolor = grey(input$inPlotBayHmGridColor),
      colsep = 1:ncol(loc.dm),
      rowsep = 1:nrow(loc.dm),
      cexRow = input$inPlotBayHmFontX,
      cexCol = input$inPlotBayHmFontY,
      main = "Bayesian Clustering (bclust)"
    )
  }
  
  plotBayImp <- function() {
    cat(file = stderr(), 'plotBayImp \n')
    
    loc.dm = dataMod()
    if (is.null(loc.dm))
      return(NULL)
    
    loc.d.bclus = userFitBclus()
    if (is.null(loc.d.bclus))
      return(NULL)
    
    #cat(imp(loc.d.bclus)$var)
    
    viplot(
      imp(loc.d.bclus)$var,
      xlab = colnames(loc.dm),
      xlab.srt = 90,
      xlab.mar = input$inPlotBayHmMarginX,
      xlab.cex = input$inPlotBayHmFontY,
      main = '\nVariable importance\n'
    )
  }
  
  
  
  output$outPlotBayHm <- renderPlot({
    plotBayHm()
  })
  
  output$plotBayInt <- renderD3heatmap({
    cat(file = stderr(), 'plotBayInt \n')
    
    loc.dm = dataMod()
    if (is.null(loc.dm))
      return(NULL)
    
    loc.dend = userDendBclus()
    if (is.null(loc.dend))
      return(NULL)
    
    loc.var.imp = imp(userFitBclus())$var
    if (is.null(loc.var.imp))
      return(NULL)
    
    col_labels <- get_leaves_branches_col(loc.dend)
    col_labels <- col_labels[order(order.dendrogram(loc.dend))]
    
    if (input$inPlotBayHmRevPalette)
      my_palette <-
      rev(colorRampPalette(brewer.pal(9, input$selectPlotBayHmPalette))(n = 99))
    else
      my_palette <-
      colorRampPalette(brewer.pal(9, input$selectPlotBayHmPalette))(n = 99)
    
    if (input$selectPlotBayDend) {
      assign("var.tmp.1", loc.dend)
      var.tmp.2 = "row"
    } else {
      assign("var.tmp.1", FALSE)
      var.tmp.2 = "none"
    }
    
    loc.colnames = paste0(ifelse(loc.var.imp < 0, "- ",
                                 ifelse(
                                   loc.var.imp < quantile(loc.var.imp, 0.25), "",
                                   ifelse(loc.var.imp < quantile(loc.var.imp, 0.5), "* ", 
                                          ifelse(loc.var.imp < quantile(loc.var.imp, 0.75), "** ", "*** "))
                                 )), colnames(loc.dm))
    
    d3heatmap(
      loc.dm,
      Rowv = var.tmp.1,
      dendrogram = var.tmp.2,
      trace = "none",
      revC = FALSE,
      margins = c(input$inPlotBayHmMarginX, input$inPlotBayHmMarginY),
      colors = my_palette,
      na.col = grey(input$inPlotBayNAcolor),
      cexRow = input$inPlotBayHmFontY,
      cexCol = input$inPlotBayHmFontX,
      xaxis_height = input$inPlotBayHmMarginX,
      yaxis_width = input$inPlotBayHmMarginY,
      show_grid = TRUE,
      labRow = rownames(loc.dm),
      labCol = loc.colnames
    )
  })
  
  output$plotBayInt_ui <- renderUI({
    ns <- session$ns
    
    if (input$inPlotBayInteractive)
      d3heatmapOutput(ns("plotBayInt"), height = paste0(input$inPlotHeight, "px"))
    else {
      plotOutput(ns('outPlotBayHm'), height = paste0(input$inPlotHeight, "px"))
    }
  })
  
  callModule(downPlot, "downPlotBayHM", 'clust_bayesian_dend.pdf', plotBayHm)
  
}