Due to a scheduled upgrade to version 14.10, GitLab will be unavailabe on Monday 30.05., from 19:00 until 20:00.

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

2

dmattek's avatar
dmattek committed
3

dmattek's avatar
dmattek committed
4
5
6
7
8
9
10
11
12
13
# 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)
dmattek's avatar
dmattek committed
14
library(gplots) # for heatmap.2
dmattek's avatar
dmattek committed
15
library(plotly)
dmattek's avatar
dmattek committed
16
17
18
19
20
library(d3heatmap) # for interactive heatmap
library(dendextend) # for color_branches
library(RColorBrewer)
library(sparcl) # sparse hierarchical and k-means
library(scales) # for percentages on y scale
dmattek's avatar
dmattek committed
21

22
# increase file upload limit
dmattek's avatar
Added:    
dmattek committed
23
options(shiny.maxRequestSize = 80 * 1024 ^ 2)
dmattek's avatar
dmattek committed
24

dmattek's avatar
dmattek committed
25
shinyServer(function(input, output, session) {
26
  useShinyjs()
dmattek's avatar
dmattek committed
27
  
28
29
30
31
32
33
34
35
  # 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
36
37
  )
  
dmattek's avatar
dmattek committed
38
39
40
  ####
  ## UI for side panel
  
dmattek's avatar
dmattek committed
41
  # FILE LOAD
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
  # 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))
    }
  })
  
dmattek's avatar
dmattek committed
69
70
71
72
73
74
75
  # This button will reset the inFileLoad
  observeEvent(input$butReset, {
    reset("inFileLoadNuc")  # reset is a shinyjs function
    #    reset("inFileStimLoad")  # reset is a shinyjs function
    
  })
  
dmattek's avatar
dmattek committed
76
77
  
  # COLUMN SELECTION
dmattek's avatar
dmattek committed
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
  output$varSelTrackLabel = renderUI({
    cat(file = stderr(), 'UI varSelTrackLabel\n')
    locCols = getDataNucCols()
    locColSel = locCols[locCols %like% 'rack'][1] # index 1 at the end in case more matches; select 1st
    
    cat(locColSel, '\n')
    selectInput(
      'inSelTrackLabel',
      'Select Track Label (e.g. objNuc_Track_ObjectsLabel):',
      locCols,
      width = '100%',
      selected = locColSel
    )
  })
  
  output$varSelTime = renderUI({
    cat(file = stderr(), 'UI varSelTime\n')
    locCols = getDataNucCols()
    locColSel = locCols[locCols %like% 'RealTime'][1] # index 1 at the end in case more matches; select 1st
    
    cat(locColSel, '\n')
    selectInput(
      'inSelTime',
      'Select time column (e.g. RealTime):',
      locCols,
      width = '100%',
      selected = locColSel
    )
  })
  
  # 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({
    cat(file = stderr(), 'UI varSelGroup\n')
    locCols = getDataNucCols()
    
    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
      )
    }
    
  })
  
  output$varSelSite = renderUI({
    cat(file = stderr(), 'UI varSelSite\n')
    
dmattek's avatar
Added:    
dmattek committed
139
140
141
142
143
144
145
146
147
148
149
150
151
    if (!input$chBtrackUni) {
      locCols = getDataNucCols()
      locColSel = locCols[locCols %like% 'ite'][1] # index 1 at the end in case more matches; select 1st
      
      cat(locColSel, '\n')
      selectInput(
        'inSelSite',
        'Select FOV (e.g. Metadata_Site or Metadata_Series):',
        locCols,
        width = '100%',
        selected = locColSel
      )
    }
dmattek's avatar
dmattek committed
152
153
154
155
156
157
158
159
160
161
  })
  
  
  
  
  output$varSelMeas1 = renderUI({
    cat(file = stderr(), 'UI varSelMeas1\n')
    locCols = getDataNucCols()
    
    if (!is.null(locCols)) {
dmattek's avatar
dmattek committed
162
163
      locColSel = locCols[locCols %like% 'objCyto_Intensity_MeanIntensity_imErkCor.*' |
                            locCols %like% 'Ratio'][1] # index 1 at the end in case more matches; select 1st
dmattek's avatar
dmattek committed
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
      #    cat(locColSel, '\n')
      selectInput(
        'inSelMeas1',
        'Select 1st measurement:',
        locCols,
        width = '100%',
        selected = locColSel
      )
    }
  })
  
  
  output$varSelMeas2 = renderUI({
    cat(file = stderr(), 'UI varSelMeas2\n')
    locCols = getDataNucCols()
    
    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 measurement',
        locCols,
        width = '100%',
        selected = locColSel
      )
    }
  })
  
dmattek's avatar
dmattek committed
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
  # UI for trimming x-axis (time)
  output$uiSlTimeTrim = renderUI({
    cat(file = stderr(), 'UI uiSlTimeTrim\n')
    
    if (input$chBtimeTrim) {
      locTpts  = getDataTpts()
      
      if(is.null(locTpts))
        return(NULL)
      
      locRTmin = min(locTpts)
      locRTmax = max(locTpts)
      
      sliderInput(
        'slTimeTrim',
        label = 'Time range to include',
        min = locRTmin,
        max = locRTmax,
        value = c(locRTmin, locRTmax),
        step = 1
      )
      
    }
  })
dmattek's avatar
dmattek committed
218
  
dmattek's avatar
dmattek committed
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
  # UI for normalization
  
  output$uiChBnorm = renderUI({
    cat(file = stderr(), 'UI uiChBnorm\n')
    
    if (input$chBnorm) {
      radioButtons(
        'rBnormMeth',
        label = 'Select method',
        choices = list('fold-change' = 'mean', 'z-score' = 'z.score')
      )
    }
  })
  
  output$uiSlNorm = renderUI({
    cat(file = stderr(), 'UI uiSlNorm\n')
    
    if (input$chBnorm) {
      locTpts  = getDataTpts()
      
      if(is.null(locTpts))
        return(NULL)
      
      locRTmin = min(locTpts)
      locRTmax = max(locTpts)
      
      sliderInput(
        'slNormRtMinMax',
        label = 'Time range for norm.',
        min = locRTmin,
        max = locRTmax,
dmattek's avatar
dmattek committed
250
251
        value = c(locRTmin, 0.1 * locRTmax), 
        step = 1
dmattek's avatar
dmattek committed
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
      )
    }
  })
  
  output$uiChBnormRobust = renderUI({
    cat(file = stderr(), 'UI uiChBnormRobust\n')
    
    if (input$chBnorm) {
      checkboxInput('chBnormRobust',
                    label = 'Robust stats',
                    FALSE)
    }
  })
  
  output$uiChBnormGroup = renderUI({
    cat(file = stderr(), 'UI uiChBnormGroup\n')
    
    if (input$chBnorm) {
      radioButtons('chBnormGroup',
                  label = 'Normalisation grouping',
                  choices = list('Entire dataset' = 'none', 'Per facet' = 'group', 'Per trajectory (Korean way)' = 'id'))
    }
  })
  
  
