auxfunc.R 33.3 KB
Newer Older
dmattek's avatar
dmattek committed
1
2
3
4
#
# Time Course Inspector: Shiny app for plotting time series data
# Author: Maciej Dobrzynski
#
dmattek's avatar
dmattek committed
5
# Auxilary functions & definitions of global constants
dmattek's avatar
dmattek committed
6
7
8
#


Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
9
10
11
12
13
library(ggplot2)
library(RColorBrewer)
library(gplots) # for heatmap.2
library(grid) # for modifying grob
library(Hmisc) # for CI calculation
dmattek's avatar
dmattek committed
14

15
16

# Global parameters ----
17

dmattek's avatar
dmattek committed
18

19
20
21
# if true, additional output printed to R console
DEB = T

22
# font sizes in pts for plots in the manuscript
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
23
24
25
26
27
28
# PLOTFONTBASE = 8
# PLOTFONTAXISTEXT = 8
# PLOTFONTAXISTITLE = 8
# PLOTFONTFACETSTRIP = 10
# PLOTFONTLEGEND = 8

dmattek's avatar
dmattek committed
29
# font sizes in pts for screen display
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
30
31
32
33
34
35
36
37
38
39
40
41
42
PLOTFONTBASE = 16
PLOTFONTAXISTEXT = 16
PLOTFONTAXISTITLE = 16
PLOTFONTFACETSTRIP = 20
PLOTFONTLEGEND = 16

# height (in pixels) of ribbon and single traj. plots
PLOTRIBBONHEIGHT = 500 # in pixels
PLOTTRAJHEIGHT = 500 # in pixels
PLOTPSDHEIGHT = 500 # in pixels
PLOTBOXHEIGHT = 500 # in pixels
PLOTSCATTERHEIGHT = 500 # in pixels
PLOTWIDTH = 85 # in percent
43
44

# default number of facets in plots
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
45
PLOTNFACETDEFAULT = 3
46

dmattek's avatar
dmattek committed
47
# internal column names
dmattek's avatar
dmattek committed
48
COLRT   = 'time'
dmattek's avatar
dmattek committed
49
50
51
52
53
54
55
56
57
58
COLY    = 'y'
COLID   = 'id'
COLIDUNI = 'trackObjectsLabelUni'
COLGR   = 'group'
COLIN   = 'mid.in'
COLOBJN = 'obj.num'
COLPOSX = 'pos.x'
COLPOSY = 'pos.y'
COLIDX = 'IDX'
COLIDXDIFF = 'IDXdiff'
dmattek's avatar
dmattek committed
59
COLCL = 'cl'
dmattek's avatar
dmattek committed
60
61
62
63
64
65

# file names
FCSVOUTLIERS = 'outliers.csv'
FCSVTCCLEAN  = 'tCoursesSelected_clean.csv'
FPDFTCMEAN   = "tCoursesMeans.pdf"
FPDFTCSINGLE = "tCourses.pdf"
66
FPDFTCPSD    = 'tCoursesPsd.pdf'
dmattek's avatar
dmattek committed
67
68
69
70
FPDFBOXAUC   = 'boxplotAUC.pdf'
FPDFBOXTP    = 'boxplotTP.pdf'
FPDFSCATTER  = 'scatter.pdf'

dmattek's avatar
dmattek committed
71
# Colour definitions ----
dmattek's avatar
dmattek committed
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
rhg_cols <- c(
  "#771C19",
  "#AA3929",
  "#E25033",
  "#F27314",
  "#F8A31B",
  "#E2C59F",
  "#B6C5CC",
  "#8E9CA3",
  "#556670",
  "#000000"
)

md_cols <- c(
  "#FFFFFF",
  "#F8A31B",
  "#F27314",
  "#E25033",
  "#AA3929",
  "#FFFFCC",
  "#C2E699",
  "#78C679",
  "#238443"
)

97
# list of palettes for the heatmap
dmattek's avatar
dmattek committed
98
l.col.pal = list(
dmattek's avatar
dmattek committed
99
100
101
102
  "Spectral" = 'Spectral',
  "Red-Yellow-Green" = 'RdYlGn',
  "Red-Yellow-Blue" = 'RdYlBu',
  "Greys" = "Greys",
dmattek's avatar
dmattek committed
103
104
105
  "Reds" = "Reds",
  "Oranges" = "Oranges",
  "Greens" = "Greens",
dmattek's avatar
dmattek committed
106
  "Blues" = "Blues"
dmattek's avatar
dmattek committed
107
108
)

109
110
111
112
113
114
115
116
117
118
# list of palettes for the dendrogram
l.col.pal.dend = list(
  "Rainbow" = 'rainbow_hcl',
  "Sequential" = 'sequential_hcl',
  "Heat" = 'heat_hcl',
  "Terrain" = 'terrain_hcl',
  "Diverge HCL" = 'diverge_hcl',
  "Diverge HSV" = 'diverge_hsv'
)

dmattek's avatar
dmattek committed
119
120
121
122
123
124
125
126
127
128
129
# list of palettes for the dendrogram
l.col.pal.dend.2 = list(
  "Colorblind 10" = 'Color Blind',
  "Tableau 10" = 'Tableau 10',
  "Tableau 20" = 'Tableau 20',
  "Classic 10" = "Classic 10",
  "Classic 20" = "Classic 20",
  "Traffic 9" = 'Traffic',
  "Seattle Grays 5" = 'Seattle Grays'
)

dmattek's avatar
dmattek committed
130
131
# Clustering algorithms ----

dmattek's avatar
dmattek committed
132
s.cl.linkage = c("average",
dmattek's avatar
dmattek committed
133
                 "complete",
dmattek's avatar
dmattek committed
134
135
136
137
138
                 "single",
                 "centroid",
                 "ward.D",
                 "ward.D2",
                 "mcquitty")
