Debian Codegraph @

R/evals.R

raw
1 #' Evaluate with messages
2 #'
3 #' This function takes text(s) of R code and \code{eval}s all at one run - returning a list with four elements. See \code{Details}.
4 #'
5 #' \code{eval.msgs} returns a detailed list of the result of evaluation:
6 #' \itemize{
7 #' \item \emph{src} - character vector of specified R code.
8 #' \item \emph{result} - result of evaluation. \code{NULL} if nothing is returned. If any R code returned an R object while evaluating then the \emph{last} R object will be returned as a raw R object. If a graph is plotted in the end of the given R code (remember: \emph{last} R object), it would be automatically printed (see e.g. \code{lattice} and \code{ggplot2}).
9 #' \item \emph{output} - character vector of printed version (\code{capture.output}) of \code{result}
10 #' \item \emph{type} - class of generated output. 'NULL' if nothing is returned, 'error' if some error occurred.
11 #' \item \emph{msg} - possible messages grabbed while evaluating specified R code with the following structure:
12 #' \itemize{
13 #' \item \emph{messages} - character vector of possible diagnostic message(s)
14 #' \item \emph{warnings} - character vector of possible warning message(s)
15 #' \item \emph{errors} - character vector of possible error message(s)
16 #' }
17 #' \item \emph{stdout} - character vector of possibly printed texts to standard output (console)
18 #' }
19 #' @param src character values containing R code
20 #' @param env environment where evaluation takes place. If not set (by default), a new temporary environment is created.
21 #' @param showInvisible return \code{invisible} results?
22 #' @param graph.unify should \code{eval.msgs} try to unify the style of (\code{lattice} and \code{ggplot2}) plots? If set to \code{TRUE} (by default), some \code{panderOptions()} would apply. Please note that this argument has no effect on \code{base} plots, use \code{evals} instead.
23 #' @return a list of parsed elements each containing: \code{src} (the command run), \code{result} (R object: \code{NULL} if nothing returned), \code{print}ed \code{output}, \code{type} (class of returned object if any), informative/wawrning and error messages (if any returned by the command run, otherwise set to \code{NULL}) and possible \code{stdout}t value. See Details above.
24 #' @seealso \code{\link{evals}}
25 #' @export
26 #' @examples \dontrun{
27 #' eval.msgs('1:5')
28 #' eval.msgs('x <- 1:5')
29 #' eval.msgs('lm(mtcars$hp ~ mtcars$wt)')
30 #'
31 #' ## plots
32 #' eval.msgs('plot(runif(100))')
33 #' eval.msgs('histogram(runif(100))')
34 #'
35 #' ## error handling
36 #' eval.msgs('runiff(23)')
37 #' eval.msgs('runif is a nice function')
38 #' eval.msgs('no.R.object.like.that')
39 #'
40 #' ## messages
41 #' eval.msgs(c('message("FOO")', '1:2'))
42 #' eval.msgs(c('warning("FOO")', '1:2'))
43 #' eval.msgs(c('message("FOO");message("FOO");warning("FOO")', '1:2'))
44 #' eval.msgs('warning("d");warning("f");1')
45 #'
46 #' ## stdout
47 #' eval.msgs('cat("writing to console")')
48 #' eval.msgs('cat("writing to console");1:4')
49 #' }
50 eval.msgs <- function(src, env = NULL, showInvisible = FALSE, graph.unify = evalsOptions('graph.unify')) {
51
52 if (is.null(env)) {
53 env <- new.env()
54 }
55
56 ## grab warnings and messages
57 warnings <- NULL
58 warning.handler <- function(w) {
59 warnings <<- c(warnings, w$message)
60 invokeRestart('muffleWarning')
61 }
62
63 messages <- NULL
64 message.handler <- function(m) {
65 messages <<- c(messages, sub('\n$', '', m$message))
66 }
67
68 ## grab stdout
69 stdout <- vector('character')
70 con <- textConnection('stdout', 'wr', local = TRUE)
71 sink(con, split = FALSE)
72
73 result <- suppressMessages(withCallingHandlers(tryCatch(withVisible(eval(parse(text = src), envir = env)),
74 error = function(e) e),
75 warning = warning.handler, message = message.handler))
76
77 sink()
78 close(con)
79 if (length(stdout) == 0)
80 stdout <- NULL
81
82 ## error handling
83 if (inherits(result, 'error')) {
84
85 error <- result$message
86 result <- NULL
87
88 if (grepl('^<text>:[0-9]*:[0-9]: unexpected ', error)) {
89 error <- sub('<text>:([0-9]*):([0-9]*): unexpected ([a-zA-Z ]*)\n.*[0-9]*:(.*)\n.*[ \t]*$',
90 'Unexpected \\3 at character \\2 in line \\1: `\\4`',
91 error)
92 }
93
94 } else
95 error <- NULL
96
97 ## check if printing is needed
98 if (!is.null(result)) {
99 rv <- result$value
100 rvc <- class(rv)
101
102 if (result$visible | showInvisible) {
103
104 ## unify images
105 if (graph.unify) {
106
107 fs <- panderOptions('graph.fontsize')
108 ff <- panderOptions('graph.fontfamily')
109 fc <- panderOptions('graph.fontcolor')
110 gc <- panderOptions('graph.grid.color')
111 gl <- panderOptions('graph.grid.lty')
112 cs <- panderOptions('graph.colors')
113 if (panderOptions('graph.color.rnd'))
114 cs <- sample(cs)
115 cb <- cs[1] # base color
116 aa <- panderOptions('graph.axis.angle')
117 bc <- panderOptions('graph.background')
118 pc <- panderOptions('graph.panel.background')
119 tc <- ifelse(pc == 'transparent', bc, pc) # 'transparent' color
120 gs <- panderOptions('graph.symbol')
121
122 ## lattice/trellis
123 if ('trellis' %in% rvc) {
124
125 ## margin
126 if (panderOptions('graph.nomargin')) {
127 rv$par.settings$layout.heights <- list(top.padding = 0.4,
128 bottom.padding = 0,
129 main = 1.4,
130 main.key.padding = 0)
131 rv$par.settings$layout.widths <- list(right.padding = -1,
132 left.padding = 0.4)
133 }
134
135 ## font family
136 rv$par.settings$axis.text <- rv$par.settings$add.text <- rv$par.settings$par.xlab.text <- rv$par.settings$par.ylab.text <- rv$par.settings$par.zlab.text <- rv$par.settings$par.sub.text <- rv$par.settings$par.main.text <- list(fontfamily = ff, col = fc) #nolint
137 rv$par.settings$fontsize <- list(text = fs, points = fs * 0.8)
138
139 ## boxes
140 rv$par.settings$strip.background$col <- 'transparent'
141 if (!panderOptions('graph.boxes')) {
142 rv$par.settings$strip.border$col <- 'transparent'
143 rv$par.settings$axis.line$col <- 'transparent'
144 } else {
145 rv$par.settings$strip.border$col <- gc
146 rv$par.settings$axis.line$col <- gc
147 }
148 rv$par.settings$between <- list(x = 0.4, y = 0.4)
149
150 ## colors
151 rv$par.settings$background$col <- bc
152 rv$par.settings$panel.background$col <- pc
153 rv$par.settings$plot.line$col <- rv$par.settings$box.rectangle$fill <- rv$par.settings$box.rectangle$col <- rv$par.settings$plot.polygon$col <- cb #nolint
154 rv$par.settings$superpose.symbol$col <- rv$par.settings$superpose.symbol$col <- cs
155 rv$par.settings$superpose.polygon$border <- rv$par.settings$plot.polygon$border <- tc
156 rv$par.settings$box.umbrella <- list(col = 'black', lty = 'solid', lwd = 2)
157 rv$par.settings$plot.line$lwd <- 2
158 ## pch
159 rv$par.settings$plot.symbol$pch <- rv$par.settings$superpose.symbol$pch <- gs
160 ##if (gs > 20 & gs <= 25 ) {}
161 rv$par.settings$plot.symbol$col <- cb
162 rv$par.settings$superpose.symbol$col <- cs
163 rv$par.settings$plot.symbol$fill <- rv$par.settings$superpose.symbol$fill <- tc
164
165 ## grid
166 if (panderOptions('graph.grid')) {
167 rv$par.settings$reference.line$col <- gc
168 rv$par.settings$reference.line$lty <- gl
169 rv$par.settings$reference.line$lwd <- 0.7
170 rv$axis <- add.lattice.grid
171 if (panderOptions('graph.grid.minor')) {
172 rv$xscale.components <- add.lattice.xsubticks
173 rv$yscale.components <- add.lattice.ysubticks
174 }
175 }
176
177 ## axis angle
178 switch(aa,
179 '0' = rv$y.scales$rot <- c(90, 90),
180 '2' = rv$x.scales$rot <- c(90, 90),
181 '3' = {
182 rv$y.scales$rot <- c(90, 90)
183 rv$x.scales$rot <- c(90, 90)
184 })
185 ## legend
186 if (!is.null(rv$legend)) {
187 rv$legend <- rv$legend[1]
188 names(rv$legend) <- panderOptions('graph.legend.position')
189 }
190
191 }
192
193 ## ggplot2
194 if ('ggplot' %in% rvc) {
195
196 ## margin
197 if (panderOptions('graph.nomargin')) {
198 rv$theme$plot.margin <- grid::unit(c(0.1, 0.1, 0.1, 0), 'lines')
199 }
200
201 ## font family
202 rv$theme$plot.title <- ggplot2::element_text(colour = fc,
203 family = ff,
204 face = 'bold',
205 size = fs * 1.2)
206 rv$theme$axis.text.x <- rv$theme$axis.text.y <- rv$theme$legend.text <- ggplot2::element_text(colour = fc, family = ff, face = 'plain', size = fs * 0.8) #nolint
207 rv$theme$axis.title.x <- ggplot2::element_text(colour = fc,
208 family = ff,
209 face = 'plain',
210 size = fs)
211 rv$theme$strip.text.x <- ggplot2::element_text(colour = fc,
212 family = ff,
213 face = 'plain',
214 size = fs)
215 rv$theme$axis.title.y <- ggplot2::element_text(colour = fc,
216 family = ff,
217 face = 'plain',
218 size = fs,
219 angle = 90)
220 rv$theme$legend.title <- ggplot2::element_text(colour = fc,
221 family = ff,
222 face = 'italic',
223 size = fs)
224 rv$theme$strip.text.y <- ggplot2::element_text(colour = fc,
225 family = ff,
226 face = 'plain',
227 size = fs,
228 angle = -90)
229
230 ## boxes
231 if (!panderOptions('graph.boxes')) {
232 rv$theme$legend.key <- rv$theme$strip.background <- ggplot2::element_rect(colour = 'transparent', fill = 'transparent') #nolint
233 rv$theme$panel.border <- ggplot2::element_rect(fill = NA,
234 colour = tc)
235 rv$theme$panel.background <- ggplot2::element_rect(fill = pc,
236 colour = tc)
237 } else {
238 rv$theme$legend.key <- rv$theme$strip.background <- ggplot2::element_rect(colour = gc, fill = 'transparent') #nolint
239 rv$theme$panel.border <- ggplot2::element_rect(fill = NA,
240 colour = gc)
241 rv$theme$panel.background <- ggplot2::element_rect(fill = pc,
242 colour = gc)
243 }
244
245 ## colors
246 rv$theme$plot.background <- ggplot2::element_rect(fill = bc, colour = NA)
247 rv$theme$axis.ticks <- ggplot2::element_line(colour = gc, size = 0.2)
248
249 ## point shape still has to be updated
250 for (i in length(rv$layers)) {
251 if (packageVersion('ggplot2') <= '1.0.1') {
252 if (rv$layers[[i]]$geom$objname %in% c('point')) {
253 rv$layers[[i]]$geom_params$size <- 3
254 rv$layers[[i]]$geom_params$shape <- gs
255 }
256 } else {
257 if (inherits(rv$layers[[i]]$geom, 'GeomPoint')) {
258 rv$layers[[i]]$aes_params$size <- 3
259 rv$layers[[i]]$aes_params$shape <- gs
260 }
261 }
262 }
263
264 ## geom colors
265 if (is.null(rv$labels$colour) & is.null(rv$labels$fill)) {
266
267 ## update layers with one color
268 ## this is an ugly hack but `update_geom_defaults`
269 ## is not reversible :(
270 if (packageVersion('ggplot2') <= '1.0.1') {
271 for (i in 1:length(rv$layers)) {
272 if (rv$layers[[i]]$geom$objname %in% c('histogram', 'bar')) {
273 rv$layers[[i]]$geom_params$fill <- cs[i]
274 rv$layers[[i]]$geom_params$colour <- tc
275 } else {
276 if (rv$layers[[i]]$geom$objname %in% c('boxplot')) {
277 rv$layers[[i]]$geom_params$fill <- cs[i]
278 rv$layers[[i]]$geom_params$colour <- 'black'
279 } else {
280 if (rv$layers[[i]]$geom$objname %in% c('point')) {
281 rv$layers[[i]]$geom_params$fill <- tc
282 rv$layers[[i]]$geom_params$colour <- cs[i]
283 } else
284 rv$layers[[i]]$geom_params$colour <- cs[i]
285 }
286 }
287 }
288 } else {
289 for (i in 1:length(rv$layers)) {
290 if (inherits(rv$layers[[i]]$geom, 'GeomBar')) {
291 rv$layers[[i]]$aes_params$fill <- cs[i]
292 rv$layers[[i]]$aes_params$colour <- tc
293 } else {
294 if (inherits(rv$layers[[i]]$geom, 'GeomBoxplot')) {
295 rv$layers[[i]]$aes_params$fill <- cs[i]
296 rv$layers[[i]]$aes_params$colour <- 'black'
297 } else {
298 if (inherits(rv$layers[[i]]$geom, 'GeomPoint')) {
299 rv$layers[[i]]$aes_params$fill <- tc
300 rv$layers[[i]]$aes_params$colour <- cs[i]
301 } else
302 rv$layers[[i]]$aes_params$colour <- cs[i]
303 }
304 }
305 }
306 }
307
308 } else {
309
310 ## we have a possible color scale (only dealing with discrete scales)
311 if (is.null(rv$labels$colour)) {
312
313 ## the scale of geom_tile is continuous
314 if (packageVersion('ggplot2') <= '1.0.1') {
315 tile <- rv$layers[[1]]$geom$objname %in% 'tile'
316 } else {
317 tile <- inherits(rv$layers[[1]]$geom, 'GeomTile')
318 }
319
320 if (length(rv$scales$scales) == 0 & !tile) {
321 rv <- rv + ggplot2::scale_fill_manual(values = cs)
322 } else {
323 ## we still might have something without a guide
324 if (!'continuous' %in% unlist(lapply(rv$scales$scales, class)) & !tile)
325 rv <- rv + ggplot2::scale_fill_manual(values = cs, guide = FALSE)
326 }
327
328 } else {
329
330 if (length(rv$scales$scales) == 0) {
331 rv <- rv + ggplot2::scale_colour_manual(values = cs)
332 } else {
333 ## we still might have something without a guide
334 if (!'continuous' %in% unlist(lapply(rv$scales$scales, class)))
335 rv <- rv + ggplot2::scale_colour_manual(values = cs, guide = FALSE)
336 }
337
338 }
339
340 ## no solid shapes
341 rv <- rv + ggplot2::scale_shape(solid = FALSE)
342
343 }
344
345 ## grid
346 if (!panderOptions('graph.grid')) {
347 rv$theme$panel.grid.minor <- rv$theme$panel.grid.major <- ggplot2::element_blank()
348 } else {
349 if (!panderOptions('graph.grid.minor')) {
350 rv$theme$panel.grid.major <- ggplot2::element_line(colour = gc,
351 size = 0.2,
352 linetype = gl)
353 rv$theme$panel.grid.minor <- ggplot2::element_blank()
354 } else {
355 rv$theme$panel.grid.minor <- ggplot2::element_line(colour = gc,
356 size = 0.1,
357 linetype = gl)
358 rv$theme$panel.grid.major <- ggplot2::element_line(colour = gc,
359 size = 0.2,
360 linetype = gl)
361 }
362 }
363
364 ## axis angle
365 if (aa == 0) {
366 rv$theme$axis.text.y <- ggplot2::element_text(colour = fc,
367 family = ff,
368 face = 'plain',
369 size = fs * 0.8,
370 angle = 90)
371 }
372 if (aa == 2) {
373 rv$theme$axis.text.x <- ggplot2::element_text(colour = fc,
374 family = ff,
375 face = 'plain',
376 size = fs * 0.8,
377 angle = 90,
378 hjust = 1)
379 }
380 if (aa == 3) {
381 rv$theme$axis.text.y <- ggplot2::element_text(colour = fc,
382 family = ff,
383 face = 'plain',
384 size = fs * 0.8,
385 angle = 90)
386 rv$theme$axis.text.x <- ggplot2::element_text(colour = fc,
387 family = ff,
388 face = 'plain',
389 size = fs * 0.8,
390 angle = 90,
391 hjust = 1)
392 }
393
394 ## legend
395 if (!is.null(rv$theme$legend.position)) {
396 if (rv$theme$legend.position != 'none') {
397 rv$theme$legend.position <- panderOptions('graph.legend.position')
398 }
399 } else {
400 rv$theme$legend.position <- panderOptions('graph.legend.position')
401 }
402
403 }
404
405 }
406
407 ## grab output
408 output <- vector('character')
409 con <- textConnection('output', 'wr', local = TRUE)
410 sink(con, split = FALSE)
411
412 p.result <- tryCatch(print(rv), error = function(e) e)
413
414 ## error while printing
415 if (inherits(p.result, 'error')) {
416 error <- p.result$message
417 }
418
419 result <- rv
420
421 sink()
422 close(con)
423
424 } else {
425
426 result <- output <- NULL
427
428 }
429 }
430
431 if (is.null(error)) {
432 type <- rvc
433 } else {
434 result <- output <- NULL
435 type <- 'error'
436 }
437
438 ## return
439 list(src = src,
440 result = result,
441 output = output,
442 type = type,
443 msg = list(
444 messages = messages,
445 warnings = warnings,
446 errors = error),
447 stdout = stdout)
448
449 }
450
451
452 #' Evaluate and Process R Code
453 #'
454 #' This function takes either a vector/list of \emph{strings} with actual R code, which it to be \code{parse}d to separate elements. Each list element is \code{eval}uated in a special environment, and a detailed list of results is returned for each logical part of the R code: a character value with R code, resulting R object, printed output, class of resulting R object, possible informative/warning/error messages and anything written to \code{stdout}. If a graph is plotted in the given text, the returned object is a string specifying the path to the saved file. Please see Details below.
455 #' If \code{parse} option set to \code{FALSE}, then the returned list's length equals to the length of the \code{parse}d input - as each string is evaluated as separate R code in the same environment. If a nested list of R code or a concatenated string (separated by \code{\\n} or \code{;}) is provided like \code{list(c('runif(1)', 'runif(1)'))} with \code{parse=FALSE}, then everything is \code{eval}ed at one run so the length of returned list equals to one or the length of the provided nested list. See examples below.
456 #'
457 #' As \code{\link{evals}} tries to grab the plots internally, pleas do not run commands that set graphic device or \code{dev.off}. E.g. running \code{evals(c('png("/tmp/x.png")', 'plot(1:10)', 'dev.off()'))} would fail. \code{print}ing of \code{lattice} and \code{ggplot2} objects is not needed, \code{evals} would deal with that automatically.
458 #'
459 #' The generated image file(s) of the plots can be fine-tuned by some specific options, please check out \code{graph.output}, \code{width}, \code{height}, \code{res}, \code{hi.res}, \code{hi.res.width}, \code{hi.res.height} and \code{hi.res.res} parameters. Most of these options are better not to touch, see details of parameters below.
460 #'
461 #' Returned result values: list with the following elements
462 #' \itemize{
463 #' \item \emph{src} - character vector of specified R code.
464 #' \item \emph{result} - result of evaluation. \code{NULL} if nothing is returned. If any R code returned an R object while evaluating then the \emph{last} R object will be returned as a raw R object. If a graph is plotted in the given text, the returned object is a string (with \code{class} set to \code{image}) specifying the path to the saved image file. If graphic device was touched, then no other R objects will be returned.
465 #' \item \emph{output} - character vector of printed version (\code{capture.output}) of \code{result}
466 #' \item \emph{type} - class of generated output. 'NULL' if nothing is returned, 'error' if some error occurred.
467 #' \item \emph{msg} - possible messages grabbed while evaluating specified R code with the following structure:
468 #' \itemize{
469 #' \item \emph{messages} - character vector of possible diagnostic message(s)
470 #' \item \emph{warnings} - character vector of possible warning message(s)
471 #' \item \emph{errors} - character vector of possible error message(s)
472 #' }
473 #' \item \emph{stdout} - character vector of possibly printed texts to standard output (console)
474 #' }
475 #'
476 #' By default \code{evals} tries to \emph{cache} results. This means that if evaluation of some R commands take too much time (specified in \code{cache.time} parameter), then \code{evals} would save the results in a file and return from there on next exact R code's evaluation. This caching algorithm tries to be smart as checks not only the passed R sources, but all variables inside that and saves the hash of those.
477 #'
478 #' Technical details of the caching algorithm:
479 #' \itemize{
480 #' \item Each passed R chunk is \code{parse}d to single commands.
481 #' \item Each parsed command's part (let it be a function, variable, constant etc.) \code{eval}uated (as a \code{name}) separately to a \code{list}. This list describes the unique structure and the content of the passed R commands, and has some IMHO really great benefits (see examples below).
482 #' \item A hash if computed to each list element and cached too in \code{pander}'s local environments. This is useful if you are using large data frames, just imagine: the caching algorithm would have to compute the hash for the same data frame each time it's touched! This way the hash is recomputed only if the R object with the given name is changed.
483 #' \item The list is \code{serialize}d and an \code{SHA-1} hash is computed for that - which is unique and there is no real risk of collision.
484 #' \item If \code{evals} can find the cached results in a file named to the computed hash, then it is returned on the spot.
485 #' \item Otherwise the call is evaluated and the results are optionally saved to cache (e.g. if \code{cache} is active, if the \code{proc.time()} of the evaluation is higher then it is defined in \code{cache.time} etc.).
486 #' }
487 #'
488 #' This is a quite secure way of caching, but if you would encounter any issues, just set \code{cache} to \code{FALSE} or tweak other cache parameters. While setting \code{cache.dir}, please do think about what you are doing and move your \code{graph.dir} accordingly, as \code{evals} might result in returning an image file path which is not found any more on your file system!
489 #'
490 #' Also, if you have generated a plot and rendered that to e.g. \code{png} before and later try to get e.g. \code{pdf} - it would fail with \code{cache} on. Similarly you cannot render a high resolution image of a cached image, but you have to (temporary) disable caching.
491 #'
492 #' The default \code{evals} options could be set globally with \code{\link{evalsOptions}}, e.g. to switch off the cache just run \code{evalsOptions('cache', FALSE)}.
493 #'
494 #' Please check the examples carefully below to get a detailed overview of \code{\link{evals}}.
495 #' @param txt a character vector containing R code. This could be a list/vector of lines of code or a simple string holding R code separated by \code{;} or \code{\\n}.
496 #' @param parse if \code{TRUE} the provided \code{txt} elements would be merged into one string and parsed to logical chunks. This is useful if you would want to get separate results of your code parts - not just the last returned value, but you are passing the whole script in one string. To manually lock lines to each other (e.g. calling a \code{plot} and on next line adding an \code{abline} or \code{text} to it), use a plus char (\code{+}) at the beginning of each line which should be evaluated with the previous one(s). If set to \code{FALSE}, \code{evals} would not try to parse R code, it would get evaluated in separate runs - as provided. Please see examples below.
497 #' @param cache caching the result of R calls if set to \code{TRUE}. Please note the caching would not work if \code{parse} set to \code{FALSE} or syntax error is to be found.
498 #' @param cache.mode cached results could be stored in an \code{environment} in \emph{current} R session or let it be permanent on \code{disk}.
499 #' @param cache.dir path to a directory holding cache files if \code{cache.mode} set to \code{disk}. Default to \code{.cache} in current working directory.
500 #' @param cache.time number of seconds to limit caching based on \code{proc.time}. If set to \code{0}, all R commands, if set to \code{Inf}, none is cached (despite the \code{cache} parameter).
501 #' @param cache.copy.images copy images to new file names if an image is returned from the \emph{disk} cache? If set to \code{FALSE} (default), the cached path would be returned.
502 #' @param showInvisible return \code{invisible} results?
503 #' @param classes a vector or list of classes which should be returned. If set to \code{NULL} (by default) all R objects will be returned.
504 #' @param hooks list of hooks to be run for given classes in the form of \code{list(class = fn)}. If you would also specify some parameters of the function, a list should be provided in the form of \code{list(fn, param1, param2=NULL)} etc. So the hooks would become \code{list(class1=list(fn, param1, param2=NULL), ...)}. See example below. A default hook can be specified too by setting the class to \code{'default'}. This can be handy if you do not want to define separate methods/functions to each possible class, but automatically apply the default hook to all classes not mentioned in the list. You may also specify only one element in the list like: \code{hooks=list('default' = pander_return)}. Please note, that nor error/warning messages, nor stdout is captured (so: updated) while running hooks!
505 #' @param length any R object exceeding the specified length will not be returned. The default value (\code{Inf}) does not filter out any R objects.
506 #' @param output a character vector of required returned values. This might be useful if you are only interested in the \code{result}, and do not want to save/see e.g. \code{messages} or \code{print}ed \code{output}. See examples below.
507 #' @param env environment where evaluation takes place. If not set (by default), a new temporary environment is created.
508 #' @param graph.unify should \code{evals} try to unify the style of (\code{base}, \code{lattice} and \code{ggplot2}) plots? If set to \code{TRUE}, some \code{panderOptions()} would apply. By default this is disabled not to freak out useRs :)
509 #' @param graph.name set the file name of saved plots which is \code{\link{tempfile}} by default. A simple character string might be provided where \code{\%d} would be replaced by the index of the generating \code{txt} source, \code{\%n} with an incremented integer in \code{graph.dir} with similar file names and \code{\%t} by some unique random characters. While running in \code{\link{Pandoc.brew}} other indices could be triggered like \code{\%i} and \code{\%I}.
510 #' @param graph.dir path to a directory where to place generated images. If the directory does not exist, \code{evals} try to create that. Default set to \code{plots} in current working directory.
511 #' @param graph.output set the required file format of saved plots. Currently it could be any of \code{grDevices}': \code{png}, \code{bmp}, \code{jpeg}, \code{jpg}, \code{tiff}, \code{svg} or \code{pdf}.
512 #' @param width width of generated plot in pixels for even vector formats
513 #' @param height height of generated plot in pixels for even vector formats
514 #' @param res nominal resolution in \code{ppi}. The height and width of vector images will be calculated based in this.
515 #' @param hi.res generate high resolution plots also? If set to \code{TRUE}, each R code parts resulting an image would be run twice.
516 #' @param hi.res.width width of generated high resolution plot in pixels for even vector formats
517 #' @param hi.res.height height of generated high resolution plot in pixels for even vector formats. This value can be left blank to be automatically calculated to match original plot aspect ratio.
518 #' @param hi.res.res nominal resolution of high resolution plot in ppi. The height and width of vector plots will be calculated based in this. This value can be left blank to be automatically calculated to fit original plot scales.
519 #' @param graph.env save the environments in which plots were generated to distinct files (based on \code{graph.name}) with \code{env} extension?
520 #' @param graph.recordplot save the plot via \code{recordPlot} to distinct files (based on \code{graph.name}) with \code{recodplot} extension?
521 #' @param graph.RDS save the raw R object returned (usually with \code{lattice} or \code{ggplot2}) while generating the plots to distinct files (based on \code{graph.name}) with \code{RDS} extension?
522 #' @param log an optionally passed \emph{namespace} for \pkg{logger} to record all info, trace, debug and error messages.
523 #' @param ... optional parameters passed to graphics device (e.g. \code{bg}, \code{pointsize} etc.)
524 #' @return a list of parsed elements each containing: \code{src} (the command run), \code{result} (R object: \code{NULL} if nothing returned, path to image file if a plot was generated), \code{print}ed \code{output}, \code{type} (class of returned object if any), informative/wawrning and error messages (if any returned by the command run, otherwise set to \code{NULL}) and possible \code{stdout}t value. See Details above.
525 #' @seealso \code{\link{eval.msgs}} \code{\link{evalsOptions}}
526 #' @examples \dontrun{
527 #' # parsing several lines of R code
528 #' txt <- readLines(textConnection('x <- rnorm(100)
529 #' runif(10)
530 #' warning('Lorem ipsum foo-bar-foo!')
531 #' plot(1:10)
532 #' qplot(rating, data = movies, geom = 'histogram')
533 #' y <- round(runif(100))
534 #' cor.test(x, y)
535 #' crl <- cor.test(runif(10), runif(10))
536 #' table(mtcars$am, mtcars$cyl)
537 #' ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))'))
538 #' evals(txt)
539 #'
540 #' ## parsing a list of commands
541 #' txt <- list('df <- mtcars',
542 #' c('plot(mtcars$hp, pch = 19)','text(mtcars$hp, label = rownames(mtcars), pos = 4)'),
543 #' 'ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))')
544 #' evals(txt)
545 #'
546 #' ## the same commands in one string but also evaluating the `plot` with `text`
547 #' ## (note the leading '+' on the beginning of `text...` line)
548 #' txt <- 'df <- mtcars
549 #' plot(mtcars$hp, pch = 19)
550 #' +text(mtcars$hp, label = rownames(mtcars), pos = 4)
551 #' ggplot(mtcars) + geom_point(aes(x = hp, y = mpg))'
552 #' evals(txt)
553 #' ## but it would fail without parsing
554 #' evals(txt, parse = FALSE)
555 #'
556 #' ## handling messages
557 #' evals('message(20)')
558 #' evals('message(20);message(20)', parse = FALSE)
559 #'
560 #' ## adding a caption to a plot
561 #' evals('set.caption("FOO"); plot(1:10)')
562 #' ## `plot` is started with a `+` to eval the codes in the same chunk
563 #' ## (no extra chunk with NULL result)
564 #' evals('set.caption("FOO"); +plot(1:10)')
565 #'
566 #' ## handling warnings
567 #' evals('chisq.test(mtcars$gear, mtcars$hp)')
568 #' evals(list(c('chisq.test(mtcars$gear, mtcars$am)', 'pi',
569 #' 'chisq.test(mtcars$gear, mtcars$hp)')), parse = FALSE)
570 #' evals(c('chisq.test(mtcars$gear, mtcars$am)',
571 #' 'pi',
572 #' 'chisq.test(mtcars$gear, mtcars$hp)'))
573 #'
574 #' ## handling errors
575 #' evals('runiff(20)')
576 #' evals('Old MacDonald had a farm\\dots')
577 #' evals('## Some comment')
578 #' evals(c('runiff(20)', 'Old MacDonald had a farm?'))
579 #' evals(list(c('runiff(20)', 'Old MacDonald had a farm?')), parse = FALSE)
580 #' evals(c('mean(1:10)', 'no.R.function()'))
581 #' evals(list(c('mean(1:10)', 'no.R.function()')), parse = FALSE)
582 #' evals(c('no.R.object', 'no.R.function()', 'very.mixed.up(stuff)'))
583 #' evals(list(c('no.R.object', 'no.R.function()', 'very.mixed.up(stuff)')), parse = FALSE)
584 #' evals(c('no.R.object', 'Old MacDonald had a farm\\dots', 'pi'))
585 #' evals('no.R.object;Old MacDonald had a farm\\dots;pi', parse = FALSE)
586 #' evals(list(c('no.R.object', 'Old MacDonald had a farm\\dots', 'pi')), parse = FALSE)
587 #'
588 #' ## graph options
589 #' evals('plot(1:10)')
590 #' evals('plot(1:10);plot(2:20)')
591 #' evals('plot(1:10)', graph.output = 'jpg')
592 #' evals('plot(1:10)', height = 800)
593 #' evals('plot(1:10)', height = 800, hi.res = TRUE)
594 #' evals('plot(1:10)', graph.output = 'pdf', hi.res = TRUE)
595 #' evals('plot(1:10)', res = 30)
596 #' evals('plot(1:10)', graph.name = 'myplot')
597 #' evals(list('plot(1:10)', 'plot(2:20)'), graph.name = 'myplots-%d')
598 #' evals('plot(1:10)', graph.env = TRUE)
599 #' evals('x <- runif(100);plot(x)', graph.env = TRUE)
600 #' evals(c('plot(1:10)', 'plot(2:20)'), graph.env = TRUE)
601 #' evals(c('x <- runif(100)', 'plot(x)','y <- runif(100)', 'plot(y)'), graph.env = TRUE)
602 #' evals(list(
603 #' c('x <- runif(100)', 'plot(x)'),
604 #' c('y <- runif(100)', 'plot(y)')),
605 #' graph.env = TRUE, parse = FALSE)
606 #' evals('plot(1:10)', graph.recordplot = TRUE)
607 #' ## unprinted lattice plot
608 #' evals('histogram(mtcars$hp)', graph.recordplot = TRUE)
609 #'
610 #' ## caching
611 #' system.time(evals('plot(mtcars)'))
612 #' system.time(evals('plot(mtcars)')) # running again to see the speed-up :)
613 #' system.time(evals('plot(mtcars)', cache = FALSE)) # cache disabled
614 #'
615 #' ## caching mechanism does check what's inside a variable:
616 #' x <- mtcars
617 #' evals('plot(x)')
618 #' x <- cbind(mtcars, mtcars)
619 #' evals('plot(x)')
620 #' x <- mtcars
621 #' system.time(evals('plot(x)'))
622 #'
623 #' ## stress your CPU - only once!
624 #' evals('x <- sapply(rep(mtcars$hp, 1e3), mean)') # run it again!
625 #'
626 #' ## play with cache
627 #' require(lattice)
628 #' evals('histogram(rep(mtcars$hp, 1e5))')
629 #' ## nor run the below call
630 #' ## that would return the cached version of the above call :)
631 #' f <- histogram
632 #' g <- rep
633 #' A <- mtcars$hp
634 #' B <- 1e5
635 #' evals('f(g(A, B))')#'
636 #'
637 #' ## or switch off cache globally:
638 #' evalsOptions('cache', FALSE)
639 #' ## and switch on later
640 #' evalsOptions('cache', TRUE)
641 #'
642 #' ## evaluate assignments inside call to evals
643 #' ## changes to environments are cached properly and retreived
644 #' evalsOptions('cache.time', 0)
645 #' x <- 2
646 #' evals('x <- x^2')[[1]]$result
647 #' evals('x <- x^2; x + 1')[[2]]$result
648 #' evalsOptions('cache.time', 0.1)
649 #'
650 #' ## returning only a few classes
651 #' txt <- readLines(textConnection('rnorm(100)
652 #' list(x = 10:1, y = 'Godzilla!')
653 #' c(1,2,3)
654 #' matrix(0,3,5)'))
655 #' evals(txt, classes = 'numeric')
656 #' evals(txt, classes = c('numeric', 'list'))
657 #'
658 #' ## hooks
659 #' txt <- 'runif(1:4); matrix(runif(25), 5, 5); 1:5'
660 #' hooks <- list('numeric' = round, 'matrix' = pander_return)
661 #' evals(txt, hooks = hooks)
662 #' ## using pander's default hook
663 #' evals(txt, hooks = list('default' = pander_return))
664 #' evals('22/7', hooks = list('numeric' = round))
665 #' evals('matrix(runif(25), 5, 5)', hooks = list('matrix' = round))
666 #'
667 #' ## setting default hook
668 #' evals(c('runif(10)', 'matrix(runif(9), 3, 3)'),
669 #' hooks = list('default'=round))
670 #' ## round all values except for matrices
671 #' evals(c('runif(10)', 'matrix(runif(9), 3, 3)'),
672 #' hooks = list(matrix = 'print', 'default' = round))
673 #'
674 #' # advanced hooks
675 #' hooks <- list('numeric' = list(round, 2), 'matrix' = list(round, 1))
676 #' evals(txt, hooks = hooks)
677 #'
678 #' # return only returned values
679 #' evals(txt, output = 'result')
680 #'
681 #' # return only messages (for checking syntax errors etc.)
682 #' evals(txt, output = 'msg')
683 #'
684 #' # check the length of returned values and do not return looong R objects
685 #' evals('runif(10)', length = 5)
686 #'
687 #' # note the following will not be filtered!
688 #' evals('matrix(1,1,1)', length = 1)
689 #'
690 #' # if you do not want to let such things be eval-ed in the middle of a string
691 #' # use it with other filters :)
692 #' evals('matrix(1,1,1)', length = 1, classes = 'numeric')
693 #'
694 #' # hooks & filtering
695 #' evals('matrix(5,5,5)',
696 #' hooks = list('matrix' = pander_return),
697 #' output = 'result')
698 #'
699 #' # eval-ing chunks in given environment
700 #' myenv <- new.env()
701 #' evals('x <- c(0,10)', env = myenv)
702 #' evals('mean(x)', env = myenv)
703 #' rm(myenv)
704 #' # note: if you had not specified 'myenv', the second 'evals' would have failed
705 #' evals('x <- c(0,10)')
706 #' evals('mean(x)')
707 #'
708 #' # log
709 #' x <- evals('1:10', log = 'foo')
710 #' # trace log
711 #' evalsOptions('cache.time', 0)
712 #' x <- evals('1:10', log = 'foo')
713 #' x <- evals('1:10', log = 'foo')
714 #' # log to file
715 #' t <- tempfile()
716 #' log_appender(appender_file(t), name = 'evals')
717 #' x <- evals('1:10', log = 'evals')
718 #' readLines(t)
719 #' # permanent log for all events
720 #' evalsOptions('log', 'evals')
721 #' log_threshold(TRACE, 'evals')
722 #' evals('foo')
723 #' }
724 #' @export
725 #' @importFrom digest digest
726 #' @importFrom grDevices dev.list dev.off dev.control dev.list recordPlot
727 #' @importFrom utils packageVersion object.size
728 evals <- function(txt, parse = evalsOptions('parse'), cache = evalsOptions('cache'), cache.mode = evalsOptions('cache.mode'), cache.dir = evalsOptions('cache.dir'), cache.time = evalsOptions('cache.time'), cache.copy.images = evalsOptions('cache.copy.images'), showInvisible = FALSE, classes = evalsOptions('classes'), hooks = evalsOptions('hooks'), length = evalsOptions('length'), output = evalsOptions('output'), env = NULL, graph.unify = evalsOptions('graph.unify'), graph.name = evalsOptions('graph.name'), graph.dir = evalsOptions('graph.dir'), graph.output = evalsOptions('graph.output'), width = evalsOptions('width'), height = evalsOptions('height'), res = evalsOptions('res'), hi.res = evalsOptions('hi.res'), hi.res.width = evalsOptions('hi.res.width'), hi.res.height = 960 * (height / width), hi.res.res = res * (hi.res.width / width), graph.env = evalsOptions('graph.env'), graph.recordplot = evalsOptions('graph.recordplot'), graph.RDS = evalsOptions('graph.RDS'), log = evalsOptions('log'), ...) { #nolint
729
730 if (missing(txt)) {
731 stop('No R code provided to evaluate!')
732 }
733 txt.original <- paste(txt, collapse = '\n')
734
735 ## logging constant
736 logging <- !is.null(log) && requireNamespace('logger', quietly = TRUE)
737
738 ## parse provided code after concatenating
739 if (parse) {
740
741 txt.parsed <- tryCatch(parse(text = txt), error = function(e) e)
742
743 ## skip parsing on syntax error and disable cache
744 if (inherits(txt.parsed, 'error')) {
745 cache <- FALSE
746 } else {
747
748 txt <- sapply(txt.parsed, function(x) paste(deparse(x), collapse = '\n'))
749
750 ## return NULL on missing R code (e.g. comments)
751 if (length(txt) == 0) {
752 return(list(structure(list(src = txt.original,
753 result = NULL,
754 output = NULL,
755 type = NULL,
756 msg = list(
757 messages = NULL,
758 warnings = NULL,
759 errors = NULL),
760 stdout = NULL
761 ), 'class' = 'evals')))
762 }
763
764 ## (re)merge lines on demand (based on `+` at the beginning of line)
765 txt.sep <- c(which(!grepl('^\\+', txt)), length(txt) + 1)
766 txt <- lapply(1:(length(txt.sep) - 1), function(i) txt[txt.sep[i] : (txt.sep[i + 1] - 1)])
767 txt <- rapply(txt, function(x) sub('^\\+', '', x), how = 'replace')
768
769 }
770 } else {
771 cache <- FALSE
772 }
773
774 ## check provided dirs
775 if (!identical(file.info(graph.dir)$isdir, TRUE) &&
776 !dir.create(graph.dir, showWarnings = FALSE, recursive = TRUE)) {
777 stop(sprintf('Something is definitely wrong with `graph.dir`: %s!', graph.dir))
778 }
779 if (cache.mode == 'disk' &&
780 !identical(file.info(cache.dir)$isdir, TRUE) &&
781 !dir.create(cache.dir, showWarnings = FALSE, recursive = TRUE)) {
782 stop(sprintf('Something is definitely wrong with `cache.dir`: %s!', cache.dir))
783 }
784
785 ## check provided parameters
786 if ('all' %in% output) {
787 output <- c('src', 'result', 'output', 'type', 'msg', 'stdout')
788 } else if (length(setdiff(output, c('src', 'result', 'output', 'type', 'msg', 'stdout'))) != 0) {
789 stop('Wrong parameter supplied to output')
790 }
791
792 if (!is.null(hooks) && !is.list(hooks)) {
793 stop('Wrong list of hooks provided!')
794 }
795
796 if (!is.character(graph.name)) {
797 stop('Wrong graph.name (!character) specified!')
798 }
799
800 if (!is.na(graph.output) && graph.output == 'jpg') {
801 graph.output <- 'jpeg'
802 }
803
804 ## env for running all lines of code
805 if (is.null(env) || !is.environment(env)) {
806 env <- new.env()
807 }
808 for (p in c('plot', 'barplot', 'lines', 'pie', 'boxplot', 'polygon',
809 'points', 'legend', 'hist', 'pairs', 'stripchart')) {
810 if (exists(p, envir = env, inherits = FALSE)) {
811 stop(paste0('Using a reserved word as variable: `', p, '`'))
812 }
813 }
814
815 `%d` <- 0
816
817 ## main loop
818 lapply(txt, function(src) {
819
820 ## log R expression
821 if (logging) {
822 logger::log_info(paste('Command run:', gsub('[ ]+', ' ', gsub('\n', ' ', src))), namespace = log)
823 }
824
825 if (!is.na(graph.output)) {
826
827 ## get image file name
828 `%d` <<- `%d` + 1
829 file.name <- gsub('%d', `%d`, graph.name, fixed = TRUE)
830
831 ## chunk ID
832 if (length(debug$chunkID) > 0) {
833 if ((length(debug$nestedID) > 0) && (debug$nestedID > 1)) {
834 file.name <- gsub('%i', paste0(debug$nestedID, '_', debug$chunkID), file.name, fixed = TRUE)
835 } else {
836 file.name <- gsub('%i', debug$chunkID, file.name, fixed = TRUE)
837 }
838 }
839 if (length(debug$cmdID) > 0) {
840 assign('cmdID', debug$cmdID + 1, envir = debug)
841 file.name <- gsub('%I', debug$cmdID, file.name, fixed = TRUE)
842 }
843 file <- sprintf('%s.%s', file.name, graph.output)
844
845 ## tempfile
846 if (grepl('%t', graph.name)) {
847 if (length(strsplit(sprintf('placeholder%splaceholder', file.name), '%t')[[1]]) > 2) {
848 stop('File name contains more then 1 "%t"!')
849 }
850 rep <- strsplit(file, '%t')[[1]]
851 file <- tempfile(pattern = rep[1], tmpdir = graph.dir, fileext = rep[2])
852 file.name <- sub(sprintf('.%s$', graph.output), '', file)
853 } else {
854 file <- file.path(graph.dir, file)
855 file.name <- file.path(graph.dir, file.name)
856 }
857 file <- gsub('\\', '/', file, fixed = TRUE)
858 file.name <- gsub('\\', '/', file.name, fixed = TRUE)
859
860 ## similar files counter
861 if (grepl('%n', file.name)) {
862 if (length(strsplit(sprintf('placeholder%splaceholder', file.name), '%n')[[1]]) > 2) {
863 stop('File name contains more then 1 "%n"!')
864 }
865 similar.files <- list.files(graph.dir, pattern = sprintf('^%s\\.(jpeg|tiff|png|svg|bmp|pdf)$', gsub('%t', '[a-z0-9]*', gsub('%d|%n|%i', '[[:digit:]]*', basename(file.name))))) #nolint
866 if (length(similar.files) > 0) {
867 similar.files <- sub('\\.(jpeg|tiff|png|svg|bmp|pdf)$', '', similar.files)
868 rep <- gsub('%t', '[a-z0-9]*',
869 gsub('%d|%i', '[[:digit:]]*',
870 strsplit(basename(file.name), '%n')[[1]]))
871 `%n` <- max(as.numeric(gsub(paste(rep, collapse = '|'), '', similar.files))) + 1
872 } else {
873 `%n` <- 1
874 }
875 file.name <- gsub('%n', `%n`, file.name, fixed = TRUE)
876 file <- gsub('%n', `%n`, file, fixed = TRUE)
877 }
878
879 }
880
881 ## checking cache
882 if (cache) {
883
884 ## helper functions
885 hash_of_eval_or_deparse <- function(x, x.deparse) {
886 ## compute the hash of the given 'name' by evaluating that or by deparsing if the prior would fail
887 v <- tryCatch(eval(x, envir = env), error = function(e) e)
888 if (inherits(v, 'error')) {
889 return(digest(x.deparse))
890 }
891 hash_from_cache(v, x.deparse)
892 }
893
894 hash_from_cache <- function(x, x.deparse) {
895 ## get the hash of the object from local cache if possible, compute it and save to cache otherwise
896 if (exists(x.deparse, envir = hash.cache.obj, inherits = FALSE)) {
897 if (identical(x, get(x.deparse, envir = hash.cache.obj))) {
898 assign(x.deparse, as.integer(Sys.time()), envir = hash.cache.last.used)
899 return(get(x.deparse, envir = hash.cache.hash))
900 }
901 }
902 x.hash <- digest(x, 'sha1')
903 assign(x.deparse, x, envir = hash.cache.obj)
904 assign(x.deparse, x.hash, envir = hash.cache.hash)
905 assign(x.deparse, as.integer(Sys.time()), envir = hash.cache.last.used)
906 return(x.hash)
907 }
908
909 get_call_parts <- function(call) {
910 ## extracting each function's and variable's hash from the call
911 lapply(call, function(x){
912 switch(mode(x),
913 'name' = hash_of_eval_or_deparse(x, deparse(x)),
914 'call' = get_call_parts(x),
915 digest(deparse(x), 'sha1')
916 )
917 })
918 }
919
920 ## get the hash of the call based on the hash of all `names`
921 cached <- digest(list(call = get_call_parts(parse(text = src)),
922 storage = digest(list(storage, panderOptions(), evalsOptions()), 'sha1')),
923 'sha1')
924
925 if (cache.mode == 'disk') {
926
927 cached <- file.path(cache.dir, cached)
928 cached.env <- paste0(cached, '.ENV')
929
930 ## load cached result
931 if (file.exists(cached)) {
932 cached.result <- readRDS(cached)
933 }
934
935 ## load the modified R objects of the cached code
936 if (file.exists(cached.env)) {
937 load(file = cached.env, envir = env)
938 }
939
940 } else {
941 ## cache is in environment
942 ## load cached result
943 if (exists(cached, envir = cached.results, inherits = FALSE)) {
944 cached.result <- get(cached, envir = cached.results)
945 }
946
947 ## if the cached expression changed the environment (for example assignment),
948 ## retrieve the respected changes too (see examples)
949 if (exists(cached, envir = cached.environments, inherits = FALSE)) {
950 cached.objs <- get(cached, envir = cached.environments)
951 sapply(names(cached.objs), function(x) assign(x, cached.objs[[x]], envir = env))
952 }
953
954 }
955
956 if (exists('cached.result')) {
957
958 if (inherits(cached.result$result, 'image')) {
959
960 if (cache.copy.images && cache.mode == 'disk' && !is.na(graph.output)) {
961
962 ## we are copying img file + possibly extra from cache dir
963 file.copy(paste0(cached, '.', graph.output), file)
964 if (graph.recordplot) {
965 file.copy(paste0(cached, '.recordedplot'), sprintf('%s.recordplot', file.name))
966 }
967 if (graph.RDS) {
968 file.copy(paste0(cached, '.RDS'), sprintf('%s.RDS', file.name))
969 }
970 if (graph.env) {
971 file.copy(paste0(cached, '.env'), sprintf('%s.env', file.name))
972 }
973 if (hi.res) {
974 file.copy(paste0(cached, '-hires.', graph.output),
975 sprintf('%s-hires.%s', file.name, graph.output))
976 }
977
978 cached.result$result <- file
979 class(cached.result$result) <- 'image'
980 if (logging) {
981 logger::log_trace(
982 paste('Image copied from cache:', file),
983 namespace = log)
984 }
985 return(cached.result)
986
987 } else {
988
989 ## we are checking in plots' dir if the img file exists
990 cached.image.file <- as.character(cached.result$result)
991 if (file.exists(cached.image.file)) {
992 if (logging) {
993 logger::log_trace(
994 paste('Image found in cache:', cached.image.file),
995 namespace = log)
996 }
997 return(cached.result)
998 } else {
999 warning(sprintf('The image file referenced in cache (%s) is no longer available: the image is recreated (%s).', shQuote(cached.image.file), shQuote(file)), call. = FALSE) #nolint
1000 }
1001
1002 }
1003
1004 } else {
1005 if (logging) {
1006 logger::log_trace('Returning cached R object.', namespace = log)
1007 }
1008 return(cached.result)
1009 }
1010
1011 } # cached result not found
1012
1013 ## starting timer
1014 timer <- proc.time()
1015
1016 }
1017
1018 ## clear graphics device (if there would be any open)
1019 clear.devs <- function() {
1020 if (!is.na(graph.output)) {
1021 sapply(dev.list(), dev.off)
1022 }
1023 }
1024 clear.devs()
1025
1026 if (!is.na(graph.output)) {
1027
1028 ## init (potential) img file
1029 pbg <- panderOptions('graph.background')
1030 if (graph.output %in% c('bmp', 'jpeg', 'png', 'tiff')) {
1031 if (capabilities('cairo')) {
1032 do.call(graph.output, list(file,
1033 width = width,
1034 height = height,
1035 res = res,
1036 bg = pbg,
1037 type = 'cairo', ...))
1038 } else {
1039 do.call(graph.output, list(file,
1040 width = width,
1041 height = height,
1042 res = res,
1043 bg = pbg, ...))
1044 }
1045 }
1046 if (graph.output == 'svg') {
1047 do.call(graph.output, list(file,
1048 width = width / res,
1049 height = height / res,
1050 bg = pbg, ...)) # TODO: font-family?
1051 }
1052 if (graph.output == 'pdf') {
1053 do.call('cairo_pdf', list(file,
1054 width = width / res,
1055 height = height / res,
1056 bg = pbg, ...)) # TODO: font-family?
1057 }
1058
1059 ## start recordPlot
1060 dev.control(displaylist = 'enable')
1061 }
1062
1063 ## if caching: save the initial environment's objects' hashes
1064 if (cache) {
1065 objs <- ls(envir = env)
1066 objs <- setdiff(objs, c('.storage', 'showCode', 'showText'))
1067 objs.hash <- sapply(objs, function(x) hash_of_eval_or_deparse(as.name(x), x))
1068 }
1069
1070 ## add modified base plot functions to update colors, `par` settings and adding a grid
1071 if (graph.unify) {
1072 sapply(ls(envir = masked.plots), function(x) {
1073 assign(x, get(x, envir = masked.plots, inherits = FALSE), envir = env)
1074 })
1075 }
1076
1077 ## env for optional high resolution images
1078 if (hi.res && !is.na(graph.output)) {
1079 env.hires <- env
1080 }
1081
1082 ## eval
1083 res <- eval.msgs(src, env = env, showInvisible = showInvisible, graph.unify = graph.unify)
1084
1085 ## grab recorded.plot
1086 if (!is.na(graph.output) && !is.null(dev.list())) {
1087 recorded.plot <- recordPlot()
1088 dev.control('inhibit')
1089 }
1090
1091 ## did we produce a plot?
1092 if (is.na(graph.output)) {
1093 graph <- FALSE
1094 } else {
1095 graph <- ifelse(exists('recorded.plot'), ifelse(is.null(recorded.plot[[1]]), FALSE, file), FALSE)
1096 }
1097
1098 ## close grDevice
1099 clear.devs()
1100
1101 ## check if image file was created
1102 if (is.character(graph)) {
1103 if (!file.exists(file)) {
1104 res$msg$errors <- c(res$msg$errors, paste('Image file not written by:', paste(src, collapse = ';')))
1105 }
1106 }
1107
1108 ## remove dummy img file (1px) on Windows if created
1109 if (grepl('w|W', .Platform$OS.type)) {
1110 if (!is.character(graph)) {
1111 if (file.exists(file)) {
1112 unlink(file)
1113 }
1114 }
1115 }
1116
1117 ## error handling
1118 if (!is.null(res$msg$errors)) {
1119
1120 ## removing injected base::plot fns
1121 if (graph.unify) {
1122 rm(list = ls(envir = masked.plots), envir = env)
1123 }
1124
1125 class(res) <- 'evals'
1126 if ('plot.new has not been called yet' %in% res$msg$errors) {
1127 res$msg$errors <- 'plot.new has not been called yet - Please note that all R commands are parsed and evaluated separately. To override this default behavior, add a plus sign (+) as the first character of the line(s) to evaluate with the prior one(s).' #nolint
1128 }
1129 if (logging) {
1130 logger::log_error(res$msg$errors, namespace = log)
1131 }
1132 return(res)
1133 }
1134
1135 result <- res$result
1136
1137 ## we have a graph
1138 if (is.character(graph)) {
1139
1140 ## log image file name
1141 if (logging) {
1142 logger::log_trace(paste('Image file written:', file), namespace = log)
1143 }
1144
1145 ## save recorded plot on demand
1146 if (graph.recordplot) {
1147 saveRDS(recorded.plot, file = sprintf('%s.recordplot', file.name))
1148 }
1149
1150 ## save plot RDS on demand
1151 if (graph.RDS) {
1152 if (!is.null(result)) {
1153 saveRDS(result, file = sprintf('%s.RDS', file.name))
1154 }
1155 }
1156
1157 result <- graph
1158 class(result) <- 'image'
1159
1160 ## saving environment on demand
1161 if (graph.env) {
1162 save(list = ls(envir = env), file = sprintf('%s.env', file.name), envir = env)
1163 }
1164
1165 ## generate high resolution images on demand
1166 if (hi.res) {
1167
1168 file.hi.res <- sprintf('%s-hires.%s', file.name, graph.output)
1169
1170 ## initialize high resolution image file
1171 if (graph.output %in% c('bmp', 'jpeg', 'png', 'tiff')) {
1172
1173 if (capabilities('cairo')) {
1174 do.call(graph.output, list(file.hi.res,
1175 width = hi.res.width,
1176 height = hi.res.height,
1177 res = hi.res.res,
1178 bg = pbg,
1179 type = 'cairo', ...))
1180 } else {
1181 do.call(graph.output, list(file.hi.res,
1182 width = hi.res.width,
1183 height = hi.res.height,
1184 res = hi.res.res,
1185 bg = pbg, ...))
1186 }
1187
1188 } else {
1189
1190 if (.Platform$OS.type == 'unix') {
1191 ## a symlink would be fine for vector formats on a unix-like OS
1192 file.symlink(file, file.hi.res)
1193 } else {
1194 ## we have no option to do so on Windows (to be backward compatible)
1195 do.call(graph.output, list(file.hi.res,
1196 width = hi.res.width / hi.res.res,
1197 height = hi.res.height / hi.res.res,
1198 bg = pbg, ...)) # TODO: font-family?
1199 }
1200 }
1201
1202 ## render high resolution image (if needed)
1203 if ((graph.output %in% c('bmp', 'jpeg', 'png', 'tiff')) | (.Platform$OS.type != 'unix')) {
1204 ## we need eval.msgs() here instead of simple eval()
1205 ## to prevent unprinted lattice/ggplot2 objects' issues
1206 eval.msgs(src, env = env.hires)
1207 clear.devs()
1208 }
1209
1210 ## add 'href' attribute to returned R object
1211 attr(result, 'href') <- file.hi.res
1212 }
1213 }
1214
1215 ## check length
1216 if (length(result) > length) {
1217 result <- NULL
1218 }
1219
1220 ## check classes
1221 if (!is.null(classes)) {
1222 if (!inherits(result, classes)) {
1223 result <- output <- NULL
1224 }
1225 }
1226
1227 ## caption
1228 if (!is.null(storage$caption) & !is.null(result)) {
1229 attr(result, 'caption') <- get.caption()
1230 }
1231
1232 ## alignment of tables
1233 if (!is.null(storage$alignment) & !is.null(result)) {
1234 attr(result, 'alignment') <- get.alignment(result)
1235 }
1236
1237 ## highlight cells
1238 if (!is.null(result)) {
1239 result <- get.emphasize(result)
1240 }
1241
1242 ## run hooks if specified
1243 if (!is.null(hooks)) {
1244 hook.name <- ifelse(inherits(result, names(hooks)), class(result), 'default')
1245 fn <- hooks[[hook.name]];
1246 params <- list(result)
1247 if (!is.null(fn)) {
1248 if (is.list(fn)) {
1249 params <- list(result, fn[[-1]])
1250 fn <- fn[[1]]
1251 }
1252 if (logging) {
1253 logger::log_trace(paste('Calling hook for', hook.name), namespace = log)
1254 }
1255 result <- do.call(fn, params)
1256 }
1257 }
1258
1259 ## return list at last
1260 res <- list(src = src,
1261 result = result,
1262 output = res$output,
1263 type = class(result),
1264 msg = list(
1265 messages = res$msg$messages,
1266 warnings = res$msg$warnings,
1267 errors = res$msg$errors),
1268 stdout = res$msg$stdout
1269 )
1270
1271 res <- res[output]
1272 class(res) <- 'evals'
1273
1274 ## removing injected base::plot fns
1275 if (graph.unify) {
1276 rm(list = ls(envir = masked.plots), envir = env)
1277 }
1278
1279 ## save to cache
1280 if (cache) {
1281
1282 ## comparing the resulting environment's objects' hashes with the original ones
1283 objs.res <- ls(envir = env)
1284 objs.res <- setdiff(objs.res, c('.storage', 'showCode', 'showText', '.graph.dir', '.graph.name'))
1285 objs.res.hash <- sapply(objs.res, function(x) hash_of_eval_or_deparse(as.name(x), x))
1286 change <- setdiff(objs.res, objs)
1287 common <- intersect(objs.res, objs)
1288 changed <- c(change, unlist(sapply(common, function(x) {
1289 if (objs.hash[[x]] != objs.res.hash[[x]])
1290 return(x)
1291 },
1292 USE.NAMES = FALSE)))
1293 if (cache.mode == 'disk') {
1294 if (as.numeric(proc.time() - timer)[3] > cache.time) {
1295
1296 ## save cached result
1297 saveRDS(res, file = cached)
1298
1299 ## save the modified R objects of the cached code
1300 if (length(changed) > 0) {
1301 save(list = changed, envir = env, file = paste0(cached, '.ENV'))
1302 }
1303
1304 ## save plot related files
1305 if ('image' %in% class(result)) {
1306 file.copy(file, paste0(cached, '.', graph.output))
1307 if (graph.recordplot) {
1308 file.copy(sprintf('%s.recordplot', file.name), paste0(cached, '.recordedplot'))
1309 }
1310 if (graph.RDS) {
1311 if (!is.null(result)) {
1312 file.copy(sprintf('%s.RDS', file.name), paste0(cached, '.RDS'))
1313 }
1314 }
1315 if (graph.env) {
1316 file.copy(sprintf('%s.env', file.name), paste0(cached, '.env'))
1317 }
1318 if (hi.res) {
1319 file.copy(sprintf('%s-hires.%s', file.name, graph.output),
1320 paste0(cached, '-hires.', graph.output))
1321 }
1322 }
1323 if (logging) {
1324 logger::log_trace('Cached result', namespace = log)
1325 }
1326 }
1327
1328 } else {
1329
1330 if (as.numeric(proc.time() - timer)[3] > cache.time) {
1331
1332 ## save cached result
1333 assign(cached, res, envir = cached.results)
1334
1335 ## save changes to environment so when expression result is retreived from cache
1336 ## changes to environment will be retreived also (see example)
1337 if (length(changed) > 0) {
1338 assign(cached, mget(changed, envir = env), envir = cached.environments)
1339 }
1340
1341 if (logging) {
1342 logger::log_trace('Cached result', namespace = log)
1343 }
1344 }
1345 }
1346 }
1347
1348 ## log
1349 if (logging) {
1350 if (!is.null(res$msg$warnings)) {
1351 logger::log_warn(res$msg$warnings, namespace = log)
1352 }
1353 if (!is.null(res$result) && res$type != 'image') {
1354 logger::log_debug(paste0(
1355 'Returned object: class = ',
1356 res$type,
1357 ', length = ',
1358 length(res$result),
1359 ', dim = ',
1360 paste(dim(res$result), collapse = '/'),
1361 ', size = ',
1362 object.size(res$result),
1363 ' bytes'
1364 ), namespace = log)
1365 }
1366 }
1367
1368 ## return
1369 res
1370
1371 })
1372 }
1373
1374 #' Redraws plot saved in file
1375 #'
1376 #' This function is a wrapper around \code{redrawPlot}.
1377 #' @param file path and name of an rds file containing a plot object to be redrawn
1378 #' @references Thanks to Jeroen Ooms \url{https://stat.ethz.ch/pipermail/r-devel/2012-January/062973.html}, JJ Allaire \url{https://github.com/rstudio/rstudio/commit/eb5f6f1db4717132c2ff111f068ffa6e8b2a5f0b}, and Gabriel Becker.
1379 #' @seealso \code{\link{evals}}
1380 #' @export
1381 redraw.recordedplot <- function(file) {
1382
1383 plot <- tryCatch(readRDS(file), error = function(e) e)
1384
1385 if (inherits(plot, 'error')) {
1386 stop(paste('Cannot read file:', plot$message))
1387 }
1388
1389 redrawPlot(plot)
1390 }
1391
1392
1393 #' Redraw a recordedplot, grid, trellis, or ggplot2 plot.
1394 #'
1395 #' This function redraws the plot represented by \code{rec_plot}. It can redraw grid/trellis/ggplot2/etc plots, as well as \code{recordedplot} objects. For \code{recordedplot} objects it acts as a wrapper around \code{replayPlot} with memory tweaks to fix native symbol address errors when the recordedplot was loaded from an rda/rds file.
1396 #' @param rec_plot the plot object to redraw
1397 #' @references Thanks to Jeroen Ooms \url{https://stat.ethz.ch/pipermail/r-devel/2012-January/062973.html}, JJ Allaire \url{https://github.com/rstudio/rstudio/commit/eb5f6f1db4717132c2ff111f068ffa6e8b2a5f0b}, and Gabriel Becker.
1398 #' @seealso \code{\link{redraw.recordedplot}}
1399 #' @export
1400 #' @importFrom methods is
1401 #' @importFrom grDevices replayPlot
1402 redrawPlot <- function(rec_plot) {
1403 ## this allows us to deal with trellis/grid/ggplot objects as well ...
1404 if (!is(rec_plot, 'recordedplot')) {
1405 res <- try(print(rec_plot))
1406 if (is(res, 'error')) {
1407 stop(res)
1408 }
1409 } else {
1410 if (getRversion() < '3.0.0') {
1411 for (i in 1:length(rec_plot[[1]])) {
1412 #@jeroenooms
1413 if ('NativeSymbolInfo' %in% class(rec_plot[[1]][[i]][[2]][[1]])) {
1414 rec_plot[[1]][[i]][[2]][[1]] <- getNativeSymbolInfo(rec_plot[[1]][[i]][[2]][[1]]$name)
1415 }
1416 }
1417 } else {
1418 for (i in 1:length(rec_plot[[1]])) {
1419 #@jjallaire
1420 symbol <- rec_plot[[1]][[i]][[2]][[1]]
1421 if ('NativeSymbolInfo' %in% class(symbol)) {
1422 if (!is.null(symbol$package)) {
1423 name <- symbol$package[['name']]
1424 } else {
1425 name <- symbol$dll[['name']]
1426 }
1427 pkg_dll <- getLoadedDLLs()[[name]]
1428 native_sumbol <- getNativeSymbolInfo(name = symbol$name,
1429 PACKAGE = pkg_dll, withRegistrationInfo = TRUE)
1430 rec_plot[[1]][[i]][[2]][[1]] <- native_sumbol
1431 }
1432 }
1433 }
1434 if (is.null(attr(rec_plot, 'pid')) || attr(rec_plot, 'pid') != Sys.getpid()) {
1435 warning('Loading plot snapshot from a different session with possible side effects or errors.')
1436 attr(rec_plot, 'pid') <- Sys.getpid()
1437 }
1438 suppressWarnings(replayPlot(rec_plot))
1439 }
1440 }