server.R 24.6 KB
Newer Older
dmattek's avatar
dmattek committed
1
#
dmattek's avatar
dmattek committed
2
3
4
5
# Time Course Inspector: Shiny app for plotting time series data
# Author: Maciej Dobrzynski
#
# This is the server logic for a Shiny web application.
dmattek's avatar
dmattek committed
6
7
8
9
10
11
#

library(shiny)
library(shinyjs) #http://deanattali.com/shinyjs/
library(data.table)
library(ggplot2)
dmattek's avatar
dmattek committed
12
library(gplots) # for heatmap.2
dmattek's avatar
dmattek committed
13
library(plotly)
dmattek's avatar
dmattek committed
14
15
library(d3heatmap) # for interactive heatmap
library(dendextend) # for color_branches
16
library(colorspace) # for palettes (used to colour dendrogram)
dmattek's avatar
dmattek committed
17
library(RColorBrewer)
dmattek's avatar
dmattek committed
18
library(sparcl) # sparse hierarchical and k-means
dmattek's avatar
dmattek committed
19
library(scales) # for percentages on y scale
dmattek's avatar
Added:    
dmattek committed
20
21
library(dtw) # for dynamic time warping
library(imputeTS) # for interpolating NAs
dmattek's avatar
dmattek committed
22

23
# Global parameters ----
dmattek's avatar
dmattek committed
24
# change to increase the limit of the upload file size
dmattek's avatar
Added:    
dmattek committed
25
options(shiny.maxRequestSize = 200 * 1024 ^ 2)
dmattek's avatar
dmattek committed
26