dmattek's avatar
dmattek committed
139
140
141
142
143
144

s.cl.spar.linkage = c("average",
                      "complete", 
                      "single",
                      "centroid")

dmattek's avatar
dmattek committed
145
146
147
148
149
150
151
152
s.cl.diss = c("euclidean", 
              "maximum", 
              "manhattan", 
              "canberra", 
              "DTW")

s.cl.spar.diss = c("squared.distance",
                   "absolute.value")
dmattek's avatar
dmattek committed
153
154
155


# Help text ----
dmattek's avatar
Added:    
dmattek committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# Creates a popup with help text
# From: https://gist.github.com/jcheng5/5913297
helpPopup <- function(title, content,
                      placement=c('right', 'top', 'left', 'bottom'),
                      trigger=c('click', 'hover', 'focus', 'manual')) {
  tagList(
    singleton(
      tags$head(
        tags$script("$(function() { $(\"[data-toggle='popover']\").popover(); })")
      )
    ),
    tags$a(
      href = "#", class = "btn btn-mini", `data-toggle` = "popover",
      title = title, `data-content` = content, `data-animation` = TRUE,
      `data-placement` = match.arg(placement, several.ok=TRUE)[1],
      `data-trigger` = match.arg(trigger, several.ok=TRUE)[1],
      #tags$i(class="icon-question-sign")
      # changed based on http://stackoverflow.com/questions/30436013/info-bubble-text-in-a-shiny-interface
      icon("question")
    )
  )
}

179
help.text.short = c(
dmattek's avatar
dmattek committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
  'Load CSV file with a column of track IDs for removal. IDs should correspond to those used for plotting.',                       #1
  'If the track ID is unique only within a group, make it unique globally by combining with the grouping column.',                 #2
  'Interpolate missing time points and pre-existing NAs. The interval of the time column must be provided!',                       #3
  'Load CSV file with 5 columns: grouping, start and end tpts of stimulation, start and end of y-position, dummy column with ID.', #4
  'Select columns to group data according to treatment, condition, etc.',                                                          #5
  'Select math operation to perform on a single or two columns,',                                                                  #6
  'Select range of time for further processing.',                                                                                  #7
  'Divide measurments by the mean/median or calculate z-score with respect to selected time span.',                                #8
  'Download time series after modification in this section.',                                                                      #9
  'Long format: a row is a single data point. Wide format: a row is a time series with columns as time points.',                   #10
  'Fold-change or z-score with respect to selected time span.',                                                                    #11
  'Normalise with respect to this time span.',                                                                                     #12
  'Calculate fold-change and z-score using the median and Median Absolute Deviation, instead of the mean and sd.',                 #13
  'Normalise to mean/median of selected time calculated globally, per group, or for individual time series.',                      #14
  'Instead of the value at a selected time point, y-axis can display a difference between values at time points on y- and x-axis.',#15
  'Add a line with linear regression and regions of 95% confidence interval.',                                                     #16
  'A number of time points left & right of selected time points; use the mean/min/max of values from these time points for the scatterplot.', #17
  'Operations to perform on values at time points selected in the field above.'                                                    #18
198
199
)

dmattek's avatar
dmattek committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# Functions for data processing ----
#' Calculate the mean and CI around time series
#'
#' @param in.dt Data table in long format
#' @param in.col.meas Name of the column with the measurement
#' @param in.col.by Column names for grouping (default NULL - no grouping). Typically, you want to use at least a column with time.
#' @param in.type Choice of normal approximation or boot-strapping
#' @param ... Other params passed to smean.cl.normal and smean.cl.boot; these include \code{conf.int} for the confidence level, \code{B} for the number of boot-strapping iterations.
#'
#' @return Datatable with columns: Mean, lower and upper CI, and grouping columns if provided.
#' @export
#' @import data.table
#' @import Hmisc
#'
#' @examples
#'
#'
#' # generate synthetic time series; 100 time points long, with 10 randomly placed NAs
#' dt.tmp = genTraj(100, 10, 6, 3, in.addna = 10)
#'
#' # calculate single stats from all time points
#' calcTrajCI(dt.tmp, 'objCyto_Intensity_MeanIntensity_imErkCor')
#'
#' # calculate the mean and CI along the time course
#' calcTrajCI(dt.tmp, 'objCyto_Intensity_MeanIntensity_imErkCor', 'Metadata_RealTime')
LOCcalcTrajCI = function(in.dt, in.col.meas, in.col.by = NULL, in.type = c('normal', 'boot'), ...) {
  in.type = match.arg(in.type)
  
  if (in.type %like% 'normal')
    loc.dt = in.dt[, as.list(smean.cl.normal(get(in.col.meas), ...)), by = in.col.by] else
      loc.dt = in.dt[, as.list(smean.cl.boot(get(in.col.meas), ...)), by = in.col.by]
    
    return(loc.dt)
}

235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
#' Calculate standard error of the mean
#'
#' @param x Vector
#' @param na.rm Remove NAs; default = FALSE
#'
#' @return A scalar with the result
#' @export
#'
#' @examples
LOCstderr = function(x, na.rm=FALSE) {
  if (na.rm) 
    x = na.omit(x)
  
  return(sqrt(var(x)/length(x)))
}