dmattek's avatar
dmattek committed
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
  # UI for removing outliers
  
  output$uiSlOutliers = renderUI({
    cat(file = stderr(), 'UI uiSlOutliers\n')
    
    if (input$chBoutliers) {

      sliderInput(
        'slOutliersPerc',
        label = 'Percentage of middle data',
        min = 90,
        max = 100,
        value = 99, 
        step = 0.1
      )
dmattek's avatar
dmattek committed
292
293
      

dmattek's avatar
dmattek committed
294
295
296
    }
  })
  
dmattek's avatar
dmattek committed
297
298
299
300
301
302
303
304
305
  output$uiTxtOutliers = renderUI({
    if (input$chBoutliers) {
      
      p("Total tracks")
      
    }
    
  })
  
dmattek's avatar
dmattek committed
306
  
dmattek's avatar
dmattek committed
307
308
309
310
311
312
313
314
315
  ####
  ## data processing
  
  # generate random dataset 1
  dataGen1 <- eventReactive(input$inDataGen1, {
    cat("dataGen1\n")
    
    return(userDataGen())
  })
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
  
  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
365
  getDataNucCols <- reactive({
366
367
368
369
370
371
372
373
374
375
376
    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({
dmattek's avatar
dmattek committed
377
    cat(file = stderr(), 'dataMod\n')
378
379
    loc.dt = dataInBoth()
    
dmattek's avatar
dmattek committed
380
    if (is.null(loc.dt))
381
382
      return(NULL)
    
dmattek's avatar
Added:    
dmattek committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
    if (!input$chBtrackUni) {
      loc.types = lapply(loc.dt, class)
      if(loc.types[[input$inSelTrackLabel]] %in% c('numeric', 'integer') & loc.types[[input$inSelSite]] %in% c('numeric', 'integer'))
      {
        loc.dt[, trackObjectsLabelUni := paste(sprintf("%03d", get(input$inSelSite)),
                                               sprintf("%04d", get(input$inSelTrackLabel)),
                                               sep = "_")]
      } else if(loc.types[[input$inSelTrackLabel]] %in% c('numeric', 'integer')) {
        loc.dt[, trackObjectsLabelUni := paste(sprintf("%s", get(input$inSelSite)),
                                               sprintf("%04d", get(input$inSelTrackLabel)),
                                               sep = "_")]
      } else if(loc.types[[input$inSelSite]] %in% c('numeric', 'integer')) {
        loc.dt[, trackObjectsLabelUni := paste(sprintf("%03d", get(input$inSelSite)),
                                               sprintf("%s", get(input$inSelTrackLabel)),
                                               sep = "_")]
      } else {
        loc.dt[, trackObjectsLabelUni := paste(sprintf("%s", get(input$inSelSite)),
                                               sprintf("%s", get(input$inSelTrackLabel)),
                                               sep = "_")]
      }
dmattek's avatar
Added:    
dmattek committed
403
    } else {
dmattek's avatar
Added:    
dmattek committed
404
      loc.dt[, trackObjectsLabelUni := get(input$inSelTrackLabel)]
dmattek's avatar
Added:    
dmattek committed
405
406
    }
    
dmattek's avatar
dmattek committed
407
    
408
409
410
    return(loc.dt)
  })
  
dmattek's avatar
dmattek committed
411
412
413
414
415
  # return all unique track object labels (created in dataMod)
  # This will be used to display in UI for trajectory highlighting
  getDataTrackObjLabUni <- reactive({
    cat(file = stderr(), 'getDataTrackObjLabUni\n')
    loc.dt = dataMod()
416
    
dmattek's avatar
dmattek committed
417
418
419
420
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt$trackObjectsLabelUni))
421
422
  })
  
dmattek's avatar
dmattek committed
423
  # return all unique track object labels (created in dataMod)
dmattek's avatar
dmattek committed
424
  # This will be used to display in UI for trajectory highlighting
dmattek's avatar
dmattek committed
425
426
427
428
429
430
431
432
433
434
435
436
437
  getDataTrackObjLabUni_afterTrim <- reactive({
    cat(file = stderr(), 'getDataTrackObjLabUni_afterTrim\n')
    loc.dt = data4trajPlot()
    
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt$id))
  })

  # return all unique time points (real time)
  # This will be used to display in UI for box-plot
  # These timepoints are from the original dt and aren't affected by trimming of x-axis
dmattek's avatar
dmattek committed
438
439
440
  getDataTpts <- reactive({
    cat(file = stderr(), 'getDataTpts\n')
    loc.dt = dataMod()
441
    
dmattek's avatar
dmattek committed
442
443
444
445
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt[[input$inSelTime]]))
446
447
  })
  
dmattek's avatar
dmattek committed
448
449
450
451
452
453
454
455
456
457
458
459
460
  # return dt with cell IDs and their corresponding condition name
  # The condition is the column defined by facet groupings
  getDataCond <- reactive({
    cat(file = stderr(), 'getDataCond\n')
    loc.dt = data4trajPlot()
    
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt[, .(id, group)]))
    
  })
  
461
462
463
  
  # prepare data for plotting time courses
  # returns dt with these columns:
dmattek's avatar
dmattek committed
464
  #    realtime - selected from input
dmattek's avatar
dmattek committed
465
  #    y        - measurement selected from input
dmattek's avatar
dmattek committed
466
467
468
469
470
  #               (can be a single column or result of an operation on two cols)
  #    id       - trackObjectsLabelUni (created in dataMod)
  #    group    - grouping variable for facetting from input
  #    mid.in   - column with trajectory selection status from the input file or
  #               highlight status from UI