dmattek's avatar
dmattek committed
27
# Server logic ----
dmattek's avatar
dmattek committed
28
shinyServer(function(input, output, session) {
29
  useShinyjs()
dmattek's avatar
dmattek committed
30
  
31
  # This is only set at session start
dmattek's avatar
dmattek committed
32
  # We use this as a way to determine which input was
33
34
  # clicked in the dataInBoth reactive
  counter <- reactiveValues(
dmattek's avatar
dmattek committed
35
36
37
    # The value of actionButton is the number of times the button is pressed
    dataGen1        = isolate(input$inDataGen1),
    dataLoadNuc     = isolate(input$inButLoadNuc),
38
39
    dataLoadTrajRem = isolate(input$inButLoadTrajRem),
    dataLoadStim    = isolate(input$inButLoadStim)
dmattek's avatar
dmattek committed
40
  )
dmattek's avatar
dmattek committed
41
42
43
44
45
46
47
48
49

  nCellsCounter <- reactiveValues(
    nCellsOrig = 0,
    nCellsAfterOutlierTrim = 0
  )
    
  myReactVals = reactiveValues(
    outlierIDs = NULL
  )
dmattek's avatar
dmattek committed
50
  
dmattek's avatar
dmattek committed
51
  # UI-side-panel-data-load ----
dmattek's avatar
dmattek committed
52
  
dmattek's avatar
dmattek committed
53
  # Generate random dataset
54
  dataGen1 <- eventReactive(input$inDataGen1, {
55
56
    if (DEB)
      cat("dataGen1\n")
57
    
dmattek's avatar
dmattek committed
58
    return(LOCgenTraj(in.nwells = 3, in.addout = 3))
59
60
  })
  
dmattek's avatar
dmattek committed
61
  # Load main data file
62
  dataLoadNuc <- eventReactive(input$inButLoadNuc, {
63
64
65
    if (DEB)
      cat("dataLoadNuc\n")

66
67
68
69
70
71
72
73
74
75
76
    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
77
78
79
80
  # This button will reset the inFileLoad
  observeEvent(input$butReset, {
    reset("inFileLoadNuc")  # reset is a shinyjs function
  })
81

dmattek's avatar
dmattek committed
82
  # Load data with trajectories to remove
83
  dataLoadTrajRem <- eventReactive(input$inButLoadTrajRem, {
84
85
86
    if (DEB)
      cat(file = stdout(), "dataLoadTrajRem\n")
    
87
88
89
90
91
92
93
94
95
96
    locFilePath = input$inFileLoadTrajRem$datapath
    
    counter$dataLoadTrajRem <- input$inButLoadTrajRem - 1
    
    if (is.null(locFilePath) || locFilePath == '')
      return(NULL)
    else {
      return(fread(locFilePath))
    }
  })
dmattek's avatar
dmattek committed
97
  
dmattek's avatar
dmattek committed
98
  # Load data with stimulation pattern
99
  dataLoadStim <- eventReactive(input$inButLoadStim, {
100
101
102
    if (DEB)
      cat(file = stdout(), "dataLoadStim\n")
    
103
104
105
106
107
108
109
110
111
112
113
114
    locFilePath = input$inFileLoadStim$datapath
    
    counter$dataLoadStim <- input$inButLoadStim - 1
    
    if (is.null(locFilePath) || locFilePath == '')
      return(NULL)
    else {
      return(fread(locFilePath))
    }
  })
  
    
dmattek's avatar
Added:    
dmattek committed
115
116
  # UI for loading csv with cell IDs for trajectory removal
  output$uiFileLoadTrajRem = renderUI({
117
118
    if (DEB)
      cat(file = stdout(), 'UI uiFileLoadTrajRem\n')
dmattek's avatar
Added:    
dmattek committed
119
120
121
122
123
124
125
126
127
128
    
    if(input$chBtrajRem) 
      fileInput(
        'inFileLoadTrajRem',
        'Select data file (e.g. badTraj.csv) and press "Load Data"',
        accept = c('text/csv', 'text/comma-separated-values,text/plain')
      )
  })
  
  output$uiButLoadTrajRem = renderUI({
129
130
    if (DEB)
      cat(file = stdout(), 'UI uiButLoadTrajRem\n')
dmattek's avatar
Added:    
dmattek committed
131
132
133
134
135
    
    if(input$chBtrajRem)
      actionButton("inButLoadTrajRem", "Load Data")
  })

136
137
  # UI for loading csv with stimulation pattern
  output$uiFileLoadStim = renderUI({
138
139
    if (DEB)
      cat(file = stdout(), 'UI uiFileLoadStim\n')
dmattek's avatar
Added:    
dmattek committed
140
    
141
142
143
144
145
146
147
148
149
    if(input$chBstim) 
      fileInput(
        'inFileLoadStim',
        'Select data file (e.g. stim.csv) and press "Load Data"',
        accept = c('text/csv', 'text/comma-separated-values,text/plain')
      )
  })
  
  output$uiButLoadStim = renderUI({
150
151
    if (DEB)
      cat(file = stdout(), 'UI uiButLoadStim\n')
dmattek's avatar
Added:    
dmattek committed
152
    
153
154
    if(input$chBstim)
      actionButton("inButLoadStim", "Load Data")
dmattek's avatar
Added:    
dmattek committed
155
156
  })
  
157

dmattek's avatar
dmattek committed
158
  
dmattek's avatar
dmattek committed
159
  # UI-side-panel-column-selection ----
dmattek's avatar
dmattek committed
160
  output$varSelTrackLabel = renderUI({
161
162
163
    if (DEB)
      cat(file = stdout(), 'UI varSelTrackLabel\n')
    
dmattek's avatar
dmattek committed
164
    locCols = getDataNucCols()
165
    locColSel = locCols[grep('(T|t)rack|ID|id', locCols)[1]] # index 1 at the end in case more matches; select 1st; matches TrackLabel, tracklabel, Track Label etc
dmattek's avatar
dmattek committed
166
167
168
    
    selectInput(
      'inSelTrackLabel',
169
      'Select Track Label:',
dmattek's avatar
dmattek committed
170
171
172
173
174
175
176
      locCols,
      width = '100%',
      selected = locColSel
    )
  })
  
  output$varSelTime = renderUI({
177
178
179
    if (DEB)
      cat(file = stdout(), 'UI varSelTime\n')
    
dmattek's avatar
dmattek committed
180
    locCols = getDataNucCols()
181
    locColSel = locCols[grep('(T|t)ime|Metadata_T', locCols)[1]] # index 1 at the end in case more matches; select 1st; matches RealTime, realtime, real time, etc.
dmattek's avatar
dmattek committed
182
183
184
    
    selectInput(
      'inSelTime',
dmattek's avatar
dmattek committed
185
      'Select time column (e.g. Metadata_T, RealTime):',
dmattek's avatar
dmattek committed
186
187
188
189
190
      locCols,
      width = '100%',
      selected = locColSel
    )
  })
191
192

  output$varSelTimeFreq = renderUI({
193
194
    if (DEB)
      cat(file = stdout(), 'UI varSelTimeFreq\n')
195
    
196
197
198
199
200
201
202
203
204
205
    if (input$chBtrajInter) {
      numericInput(
        'inSelTimeFreq',
        'Provide time frequency:',
        min = 1,
        step = 1,
        width = '100%',
        value = 1
      )
    }
206
  })
dmattek's avatar
dmattek committed
207
  
dmattek's avatar
dmattek committed
208
  # This is the main field to select plot facet grouping
dmattek's avatar
dmattek committed
209
  # It's typically a column with the entire experimental description,
dmattek's avatar
dmattek committed
210
211
  # e.g.1 Stim_All_Ch or Stim_All_S.
  # e.g.2 a combination of 3 columns called Stimulation_...
dmattek's avatar
dmattek committed
212
  output$varSelGroup = renderUI({
213
214
    if (DEB)
      cat(file = stdout(), 'UI varSelGroup\n')
dmattek's avatar
dmattek committed
215
    
dmattek's avatar
dmattek committed
216
217
218
219
220
    if (input$chBgroup) {
      
      locCols = getDataNucCols()
      
      if (!is.null(locCols)) {
221
        locColSel = locCols[grep('(G|g)roup|(S|s)tim|(S|s)timulation|(S|s)ite', locCols)[1]]
222
223

        #cat('UI varSelGroup::locColSel ', locColSel, '\n')
dmattek's avatar
dmattek committed
224
225
        selectInput(
          'inSelGroup',
226
          'Select columns for plot grouping:',
dmattek's avatar
dmattek committed
227
228
229
230
231
          locCols,
          width = '100%',
          selected = locColSel,
          multiple = TRUE
        )
dmattek's avatar
dmattek committed
232
233
234
235
      }
    }
  })
  
236
237
  # UI for selecting grouping to add to track ID to make 
  # the track ID unique across entire dataset
dmattek's avatar
dmattek committed
238
  output$varSelSite = renderUI({
239
240
    if (DEB)
      cat(file = stdout(), 'UI varSelSite\n')
dmattek's avatar
dmattek committed
241
    
242
    if (input$chBtrackUni) {
dmattek's avatar
Added:    
dmattek committed
243
      locCols = getDataNucCols()
244
      locColSel = locCols[grep('(S|s)ite|(S|s)eries|(F|f)ov', locCols)[1]] # index 1 at the end in case more matches; select 1st
dmattek's avatar
Added:    
dmattek committed
245
246
247
      
      selectInput(
        'inSelSite',
248
        'Select grouping columns to add to track label:',
dmattek's avatar
Added:    
dmattek committed
249
250
        locCols,
        width = '100%',
251
252
        selected = locColSel,
        multiple = T
dmattek's avatar
Added:    
dmattek committed
253
254
      )
    }
dmattek's avatar
dmattek committed
255
256
257
258
  })
  
  
  output$varSelMeas1 = renderUI({
259
260
    if (DEB)
      cat(file = stdout(), 'UI varSelMeas1\n')
dmattek's avatar
dmattek committed
261
262
263
    locCols = getDataNucCols()
    
    if (!is.null(locCols)) {
264
      locColSel = locCols[grep('(R|r)atio|(I|i)ntensity|y|Meas', locCols)[1]] # index 1 at the end in case more matches; select 1st
dmattek's avatar
dmattek committed
265

dmattek's avatar
dmattek committed
266
267
268
269
270
271
272
273
274
275
276
277
      selectInput(
        'inSelMeas1',
        'Select 1st measurement:',
        locCols,
        width = '100%',
        selected = locColSel
      )
    }
  })
  
  
  output$varSelMeas2 = renderUI({
278
279
280
    if (DEB)
      cat(file = stdout(), 'UI varSelMeas2\n')
    
dmattek's avatar
dmattek committed
281
282
283
284
    locCols = getDataNucCols()
    
    if (!is.null(locCols) &&
        !(input$inSelMath %in% c('', '1 / '))) {
285
      locColSel = locCols[grep('(R|r)atio|(I|i)ntensity|y|Meas', locCols)[1]] # index 1 at the end in case more matches; select 1st
dmattek's avatar
dmattek committed
286

dmattek's avatar
dmattek committed
287
288
289
290
291
292
293
294
295
296
      selectInput(
        'inSelMeas2',
        'Select 2nd measurement',
        locCols,
        width = '100%',
        selected = locColSel
      )
    }
  })
  
dmattek's avatar
dmattek committed
297
  # UI-side-panel-trim x-axis (time) ----
dmattek's avatar
dmattek committed
298
  output$uiSlTimeTrim = renderUI({
299
300
    if (DEB)
      cat(file = stdout(), 'UI uiSlTimeTrim\n')
dmattek's avatar
dmattek committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
    
    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
322
  
dmattek's avatar
dmattek committed
323
  # UI-side-panel-normalization ----
dmattek's avatar
dmattek committed
324
  output$uiChBnorm = renderUI({
325
326
    if (DEB)
      cat(file = stdout(), 'UI uiChBnorm\n')
dmattek's avatar
dmattek committed
327
328
329
330
331
332
333
334
335
336
337
    
    if (input$chBnorm) {
      radioButtons(
        'rBnormMeth',
        label = 'Select method',
        choices = list('fold-change' = 'mean', 'z-score' = 'z.score')
      )
    }
  })
  
  output$uiSlNorm = renderUI({
338
339
    if (DEB)
      cat(file = stdout(), 'UI uiSlNorm\n')
dmattek's avatar
dmattek committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    
    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
355
356
        value = c(locRTmin, 0.1 * locRTmax), 
        step = 1
dmattek's avatar
dmattek committed
357
358
359
360
361
      )
    }
  })
  
  output$uiChBnormRobust = renderUI({
362
363
    if (DEB)
      cat(file = stdout(), 'UI uiChBnormRobust\n')
dmattek's avatar
dmattek committed
364
365
366
367
368
369
370
371
372
    
    if (input$chBnorm) {
      checkboxInput('chBnormRobust',
                    label = 'Robust stats',
                    FALSE)
    }
  })
  
  output$uiChBnormGroup = renderUI({
373
374
    if (DEB)
      cat(file = stdout(), 'UI uiChBnormGroup\n')
dmattek's avatar
dmattek committed
375
376
377
    
    if (input$chBnorm) {
      radioButtons('chBnormGroup',
dmattek's avatar
Mod:    
dmattek committed
378
                   label = 'Normalisation grouping',
379
                   choices = list('Entire dataset' = 'none', 'Per facet' = 'group', 'Per trajectory' = 'id'))
dmattek's avatar
dmattek committed
380
381
382
383
    }
  })
  
  
dmattek's avatar
dmattek committed
384
  
dmattek's avatar
dmattek committed
385

dmattek's avatar
dmattek committed
386
  # Processing-data ----
dmattek's avatar
dmattek committed
387
  
388
389
390
391
392
393
394
395
396
397
398
399
  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
    
400
    # Don't wrap around if(DEB)
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
    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
437
  getDataNucCols <- reactive({
438
439
440
    if (DEB)
      cat(file = stdout(), 'getDataNucCols: in\n')
    
441
442
443
444
445
446
447
448
449
450
    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({
451
452
453
    if (DEB)
      cat(file = stdout(), 'dataMod\n')
    
454
455
    loc.dt = dataInBoth()
    
dmattek's avatar
dmattek committed
456
    if (is.null(loc.dt))
457
458
      return(NULL)
    
459
    if (input$chBtrackUni) {
460
      # create unique track ID based on columns specified in input$inSelSite field and combine with input$inSelTrackLabel
461
      loc.dt[, (COLIDUNI) := do.call(paste, c(.SD, sep = "_")), .SDcols = c(input$inSelSite, input$inSelTrackLabel) ]
dmattek's avatar
Added:    
dmattek committed
462
    } else {
463
      # stay with track ID provided in the loaded dataset; has to be unique
464
      loc.dt[, (COLIDUNI) := get(input$inSelTrackLabel)]
dmattek's avatar
Added:    
dmattek committed
465
466
    }
    
dmattek's avatar
dmattek committed
467
    
dmattek's avatar
Added:    
dmattek committed
468
469
470
    # remove trajectories based on uploaded csv

    if (input$chBtrajRem) {
471
472
      if (DEB)
        cat(file = stdout(), 'dataMod: trajRem not NULL\n')
dmattek's avatar
Added:    
dmattek committed
473
474
      
      loc.dt.rem = dataLoadTrajRem()
dmattek's avatar
dmattek committed
475
      loc.dt = loc.dt[!(trackObjectsLabelUni %in% loc.dt.rem[[1]])]
dmattek's avatar
Added:    
dmattek committed
476
477
    }
    
478
479
480
    return(loc.dt)
  })
  
dmattek's avatar
dmattek committed
481
482
483
  # return all unique track object labels (created in dataMod)
  # This will be used to display in UI for trajectory highlighting
  getDataTrackObjLabUni <- reactive({
484
485
486
    if (DEB)
      cat(file = stdout(), 'getDataTrackObjLabUni\n')
    
dmattek's avatar
dmattek committed
487
    loc.dt = dataMod()
488
    
dmattek's avatar
dmattek committed
489
490
491
492
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt$trackObjectsLabelUni))
493
494
  })
  
dmattek's avatar
Mod:    
dmattek committed
495
  
dmattek's avatar
dmattek committed
496
497
498
  # 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
499
  getDataTpts <- reactive({
500
501
502
    if (DEB)
      cat(file = stdout(), 'getDataTpts\n')
    
dmattek's avatar
dmattek committed
503
    loc.dt = dataMod()
504
    
dmattek's avatar
dmattek committed
505
506
507
508
    if (is.null(loc.dt))
      return(NULL)
    else
      return(unique(loc.dt[[input$inSelTime]]))
509
510
  })
  
dmattek's avatar
dmattek committed
511
  
512
513
514
  
  # prepare data for plotting time courses
  # returns dt with these columns:
dmattek's avatar
dmattek committed
515
  #    realtime - selected from input
dmattek's avatar
dmattek committed
516
  #    y        - measurement selected from input
dmattek's avatar
dmattek committed
517
  #               (can be a single column or result of an operation on two cols)
518
519
  #    id       - trackObjectsLabelUni; created in dataMod based on TrackObjects_Label
  #               and FOV column such as Series or Site (if TrackObjects_Label not unique across entire dataset)
dmattek's avatar
dmattek committed
520
521
  #    group    - grouping variable for facetting from input
  #    mid.in   - column with trajectory selection status from the input file or
522
523
524
525
  #               highlight status from UI 
  #               (column created if mid.in present in uploaded data or tracks are selected in the UI)
  #    obj.num  - created if ObjectNumber column present in the input data 
  #    pos.x,y  - created if columns with x and y positions present in the input data
526
  data4trajPlot <- reactive({
527
528
    if (DEB)
      cat(file = stdout(), 'data4trajPlot\n')
529
530
    
    loc.dt = dataMod()
dmattek's avatar
dmattek committed
531
    if (is.null(loc.dt))
532
533
      return(NULL)
    
534
    # create expression for 'y' column based on measurements and math operations selected in UI
dmattek's avatar
dmattek committed
535
    if (input$inSelMath == '')
536
537
538
539
540
541
      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)
    
542
    # create expression for 'group' column
543
544
    # creates a merged column based on other columns from input
    # used for grouping of plot facets
dmattek's avatar
dmattek committed
545
546
547
548
549
550
551
552
553
554
555
    if (input$chBgroup) {
      if(length(input$inSelGroup) == 0)
        return(NULL)
      
      loc.s.gr = sprintf("paste(%s, sep=';')",
                         paste(input$inSelGroup, sep = '', collapse = ','))
    } else {
      # if no grouping required, fill 'group' column with 0
      # because all the plotting relies on the presence of the group column
      loc.s.gr = "paste('0')"
    }
556
    
dmattek's avatar
dmattek committed
557
558

    # column name with time
559
560
    loc.s.rt = input$inSelTime
    
dmattek's avatar
dmattek committed
561
562
    # Assign tracks selected for highlighting in UI
    loc.tracks.highlight = input$inSelHighlight
563
    locButHighlight = input$chBhighlightTraj
dmattek's avatar
dmattek committed
564
    
dmattek's avatar
Added:    
dmattek committed
565
566
    
    # Find column names with position
567
    loc.s.pos.x = names(loc.dt)[grep('(L|l)ocation.*X|(P|p)os.x|(P|p)osx', names(loc.dt))[1]]
568
    loc.s.pos.y = names(loc.dt)[grep('(L|l)ocation.*Y|(P|p)os.y|(P|p)osy', names(loc.dt))[1]]
dmattek's avatar
Added:    
dmattek committed
569
    
570
571
    if (DEB)
      cat('Position columns: ', loc.s.pos.x, loc.s.pos.y, '\n')
572
573
    
    if (!is.na(loc.s.pos.x) & !is.na(loc.s.pos.y))
dmattek's avatar
Added:    
dmattek committed
574
575
576
577
      locPos = TRUE
    else
      locPos = FALSE
    
578
579
580
581
    
    # Find column names with ObjectNumber
    # This is different from TrackObject_Label and is handy to keep
    # because labels on segmented images are typically ObjectNumber
582
583
584
585
586
587
    loc.s.objnum = names(loc.dt)[grep('(O|o)bject(N|n)umber', names(loc.dt))[1]]
    #cat('data4trajPlot::loc.s.objnum ', loc.s.objnum, '\n')
    if (is.na(loc.s.objnum)) {
      locObjNum = FALSE
    }
    else {
dmattek's avatar
dmattek committed
588
      loc.s.objnum = loc.s.objnum[1]
589
      locObjNum = TRUE
dmattek's avatar
dmattek committed
590
    }
591
592
    
    
593
594
    # if dataset contains column mid.in with trajectory filtering status,
    # then, include it in plotting
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
    if (sum(names(loc.dt) %in% 'mid.in') > 0)
      locMidIn = TRUE
    else
      locMidIn = FALSE
    
    ## Build expression for selecting columns from loc.dt
    # Core columns
    s.colexpr = paste0('.(y = ', loc.s.y,
                       ', id = trackObjectsLabelUni', 
                       ', group = ', loc.s.gr,
                       ', realtime = ', loc.s.rt)
    
    # account for the presence of 'mid.in' column in uploaded data
    if(locMidIn)
      s.colexpr = paste0(s.colexpr, 
                         ', mid.in = mid.in')
    
    # include position x,y columns in uploaded data
    if(locPos)
      s.colexpr = paste0(s.colexpr, 
                         ', pos.x = ', loc.s.pos.x,
                         ', pos.y = ', loc.s.pos.y)
    
    # include ObjectNumber column
    if(locObjNum)
      s.colexpr = paste0(s.colexpr, 
                         ', obj.num = ', loc.s.objnum)
    
    # close bracket, finish the expression
    s.colexpr = paste0(s.colexpr, ')')
    
    # create final dt for output based on columns selected above
    loc.out = loc.dt[, eval(parse(text = s.colexpr))]
    
    
    # if track selection ON
    if (locButHighlight){
      # add a 3rd level with status of track selection
      # to a column with trajectory filtering status in the uploaded file
      if(locMidIn)
        loc.out[, mid.in := ifelse(id %in% loc.tracks.highlight, 'SELECTED', mid.in)]
      else
dmattek's avatar
Mod:    
dmattek committed
637
        # add a column with status of track selection
638
        loc.out[, mid.in := ifelse(id %in% loc.tracks.highlight, 'SELECTED', 'NOT SEL')]
639
    }
640
      
dmattek's avatar
dmattek committed
641

642
    ## Interpolate missing data and NA data points
643
    # From: https://stackoverflow.com/questions/28073752/r-how-to-add-rows-for-missing-values-for-unique-group-sequences
644
    # Tracks are interpolated only within first and last time points of every track id
645
646
    # Datasets can have different realtime frequency (e.g. every 1', 2', etc),
    # or the frame number metadata can be missing, as is the case for tCourseSelected files that already have realtime column.
647
    # Therefore, we cannot rely on that info to get time frequency; user must provide this number!
648
    
649
    setkeyv(loc.out, c(COLGR, COLID, COLRT))
650

651
652
    if (input$chBtrajInter) {
      # here we fill missing data with NA's
dmattek's avatar
dmattek committed
653
      loc.out = loc.out[setkeyv(loc.out[, .(seq(min(get(COLRT), na.rm = T), max(get(COLRT), na.rm = T), input$inSelTimeFreq)), by = c(COLGR, COLID)], c(COLGR, COLID, 'V1'))]
654
655
      
      # x-check: print all rows with NA's
656
657
658
659
      if (DEB) {
        cat(file = stdout(), 'Rows with NAs:\n')
        print(loc.out[rowSums(is.na(loc.out)) > 0, ])
      }
660
661
662
663
      
      # NA's may be already present in the dataset'.
      # Interpolate (linear) them with na.interpolate as well
      if(locPos)
dmattek's avatar
dmattek committed
664
        s.cols = c(COLY, COLPOSX, COLPOSY)
665
      else
dmattek's avatar
dmattek committed
666
        s.cols = c(COLY)
667
      
668
669
670
671
672
673
674
675
676
677
678
679
      # Interpolated columns should be of type numeric (float)
      # This is to ensure that interpolated columns are of porper type.
      
      # Apparently the loop is faster than lapply+SDcols
      for(col in s.cols) {
        #loc.out[, (col) := as.numeric(get(col))]
        data.table::set(loc.out, j = col, value = as.numeric(loc.out[[col]]))

        loc.out[, (col) := na.interpolation(get(col)), by = c(COLID)]        
      }
      
      # loc.out[, (s.cols) := lapply(.SD, na.interpolation), by = c(COLID), .SDcols = s.cols]
680
681
682
683
684
685
686
687
688
689
690
691
692
693
      
      
      # !!! Current issue with interpolation:
      # The column mid.in is not taken into account.
      # If a trajectory is selected in the UI,
      # the mid.in column is added (if it doesn't already exist in the dataset),
      # and for the interpolated point, it will still be NA. Not really an issue.
      #
      # Also, think about the current option of having mid.in column in the uploaded dataset.
      # Keep it? Expand it?
      # Create a UI filed for selecting the column with mid.in data.
      # What to do with that column during interpolation (see above)
      
    }    
dmattek's avatar
Mod:    
dmattek committed
694
    
695
    ## Trim x-axis (time)
dmattek's avatar
dmattek committed
696
    if(input$chBtimeTrim) {
dmattek's avatar
dmattek committed
697
      loc.out = loc.out[get(COLRT) >= input$slTimeTrim[[1]] & get(COLRT) <= input$slTimeTrim[[2]] ]
dmattek's avatar
dmattek committed
698
    }
dmattek's avatar
dmattek committed
699
    
700
    ## Normalization
dmattek's avatar
dmattek committed
701
    # F-n normTraj adds additional column with .norm suffix
dmattek's avatar
dmattek committed
702
    if (input$chBnorm) {
dmattek's avatar
dmattek committed
703
      loc.out = LOCnormTraj(
dmattek's avatar
dmattek committed
704
        in.dt = loc.out,
dmattek's avatar
dmattek committed
705
706
        in.meas.col = COLY,
        in.rt.col = COLRT,
dmattek's avatar
dmattek committed
707
708
709
710
711
712
713
        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
714
715
      # Column with normalized data is renamed to the original name
      # Further code assumes column name y produced by data4trajPlot
dmattek's avatar
dmattek committed
716
717
      loc.out[, get(COLY) := NULL]
      setnames(loc.out, 'y.norm', COLY)
dmattek's avatar
dmattek committed
718
719
720
    }
    
    return(loc.out)
dmattek's avatar
dmattek committed
721
722
  })
  
dmattek's avatar
dmattek committed
723
724
725
726
727
728
  
  # prepare data for clustering
  # return a matrix with:
  # cells as columns
  # time points as rows
  data4clust <- reactive({
729
730
    if (DEB)  
      cat(file = stdout(), 'data4clust\n')
dmattek's avatar
dmattek committed
731
    
dmattek's avatar
dmattek committed
732
    loc.dt = data4trajPlotNoOut()
dmattek's avatar
dmattek committed
733
734
735
    if (is.null(loc.dt))
      return(NULL)
    
dmattek's avatar
Added:    
dmattek committed
736
    #print(loc.dt)
dmattek's avatar
dmattek committed
737
    loc.out = dcast(loc.dt, id ~ realtime, value.var = 'y')
dmattek's avatar
Added:    
dmattek committed
738
    #print(loc.out)
dmattek's avatar
dmattek committed
739
740
    loc.rownames = loc.out$id
    
dmattek's avatar
Mod:    
dmattek committed
741
    
dmattek's avatar
dmattek committed
742
743
    loc.out = as.matrix(loc.out[, -1])
    rownames(loc.out) = loc.rownames
dmattek's avatar
Added:    
dmattek committed
744
    
745
746
    # This might be removed entirely because all NA treatment happens in data4trajPlot
    # Clustering should work with NAs present. These might result from data itself or from missing time point rows that were turned into NAs when dcast-ing from long format.
dmattek's avatar
Added:    
dmattek committed
747
748
749
750
    # Remove NA's
    # na.interpolation from package imputeTS works with multidimensional data
    # but imputation is performed for each column independently
    # The matrix for clustering contains time series in rows, hence transposing it twice
751
    # loc.out = t(na.interpolation(t(loc.out)))
dmattek's avatar
Added:    
dmattek committed
752
    
dmattek's avatar
dmattek committed
753
    return(loc.out)
dmattek's avatar
Mod:    
dmattek committed
754
  }) 
dmattek's avatar
dmattek committed
755
  
dmattek's avatar
dmattek committed
756
  
757
758
759
  # prepare data with stimulation pattern
  # this dataset is displayed underneath of trajectory plot (modules/trajPlot.R) as geom_segment
  data4stimPlot <- reactive({
760
761
    if (DEB)  
      cat(file = stdout(), 'data4stimPlot\n')
762
763
    
    if (input$chBstim) {
764
765
      if (DEB)  
        cat(file = stdout(), 'data4stimPlot: stim not NULL\n')
766
767
768
769
      
      loc.dt.stim = dataLoadStim()
      return(loc.dt.stim)
    } else {
770
771
772
      if (DEB)  
        cat(file = stdout(), 'data4stimPlot: stim is NULL\n')
      
773
774
775
776
      return(NULL)
    }
  })
  
dmattek's avatar
Added:    
dmattek committed
777
778
779
  # download data as prepared for plotting
  # after all modification
  output$downloadDataClean <- downloadHandler(
dmattek's avatar
dmattek committed
780
    filename = FCSVTCCLEAN,
dmattek's avatar
Added:    
dmattek committed
781
    content = function(file) {
dmattek's avatar
dmattek committed
782
      write.csv(data4trajPlotNoOut(), file, row.names = FALSE)
dmattek's avatar
Added:    
dmattek committed
783
784
785
    }
  )
  
dmattek's avatar
dmattek committed
786
787
788
  # Plotting-trajectories ----

  # UI for selecting trajectories
789
  # The output data table of data4trajPlot is modified based on inSelHighlight field
dmattek's avatar
dmattek committed
790
  output$varSelHighlight = renderUI({
791
792
    if (DEB)  
      cat(file = stdout(), 'UI varSelHighlight\n')
dmattek's avatar
dmattek committed
793
    
dmattek's avatar
dmattek committed
794
795
796
    locBut = input$chBhighlightTraj
    if (!locBut)
      return(NULL)
dmattek's avatar
dmattek committed
797
    
dmattek's avatar
dmattek committed
798
    loc.v = getDataTrackObjLabUni()
dmattek's avatar
dmattek committed
799
    if (!is.null(loc.v)) {
800
      selectInput(
dmattek's avatar
dmattek committed
801
802
803
        'inSelHighlight',
        'Select one or more rajectories:',
        loc.v,
804
        width = '100%',
dmattek's avatar
dmattek committed
805
        multiple = TRUE
806
      )
dmattek's avatar
dmattek committed
807
808
809
    }
  })
  
dmattek's avatar
dmattek committed
810
811
812
  # Taking out outliers 
  data4trajPlotNoOut = callModule(modSelOutliers, 'returnOutlierIDs', data4trajPlot)
  
dmattek's avatar
dmattek committed
813
814
  # Trajectory plotting - ribbon
  callModule(modTrajRibbonPlot, 'modTrajRibbon', 
dmattek's avatar
dmattek committed
815
             in.data = data4trajPlotNoOut,
dmattek's avatar
dmattek committed
816
             in.data.stim = data4stimPlot,
dmattek's avatar
dmattek committed
817
             in.fname = function() return(FPDFTCMEAN))
dmattek's avatar
dmattek committed
818
  
dmattek's avatar
dmattek committed
819
  # Trajectory plotting - individual
dmattek's avatar
dmattek committed
820
  callModule(modTrajPlot, 'modTrajPlot', 
dmattek's avatar
dmattek committed
821
             in.data = data4trajPlotNoOut, 
dmattek's avatar
dmattek committed
822
             in.data.stim = data4stimPlot,
dmattek's avatar
dmattek committed
823
             in.fname = function() {return(FPDFTCSINGLE)})
dmattek's avatar
dmattek committed
824
825
826
  
  
  # Tabs ----
827
  ###### AUC calculation and plotting
dmattek's avatar
dmattek committed
828
  callModule(modAUCplot, 'tabAUC', data4trajPlotNoOut, in.fname = function() return(FPDFBOXAUC))
dmattek's avatar
Added:    
dmattek committed
829
  
dmattek's avatar
Added:    
dmattek committed
830
  ###### Box-plot
dmattek's avatar
dmattek committed
831
  callModule(tabBoxPlot, 'tabBoxPlot', data4trajPlotNoOut, in.fname = function() return(FPDFBOXTP))
dmattek's avatar
dmattek committed
832
  
dmattek's avatar
dmattek committed
833
  ###### Scatter plot
dmattek's avatar
dmattek committed
834
  callModule(tabScatterPlot, 'tabScatter', data4trajPlotNoOut, in.fname = function() return(FPDFSCATTER))
dmattek's avatar
dmattek committed
835
  
dmattek's avatar
dmattek committed
836
  ##### Hierarchical clustering
dmattek's avatar
dmattek committed
837
  callModule(clustHier, 'tabClHier', data4clust, data4trajPlotNoOut, data4stimPlot)
dmattek's avatar
dmattek committed
838
839
  
  ##### Sparse hierarchical clustering using sparcl
dmattek's avatar
dmattek committed
840
  callModule(clustHierSpar, 'tabClHierSpar', data4clust, data4trajPlotNoOut, data4stimPlot)
dmattek's avatar
dmattek committed
841

dmattek's avatar
Mod:    
dmattek committed
842
  
dmattek's avatar
dmattek committed
843
})