252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
#' Calculate the power spectrum density for time-series
#'
#' @param in.dt Data table in long format
#' @param in.col.meas Name of the column with the measurement
#' @param in.col.id Name of the column with the unique series identifier
#' @param in.col.by Column names for grouping (default NULL - no grouping). PSD of individual trajectories will be averaged within a group.
#' @param in.method Name of the method for PSD estimation, must be one of c("pgram", "ar"). Default to "pgram*.
#' @param in.return.period Wheter to return densities though periods (1/frequencies) instead of frequencies.
#' @param ... Other paramters to pass to stats::spectrum()
#'
#' @return Datatable with columns: (frequency or period), spec (the density) and grouping column
#' @export
#' @import data.table
#'
#' @examples
LOCcalcPSD <- function(in.dt,
                    in.col.meas,
                    in.col.id,
                    in.col.by,
                    in.method = "pgram",
                    in.return.period = TRUE,
273
                    in.time.btwPoints = 1,
274
275
                    ...){
  require(data.table)
276
277
278
279
280
281
282
283
284
  # Method "ar" returns $spec as matrix whereas "pgram" returns a vector, custom function to homogenze output format
  mySpectrum <- function(x, ...){
    args_spec <- list(x=x, plot=FALSE)
    inargs <- list(...)
    args_spec[names(inargs)] <- inargs
    out <- do.call(spectrum, args_spec)
    out$spec <- as.vector(out$spec)
    return(out)
  }
285
286
287
  if(!in.method %in% c("pgram", "ar")){
    stop('Method should be one of: c("pgram", "ar"')
  }
288
289
290
291
292
  dt_spec <-  in.dt[, (mySpectrum(get(in.col.meas), plot = FALSE, method = in.method)[c("freq", "spec")]), by = in.col.id]
  dt_group <- in.dt[, .SD[1, get(in.col.by)], by = in.col.id]
  setnames(dt_group, "V1", in.col.by)
  dt_spec <- merge(dt_spec, dt_group, by = in.col.id)
  dt_agg <- dt_spec[, .(spec = mean(spec)), by = c(in.col.by, "freq")]
293
  if(in.return.period){
294
    dt_agg[, period := 1/freq]
295
296
297
    dt_agg[, freq := NULL]
    # Adjust period unit to go from frame unit  to time unit
    dt_agg[, period := period * in.time.btwPoints]
298
  } else {
299
    dt_agg[, freq := freq * (1/in.time.btwPoints)]
300
    setnames(dt_agg, "freq", "frequency")
301
302
303
304
305
  }
  return(dt_agg)
}


dmattek's avatar
dmattek committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#' Generate synthetic CellProfiler output with single cell time series
#'
#'
#'
#' @param in.ntpts Number of time points (default 60)
#' @param in.ntracks Number of tracks per FOV (default 10)
#' @param in.nfov Number of FOV (default 6)
#' @param in.nwells Number of wells (default 1)
#' @param in.addna Number of NAs to add randomly in the data (default NULL)
#'
#' @return Data table with the follwoing columns: Metadata_Site, Metadata_Well, Metadata_RealTime, objCyto_Intensity_MeanIntensity_imErkCor (normal distributed),
#' objNuc_Intensity_MeanIntensity_imErkCor (normal distributed), objNuc_Location_X and objNuc_Location_Y (uniform ditributed), TrackLabel
#' @export
#' @import data.table

dmattek's avatar
dmattek committed
321
LOCgenTraj <- function(in.ntpts = 60, in.ntracks = 10, in.nfov = 6, in.nwells = 1, in.addna = NULL, in.addout = NULL) {
dmattek's avatar
dmattek committed
322
323
324
325
326
327
328
329
330
331
332
  
  x.rand.1 = c(rnorm(in.ntpts * in.ntracks * in.nfov * 1/3, 0.5, 0.1), rnorm(in.ntpts * in.ntracks * in.nfov * 1/3,   1, 0.2), rnorm(in.ntpts * in.ntracks * in.nfov * 1/3,  2, 0.5))
  x.rand.2 = c(rnorm(in.ntpts * in.ntracks * in.nfov * 1/3, 0.25, 0.1), rnorm(in.ntpts * in.ntracks * in.nfov * 1/3, 0.5, 0.2),  rnorm(in.ntpts * in.ntracks * in.nfov * 1/3, 1, 0.2))
  
  # add NA's for testing
  if (!is.null(in.addna)) {
    locTabLen = length(x.rand.1)
    x.rand.1[round(runif(in.addna) * locTabLen)] = NA
    x.rand.2[round(runif(in.addna) * locTabLen)] = NA
  }
  
dmattek's avatar
dmattek committed
333
334
335
  # add outliers for testing
  if (!is.null(in.addout)) {
    locTabLen = length(x.rand.1)
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
336
337
    x.rand.1[round(runif(in.addout) * locTabLen)] = 5
    x.rand.2[round(runif(in.addout) * locTabLen)] = 5
dmattek's avatar
dmattek committed
338
339
  }
  
dmattek's avatar
dmattek committed
340
341
  x.arg = rep(seq(1, in.ntpts), in.ntracks * in.nfov)
  
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
342
343
344
345
346
347
348
349
  dt.nuc = data.table(well = rep(LETTERS[1:in.nwells], each = in.ntpts * in.nfov * in.ntracks / in.nwells),
                      group = rep(1:in.nfov, each = in.ntpts * in.ntracks),
                      time = x.arg,
                      y1 = x.rand.1,
                      y2  = x.rand.2,
                      posx = runif(in.ntpts * in.ntracks * in.nfov, min = 0, max = 1),
                      posy = runif(in.ntpts * in.ntracks * in.nfov, min = 0, max = 1),
                      id = rep(1:(in.ntracks*in.nfov), each = in.ntpts))
dmattek's avatar
dmattek committed
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
  
  return(dt.nuc)
}

