trajPsdPlot.R 7.94 KB
Newer Older
dmattek's avatar
dmattek committed
1
2
3
4
5
6
7
#
# Time Course Inspector: Shiny app for plotting time series data
# Author: Marc-Antoine Jacques
#
# This module is for plotting Power Spectral Analysis
#

majpark21's avatar
majpark21 committed
8
require(DT)
9
require(scales)
majpark21's avatar
majpark21 committed
10

11
 # UI ----
majpark21's avatar
majpark21 committed
12
13
14
15
16
17
modPSDPlotUI =  function(id, label = "Plot PSD of average trajectory.") {
  ns <- NS(id)
  
  tagList(
    fluidRow(
      column(
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
18
        2,
19
        radioButtons(ns('rBPSDmethod'), 'Method for PSD estimation:', list('Smoothed Fourier' = 'pgram', 'AR Fit' = 'ar')),
majpark21's avatar
majpark21 committed
20
21
22
23
        checkboxInput(ns('chBplotTrajInt'), 'Interactive Plot'),
        actionButton(ns('butPlotTraj'), 'Plot!')
      ),
      column(
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
24
        2,
25
26
        selectInput(ns('inPSDxchoice'), 'X-axis:', list('Period'= TRUE, 'Frequency'= FALSE)),
        numericInput(ns('ninPSDsamplFreq'), '# time units between 2 points:', value = 1, min = 0, step = 1)
27
28
      ),
      column(
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
29
30
31
32
33
34
35
36
37
38
39
        2,
        selectInput(ns('inPSDtransXtype'), 'Transform X-axis:', list('none' = 'none',
                                                                   '1/x'='inverse_trans', 
                                                                   'log2'= 'log2', 
                                                                   'log10'= 'log10', 
                                                                   'ln'= 'log')),
        selectInput(ns('inPSDtransYtype'), 'Transform Y-axis:', list('none' = 'none',
                                                                   '1/y'='inverse_trans', 
                                                                   'log2'= 'log2', 
                                                                   'log10'= 'log10', 
                                                                   'ln'= 'log'))
majpark21's avatar
majpark21 committed
40
41
      ),
      column(
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
42
        2,
majpark21's avatar
majpark21 committed
43
44
45
46
47
48
49
50
51
52
53
        numericInput(
          ns('inPlotTrajWidth'),
          'Width [%]:',
          value = 100,
          min = 10,
          width = '100px',
          step = 10
        ),
        numericInput(
          ns('inPlotTrajHeight'),
          'Height [px]:',
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
54
          value = PLOTPSDHEIGHT,
majpark21's avatar
majpark21 committed
55
56
57
58
59
60
61
62
63
64
65
          min = 100,
          width = '100px',
          step = 50
        )
      )
    ),
    uiOutput(ns('uiPlotTraj')),
    downPlotUI(ns('downPlotTraj'), "Download PDF")
  )
}

66
# Server ----
majpark21's avatar
majpark21 committed
67
68

