server.R 10.6 KB
Newer Older
dmattek's avatar
dmattek committed
1

2

dmattek's avatar
dmattek committed
3 4 5 6 7 8 9 10 11 12 13 14
# This is the server logic for a Shiny web application.
# You can find out more about building applications with Shiny here:
#
# http://shiny.rstudio.com
#

library(shiny)
library(shinyjs) #http://deanattali.com/shinyjs/
library(data.table)
library(ggplot2)
library(plotly)

15 16
# increase file upload limit
options(shiny.maxRequestSize = 30 * 1024 ^ 2)
dmattek's avatar
dmattek committed
17 18
source('auxfunc.R')

dmattek's avatar
dmattek committed
19
shinyServer(function(input, output, session) {
20
  useShinyjs()
dmattek's avatar
dmattek committed
21
  
22 23 24 25 26 27 28 29
  # This is only set at session start
  # we use this as a way to determine which input was
  # clicked in the dataInBoth reactive
  counter <- reactiveValues(
    # The value of inDataGen1,2 actionButton is the number of times they were pressed
    dataGen1     = isolate(input$inDataGen1),
    dataLoadNuc  = isolate(input$inButLoadNuc)
    #dataLoadStim = isolate(input$inButLoadStim)
dmattek's avatar
dmattek committed
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
  # This button will reset the inFileLoad
  observeEvent(input$inButReset, {
    reset("inFileLoadNuc")  # reset is a shinyjs function
    #reset("inButLoadStim")  # reset is a shinyjs function
  })
  
  # generate random dataset 1
  dataGen1 <- eventReactive(input$inDataGen1, {
    cat("dataGen1\n")
    
    return(userDataGen())
  })
  
  # load main data file
  dataLoadNuc <- eventReactive(input$inButLoadNuc, {
    cat("dataLoadNuc\n")
    locFilePath = input$inFileLoadNuc$datapath
    
    counter$dataLoadNuc <- input$inButLoadNuc - 1
    
    if (is.null(locFilePath) || locFilePath == '')
      return(NULL)
    else {
      return(fread(locFilePath))
    }
  })
  
  # load stimulation pattern
  # dataLoadStim <- eventReactive(input$inButLoadStim, {
  #   cat("dataLoadStim\n")
  #   locFilePath = input$inFileLoadStim$datapath
  #   counter$dataLoadStim <- input$inButLoadStim - 1
  #   
  #   return(fread(locFilePath))
  # })
  
  dataInBoth <- reactive({
    # Without direct references to inDataGen1,2 and inFileLoad, inDataGen2
    #    does not trigger running this reactive once inDataGen1 is used.
    # This is one of the more nuanced areas of reactive programming in shiny
    #    due to the if else logic, it isn't fetched once inDataGen1 is available
    # The morale is use direct retrieval of inputs to guarantee they are available
    #    for if else logic checks!
    
    locInGen1 = input$inDataGen1
    locInLoadNuc = input$inButLoadNuc
    #locInLoadStim = input$inButLoadStim
    
    cat(
      "dataInBoth\ninGen1: ",
      locInGen1,
      "   prev=",
      isolate(counter$dataGen1),
      "\ninDataNuc: ",
      locInLoadNuc,
      "   prev=",
      isolate(counter$dataLoadNuc),
      # "\ninDataStim: ",
      # locInLoadStim,
      # "   prev=",
      # isolate(counter$dataLoadStim),
      "\n"
    )
    
    # isolate the checks of counter reactiveValues
    # as we set the values in this same reactive
    if (locInGen1 != isolate(counter$dataGen1)) {
      cat("dataInBoth if inDataGen1\n")
      dm = dataGen1()
      # no need to isolate updating the counter reactive values!
      counter$dataGen1 <- locInGen1
    } else if (locInLoadNuc != isolate(counter$dataLoadNuc)) {
      cat("dataInBoth if inDataLoadNuc\n")
      dm = dataLoadNuc()
      # no need to isolate updating the counter reactive values!
      counter$dataLoadNuc <- locInLoadNuc
    } else {
      cat("dataInBoth else\n")
      dm = NULL
    }
    return(dm)
  })
  
  # return column names of the main dt
dmattek's avatar
dmattek committed
116
  getDataNucCols <- reactive({
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    cat(file = stderr(), 'getDataNucCols: in\n')
    loc.dt = dataInBoth()
    
    if (is.null(loc.dt))
      return(NULL)
    else
      return(colnames(loc.dt))
  })
  
  # return dt with an added column with unique track object label
  dataMod <- reactive({
    cat(file=stderr(), 'dataMod\n')
    loc.dt = dataInBoth()
    
    if(is.null(loc.dt))
      return(NULL)
    
    loc.dt[, trackObjectsLabelUni := paste(sprintf("%03d", get(input$inSelSite)),
                                           sprintf("%04d", get(input$inSelTrackLabel)),
                                           sep = "_")]
dmattek's avatar
dmattek committed
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
    return(loc.dt)
  })

  

  
  # This button will reset the inFileLoad
  observeEvent(input$butReset, {
    reset("inFileLoadNuc")  # reset is a shinyjs function
    #    reset("inFileStimLoad")  # reset is a shinyjs function
    
  })
  
  # generate random dataset 1
  dataGen1 <- eventReactive(input$inDataGen1, {
    cat("dataGen1\n")
    
    return(userDataGen())
  })
  
  
  # prepare data for plotting time courses
  # returns dt with these columns:
  # realtime - selected from input
  # y - measurement selected from input (can be a single column or result of an operation on two cols)
  # id - trackObjectsLabelUni (created in dataMod)
  # group - grouping variable from input
  data4trajPlot <- reactive({
    cat(file=stderr(), 'data4trajPlot\n')
    
    loc.dt = dataMod()
    if(is.null(loc.dt))
      return(NULL)
    
    
    if(input$inSelMath == '')
      loc.s.y = input$inSelMeas1
    else if (input$inSelMath == '1 / ')
      loc.s.y = paste0(input$inSelMath, input$inSelMeas1)
    else
      loc.s.y = paste0(input$inSelMeas1, input$inSelMath, input$inSelMeas2)
    
    # create expression for parsing
    # creates a merged column based on other columns from input
    # used for grouping of plot facets
    loc.s.gr = sprintf("paste(%s, sep=';')", paste(input$inSelGroup, sep = '', collapse = ','))
    
    loc.s.rt = input$inSelTime
    
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    # if dataset contains column mid.in with trajectory filtering status,
    # then, include it in plotting
    if (sum(names(loc.dt) %in% 'mid.in') > 0) {
      loc.out = loc.dt[, .(
        y = eval(parse(text = loc.s.y)),
        id = trackObjectsLabelUni,
        group = eval(parse(text = loc.s.gr)),
        realtime = eval(parse(text = loc.s.rt)),
        mid.in = mid.in
      )]
    } else {
      loc.out = loc.dt[, .(
        y = eval(parse(text = loc.s.y)),
        id = trackObjectsLabelUni,
        group = eval(parse(text = loc.s.gr)),
        realtime = eval(parse(text = loc.s.rt))
      )]
    }
205 206 207
    
    # remove rows with NA
    return(loc.out[complete.cases(loc.out)])
dmattek's avatar
dmattek committed
208 209 210
  })
  
  output$varSelSite = renderUI({
211
    cat(file = stderr(), 'UI varSelSite\n')
dmattek's avatar
dmattek committed
212 213
    locCols = getDataNucCols()
    locColSel = locCols[locCols %like% 'ite'][1] # index 1 at the end in case more matches; select 1st
214
    
dmattek's avatar
dmattek committed
215
    cat(locColSel, '\n')
216 217 218 219 220 221 222
    selectInput(
      'inSelSite',
      'Select FOV (e.g. Metadata_Site or Metadata_Series):',
      locCols,
      width = '100%',
      selected = locColSel
    )
dmattek's avatar
dmattek committed
223 224 225
  })
  
  output$varSelTrackLabel = renderUI({
226
    cat(file = stderr(), 'UI varSelTrackLabel\n')
dmattek's avatar
dmattek committed
227 228 229 230
    locCols = getDataNucCols()
    locColSel = locCols[locCols %like% 'rack'][1] # index 1 at the end in case more matches; select 1st
    
    cat(locColSel, '\n')
231 232 233 234 235 236 237
    selectInput(
      'inSelTrackLabel',
      'Select Track Label (e.g. objNuc_Track_ObjectsLabel):',
      locCols,
      width = '100%',
      selected = locColSel
    )
dmattek's avatar
dmattek committed
238 239 240
  })
  
  output$varSelTime = renderUI({
241
    cat(file = stderr(), 'UI varSelTime\n')
dmattek's avatar
dmattek committed
242
    locCols = getDataNucCols()
243
    locColSel = locCols[locCols %like% 'RealTime'][1] # index 1 at the end in case more matches; select 1st
dmattek's avatar
dmattek committed
244 245
    
    cat(locColSel, '\n')
246 247 248 249 250 251 252
    selectInput(
      'inSelTime',
      'Select X-axis (e.g. RealTime):',
      locCols,
      width = '100%',
      selected = locColSel
    )
dmattek's avatar
dmattek committed
253
  })
254
  
dmattek's avatar
dmattek committed
255 256 257 258 259
  # This is main field to select plot facet grouping
  # It's typically a column with the entire experimental description,
  # e.g. in Yannick's case it's Stim_All_Ch or Stim_All_S.
  # In Coralie's case it's a combination of 3 columns called Stimulation_...
  output$varSelGroup = renderUI({
260
    cat(file = stderr(), 'UI varSelGroup\n')
dmattek's avatar
dmattek committed
261 262
    locCols = getDataNucCols()
    
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
    if (!is.null(locCols)) {
      locColSel = locCols[locCols %like% 'ite']
      if (length(locColSel) == 0)
        locColSel = locCols[locCols %like% 'eries'][1] # index 1 at the end in case more matches; select 1st
      else if (length(locColSel) > 1) {
        locColSel = locColSel[1]
      }
      #    cat('UI varSelGroup::locColSel ', locColSel, '\n')
      selectInput(
        'inSelGroup',
        'Select one or more facet groupings (e.g. Site, Well, Channel):',
        locCols,
        width = '100%',
        selected = locColSel,
        multiple = TRUE
      )
dmattek's avatar
dmattek committed
279 280 281 282 283 284
    }
    
  })
  
  
  output$varSelMeas1 = renderUI({
285
    cat(file = stderr(), 'UI varSelMeas1\n')
dmattek's avatar
dmattek committed
286 287
    locCols = getDataNucCols()
    
288 289 290 291 292 293 294 295 296 297 298
    if (!is.null(locCols)) {
      locColSel = locCols[locCols %like% 'objCyto_Intensity_MeanIntensity_imErkCor.*'][1] # index 1 at the end in case more matches; select 1st
      #    cat(locColSel, '\n')
      selectInput(
        'inSelMeas1',
        'Select Y-axis:',
        locCols,
        width = '100%',
        selected = locColSel
      )
    }
dmattek's avatar
dmattek committed
299 300 301
  })
  
  
302 303 304
  output$varSelMeas2 = renderUI({
    cat(file = stderr(), 'UI varSelMeas2\n')
    locCols = getDataNucCols()
dmattek's avatar
dmattek committed
305
    
306 307 308 309 310 311 312 313 314 315 316
    if (!is.null(locCols) &&
        !(input$inSelMath %in% c('', '1 / '))) {
      locColSel = locCols[locCols %like% 'objNuc_Intensity_MeanIntensity_imErkCor.*'][1] # index 1 at the end in case more matches; select 1st
      #    cat(locColSel, '\n')
      selectInput(
        'inSelMeas2',
        'Select 2nd opernad for Y-axis',
        locCols,
        width = '100%',
        selected = locColSel
      )
dmattek's avatar
dmattek committed
317 318 319 320
    }
  })
  
  
321
  output$uiPlot = renderUI({
dmattek's avatar
dmattek committed
322
    
323
    plotlyOutput("plotTraj", width = paste0(input$inPlotWidth, '%'), height = paste0(input$inPlotHeight, 'px'))
dmattek's avatar
dmattek committed
324 325
  })
  
326 327

  output$plotTraj <- renderPlotly({
dmattek's avatar
dmattek committed
328
    
329
    cat(file=stderr(), 'plotTraj: in\n')
dmattek's avatar
dmattek committed
330 331 332
    locBut = input$butGo
    
    if (locBut == 0) {
333
      cat(file=stderr(), 'plotTraj: Go button not pressed\n')
dmattek's avatar
dmattek committed
334 335 336 337
      
      return(NULL)
    }
    
338
    loc.dt = isolate(data4trajPlot())
dmattek's avatar
dmattek committed
339
    
340 341 342
    cat("plotScatter on to plot\n\n")
    if (is.null(loc.dt)) {
      cat(file=stderr(), 'plotTraj: dt is NULL\n')
dmattek's avatar
dmattek committed
343
      return(NULL)
dmattek's avatar
dmattek committed
344 345
    }
    
346
    cat(file=stderr(), 'plotTraj:dt not NULL\n')
dmattek's avatar
dmattek committed
347
    
348 349 350 351 352 353
    # colour trajectories, if dataset contains mi.din column
    # with filtering status of trajectory
    if(sum(names(loc.dt) %in% 'mid.in') > 0)
      loc.line.col.arg = 'mid.in'
    else
      loc.line.col.arg = NULL
dmattek's avatar
dmattek committed
354 355
    
    p.out = myGgplotTraj(
356 357 358 359 360 361
      dt.arg = loc.dt,
      x.arg = 'realtime',
      y.arg = 'y',
      group.arg = "id",
      facet.arg = 'group',
      facet.ncol.arg = input$inPlotTrajFacetNcol,
362 363
      xlab.arg = 'Time (min)',
      line.col.arg = loc.line.col.arg
dmattek's avatar
dmattek committed
364
    )
365
      
dmattek's avatar
dmattek committed
366
    
dmattek's avatar
dmattek committed
367 368 369 370
    # This is required to avoid 
    # "Warning: Error in <Anonymous>: cannot open file 'Rplots.pdf'"
    # When running on a server. Based on:
    # https://github.com/ropensci/plotly/issues/494
dmattek's avatar
dmattek committed
371 372 373
    if (names(dev.cur()) != "null device") dev.off()
    pdf(NULL)
    
dmattek's avatar
dmattek committed
374 375
    p.out.ly = plotly_build(p.out)
    return(p.out.ly)
dmattek's avatar
dmattek committed
376 377 378
  })
  
})