#' Normalize Trajectory
#'
#' Returns original dt with an additional column with normalized quantity.
#' The column to be normalised is given by 'in.meas.col'.
#' The name of additional column is the same as in.meas.col but with ".norm" suffix added.
#' Normalisation is based on part of the trajectory;
#' this is defined by in.rt.min and max, and the column with time in.rt.col.#'
#'
#' @param in.dt Data table in long format
#' @param in.meas.col String with the column name to normalize
#' @param in.rt.col String with the colum name holding time
#' @param in.rt.min Lower bound for time period used for normalization
#' @param in.rt.max Upper bound for time period used for normalization
#' @param in.by.cols String vector with 'by' columns to calculate normalization per group; if NULL, no grouping is done
#' @param in.robust Whether robust measures should be used (median instead of mean, mad instead of sd); default TRUE
#' @param in.type Type of normalization: z.score or mean (i.e. fold change w.r.t. mean); default 'z-score'
#'
#' @return Returns original dt with an additional column with normalized quantity.
#' @export
#' @import data.table

LOCnormTraj = function(in.dt,
                    in.meas.col,
dmattek's avatar
dmattek committed
377
                    in.rt.col = COLRT,
dmattek's avatar
dmattek committed
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
                    in.rt.min = 10,
                    in.rt.max = 20,
                    in.by.cols = NULL,
                    in.robust = TRUE,
                    in.type = 'z.score') {
  loc.dt <-
    copy(in.dt) # copy so as not to alter original dt object w intermediate assignments
  
  if (is.null(in.by.cols)) {
    if (in.robust)
      loc.dt.pre.aggr = loc.dt[get(in.rt.col) >= in.rt.min &
                                 get(in.rt.col) <= in.rt.max, .(meas.md = median(get(in.meas.col), na.rm = TRUE),
                                                                meas.mad = mad(get(in.meas.col), na.rm = TRUE))]
    else
      loc.dt.pre.aggr = loc.dt[get(in.rt.col) >= in.rt.min &
                                 get(in.rt.col) <= in.rt.max, .(meas.md = mean(get(in.meas.col), na.rm = TRUE),
                                                                meas.mad = sd(get(in.meas.col), na.rm = TRUE))]
    
    loc.dt = cbind(loc.dt, loc.dt.pre.aggr)
  }  else {
    if (in.robust)
      loc.dt.pre.aggr = loc.dt[get(in.rt.col) >= in.rt.min &
                                 get(in.rt.col) <= in.rt.max, .(meas.md = median(get(in.meas.col), na.rm = TRUE),
                                                                meas.mad = mad(get(in.meas.col), na.rm = TRUE)), by = in.by.cols]
    else
      loc.dt.pre.aggr = loc.dt[get(in.rt.col) >= in.rt.min &
                                 get(in.rt.col) <= in.rt.max, .(meas.md = mean(get(in.meas.col), na.rm = TRUE),
                                                                meas.mad = sd(get(in.meas.col), na.rm = TRUE)), by = in.by.cols]
    
    loc.dt = merge(loc.dt, loc.dt.pre.aggr, by = in.by.cols)
  }
  
  
  if (in.type == 'z.score') {
    loc.dt[, meas.norm := (get(in.meas.col) - meas.md) / meas.mad]
  } else {
    loc.dt[, meas.norm := (get(in.meas.col) / meas.md)]
  }
  
  setnames(loc.dt, 'meas.norm', paste0(in.meas.col, '.norm'))
  
  loc.dt[, c('meas.md', 'meas.mad') := NULL]
  return(loc.dt)
}


dmattek's avatar
Added:    
dmattek committed
424

dmattek's avatar
dmattek committed
425
# Functions for clustering ----
dmattek's avatar
dmattek committed
426
427
428
429
430
431
432
433
434

# Return a dt with cell IDs and corresponding cluster assignments depending on dendrogram cut (in.k)
# This one works wth dist & hclust pair
# For sparse hierarchical clustering use getDataClSpar
# Arguments:
# in.dend  - dendrogram; usually output from as.dendrogram(hclust(distance_matrix))
# in.k - level at which dendrogram should be cut

getDataCl = function(in.dend, in.k) {
dmattek's avatar
Added:    
dmattek committed
435
436
  cat(file = stderr(), 'getDataCl \n')
  
dmattek's avatar
dmattek committed
437
  loc.clAssign = dendextend::cutree(in.dend, in.k, order_clusters_as_data = TRUE, )
dmattek's avatar
dmattek committed
438
439
440
441
  #print(loc.m)
  
  # The result of cutree containes named vector with names being cell id's
  # THIS WON'T WORK with sparse hierarchical clustering because there, the dendrogram doesn't have original id's
dmattek's avatar
dmattek committed
442
443
444
  loc.dt.clAssign = as.data.table(loc.clAssign, keep.rownames = T)
  setnames(loc.dt.clAssign, c(COLID, COLCL))
  
dmattek's avatar
dmattek committed
445
  
446
447
  #cat('===============\ndataCl:\n')
  #print(loc.dt.cl)
dmattek's avatar
dmattek committed
448
  return(loc.dt.clAssign)
dmattek's avatar
Added:    
dmattek committed
449
450
}

dmattek's avatar
dmattek committed
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469

# Return a dt with cell IDs and corresponding cluster assignments depending on dendrogram cut (in.k)
# This one works with sparse hierarchical clustering!
# Arguments:
# in.dend  - dendrogram; usually output from as.dendrogram(hclust(distance_matrix))
# in.k - level at which dendrogram should be cut
# in.id - vector of cell id's