471
  data4trajPlot <- reactive({
dmattek's avatar
dmattek committed
472
    cat(file = stderr(), 'data4trajPlot\n')
473
474
    
    loc.dt = dataMod()
dmattek's avatar
dmattek committed
475
    if (is.null(loc.dt))
476
477
478
      return(NULL)
    
    
dmattek's avatar
dmattek committed
479
    if (input$inSelMath == '')
480
481
482
483
484
485
486
487
488
      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
dmattek's avatar
dmattek committed
489
490
491
492
    if(length(input$inSelGroup) == 0)
      return(NULL)
    loc.s.gr = sprintf("paste(%s, sep=';')",
                       paste(input$inSelGroup, sep = '', collapse = ','))
493
494
495
    
    loc.s.rt = input$inSelTime
    
dmattek's avatar
dmattek committed
496
497
498
499
    # Assign tracks selected for highlighting in UI
    loc.tracks.highlight = input$inSelHighlight
    locBut = input$chBhighlightTraj
    
dmattek's avatar
Added:    
dmattek committed
500
501
    
    # Find column names with position
dmattek's avatar
Mod:    
dmattek committed
502
503
    loc.s.pos.x = names(loc.dt)[names(loc.dt) %like% c('.*ocation.*X') | names(loc.dt) %like% c('.*os.x')]
    loc.s.pos.y = names(loc.dt)[names(loc.dt) %like% c('.*ocation.*Y') | names(loc.dt) %like% c('.*os.y')]
dmattek's avatar
Added:    
dmattek committed
504
505
506
507
508
509
    
    if (length(loc.s.pos.x) == 1 & length(loc.s.pos.y) == 1)
      locPos = TRUE
    else
      locPos = FALSE
    
510
511
512
    # if dataset contains column mid.in with trajectory filtering status,
    # then, include it in plotting
    if (sum(names(loc.dt) %in% 'mid.in') > 0) {
dmattek's avatar
Added:    
dmattek committed
513
      if (locPos) # position columns present
514
515
516
517
518
      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)),
dmattek's avatar
Added:    
dmattek committed
519
520
        pos.x = get(loc.s.pos.x),
        pos.y = get(loc.s.pos.y),
521
        mid.in = mid.in
dmattek's avatar
Added:    
dmattek committed
522
523
524
525
526
527
528
529
530
531
532
      )] 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)),
          mid.in = mid.in
        )]
      
      
      
dmattek's avatar
dmattek committed
533
534
535
536
537
538
539
      
      # add 3rd level with status of track selection
      # to a column with trajectory filtering status
      if (locBut) {
        loc.out[, mid.in := ifelse(id %in% loc.tracks.highlight, 'SELECTED', mid.in)]
      }
      
540
    } else {
dmattek's avatar
Added:    
dmattek committed
541
      if (locPos) # position columns present
542
543
544
545
      loc.out = loc.dt[, .(
        y = eval(parse(text = loc.s.y)),
        id = trackObjectsLabelUni,
        group = eval(parse(text = loc.s.gr)),
dmattek's avatar
Added:    
dmattek committed
546
547
548
549
550
551
552
553
554
555
556
        realtime = eval(parse(text = loc.s.rt)),
        pos.x = get(loc.s.pos.x),
        pos.y = get(loc.s.pos.y)
      )] 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))
        )]
      
dmattek's avatar
dmattek committed
557
558
559
560
561
      
      # add a column with status of track selection
      if (locBut) {
        loc.out[, mid.in := ifelse(id %in% loc.tracks.highlight, 'SELECTED', 'NOT SEL')]
      }
562
    }
563
    
dmattek's avatar
Added:    
dmattek committed
564
565
    # add XY location if present in the dataset
    
dmattek's avatar
dmattek committed
566
567
568
569
570
571
572
    # remove NAs
    loc.out = loc.out[complete.cases(loc.out)]

    # Trim x-axis (time)
    if(input$chBtimeTrim) {
      loc.out = loc.out[realtime >= input$slTimeTrim[[1]] & realtime <= input$slTimeTrim[[2]] ]
    }
dmattek's avatar
dmattek committed
573
574
    
    # Normalization
dmattek's avatar
dmattek committed
575
    # F-n myNorm adds additional column with .norm suffix
dmattek's avatar
dmattek committed
576
577
578
579
580
581
582
583
584
585
586
587
    if (input$chBnorm) {
      loc.out = myNorm(
        in.dt = loc.out,
        in.meas.col = 'y',
        in.rt.col = 'realtime',
        in.rt.min = input$slNormRtMinMax[1],
        in.rt.max = input$slNormRtMinMax[2],
        in.type = input$rBnormMeth,
        in.robust = input$chBnormRobust,
        in.by.cols = if(input$chBnormGroup %in% 'none') NULL else input$chBnormGroup
      )
      
dmattek's avatar
dmattek committed
588
589
      # Column with normalized data is renamed to the original name
      # Further code assumes column name y produced by data4trajPlot
dmattek's avatar
dmattek committed
590
591
592
593
      loc.out[, y := NULL]
      setnames(loc.out, 'y.norm', 'y')
    }
    
dmattek's avatar
dmattek committed
594
595
596
597
598
599
    ##### MOD HERE
    ## display number of filtered tracks in textUI: uiTxtOutliers
    ## How? 
    ## 1. through reactive values?
    ## 2. through additional comumn to tag outliers?
    
dmattek's avatar
dmattek committed
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
    # Remove outliers
    # 1. Scale all points (independently per track)
    # 2. Pick time points that exceed the bounds
    # 3. Identify IDs of outliers
    # 4. Select cells that don't have these IDs
    
    cat('Ncells orig = ', length(unique(loc.out$id)), '\n')
    
    if (input$chBoutliers) {
      loc.out[, y.sc := scale(y)]  
      loc.tmp = loc.out[ y.sc < quantile(y.sc, (1 - input$slOutliersPerc * 0.01)*0.5) | 
                           y.sc > quantile(y.sc, 1 - (1 - input$slOutliersPerc * 0.01)*0.5)]
      loc.out = loc.out[!(id %in% unique(loc.tmp$id))]
      loc.out[, y.sc := NULL]
    }
    
    cat('Ncells trim = ', length(unique(loc.out$id)), '\n')

    return(loc.out)
dmattek's avatar
dmattek committed
619
620
  })
  