modPSDPlot = function(input, output, session, 
69
70
                             in.data,
                             in.fname,
majpark21's avatar
majpark21 committed
71
                             in.facet = 'group', 
72
73
                             in.facet.color = NULL
                             ) {
majpark21's avatar
majpark21 committed
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
  
  ns <- session$ns
  
  output$uiPlotTraj = renderUI({
    if (input$chBplotTrajInt)
      plotlyOutput(
        ns("outPlotTrajInt"),
        width = paste0(input$inPlotTrajWidth, '%'),
        height = paste0(input$inPlotTrajHeight, 'px')
      ) else
        plotOutput(
          ns("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)
  })
  
  
  output$outPlotTrajInt <- renderPlotly({
    # 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))
  })
  
  
  
  # PSD plot - download pdf
  callModule(downPlot, "downPlotTraj", 
122
             in.fname = in.fname,
majpark21's avatar
majpark21 committed
123
124
             plotTraj, TRUE)
  
125
  plotTraj <- function() {
majpark21's avatar
majpark21 committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
    cat(file = stderr(), 'plotPSD: in\n')
    locBut = input$butPlotTraj
    
    if (locBut == 0) {
      cat(file = stderr(), 'plotPSD: Go button not pressed\n')
      
      return(NULL)
    }
    
    # check if main data exists
    loc.dt = isolate(in.data())
    
    cat("plotPSD: on to plot\n\n")
    if (is.null(loc.dt)) {
      cat(file = stderr(), 'plotPSD: dt is NULL\n')
      return(NULL)
    }
    
    cat(file = stderr(), 'plotPSD: dt not NULL\n')
    
    
    
    # Future: change such that a column with colouring status is chosen by the user
    # colour trajectories, if dataset contains mid.in 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
    
156
157
158
    # select every other point for plotting (fixed for PSD because lead to false interpretation of PSD)
    loc.dt = loc.dt[, .SD[seq(1, .N, 1)], by = id]

majpark21's avatar
majpark21 committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
    # check if columns with XY positions are present
    if (sum(names(loc.dt) %like% 'pos') == 2)
      locPos = TRUE
    else
      locPos = FALSE
    
    # check if column with ObjectNumber is present
    if (sum(names(loc.dt) %like% 'obj.num') == 1)
      locObjNum = TRUE
    else
      locObjNum = FALSE
    
    
    # If in.facet.color present,
    # make sure to include the same number of colours in the palette,
    # as the number of groups in dt.
    # in.facet.color is typically used when plotting time series within clusters.
    # Then, the number of colours in the palette has to be equal to the number of clusters (facetted according to in.facet variable).
    # This might differ if the user selects manually clusters to display.
    if (is.null(in.facet.color)) 
      loc.facet.col = NULL 
    else {
      # get group numbers in dt; 
      # loc.dt[, c(in.facet), with = FALSE] returns a data table with a single column
      # [[1]] at the end extracts the first column and returns as a vector
      loc.groups = unique(loc.dt[, c(in.facet), with = FALSE][[1]])
      
      # get colour palette
      # the length is equal to the number of groups in the original dt.
      # When plotting time series within clusters, the length equals the number of clusters.
      loc.facet.col = in.facet.color()$cl.col
      loc.facet.col = loc.facet.col[loc.groups]
    }
    

    loc.dt.aggr <- LOCcalcPSD(in.dt = loc.dt,
                              in.col.meas = 'y',
                              in.col.id = 'id',
                              in.col.by = in.facet,
198
                              in.method = input$rBPSDmethod,
199
200
                              in.return.period = input$inPSDxchoice,
                              in.time.btwPoints = input$ninPSDsamplFreq
majpark21's avatar
majpark21 committed
201
202
203
204
                              )
    loc.dt.aggr[, (in.facet) := as.factor(get(in.facet))]
    
    x_arg <- ifelse('period' %in% colnames(loc.dt.aggr), 'period', 'frequency')
205
    x_arg_str <- paste0(toupper(substr(x_arg, 1, 1)), tolower(substring(x_arg, 2)))  # capitalized
majpark21's avatar
majpark21 committed
206
207
208
209
    p.out <- LOCplotPSD(dt.arg = loc.dt.aggr,
                        x.arg = x_arg,
                        y.arg = 'spec',
                        group.arg = in.facet,
210
                        facet.color.arg = loc.facet.col,
211
                        xlab.arg = x_arg_str,
majpark21's avatar
majpark21 committed
212
213
214
215
216
                        ylab.arg = '') +
      LOCggplotTheme(in.font.base = PLOTFONTBASE, 
                     in.font.axis.text = PLOTFONTAXISTEXT, 
                     in.font.axis.title = PLOTFONTAXISTITLE, 
                     in.font.strip = PLOTFONTFACETSTRIP, 
217
                     in.font.legend = PLOTFONTLEGEND)
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
218

219
220
221
222
    # TODO: Restore tick labels when using inverse transformation
    # See: https://stackoverflow.com/questions/56130614/ggplot2-missing-labels-after-custom-scaling-of-axis
    inverse_trans <- scales::trans_new("myinverse", transform = function(x) 1/x,
                                       inverse = function(x) 1/(1/x))
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
223
224
225
226
227
    
    if(input$inPSDtransXtype == "inverse_trans"){
      p.out <- p.out + scale_x_continuous(trans = inverse_trans)
    } else if (!(input$inPSDtransXtype == "none")) {
      p.out <- p.out + scale_x_continuous(trans = input$inPSDtransXtype)
228
    }
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
229
230
231
232
233
    
    if(input$inPSDtransYtype == "inverse_trans"){
      p.out <- p.out + scale_y_continuous(trans = inverse_trans)
    } else if (!(input$inPSDtransYtype == "none")) {
      p.out <- p.out + scale_y_continuous(trans = input$inPSDtransYtype)
234
    }
Maciej Dobrzynski's avatar
Maciej Dobrzynski committed
235
    
majpark21's avatar
majpark21 committed
236
237
238
    return(p.out)
  }
}