getDataClSpar = function(in.dend, in.k, in.id) {
  cat(file = stderr(), 'getDataClSpar \n')
  
  loc.m = dendextend::cutree(in.dend, in.k, order_clusters_as_data = TRUE)
  #print(loc.m)
  
  # The result of cutree containes named vector with names being cell id's
  # THIS WON'T WORK with sparse hierarchical clustering because there, the dendrogram doesn't have original id's
  loc.dt.cl = data.table(id = in.id,
                         cl = loc.m)
  
470
471
  #cat('===============\ndataCl:\n')
  #print(loc.dt.cl)
dmattek's avatar
dmattek committed
472
473
474
475
476
  return(loc.dt.cl)
}



dmattek's avatar
Added:    
dmattek committed
477
478
479
480
481
482
483
484
485
486
487
488
489
# prepares a table with cluster numbers in 1st column and colour assignments in 2nd column
# the number of rows is determined by dendrogram cut
getClCol <- function(in.dend, in.k) {
  
  loc.col_labels <- get_leaves_branches_col(in.dend)
  loc.col_labels <- loc.col_labels[order(order.dendrogram(in.dend))]
  
  return(unique(
    data.table(cl.no = dendextend::cutree(in.dend, k = in.k, order_clusters_as_data = TRUE),
               cl.col = loc.col_labels)))
}


dmattek's avatar
dmattek committed
490
# Custom plotting functions ----
dmattek's avatar
dmattek committed
491

dmattek's avatar
dmattek committed
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530

#' Custom ggPlot theme based on theme_bw
#'
#' @param in.font.base
#' @param in.font.axis.text
#' @param in.font.axis.title
#' @param in.font.strip
#' @param in.font.legend
#'
#' @return
#' @export
#'
#' @examples
#'
LOCggplotTheme = function(in.font.base = 12,
                       in.font.axis.text = 12,
                       in.font.axis.title = 12,
                       in.font.strip = 14,
                       in.font.legend = 12) {
  loc.theme =
    theme_bw(base_size = in.font.base, base_family = "Helvetica") +
    theme(
      panel.spacing = unit(1, "lines"),
      panel.grid.minor = element_blank(),
      panel.grid.major = element_blank(),
      panel.border = element_blank(),
      axis.line = element_line(color = "black", size = 0.25),
      axis.text = element_text(size = in.font.axis.text),
      axis.title = element_text(size = in.font.axis.title),
      strip.text = element_text(size = in.font.strip, face = "bold"),
      strip.background = element_blank(),
      legend.key = element_blank(),
      legend.text = element_text(size = in.font.legend),
      legend.key.height = unit(1, "lines"),
      legend.key.width = unit(2, "lines"))
  
  return(loc.theme)
}

dmattek's avatar
dmattek committed
531
532
# Build Function to Return Element Text Object
# From: https://stackoverflow.com/a/36979201/1898713
dmattek's avatar
dmattek committed
533
LOCrotatedAxisElementText = function(angle, position='x', size = 12){
dmattek's avatar
dmattek committed
534
535
536
537
538
539
540
541
542
543
  angle     = angle[1]; 
  position  = position[1]
  positions = list(x=0, y=90, top=180, right=270)
  if(!position %in% names(positions))
    stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")), call.=FALSE)
  if(!is.numeric(angle))
    stop("'angle' must be numeric",call.=FALSE)
  rads = (-angle - positions[[ position ]])*pi/180
  hjust = round((1 - sin(rads)))/2
  vjust = round((1 + cos(rads)))/2
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
544
  element_text(size = size, angle = angle, vjust = vjust, hjust = hjust)
dmattek's avatar
dmattek committed
545
546
}

