Debian Codegraph @

inst/doc/evals.Rmd

raw
1 ---
2 title: "Capturing evaluation information with evals"
3 author: "Roman Tsegelskyi, Gergely Daróczi"
4 date: "`r Sys.Date()`"
5 output: rmarkdown::html_vignette
6 vignette: >
7 %\VignetteIndexEntry{Capturing evaluation information with evals}
8 %\VignetteEngine{knitr::rmarkdown}
9 %\VignetteEncoding{UTF-8}
10 ---
11
12 ```{r, echo = FALSE, message = FALSE}
13 knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
14 library(pander)
15 library(logger)
16 evalsOptions('graph.name', 'test')
17 evalsOptions('graph.dir', 'my_plots')
18 evalsOptions('graph.output', 'jpg')
19 ```
20
21 `evals` is aimed at collecting as much information as possible while evaluating R code. It can evaluate a character vector of R expressions, and it returns a list of information captured while running them:
22
23 * `src` holds the R expression,
24 * `result` contains the raw R object as-is,
25 * `output` represents how the R object is printed to the standard output,
26 * `type` is the class of the returned R object,
27 * `msg` is a list of messages captured while evaluating the R expression. Among other messages, warnings/errors will appear here.
28 * `stdout` contains what, if anything, was written to the standard output.
29
30 Besides capturing evaluation information, `evals` is able to automatically identify whether an R expression is returning anything to a graphical device, and can save the resulting image in a variety of file formats.
31
32 Another interesting `evals` feature is caching the results of evaluated expressions. Read the [caching](#result-caching) section for more details.
33
34 `evals` has a large number of options, which allow users to customize the call exactly as needed. Here we will focus on the most useful features, but the full list of options, with explanations, can be viewed by calling `?evalsOptions`. Also `evals` support permanent options that will persist for all calls to `evals`, this can be achieved by calling `evalsOptions`.
35
36 Let's start with a basic example by evaluating `1:10` and collecting all information about it:
37
38 ```{r}
39 evals('1:10')
40 ```
41
42 Not all the information might be useful, so `evals` makes it is possible to capture only some of the information, by specifying the `output` parameter:
43
44 ```{r}
45 evals('1:10', output = c('result', 'output'))
46 ```
47
48 One of the neat features of `evals` that it catches errors/warnings without interrupting the evaluation and saves them.
49
50 ```{r}
51 evals('x')[[1]]$msg
52 evals('as.numeric("1.1a")')[[1]]$msg
53 ```
54
55 ## Graphs and Graphical Options
56
57 As mentioned before, `evals` captures the output to graphical devices and saves it:
58
59 ```{r}
60 evals('plot(mtcars)')[[1]]$result
61 ```
62
63 ![](https://rapporter.github.io/pander/plots/evals-mtcars.jpeg)
64
65 You can specify the output directory using the `graph.dir` parameter, and the output type using the `graph.output` parameter. Currently, it could be any of `grDevices`: `png`, `bmp`,` jpeg`,` jpg`, `tiff`, `svg`, or `pdf`.
66
67 ```{r}
68 evals('plot(mtcars)', graph.dir = 'my_plots', graph.output = 'jpg')[[1]]$result
69 ```
70
71 Moreover, `evals` provides facilities to:
72
73 * save the environments in which plots were generated
74 * save the plot via `recordPlot` to distinct files with `recodplot` extension
75 * save the raw R object returned (usually with `lattice` or `ggplot2`) while generating the plot to distinct files with `RDS` extension
76
77 ### Style unification
78
79 `evals` provides very powerful facilities to unify the styling of images produced by different packages, like `ggplot2` and `lattice`.
80
81 Let's prepare the data for plotting:
82
83 ```{r}
84 ## generating dataset
85 set.seed(1)
86 df <- mtcars[, c('hp', 'wt')]
87 df$factor <- sample(c('Foo', 'Bar', 'Foo bar'), size = nrow(df), replace = TRUE)
88 df$factor2 <- sample(c('Foo', 'Bar', 'Foo bar'), size = nrow(df), replace = TRUE)
89 df$time <- 1:nrow(df)
90 ```
91
92 ```{r echo=FALSE}
93 ## loading packages
94 require(ggplot2, quietly = TRUE)
95 require(lattice, quietly = TRUE)
96 ```
97
98 Now let's plot the histograms:
99
100 ```{r}
101 evalsOptions('graph.unify', TRUE)
102 evals('histogram(df$hp, main = "Histogram with lattice")')[[1]]$result
103 evals('ggplot(df) + geom_histogram(aes(x = hp), binwidth = 50) + ggtitle("Histogram with ggplot2")')[[1]]$result
104 evalsOptions('graph.unify', FALSE)
105 ```
106
107 ![](https://rapporter.github.io/pander/plots/evals-lattice.jpeg)
108 ![](https://rapporter.github.io/pander/plots/evals-ggplot2.jpeg)
109
110 Options for unification can be set with `panderOptions`. For example:
111
112 ```r
113 panderOptions('graph.fontfamily', "Comic Sans MS")
114 panderOptions('graph.fontsize', 18)
115 panderOptions('graph.fontcolor', 'blue')
116 panderOptions('graph.grid.color', 'blue')
117 panderOptions('graph.axis.angle', 3)
118 panderOptions('graph.boxes', T)
119 panderOptions('graph.legend.position', 'top')
120 panderOptions('graph.colors', rainbow(5))
121 panderOptions('graph.grid', FALSE)
122 panderOptions('graph.symbol', 22)
123 ```
124
125 More information and examples on style unification can be obtained by `Pandoc.brew`ing the tutorial available [here](https://github.com/Rapporter/pander/blob/master/inst/examples/graphs.brew).
126
127 ## Logging
128
129 To make execution and debugging easier to understand, `evals` provides logging with the `log` parameter. Logging in `evals` relies on the [`logger`](https://cran.r-project.org/package=logger) package, which provides a logging API similar to `log4j`. Basic example:
130
131 ```{r}
132 x <- evals('1:10', log = 'foo')
133 ```
134
135 `logger`'s thresholds range from most verbose to least verbose: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`. The threshold defaults to `INFO`, which will hide some unessential information. To permanently set the threshold for logger use `log_threshold`:
136
137 ```{r}
138 evalsOptions('log', 'evals')
139 log_threshold(TRACE, namespace = 'evals')
140 x <- evals('1:10', cache.time = 0)
141 ```
142
143 `logger` also provides a very useful ability to write logs to files instead of printing them to the prompt:
144
145 ```{r}
146 t <- tempfile()
147 log_appender(appender_file(t), namespace = 'evals')
148 x <- evals('1:10', log = 'evals')
149 readLines(t)
150 # revert back to console
151 log_appender(appender_stdout, namespace = 'evals')
152 ```
153
154 ## Result Caching
155
156 `evals` is uses a custom caching algorithm to cache the results of evaluated R expressions.
157
158 ### How it works
159
160 * All R code passed to `evals` is split into single expressions and parsed.
161 * For each R expression (function call, assignment, etc.), `evals` extracts symbols in a separate list in `getCallParts`. This list describes the unique structure and the content of the passed R expressions
162 * A hash is computed for each list element and cached in `pander`'s local environments. This is useful if you are using large data frames; otherwise, 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.
163 * The list of such R objects is serialized, then an SHA-1 hash is computed, taking into consideration `panderOptions` and `evalsOptions`, which all together is unique and there is no real risk of collision.
164 * If `evals` can find the cached results in the appropriate environment (if `cache.mode set` to environment) or in a file named to the computed hash (if `cache.mode` set to `disk`), then it is returned on the spot. The objects modified/created by the cached code are also updated.
165 * Otherwise the call is evaluated and the results and the modified R objects of the environment are optionally saved to cache (e.g. if `cache` is active and if the evaluation `proc.time()` > `cache.time` parameter). Cached results are saved in `cached.results` in `pander`'s namespace. `evals` also remembers if R expressions change the evaluation environment (for example assignments) and saves such changes in `cached.environemnts` in `pander`'s namespace.
166
167 ### Examples
168
169 We will set `cache.time` to 0, to cache all expressions regardless of time they took to evaluate. We will also use the logging facilites described above to simplify the understanding of how caching works.
170
171 ```{r}
172 evalsOptions('cache.time', 0)
173 evalsOptions('log', 'evals')
174 log_threshold(TRACE, 'evals')
175 ```
176
177 Let's start with small example.
178
179 ```{r}
180 system.time(evals('1:1e5'))
181 system.time(evals('1:1e5'))
182 ```
183
184 Results cached by `evals` can be stored in an *environment* in current `R` session or permanently on disk by setting the `cache.mode` parameter appropriately.
185
186 ```{r}
187 res <- evals('1:1e5', cache.mode = 'disk', cache.dir = 'cachedir')
188 list.files('cachedir')
189 ```
190
191 Since the hash for caching is computed based on the *structure* and *content* of the R commands, instead of the variable names or R expressions, `evals` is able to achieve great results:
192
193 ```{r}
194 x <- mtcars$hp
195 y <- 1e3
196 system.time(evals('sapply(rep(x, y), mean)'))
197 ```
198
199 Let us create some custom functions and variables, which are not identical to the above call:
200
201 ```{r}
202 f <- sapply
203 g <- rep
204 h <- mean
205 X <- mtcars$hp * 1
206 Y <- 1000
207 system.time(evals('f(g(X, Y), h)'))
208 ```
209
210 Another important feature of `evals` is that it notes changes in the evaluation environment. For example:
211
212 ```{r}
213 x <- 1
214 res <- evals('x <- 1:10;')
215 ```
216
217 `x <- 1:10` will be cached; if the same assignment occurs again we won't need to evaluate it. But what about the change of `x` when we get the result from the cache? `evals` takes care of that.
218
219 So in the following example we can see that `x <- 1:10` is not evaluated, but retrieved from cache with the change to `x` in the environment.
220
221 ```{r}
222 evals('x <- 1:10; x[3]')[[2]]$result
223 ```
224
225 Also `evals` is able to cache output to graphical devices produced during evaluation:
226
227 ```{r}
228 system.time(evals('plot(mtcars)'))
229 system.time(evals('plot(mtcars)'))
230 ```
231 ```{r, echo = FALSE, message = FALSE}
232 unlink('cachedir', recursive = TRUE, force = TRUE)
233 unlink('my_plots', recursive = TRUE, force = TRUE)
234 ```