dmattek's avatar
dmattek committed
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
  
  
  # prepare data for clustering
  # return a matrix with:
  # cells as columns
  # time points as rows
  data4clust <- reactive({
    cat(file = stderr(), 'data4clust\n')
    
    loc.dt = data4trajPlot()
    if (is.null(loc.dt))
      return(NULL)
    
    loc.out = dcast(loc.dt, id ~ realtime, value.var = 'y')
    loc.rownames = loc.out$id
    

    loc.out = as.matrix(loc.out[, -1])
    rownames(loc.out) = loc.rownames
    return(loc.out)
  })
  
  # prepare data for plotting timecourses facetted per cluster
  # uses the same dt as for trajectory plotting
  # returns dt with these columns:
  data4hierSparTrajPlot <- reactive({
    cat(file = stderr(), 'data4hierSparTrajPlot\n')
dmattek's avatar
dmattek committed
648
    
dmattek's avatar
dmattek committed
649
    loc.dt = data4trajPlot()
dmattek's avatar
dmattek committed
650
    if (is.null(loc.dt))
dmattek's avatar
dmattek committed
651
      return(NULL)
dmattek's avatar
dmattek committed
652
    
dmattek's avatar
dmattek committed
653
    loc.out = loc.dt[realtime %in% input$inSelTpts]
dmattek's avatar
dmattek committed
654
655
  })
  
dmattek's avatar
dmattek committed
656
657
  
  # get cell IDs with cluster assignments depending on dendrogram cut
dmattek's avatar
dmattek committed
658
659
660
661
  getDataCl = function(in.dend, in.k, in.ids) {
    cat(file = stderr(), 'getDataCl \n')
    cat(in.k, '\n')
    loc.dt.cl = data.table(id = in.ids,
dmattek's avatar
dmattek committed
662
663
664
665
                           cl = cutree(as.dendrogram(in.dend), k = in.k))
  }
  

dmattek's avatar
dmattek committed
666
667
668
669
670
671
672
673
674
  getDataHierClReact = reactive({
    cat(file = stderr(), 'getDataHierClReact \n')
    cat(input$inPlotHierNclust, '\n')
    loc.dt.cl = data.table(id = getDataTrackObjLabUni_afterTrim(),
                           cl = cutree(userFitDendHier(), k = input$inPlotHierNclust))
    
    loc.dt.cl = merge(loc.dt.cl, getDataCond(), by = 'id')
  })
  
dmattek's avatar
dmattek committed
675
676
  ####
  ## UI for trajectory plot
dmattek's avatar
dmattek committed
677
  
dmattek's avatar
dmattek committed
678
679
  output$varSelHighlight = renderUI({
    cat(file = stderr(), 'UI varSelHighlight\n')
dmattek's avatar
dmattek committed
680
    
dmattek's avatar
dmattek committed
681
682
683
    locBut = input$chBhighlightTraj
    if (!locBut)
      return(NULL)
dmattek's avatar
dmattek committed
684
    
dmattek's avatar
dmattek committed
685
    loc.v = getDataTrackObjLabUni()
dmattek's avatar
dmattek committed
686
    if (!is.null(loc.v)) {
687
      selectInput(
dmattek's avatar
dmattek committed
688
689
690
        'inSelHighlight',
        'Select one or more rajectories:',
        loc.v,
691
        width = '100%',
dmattek's avatar
dmattek committed
692
        multiple = TRUE
693
      )
dmattek's avatar
dmattek committed
694
695
696
    }
  })
  
dmattek's avatar
dmattek committed
697
  output$uiPlotTraj = renderUI({
dmattek's avatar
Added:    
dmattek committed
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
    if (input$chBplotTrajInt)
      plotlyOutput(
        "outPlotTrajInt",
        width = paste0(input$inPlotTrajWidth, '%'),
        height = paste0(input$inPlotTrajHeight, 'px')
      ) else
        plotOutput(
          "outPlotTraj",
          width = paste0(input$inPlotTrajWidth, '%'),
          height = paste0(input$inPlotTrajHeight, 'px')
        )
  })
  
  output$outPlotTraj <- renderPlot({

    loc.p = plotTraj()
    if(is.null(loc.p))
      return(NULL)
    
    return(loc.p)
dmattek's avatar
dmattek committed
718
  })
dmattek's avatar
Added:    
dmattek committed
719

dmattek's avatar
dmattek committed
720
  
dmattek's avatar
Added:    
dmattek committed
721
  output$outPlotTrajInt <- renderPlotly({
dmattek's avatar
dmattek committed
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
    # 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
    if (names(dev.cur()) != "null device")
      dev.off()
    pdf(NULL)
    
    loc.p = plotTraj()
    if(is.null(loc.p))
      return(NULL)
    
    return(plotly_build(loc.p))
  })
  
dmattek's avatar
Added:    
dmattek committed
737
738
  
  
dmattek's avatar
dmattek committed
739
  # Trajectory plot - download pdf
dmattek's avatar
dmattek committed
740
  callModule(downPlot, "downPlotTraj", 'tcourses.pdf', plotTraj, TRUE)
dmattek's avatar
dmattek committed
741
742
  
  plotTraj <- function() {
dmattek's avatar
dmattek committed
743
    cat(file = stderr(), 'plotTraj: in\n')
dmattek's avatar
dmattek committed
744
    locBut = input$butPlotTraj
dmattek's avatar
dmattek committed
745
746
    
    if (locBut == 0) {
dmattek's avatar
dmattek committed
747
      cat(file = stderr(), 'plotTraj: Go button not pressed\n')
dmattek's avatar
dmattek committed
748
749
750
751
      
      return(NULL)
    }
    
752
    loc.dt = isolate(data4trajPlot())
dmattek's avatar
dmattek committed
753
    
dmattek's avatar
dmattek committed
754
    cat("plotTraj: on to plot\n\n")
755
    if (is.null(loc.dt)) {
dmattek's avatar
dmattek committed
756
      cat(file = stderr(), 'plotTraj: dt is NULL\n')
dmattek's avatar
dmattek committed
757
      return(NULL)
dmattek's avatar
dmattek committed
758
759
    }
    
dmattek's avatar
dmattek committed
760
    cat(file = stderr(), 'plotTraj: dt not NULL\n')
dmattek's avatar
dmattek committed
761
    
dmattek's avatar
dmattek committed
762

dmattek's avatar
dmattek committed
763
    # Future: change such that a column with colouring status is chosen by the user
764
765
    # colour trajectories, if dataset contains mi.din column
    # with filtering status of trajectory
dmattek's avatar
dmattek committed
766
    if (sum(names(loc.dt) %in% 'mid.in') > 0)
767
768
769
      loc.line.col.arg = 'mid.in'
    else
      loc.line.col.arg = NULL
dmattek's avatar
Added:    
dmattek committed
770
771
772
773
774
775
776
777
778

    # select every other point for plotting
    loc.dt = loc.dt[, .SD[seq(1, .N, input$sliPlotTrajSkip)], by = id]
    
    # check if columns with XY positions are present
    if (sum(names(loc.dt) %like% 'pos') == 2)
      locPos = TRUE
    else
      locPos = FALSE
dmattek's avatar
dmattek committed
779
780
    
    p.out = myGgplotTraj(
781
782
783
784
785
786
      dt.arg = loc.dt,
      x.arg = 'realtime',
      y.arg = 'y',
      group.arg = "id",
      facet.arg = 'group',
      facet.ncol.arg = input$inPlotTrajFacetNcol,
787
      xlab.arg = 'Time (min)',
dmattek's avatar
Added:    
dmattek committed
788
789
      line.col.arg = loc.line.col.arg,
      aux.label1 = if (locPos) 'pos.x' else NULL,
dmattek's avatar
Added:    
dmattek committed
790
791
      aux.label2 = if (locPos) 'pos.y' else NULL,
      stat.arg = input$chBPlotTrajStat
dmattek's avatar
dmattek committed
792
    )
dmattek's avatar
dmattek committed
793
    
dmattek's avatar
dmattek committed
794
795
796
    return(p.out)
  }
  