547
548
# Plot individual time series
LOCplotTraj = function(dt.arg, # input data table
dmattek's avatar
Mod:    
dmattek committed
549
550
551
552
553
554
555
556
557
558
559
                        x.arg,  # string with column name for x-axis
                        y.arg, # string with column name for y-axis
                        group.arg, # string with column name for grouping time series (typicaly cell ID)
                        facet.arg, # string with column name for facetting
                        facet.ncol.arg = 2, # default number of facet columns
                        facet.color.arg = NULL, # vector with list of colours for adding colours to facet names (currently a horizontal line on top of the facet is drawn)
                        line.col.arg = NULL, # string with column name for colouring time series (typically when individual time series are selected in UI)
                        xlab.arg = NULL, # string with x-axis label
                        ylab.arg = NULL, # string with y-axis label
                        plotlab.arg = NULL, # string with plot label
                        dt.stim.arg = NULL, # plotting additional dataset; typically to indicate stimulations (not fully implemented yet, not tested!)
560
561
                        x.stim.arg = c('tstart', 'tend'), # column names in stimulation dt with x and xend parameters
                        y.stim.arg = c('ystart', 'yend'), # column names in stimulation dt with y and yend parameters
dmattek's avatar
dmattek committed
562
563
564
565
                        tfreq.arg = 1, # unused
                        xlim.arg = NULL, # limits of x-axis; for visualisation only, not trimmimng data
                        ylim.arg = NULL, # limits of y-axis; for visualisation only, not trimmimng data
                        stim.bar.width.arg = 0.5, # width of the stimulation line; plotted under time series
dmattek's avatar
Mod:    
dmattek committed
566
                        aux.label1 = NULL, # 1st point label; used for interactive plotting; displayed in the tooltip; typically used to display values of column holding x & y coordinates
dmattek's avatar
Added:    
dmattek committed
567
                        aux.label2 = NULL,
568
                        aux.label3 = NULL,
dmattek's avatar
Added:    
dmattek committed
569
570
571
572
573
                        stat.arg = c('', 'mean', 'CI', 'SE')) {
  
  # match arguments for stat plotting
  loc.stat = match.arg(stat.arg, several.ok = TRUE)

dmattek's avatar
Added:    
dmattek committed
574
575
  
  # aux.label12 are required for plotting XY positions in the tooltip of the interactive (plotly) graph
dmattek's avatar
dmattek committed
576
577
  p.tmp = ggplot(dt.arg,
                 aes_string(x = x.arg,
dmattek's avatar
dmattek committed
578
                            y = y.arg,
dmattek's avatar
Added:    
dmattek committed
579
                            group = group.arg,
580
581
582
583
584
                            label = group.arg))
  #,
  #                          label  = aux.label1,
  #                          label2 = aux.label2,
  #                          label3 = aux.label3))
dmattek's avatar
dmattek committed
585
  
dmattek's avatar
dmattek committed
586
587
588
589
590
591
592
593
594
595
596
597
598
  if (is.null(line.col.arg)) {
    p.tmp = p.tmp +
      geom_line(alpha = 0.25, 
                              size = 0.25)
  }
  else {
    p.tmp = p.tmp + 
      geom_line(aes_string(colour = line.col.arg), 
                              alpha = 0.5, 
                              size = 0.5) +
      scale_color_manual(name = '', 
                         values =c("FALSE" = rhg_cols[7], "TRUE" = rhg_cols[3], "SELECTED" = 'green', "NOT SEL" = rhg_cols[7]))
  }
dmattek's avatar
Mod:    
dmattek committed
599
600
601
602
603
604
605
606
607
608

  # this is temporary solution for adding colour according to cluster number
  # use only when plotting traj from clustering!
  # a horizontal line is added at the top of data
  if (!is.null(facet.color.arg)) {

    loc.y.max = max(dt.arg[, c(y.arg), with = FALSE])
    loc.dt.cl = data.table(xx = 1:length(facet.color.arg), yy = loc.y.max)
    setnames(loc.dt.cl, 'xx', facet.arg)
    
dmattek's avatar
Fixed:    
dmattek committed
609
610
    # adjust facet.color.arg to plot
    
dmattek's avatar
Mod:    
dmattek committed
611
612
613
614
615
    p.tmp = p.tmp +
      geom_hline(data = loc.dt.cl, colour = facet.color.arg, yintercept = loc.y.max, size = 4) +
      scale_colour_manual(values = facet.color.arg,
                          name = '')
  }
dmattek's avatar
dmattek committed
616
  
dmattek's avatar
Added:    
dmattek committed
617
618
  if ('mean' %in% loc.stat)
    p.tmp = p.tmp + 
dmattek's avatar
dmattek committed
619
620
    stat_summary(
      aes_string(y = y.arg, group = 1),
dmattek's avatar
dmattek committed
621
622
      fun.y = mean, 
      na.rm = T,
dmattek's avatar
Added:    
dmattek committed
623
      colour = 'red',
dmattek's avatar
dmattek committed
624
625
626
627
      linetype = 'solid',
      size = 1,
      geom = "line",
      group = 1
dmattek's avatar
Added:    
dmattek committed
628
629
630
631
632
633
634
    )

  if ('CI' %in% loc.stat)
    p.tmp = p.tmp + 
    stat_summary(
      aes_string(y = y.arg, group = 1),
      fun.data = mean_cl_normal,
dmattek's avatar
dmattek committed
635
      na.rm = T,
dmattek's avatar
Added:    
dmattek committed
636
      colour = 'red',
dmattek's avatar
Mod:    
dmattek committed
637
      alpha = 0.25,
dmattek's avatar
Added:    
dmattek committed
638
639
640
641
642
643
644
645
646
      geom = "ribbon",
      group = 1
    )
  
  if ('SE' %in% loc.stat)
    p.tmp = p.tmp + 
    stat_summary(
      aes_string(y = y.arg, group = 1),
      fun.data = mean_se,
dmattek's avatar
dmattek committed
647
      na.rm = T,
dmattek's avatar
Added:    
dmattek committed
648
      colour = 'red',
dmattek's avatar
Mod:    
dmattek committed
649
      alpha = 0.25,
dmattek's avatar
Added:    
dmattek committed
650
651
652
653
654
655
656
      geom = "ribbon",
      group = 1
    )
  
  
  
  p.tmp = p.tmp + 
dmattek's avatar
dmattek committed
657
658
659
    facet_wrap(as.formula(paste("~", facet.arg)),
               ncol = facet.ncol.arg,
               scales = "free_x")
660
661
662
663

  # plot stimulation bars underneath time series
  # dt.stim.arg is read separately and should contain 4 columns with
  # xy positions of beginning and end of the bar
dmattek's avatar
dmattek committed
664
665
  if(!is.null(dt.stim.arg)) {
    p.tmp = p.tmp + geom_segment(data = dt.stim.arg,
666
667
668
669
670
                                 aes_string(x = x.stim.arg[1],
                                            xend = x.stim.arg[2],
                                            y = y.stim.arg[1],
                                            yend = y.stim.arg[2],
                                            group = 'group'),
dmattek's avatar
dmattek committed
671
                                 colour = rhg_cols[[3]],
672
                                 size = stim.bar.width.arg) 
dmattek's avatar
dmattek committed
673
674
  }
  
dmattek's avatar
dmattek committed
675
  p.tmp = p.tmp + coord_cartesian(xlim = xlim.arg, ylim = ylim.arg)
dmattek's avatar
dmattek committed
676
  
dmattek's avatar
dmattek committed
677
678
679
680
  p.tmp = p.tmp + 
    xlab(paste0(xlab.arg, "\n")) +
    ylab(paste0("\n", ylab.arg)) +
    ggtitle(plotlab.arg) +
681
682
683
684
685
    LOCggplotTheme(in.font.base = PLOTFONTBASE, 
                   in.font.axis.text = PLOTFONTAXISTEXT, 
                   in.font.axis.title = PLOTFONTAXISTITLE, 
                   in.font.strip = PLOTFONTFACETSTRIP, 
                   in.font.legend = PLOTFONTLEGEND) + 
686
    theme(legend.position = "top")
dmattek's avatar
dmattek committed
687
  
dmattek's avatar
Mod:    
dmattek committed
688
  return(p.tmp)
dmattek's avatar
dmattek committed
689
690
}

