Debian Codegraph @

R/render-cached-plot.R

raw
1 #' Plot output with cached images
2 #'
3 #' Renders a reactive plot, with plot images cached to disk. As of Shiny 1.6.0,
4 #' this is a shortcut for using [bindCache()] with [renderPlot()].
5 #'
6 #' `expr` is an expression that generates a plot, similar to that in
7 #' `renderPlot`. Unlike with `renderPlot`, this expression does not
8 #' take reactive dependencies. It is re-executed only when the cache key
9 #' changes.
10 #'
11 #' `cacheKeyExpr` is an expression which, when evaluated, returns an object
12 #' which will be serialized and hashed using the [rlang::hash()]
13 #' function to generate a string that will be used as a cache key. This key is
14 #' used to identify the contents of the plot: if the cache key is the same as a
15 #' previous time, it assumes that the plot is the same and can be retrieved from
16 #' the cache.
17 #'
18 #' This `cacheKeyExpr` is reactive, and so it will be re-evaluated when any
19 #' upstream reactives are invalidated. This will also trigger re-execution of
20 #' the plotting expression, `expr`.
21 #'
22 #' The key should consist of "normal" R objects, like vectors and lists. Lists
23 #' should in turn contain other normal R objects. If the key contains
24 #' environments, external pointers, or reference objects --- or even if it has
25 #' such objects attached as attributes --- then it is possible that it will
26 #' change unpredictably even when you do not expect it to. Additionally, because
27 #' the entire key is serialized and hashed, if it contains a very large object
28 #' --- a large data set, for example --- there may be a noticeable performance
29 #' penalty.
30 #'
31 #' If you face these issues with the cache key, you can work around them by
32 #' extracting out the important parts of the objects, and/or by converting them
33 #' to normal R objects before returning them. Your expression could even
34 #' serialize and hash that information in an efficient way and return a string,
35 #' which will in turn be hashed (very quickly) by the
36 #' [rlang::hash()] function.
37 #'
38 #' Internally, the result from `cacheKeyExpr` is combined with the name of
39 #' the output (if you assign it to `output$plot1`, it will be combined
40 #' with `"plot1"`) to form the actual key that is used. As a result, even
41 #' if there are multiple plots that have the same `cacheKeyExpr`, they
42 #' will not have cache key collisions.
43 #'
44 #' @section Interactive plots:
45 #'
46 #' `renderCachedPlot` can be used to create interactive plots. See
47 #' [plotOutput()] for more information and examples.
48 #'
49 #'
50 #' @inheritParams renderPlot
51 #' @inheritParams bindCache
52 #' @param cacheKeyExpr An expression that returns a cache key. This key should
53 #' be a unique identifier for a plot: the assumption is that if the cache key
54 #' is the same, then the plot will be the same.
55 #' @param sizePolicy A function that takes two arguments, `width` and
56 #' `height`, and returns a list with `width` and `height`. The
57 #' purpose is to round the actual pixel dimensions from the browser to some
58 #' other dimensions, so that this will not generate and cache images of every
59 #' possible pixel dimension. See [sizeGrowthRatio()] for more
60 #' information on the default sizing policy.
61 #' @param res The resolution of the PNG, in pixels per inch.
62 #' @param width,height not used. They are specified via the argument
63 #' `sizePolicy`.
64 #'
65 #' @seealso See [renderPlot()] for the regular, non-cached version of this
66 #' function. It can be used with [bindCache()] to get the same effect as
67 #' `renderCachedPlot()`. For more about configuring caches, see
68 #' [cachem::cache_mem()] and [cachem::cache_disk()].
69 #'
70 #'
71 #' @examples
72 #' ## Only run examples in interactive R sessions
73 #' if (interactive()) {
74 #'
75 #' # A basic example that uses the default app-scoped memory cache.
76 #' # The cache will be shared among all simultaneous users of the application.
77 #' shinyApp(
78 #' fluidPage(
79 #' sidebarLayout(
80 #' sidebarPanel(
81 #' sliderInput("n", "Number of points", 4, 32, value = 8, step = 4)
82 #' ),
83 #' mainPanel(plotOutput("plot"))
84 #' )
85 #' ),
86 #' function(input, output, session) {
87 #' output$plot <- renderCachedPlot({
88 #' Sys.sleep(2) # Add an artificial delay
89 #' seqn <- seq_len(input$n)
90 #' plot(mtcars$wt[seqn], mtcars$mpg[seqn],
91 #' xlim = range(mtcars$wt), ylim = range(mtcars$mpg))
92 #' },
93 #' cacheKeyExpr = { list(input$n) }
94 #' )
95 #' }
96 #' )
97 #'
98 #'
99 #'
100 #' # An example uses a data object shared across sessions. mydata() is part of
101 #' # the cache key, so when its value changes, plots that were previously
102 #' # stored in the cache will no longer be used (unless mydata() changes back
103 #' # to its previous value).
104 #' mydata <- reactiveVal(data.frame(x = rnorm(400), y = rnorm(400)))
105 #'
106 #' ui <- fluidPage(
107 #' sidebarLayout(
108 #' sidebarPanel(
109 #' sliderInput("n", "Number of points", 50, 400, 100, step = 50),
110 #' actionButton("newdata", "New data")
111 #' ),
112 #' mainPanel(
113 #' plotOutput("plot")
114 #' )
115 #' )
116 #' )
117 #'
118 #' server <- function(input, output, session) {
119 #' observeEvent(input$newdata, {
120 #' mydata(data.frame(x = rnorm(400), y = rnorm(400)))
121 #' })
122 #'
123 #' output$plot <- renderCachedPlot(
124 #' {
125 #' Sys.sleep(2)
126 #' d <- mydata()
127 #' seqn <- seq_len(input$n)
128 #' plot(d$x[seqn], d$y[seqn], xlim = range(d$x), ylim = range(d$y))
129 #' },
130 #' cacheKeyExpr = { list(input$n, mydata()) },
131 #' )
132 #' }
133 #'
134 #' shinyApp(ui, server)
135 #'
136 #'
137 #' # A basic application with two plots, where each plot in each session has
138 #' # a separate cache.
139 #' shinyApp(
140 #' fluidPage(
141 #' sidebarLayout(
142 #' sidebarPanel(
143 #' sliderInput("n", "Number of points", 4, 32, value = 8, step = 4)
144 #' ),
145 #' mainPanel(
146 #' plotOutput("plot1"),
147 #' plotOutput("plot2")
148 #' )
149 #' )
150 #' ),
151 #' function(input, output, session) {
152 #' output$plot1 <- renderCachedPlot({
153 #' Sys.sleep(2) # Add an artificial delay
154 #' seqn <- seq_len(input$n)
155 #' plot(mtcars$wt[seqn], mtcars$mpg[seqn],
156 #' xlim = range(mtcars$wt), ylim = range(mtcars$mpg))
157 #' },
158 #' cacheKeyExpr = { list(input$n) },
159 #' cache = cachem::cache_mem()
160 #' )
161 #' output$plot2 <- renderCachedPlot({
162 #' Sys.sleep(2) # Add an artificial delay
163 #' seqn <- seq_len(input$n)
164 #' plot(mtcars$wt[seqn], mtcars$mpg[seqn],
165 #' xlim = range(mtcars$wt), ylim = range(mtcars$mpg))
166 #' },
167 #' cacheKeyExpr = { list(input$n) },
168 #' cache = cachem::cache_mem()
169 #' )
170 #' }
171 #' )
172 #'
173 #' }
174 #'
175 #' \dontrun{
176 #' # At the top of app.R, this set the application-scoped cache to be a memory
177 #' # cache that is 20 MB in size, and where cached objects expire after one
178 #' # hour.
179 #' shinyOptions(cache = cachem::cache_mem(max_size = 20e6, max_age = 3600))
180 #'
181 #' # At the top of app.R, this set the application-scoped cache to be a disk
182 #' # cache that can be shared among multiple concurrent R processes, and is
183 #' # deleted when the system reboots.
184 #' shinyOptions(cache = cachem::cache_disk(file.path(dirname(tempdir()), "myapp-cache")))
185 #'
186 #' # At the top of app.R, this set the application-scoped cache to be a disk
187 #' # cache that can be shared among multiple concurrent R processes, and
188 #' # persists on disk across reboots.
189 #' shinyOptions(cache = cachem::cache_disk("./myapp-cache"))
190 #'
191 #' # At the top of the server function, this set the session-scoped cache to be
192 #' # a memory cache that is 5 MB in size.
193 #' server <- function(input, output, session) {
194 #' shinyOptions(cache = cachem::cache_mem(max_size = 5e6))
195 #'
196 #' output$plot <- renderCachedPlot(
197 #' ...,
198 #' cache = "session"
199 #' )
200 #' }
201 #'
202 #' }
203 #' @export
204 renderCachedPlot <- function(expr,
205 cacheKeyExpr,
206 sizePolicy = sizeGrowthRatio(width = 400, height = 400, growthRate = 1.2),
207 res = 72,
208 cache = "app",
209 ...,
210 alt = "Plot object",
211 outputArgs = list(),
212 width = NULL,
213 height = NULL
214 ) {
215
216 expr <- substitute(expr)
217 if (!is_quosure(expr)) {
218 expr <- new_quosure(expr, env = parent.frame())
219 }
220
221 cacheKeyExpr <- substitute(cacheKeyExpr)
222 if (!is_quosure(cacheKeyExpr)) {
223 cacheKeyExpr <- new_quosure(cacheKeyExpr, env = parent.frame())
224 }
225
226 if (!is.null(width) || !is.null(height)) {
227 warning("Unused argument(s) 'width' and/or 'height'. ",
228 "'sizePolicy' is used instead.")
229 }
230
231 inject(
232 bindCache(
233 renderPlot(!!expr, res = res, alt = alt, outputArgs = outputArgs, ...),
234 !!cacheKeyExpr,
235 sizePolicy = sizePolicy,
236 cache = cache
237 )
238 )
239 }
240
241
242 #' Create a sizing function that grows at a given ratio
243 #'
244 #' Returns a function which takes a two-element vector representing an input
245 #' width and height, and returns a two-element vector of width and height. The
246 #' possible widths are the base width times the growthRate to any integer power.
247 #' For example, with a base width of 500 and growth rate of 1.25, the possible
248 #' widths include 320, 400, 500, 625, 782, and so on, both smaller and larger.
249 #' Sizes are rounded up to the next pixel. Heights are computed the same way as
250 #' widths.
251 #'
252 #' @param width,height Base width and height.
253 #' @param growthRate Growth rate multiplier.
254 #'
255 #' @seealso This is to be used with [renderCachedPlot()].
256 #'
257 #' @examples
258 #' f <- sizeGrowthRatio(500, 500, 1.25)
259 #' f(c(400, 400))
260 #' f(c(500, 500))
261 #' f(c(530, 550))
262 #' f(c(625, 700))
263 #'
264 #' @export
265 sizeGrowthRatio <- function(width = 400, height = 400, growthRate = 1.2) {
266 round_dim_up <- function(x, base, rate) {
267 power <- ceiling(log(x / base, rate))
268 ceiling(base * rate^power)
269 }
270
271 function(dims) {
272 if (length(dims) != 2) {
273 stop("dims must be a vector with two numbers, for width and height.")
274 }
275 c(
276 round_dim_up(dims[1], width, growthRate),
277 round_dim_up(dims[2], height, growthRate)
278 )
279 }
280 }