dmattek's avatar
dmattek committed
797
  
dmattek's avatar
Added:    
dmattek committed
798
799
  ###### Box-plot
  callModule(tabBoxPlot, 'tabBoxPlot', data4trajPlot)
dmattek's avatar
dmattek committed
800
  
dmattek's avatar
dmattek committed
801
802
  
  
dmattek's avatar
dmattek committed
803
804
805
  ###### Scatter plot
  callModule(tabScatterPlot, 'tabScatter', data4trajPlot)
  
dmattek's avatar
dmattek committed
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
  ##### Hierarchical clustering
  
  output$uiPlotHierClSel = renderUI({
    if(input$chBPlotHierClSel) {
      selectInput('inPlotHierClSel', 'Select clusters to display', 
                  choices = seq(1, input$inPlotHierNclust, 1),
                  multiple = TRUE, 
                  selected = 1)
    }
  })
  
  userFitDendHier <- reactive({
    dm.t = data4clust()
    if (is.null(dm.t)) {
      return()
    }
    
    cl.dist = dist(dm.t, method = s.cl.diss[as.numeric(input$selectPlotHierDiss)])
    cl.hc = hclust(cl.dist, method = s.cl.linkage[as.numeric(input$selectPlotHierLinkage)])
    cl.lev = rev(row.names(dm.t))
    
    dend <- as.dendrogram(cl.hc)
    dend <- color_branches(dend, k = input$inPlotHierNclust)
    
    return(dend)
  })
  
  # Function instead of reactive as per:
  # http://stackoverflow.com/questions/26764481/downloading-png-from-shiny-r
  # This function is used to plot and to downoad a pdf
  plotHier <- function() {
    
    loc.dm = data4clust()
    if (is.null(loc.dm))
      return(NULL)
    
    loc.dend <- userFitDendHier()
    if (is.null(loc.dend))
      return(NULL)
    
    if (input$inPlotHierRevPalette)
      my_palette <-
      rev(colorRampPalette(brewer.pal(9, input$selectPlotHierPalette))(n = 99))
    else
      my_palette <-
      colorRampPalette(brewer.pal(9, input$selectPlotHierPalette))(n = 99)
    
    
    col_labels <- get_leaves_branches_col(loc.dend)
    col_labels <- col_labels[order(order.dendrogram(loc.dend))]
    
    if (input$selectPlotHierDend) {
      assign("var.tmp.1", loc.dend)
      var.tmp.2 = "row"
    } else {
      assign("var.tmp.1", FALSE)
      var.tmp.2 = "none"
    }
    
    loc.p = heatmap.2(
      loc.dm,
      Colv = "NA",
      Rowv = var.tmp.1,
      srtCol = 90,
      dendrogram = var.tmp.2,
      trace = "none",
      key = input$selectPlotHierKey,
      margins = c(input$inPlotHierMarginX, input$inPlotHierMarginY),
      col = my_palette,
      na.col = grey(input$inPlotHierNAcolor),
      denscol = "black",
      density.info = "density",
      RowSideColors = col_labels,
      colRow = col_labels,
#      sepcolor = grey(input$inPlotHierGridColor),
#      colsep = 1:ncol(loc.dm),
#      rowsep = 1:nrow(loc.dm),
      cexRow = input$inPlotHierFontX,
      cexCol = input$inPlotHierFontY,
      main = paste(
        "Distance measure: ",
        s.cl.diss[as.numeric(input$selectPlotHierDiss)],
        "\nLinkage method: ",
        s.cl.linkage[as.numeric(input$selectPlotHierLinkage)]
      )
    )
    
    return(loc.p)
  }
  
  
  plotHierTraj <- function(){
    cat(file = stderr(), 'plotHierTraj: in\n')
    
    loc.dt = isolate(data4trajPlot())
    
    cat("plotHierTraj: on to plot\n\n")
    if (is.null(loc.dt)) {
      cat(file = stderr(), 'plotHierTraj: dt is NULL\n')
      return(NULL)
    }
    
    cat(file = stderr(), 'plotHierTraj: dt not NULL\n')
    
    # get cellIDs with cluster assignments based on dendrogram cut
dmattek's avatar
dmattek committed
911
    loc.dt.cl = getDataCl(userFitDendHier(), input$inPlotHierNclust, getDataTrackObjLabUni_afterTrim())
dmattek's avatar
dmattek committed
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
    loc.dt = merge(loc.dt, loc.dt.cl, by = 'id')
    
    # display only selected clusters
    if(isolate(input$chBPlotHierClSel))
      loc.dt = loc.dt[cl %in% isolate(input$inPlotHierClSel)]
    
    # Future: change such that a column with colouring status is chosen by the user
    # 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
    
    p.out = myGgplotTraj(
      dt.arg = loc.dt,
      x.arg = 'realtime',
      y.arg = 'y',
      group.arg = "id",
      facet.arg = 'cl',
      facet.ncol.arg = input$inPlotTrajFacetNcol,
      xlab.arg = 'Time (min)',
      line.col.arg = loc.line.col.arg
    )
    
    return(p.out)
  }
  
  
dmattek's avatar
Added:    
dmattek committed
941
  # download a list of cellIDs with cluster assignments