691
692
693
694
695
696
697
698
699
700
# Plot average time series with CI together in one facet
LOCplotTrajRibbon = function(dt.arg, # input data table
                          x.arg, # string with column name for x-axis
                          y.arg, # string with column name for y-axis
                          group.arg = NULL, # string with column name for grouping time series (here, it's a column corresponding to grouping by condition)
                          col.arg = NULL, # colour pallette for individual time series
                          dt.stim.arg = NULL, # data table with stimulation pattern
                          x.stim.arg = c('tstart', 'tend'), # column names in stimulation dt with x and xend parameters
                          y.stim.arg = c('ystart', 'yend'), # column names in stimulation dt with y and yend parameters
                          stim.bar.width.arg = 0.5,
dmattek's avatar
dmattek committed
701
702
                          xlim.arg = NULL, # limits of x-axis; for visualisation only, not trimmimng data
                          ylim.arg = NULL, # limits of y-axis; for visualisation only, not trimmimng data
703
                          ribbon.lohi.arg = c('Lower', 'Upper'), # column names containing lower and upper bound for plotting the ribbon, e.g. for CI; set to NULL to avoid plotting the ribbon
704
705
706
707
708
709
                          ribbon.fill.arg = 'grey50',
                          ribbon.alpha.arg = 0.5,
                          xlab.arg = NULL,
                          ylab.arg = NULL,
                          plotlab.arg = NULL) {
  
710
711
712
713
714
  p.tmp = ggplot(dt.arg, aes_string(x = x.arg, group = group.arg))
  
  if (!is.null(ribbon.lohi.arg))
    p.tmp = p.tmp + 
      geom_ribbon(aes_string(ymin = ribbon.lohi.arg[1], ymax = ribbon.lohi.arg[2]),
715
                fill = ribbon.fill.arg,
716
717
718
                alpha = ribbon.alpha.arg)
  
  p.tmp = p.tmp + geom_line(aes_string(y = y.arg, colour = group.arg))
719
  
dmattek's avatar
dmattek committed
720

721
722
723
724
725
726
727
728
729
730
731
732
733
734
  # plot stimulation bars underneath time series
  # dt.stim.arg is read separately and should contain 4 columns with
  # xy positions of beginning and end of the bar
  if(!is.null(dt.stim.arg)) {
    p.tmp = p.tmp + geom_segment(data = dt.stim.arg,
                                 aes_string(x = x.stim.arg[1],
                                     xend = x.stim.arg[2],
                                     y = y.stim.arg[1],
                                     yend = y.stim.arg[2]),
                                 colour = rhg_cols[[3]],
                                 size = stim.bar.width.arg,
                                 group = 1) 
  }

dmattek's avatar
dmattek committed
735
  p.tmp = p.tmp + coord_cartesian(xlim = xlim.arg, ylim = ylim.arg)
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
  
  if (is.null(col.arg)) {
    p.tmp = p.tmp +
      scale_color_discrete(name = '')
  } else {
    p.tmp = p.tmp +
      scale_colour_manual(values = col.arg, name = '')
  }
  
  if (!is.null(plotlab.arg))
    p.tmp = p.tmp + ggtitle(plotlab.arg)
  
  p.tmp = p.tmp +
    xlab(xlab.arg) +
    ylab(ylab.arg)
  
  return(p.tmp)
753
754
}

755
# Plot average power spectrum density per facet
majpark21's avatar
majpark21 committed
756
757
758
759
760
LOCplotPSD <- function(dt.arg, # input data table
                    x.arg, # string with column name for x-axis
                    y.arg, # string with column name for y-axis
                    group.arg=NULL, # string with column name for grouping time series (here, it's a column corresponding to grouping by condition)
                    xlab.arg = x.arg,
761
                    ylab.arg = y.arg,
762
                    facet.color.arg = NULL){
majpark21's avatar
majpark21 committed
763
764
765
766
767
768
  require(ggplot2)
  if(length(setdiff(c(x.arg, y.arg, group.arg), colnames(dt.arg))) > 0){
    stop(paste("Missing columns in dt.arg: ", setdiff(c(x.arg, y.arg, group.arg), colnames(dt.arg))))
  }
  p.tmp <- ggplot(dt.arg, aes_string(x=x.arg, y=y.arg)) +
    geom_line() +
769
    geom_rug(sides="b", alpha = 1, color = "lightblue") +
majpark21's avatar
majpark21 committed
770
771
    facet_wrap(group.arg) +
    labs(x = xlab.arg, y = ylab.arg)
772
  
773
774
775
776
777
778
779
780
  if (!is.null(facet.color.arg)) {
    
    loc.y.max = max(dt.arg[, c(y.arg), with = FALSE])
    loc.dt.cl = data.table(xx = 1:length(facet.color.arg), yy = loc.y.max)
    setnames(loc.dt.cl, 'xx', group.arg)
    
    # adjust facet.color.arg to plot
    
781
    p.tmp = p.tmp +
782
783
784
      geom_hline(data = loc.dt.cl, colour = facet.color.arg, yintercept = loc.y.max, size = 4) +
      scale_colour_manual(values = facet.color.arg,
                          name = '')
785
786
  }
  
majpark21's avatar
majpark21 committed
787
788
  return(p.tmp)
}
789

dmattek's avatar
dmattek committed
790
791
792
793
794
795
796
797
798
799
800
801
802
#' Plot a scatter plot with an optional linear regression
#'
#' @param dt.arg input of data.table with 2 columns with x and y coordinates
#' @param facet.arg 
#' @param facet.ncol.arg 
#' @param xlab.arg 
#' @param ylab.arg 
#' @param plotlab.arg 
#' @param alpha.arg 
#' @param trend.arg 
#' @param ci.arg 

LOCggplotScat = function(dt.arg, 
dmattek's avatar
dmattek committed
803
804
805
806
807
808
                        facet.arg = NULL,
                        facet.ncol.arg = 2,
                        xlab.arg = NULL,
                        ylab.arg = NULL,
                        plotlab.arg = NULL,
                        alpha.arg = 1,
dmattek's avatar
dmattek committed
809
810
                        trend.arg = T,
                        ci.arg = 0.95) {
dmattek's avatar
dmattek committed
811
  
dmattek's avatar
dmattek committed
812
813
814
815
  p.tmp = ggplot(dt.arg, aes(x = x, y = y)) +
    geom_point(alpha = alpha.arg)

  if (trend.arg) {
dmattek's avatar
dmattek committed
816
817
    p.tmp = p.tmp +
      stat_smooth(
dmattek's avatar
dmattek committed
818
        method = "lm",
dmattek's avatar
dmattek committed
819
        fullrange = FALSE,
dmattek's avatar
dmattek committed
820
        level = ci.arg,
dmattek's avatar
dmattek committed
821
822
823
        colour = 'blue'
      )
  }
dmattek's avatar
dmattek committed
824

dmattek's avatar
dmattek committed
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
  if (!is.null(facet.arg)) {
    p.tmp = p.tmp +
      facet_wrap(as.formula(paste("~", facet.arg)),
                 ncol = facet.ncol.arg)
    
  }
  
  if (!is.null(xlab.arg))
    p.tmp = p.tmp +
      xlab(paste0(xlab.arg, "\n"))
  
  if (!is.null(ylab.arg))
    p.tmp = p.tmp +
      ylab(paste0("\n", ylab.arg))
  
  if (!is.null(plotlab.arg))
    p.tmp = p.tmp +
      ggtitle(paste0(plotlab.arg, "\n"))
  
  p.tmp = p.tmp +
845
846
847
848
849
    LOCggplotTheme(in.font.base = PLOTFONTBASE, 
                   in.font.axis.text = PLOTFONTAXISTEXT, 
                   in.font.axis.title = PLOTFONTAXISTITLE, 
                   in.font.strip = PLOTFONTFACETSTRIP, 
                   in.font.legend = PLOTFONTLEGEND) + 
850
851
    theme(legend.position = "none")

dmattek's avatar
dmattek committed
852
853
  return(p.tmp)
}
dmattek's avatar
dmattek committed
854

855

dmattek's avatar
dmattek committed
856
LOCplotHeatmap <- function(data.arg,
dmattek's avatar
Mod:    
dmattek committed
857
858
859
860
861
862
863
864
865
866
867
868
                          dend.arg,
                          palette.arg,
                          palette.rev.arg = TRUE,
                          dend.show.arg = TRUE,
                          key.show.arg = TRUE,
                          margin.x.arg = 5,
                          margin.y.arg = 20,
                          nacol.arg = 0.5,
                          colCol.arg = NULL,
                          labCol.arg = NULL,
                          font.row.arg = 1,
                          font.col.arg = 1,
869
                          breaks.arg = NULL,
dmattek's avatar
Mod:    
dmattek committed
870
871
                          title.arg = 'Clustering') {
  
872
873
  loc.n.colbreaks = 99
  
dmattek's avatar
Mod:    
dmattek committed
874
875
  if (palette.rev.arg)
    my_palette <-
876
    rev(colorRampPalette(brewer.pal(9, palette.arg))(n = loc.n.colbreaks))
dmattek's avatar
Mod:    
dmattek committed
877
878
  else
    my_palette <-
879
    colorRampPalette(brewer.pal(9, palette.arg))(n = loc.n.colbreaks)
dmattek's avatar
Mod:    
dmattek committed
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
  
  
  col_labels <- get_leaves_branches_col(dend.arg)
  col_labels <- col_labels[order(order.dendrogram(dend.arg))]
  
  if (dend.show.arg) {
    assign("var.tmp.1", dend.arg)
    var.tmp.2 = "row"
  } else {
    assign("var.tmp.1", FALSE)
    var.tmp.2 = "none"
  }
  
  loc.p = heatmap.2(
    data.arg,
    Colv = "NA",
    Rowv = var.tmp.1,
    srtCol = 90,
    dendrogram = var.tmp.2,
    trace = "none",
    key = key.show.arg,
    margins = c(margin.x.arg, margin.y.arg),
    col = my_palette,
    na.col = grey(nacol.arg),
    denscol = "black",
    density.info = "density",
    RowSideColors = col_labels,
    colRow = col_labels,
    colCol = colCol.arg,
    labCol = labCol.arg,
    #      sepcolor = grey(input$inPlotHierGridColor),
    #      colsep = 1:ncol(loc.dm),
    #      rowsep = 1:nrow(loc.dm),
    cexRow = font.row.arg,
    cexCol = font.col.arg,
dmattek's avatar
dmattek committed
915
916
    main = title.arg,
    symbreaks = FALSE,
917
918
    symkey = FALSE,
    breaks = if (is.null(breaks.arg)) NULL else seq(breaks.arg[1], breaks.arg[2], length.out = loc.n.colbreaks+1)
dmattek's avatar
Mod:    
dmattek committed
919
920
921
922
  )
  
  return(loc.p)
}