dmattek's avatar
dmattek committed
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
  output$downCellCl <- downloadHandler(
    filename = function() {
      paste0('clust_hierch_data_',
             s.cl.diss[as.numeric(input$selectPlotHierDiss)],
             '_',
             s.cl.linkage[as.numeric(input$selectPlotHierLinkage)], '.csv')
    },
    
    content = function(file) {
      write.csv(x = getDataCl(userFitDendHier(), input$inPlotHierNclust, getDataTrackObjLabUni_afterTrim()), file = file, row.names = FALSE)
    }
  )
  
  output$downCellClSpar <- downloadHandler(
    filename = function() {
      paste0('clust_hierchSpar_data_',
             s.cl.spar.diss[as.numeric(input$selectPlotHierSparDiss)],
             '_',
             s.cl.spar.linkage[as.numeric(input$selectPlotHierSparLinkage)], '.csv')
    },
    
    content = function(file) {
      write.csv(x = getDataCl(userFitDendHierSpar(), input$inPlotHierSparNclust, getDataTrackObjLabUni_afterTrim()), file = file, row.names = FALSE)
    }
  )
  
  
    # callModule(downCellCl, 'downDataHier', paste0('clust_hierch_data_',
    #                                               s.cl.diss[as.numeric(input$selectPlotHierDiss)],
    #                                               '_',
    #                                               s.cl.linkage[as.numeric(input$selectPlotHierLinkage)], '.csv'),
    #            getDataCl(userFitDendHier, input$inPlotHierNclust, getDataTrackObjLabUni_afterTrim))
    # 
dmattek's avatar
Added:    
dmattek committed
975
  
dmattek's avatar
dmattek committed
976
977
978
979
980
981
    output$downloadDataClean <- downloadHandler(
      filename = 'tCoursesSelected_clean.csv',
      content = function(file) {
        write.csv(data4trajPlot(), file, row.names = FALSE)
      }
    )
dmattek's avatar
dmattek committed
982
983
984
    
    
    
dmattek's avatar
dmattek committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
  # Barplot with distribution of clusters across conditions
  plotHierClDist = function() {
    cat(file = stderr(), 'plotClDist: in\n')
    
    # get cell IDs with cluster assignments depending on dendrogram cut
    loc.dend <- isolate(userFitDendHier())
    if (is.null(loc.dend)) {
      cat(file = stderr(), 'plotClDist: loc.dend is NULL\n')
      return(NULL)
    }
    
    loc.dt.cl = data.table(id = getDataTrackObjLabUni_afterTrim(),
                           cl = cutree(as.dendrogram(loc.dend), k = input$inPlotHierNclust))
    
    
dmattek's avatar
dmattek committed
1000
    # get cellIDs with condition name
dmattek's avatar
dmattek committed
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
    loc.dt.gr = isolate(getDataCond())
    if (is.null(loc.dt.gr)) {
      cat(file = stderr(), 'plotClDist: loc.dt.gr is NULL\n')
      return(NULL)
    }
    
    loc.dt = merge(loc.dt.cl, loc.dt.gr, by = 'id')
    
    # display only selected clusters
    if(isolate(input$chBPlotHierClSel))
      loc.dt = loc.dt[cl %in% isolate(input$inPlotHierClSel)]
    
    loc.dt.aggr = loc.dt[, .(nCells = .N), by = .(group, cl)]
    
    
    p.out = ggplot(loc.dt.aggr, aes(x = group, y = nCells)) +
      geom_bar(aes(fill = as.factor(cl)), stat = 'identity', position = 'fill') +
      scale_y_continuous(labels = percent) +
      ylab("percentage of cells\n") +  
      xlab("") +  
      scale_fill_discrete(name = "Cluster no.") +
      myGgplotTheme
    
    return(p.out)
    
  }
  
  #  Hierarchical - display heatmap
  getPlotHierHeatMapHeight <- function() {
    return (input$inPlotHierHeatMapHeight)
  }
  
  getPlotHierTrajHeight <- function() {
    return (input$inPlotHierTrajHeight)
  }
  
  output$outPlotHier <- renderPlot({
    locBut = input$butPlotHierHeatMap
    
    if (locBut == 0) {
      cat(file = stderr(), 'outPlotHier: Go button not pressed\n')
      
      return(NULL)
    }
    
    plotHier()
  }, height = getPlotHierHeatMapHeight)
  
  #  Hierarchical - display timecourses plot
  output$outPlotHierTraj <- renderPlot({
    locBut = input$butPlotHierTraj
    
    if (locBut == 0) {
      cat(file = stderr(), 'outPlotHierTraj: Go button not pressed\n')
      
      return(NULL)
    }
    
    plotHierTraj()
  })
  
  #  Hierarchical - display bar plot
  output$outPlotHierClDist <- renderPlot({
    locBut = input$butPlotHierClDist
    
    if (locBut == 0) {
      cat(file = stderr(), 'outPlotClDist: Go button not pressed\n')
      
      return(NULL)
    }
    
    plotHierClDist()
  })
  
  
  
dmattek's avatar
dmattek committed
1077
1078
1079
1080
1081
1082
  #  Hierarchical - Heat Map - download pdf
  callModule(downPlot, "downPlotHier",       paste0('clust_hierch_heatMap_',
                                                    s.cl.diss[as.numeric(input$selectPlotHierDiss)],
                                                    '_',
                                                    s.cl.linkage[as.numeric(input$selectPlotHierLinkage)], '.pdf'), plotHier)

dmattek's avatar
dmattek committed
1083
  # Hierarchical - Trajectories - download pdf
dmattek's avatar
dmattek committed
1084
1085
1086
1087
1088
  callModule(downPlot, "downPlotHierTraj",       paste0('clust_hierch_tCourses_',
                                                    s.cl.diss[as.numeric(input$selectPlotHierDiss)],
                                                    '_',
                                                    s.cl.linkage[as.numeric(input$selectPlotHierLinkage)], '.pdf'), plotHierTraj, TRUE)

dmattek's avatar
dmattek committed
1089
  # Hierarchical - Bar Plot - download pdf
dmattek's avatar
dmattek committed
1090
1091
1092
1093
  callModule(downPlot, "downPlotHierClDist",       paste0('clust_hierch_clDist_',
                                                        s.cl.diss[as.numeric(input$selectPlotHierDiss)],
                                                        '_',
                                                        s.cl.linkage[as.numeric(input$selectPlotHierLinkage)], '.pdf'), plotHierClDist, TRUE)
dmattek's avatar
dmattek committed
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
  
  ##### Sparse hierarchical clustering using sparcl
  
  # UI for advanced options
  output$uiPlotHierSparNperms = renderUI({
    if (input$inHierSparAdv)
      sliderInput(
        'inPlotHierSparNperms',
        'Number of permutations',
        min = 1,
        max = 20,
        value = 1,
        step = 1,
        ticks = TRUE
      )
  })
  
  # UI for advanced options
  output$uiPlotHierSparNiter = renderUI({
    if (input$inHierSparAdv)
      sliderInput(
        'inPlotHierSparNiter',
        'Number of iterations',
        min = 1,
        max = 50,
        value = 1,
        step = 1,
        ticks = TRUE
      )
  })
  
  output$uiPlotHierSparClSel = renderUI({
    if(input$chBPlotHierSparClSel) {
      selectInput('inPlotHierSparClSel', 'Select clusters to display', 
                  choices = seq(1, input$inPlotHierSparNclust, 1),
                  multiple = TRUE, 
                  selected = 1)
    }
  })
  

  getPlotHierSparHeatMapHeight <- function() {
    return (input$inPlotHierSparHeatMapHeight)
  }
  
  userFitHierSpar <- reactive({
    dm.t = data4clust()
    if (is.null(dm.t)) {
      return()
    }
    
    #cat('rownames: ', rownames(dm.t), '\n')
    
    perm.out <- HierarchicalSparseCluster.permute(
      dm.t,
      wbounds = NULL,
      nperms = ifelse(input$inHierSparAdv, input$inPlotHierSparNperms, 1),
      dissimilarity = s.cl.spar.diss[as.numeric(input$selectPlotHierSparDiss)]
    )
    
    sparsehc <- HierarchicalSparseCluster(
      dists = perm.out$dists,
      wbound = perm.out$bestw,
      niter = ifelse(input$inHierSparAdv, input$inPlotHierSparNiter, 1),
      method = s.cl.spar.linkage[as.numeric(input$selectPlotHierSparLinkage)],
      dissimilarity = s.cl.spar.diss[as.numeric(input$selectPlotHierSparDiss)]
    )
    return(sparsehc)
  })
  
  
  userFitDendHierSpar <- reactive({
    sparsehc = userFitHierSpar()
    if (is.null(sparsehc)) {
      return()
    }
    
    dend <- as.dendrogram(sparsehc$hc)
    dend <- color_branches(dend, k = input$inPlotHierSparNclust)
    
    return(dend)
  })
  
  # Function instead of reactive as per:
  # http://stackoverflow.com/questions/26764481/downloading-png-from-shiny-r
  # This function is used to plot and to downoad a pdf
  plotHierSpar <- function() {
    
    dm.t = data4clust()
    if (is.null(dm.t)) {
      return()
    }
    
    sparsehc <- userFitHierSpar()
    
    dend <- as.dendrogram(sparsehc$hc)
    dend <- color_branches(dend, k = input$inPlotHierSparNclust)
    
    if (input$inPlotHierSparRevPalette)
      my_palette <-
      rev(colorRampPalette(brewer.pal(9, input$selectPlotHierSparPalette))(n = 99))
    else
      my_palette <-
      colorRampPalette(brewer.pal(9, input$selectPlotHierSparPalette))(n = 99)
    
    
    col_labels <- get_leaves_branches_col(dend)
    col_labels <- col_labels[order(order.dendrogram(dend))]
    
    if (input$selectPlotHierSparDend == 1)
      assign("var.tmp", dend)
    else
      assign("var.tmp", FALSE)
    
    
    loc.colnames = paste0(ifelse(sparsehc$ws == 0, "",
                                 ifelse(
                                   sparsehc$ws <= 0.1,
                                   "* ",
                                   ifelse(sparsehc$ws <= 0.5, "** ", "*** ")
                                 )),  colnames(dm.t))
    
    loc.colcol   = ifelse(sparsehc$ws == 0,
                          "black",
                          ifelse(
                            sparsehc$ws <= 0.1,
                            "blue",
                            ifelse(sparsehc$ws <= 0.5, "green", "red")
                          ))
    
    
    loc.p = heatmap.2(
      dm.t,
      Colv = "NA",
      Rowv = var.tmp,
      srtCol = 90,
      dendrogram = ifelse(input$selectPlotHierSparDend == 1, "row", 'none'),
      trace = "none",
      key = input$selectPlotHierSparKey,
      margins = c(
        input$inPlotHierSparMarginX,
        input$inPlotHierSparMarginY
      ),
      col = my_palette,
      na.col = grey(input$inPlotHierSparNAcolor),
      denscol = "black",
      density.info = "density",
      RowSideColors = col_labels,
      colRow = col_labels,
      colCol = loc.colcol,
      labCol = loc.colnames,
#      sepcolor = grey(input$inPlotHierSparGridColor),
#      colsep = 1:ncol(dm.t),
#      rowsep = 1:nrow(dm.t),
      cexRow = input$inPlotHierSparFontX,
      cexCol = input$inPlotHierSparFontY,
      main = paste("Linkage method: ", s.cl.spar.linkage[as.numeric(input$selectPlotHierSparLinkage)])
    )
    
    return(loc.p)
  }
  
  
  plotHierSparTraj <- function(){
    cat(file = stderr(), 'plotHierSparTraj: in\n')

    loc.dt = isolate(data4trajPlot())
    
    cat("plotHierSparTraj: on to plot\n\n")
    if (is.null(loc.dt)) {
      cat(file = stderr(), 'plotHierSparTraj: dt is NULL\n')
      return(NULL)
    }
    
    cat(file = stderr(), 'plotHierSparTraj: dt not NULL\n')
    
    # get cellIDs with cluster assignments based on dendrogram cut
dmattek's avatar
dmattek committed
1271
    loc.dt.cl = getDataCl(userFitDendHierSpar(), isolate(input$inPlotHierSparNclust), getDataTrackObjLabUni_afterTrim())
dmattek's avatar
dmattek committed
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
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
1378
1379
1380
1381
1382
1383
    loc.dt = merge(loc.dt, loc.dt.cl, by = 'id')
    
    # plot only selected clusters
    if(isolate(input$chBPlotHierSparClSel))
      loc.dt = loc.dt[cl %in% isolate(input$inPlotHierSparClSel)]
    
    
    # Future: change such that a column with colouring status is chosen by the user
    # 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
    
    p.out = myGgplotTraj(
      dt.arg = loc.dt,
      x.arg = 'realtime',
      y.arg = 'y',
      group.arg = "id",
      facet.arg = 'cl',
      facet.ncol.arg = input$inPlotTrajFacetNcol,
      xlab.arg = 'Time (min)',
      line.col.arg = loc.line.col.arg
    )
    
    return(p.out)
  }
  
  
  # Barplot with distribution of clusters across conditions
  plotHierSparClDist = function() {
    cat(file = stderr(), 'plotHierSparClDist: in\n')
    
    # get cell IDs with cluster assignments depending on dendrogram cut
    sparsehc <- isolate(userFitHierSpar())
    if (is.null(sparsehc)) {
      cat(file = stderr(), 'plotHierSparClDist: sparsehc is NULL\n')
      return(NULL)
    }
    
    loc.dt.cl = data.table(id = getDataTrackObjLabUni_afterTrim(),
                           cl = cutree(as.dendrogram(sparsehc$hc), k = input$inPlotHierSparNclust))
    
    
    loc.dt.gr = isolate(getDataCond())
    if (is.null(loc.dt.gr)) {
      cat(file = stderr(), 'plotHierSparClDist: loc.dt.gr is NULL\n')
      return(NULL)
    }
    
    loc.dt = merge(loc.dt.cl, loc.dt.gr, by = 'id')
    
    # plot only selected clusters
    if(isolate(input$chBPlotHierSparClSel))
      loc.dt = loc.dt[cl %in% isolate(input$inPlotHierSparClSel)]
    
    loc.dt.aggr = loc.dt[, .(nCells = .N), by = .(group, cl)]
    
    p.out = ggplot(loc.dt.aggr, aes(x = group, y = nCells)) +
      geom_bar(aes(fill = as.factor(cl)), stat = 'identity', position = 'fill') +
      scale_y_continuous(labels = percent) +
      ylab("percentage of cells\n") +  
      xlab("") +  
      scale_fill_discrete(name = "Cluster no.") +
      myGgplotTheme
    
    return(p.out)
    
  }

  # Sparse Hierarchical - display heatmap
  output$outPlotHierSpar <- renderPlot({
    locBut = input$butPlotHierSparHeatMap
    
    if (locBut == 0) {
      cat(file = stderr(), 'outPlotHierSpar: Go button not pressed\n')
      
      return(NULL)
    }
    
    plotHierSpar()
  }, height = getPlotHierSparHeatMapHeight)
  
  # Sparse Hierarchical - display timecourses plot
  output$outPlotHierSparTraj <- renderPlot({
    locBut = input$butPlotHierSparTraj
    
    if (locBut == 0) {
      cat(file = stderr(), 'outPlotHierSparTraj: Go button not pressed\n')
      
      return(NULL)
    }
    
    plotHierSparTraj()
  })
  
  # Sparse Hierarchical - display timecourses plot
  output$outPlotHierSparClDist <- renderPlot({
    locBut = input$butPlotHierSparClDist
    
    if (locBut == 0) {
      cat(file = stderr(), 'outPlotHierSparClDist: Go button not pressed\n')
      
      return(NULL)
    }
    
    plotHierSparClDist()
  })
  
  
  # Sparse Hierarchical - Heat Map - download pdf
dmattek's avatar
dmattek committed
1384
1385
1386
1387
  callModule(downPlot, "downPlotHierSparHM",       paste0('clust_hierchSparse_heatMap_',
                                                    s.cl.spar.diss[as.numeric(input$selectPlotHierSparDiss)],
                                                    '_',
                                                    s.cl.spar.linkage[as.numeric(input$selectPlotHierSparLinkage)], '.pdf'), plotHierSpar)
dmattek's avatar
dmattek committed
1388
1389
  
  # Sparse Hierarchical - Trajectories - download pdf
dmattek's avatar
dmattek committed
1390
1391
1392
1393
  callModule(downPlot, "downPlotHierSparTraj",       paste0('clust_hierchSparse_tCourses_',
                                                        s.cl.spar.diss[as.numeric(input$selectPlotHierSparDiss)],
                                                        '_',
                                                        s.cl.spar.linkage[as.numeric(input$selectPlotHierSparLinkage)], '.pdf'), plotHierSparTraj, TRUE)
dmattek's avatar
dmattek committed
1394
  
dmattek's avatar
dmattek committed
1395
1396
1397
1398
1399
  # Sparse Hierarchical - Bar Plot - download pdf
  callModule(downPlot, "downPlotHierSparClDist",       paste0('clust_hierchSparse_clDist_',
                                                          s.cl.spar.diss[as.numeric(input$selectPlotHierSparDiss)],
                                                          '_',
                                                          s.cl.spar.linkage[as.numeric(input$selectPlotHierSparLinkage)], '.pdf'), plotHierSparClDist, TRUE)
dmattek's avatar
dmattek committed
1400
  
dmattek's avatar
dmattek committed
1401

dmattek's avatar
dmattek committed
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
  # Sparse Hierarchical clustering (sparcl) interactive version
  output$plotHierSparInt <- renderD3heatmap({
    dm.t = data4clust()
    if (is.null(dm.t)) {
      return()
    }
    
    sparsehc <- userFitHierSpar()
    
    dend <- as.dendrogram(sparsehc$hc)
    dend <- color_branches(dend, k = input$inPlotHierSparNclust)
    
    if (input$inPlotHierSparRevPalette)
      my_palette <-
      rev(colorRampPalette(brewer.pal(9, input$selectPlotHierSparPalette))(n = 99))
    else
      my_palette <-
      colorRampPalette(brewer.pal(9, input$selectPlotHierSparPalette))(n = 99)
    
    
    col_labels <- get_leaves_branches_col(dend)
    col_labels <- col_labels[order(order.dendrogram(dend))]
    
    if (input$selectPlotHierSparDend == 1)
      assign("var.tmp", dend)
    else
      assign("var.tmp", FALSE)
    
    
    loc.colnames = paste0(colnames(dm.t), ifelse(sparsehc$ws == 0, "",
                                                 ifelse(
                                                   sparsehc$ws <= 0.1,
                                                   " *",
                                                   ifelse(sparsehc$ws <= 0.5, " **", " ***")
                                                 )))
    
    d3heatmap(
      dm.t,
      Rowv = var.tmp,
      dendrogram = ifelse(input$selectPlotHierSparDend == 1, "row", 'none'),
      trace = "none",
      revC = FALSE,
      na.rm = FALSE,
      margins = c(
        input$inPlotHierSparMarginX * 10,
        input$inPlotHierSparMarginY * 10
      ),
      colors = my_palette,
      na.col = grey(input$inPlotHierSparNAcolor),
      cexRow = input$inPlotHierSparFontY,
      cexCol = input$inPlotHierSparFontX,
      xaxis_height = input$inPlotHierSparMarginX * 10,
      yaxis_width = input$inPlotHierSparMarginY * 10,
      show_grid = TRUE,
      #labRow = rownames(dm.t),
      labCol = loc.colnames
    )
  })
1460
1461
1462

  callModule(clustBay, 'TabClustBay', data4clust)
  
dmattek's avatar
dmattek committed
1463
})