-
Notifications
You must be signed in to change notification settings - Fork 3
/
DetailedDocumentation.Rmd
553 lines (441 loc) · 13.7 KB
/
DetailedDocumentation.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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
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
122
123
124
125
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
156
157
158
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
198
199
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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
377
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
---
title: "Detailed Documentation"
author: "Konrad Kraemer"
output: html_document
# pdf_document
#classoption:
# - twocolumn
# rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Detailed Documentation}
%\VignetteEngine{knitr::rmarkdown}
\usepackage{UTF-8}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval = FALSE)
```
```{css echo=FALSE}
/* Define a margin before h2 element */
h2 {
margin-top: 6em;
}
/* Define a margin after every first p elements */
p:first-of-type {
margin-bottom: 3em;
}
```
- [Documentation](#documentation)
* [Objects](#objects)
* [Variable declaration](#variable-declaration)
* [Basic arithmetics](#basic-arithmetics)
* [Subsetting](#subsetting)
* [Helper functions](#helper-functions)
* [Comparison functions](#comparison-functions)
* [Control flow](#Control flow)
* [Printing](#printing)
* [Math functions](#math-functions)
* [Interpolation](#interpolation)
<style>
body {
text-align: justify}
</style>
## Documentation
The package *ast2ast* translates an R function into a C++ function. Either an external pointer (XPtr) or an R function is returned. The scope of *ast2ast* is to generate functions that can be used during solving ode-systems (derivative function or jacobian function) or during optimization. More generally, the translated function can be used in fields where it is necessary to evaluate a function very often. Especially when the function is evaluated by C++ the generated external pointer is very sufficient see the benchmark below. \
Within this vignette the functions supported by *ast2ast* are presented. The examples are presented using the R output form. If the XPtr output differs this is described.
First of all, the supported objects and functions listed below are explained in detail. Here, the arguments which have to be passed to the functions are described and it is explained what the function returns. Furthermore, for each function, a small example is given showing how to use it. Moreover, it is explained how the function differs from R equivalents. If another differences are detected please report them. \
![Benchmark](benchmark.png)
Supported objects:
* vectors (containing numbers)
* matrices (containing numbers)
Supported functions:
* assignment: = and <-
* allocation: vector and matrix
* information about objects: length and dim
* Basic operations: +, -, *, /
* Indices: [] and at
* mathematical functions: sin, asin, sinh, cos, acos, cosh, tan, atan, tanh, log, ^ and exp
* concatenate objects: c
* control flow: for, if, else if, else
* comparison: ==, !=, >, <, >= and <=
* printing: print
* returning objects: return
* is.na and is.infinite can be used to test for NA and Inf.
* d-, p-, q- and r-unif, -norm, -lnorm and -gamma (for gamma argument *Scale* cannot be defined and is calculated using *1/rate*)
### Objects
There exist two containers that can be used in *ast2ast* functions. Both containers can only hold the *numeric* type of R (which is equivalent to double). The first container is a vector and the second one is a matrix. **It is possible to declare a variable of a scalar numeric data type. This is done by adding *\_db* (e.g. varname\_db) to the end of the variable. Each time *\_db* is found the variable is declared as a scalar numeric data type. In this case, the object cannot change its type!** \
It is pivotal to follow the rules of variable naming in C++. For instance, it is not allowed to use '*.*' in variable names.
**Features of *ast2ast* **
* The variables can change the type within a function. This is usually not possible when using C++.
* The index of vectors and matrices starts at 1 as in R.
* The index has to be in the boundaries of the vector or matrix. Even though this is different from the behavior in R it is a nice feature. If you access an element outside the boundaries of a vector in R *NA* is returned.
* The memory of the matrices is arranged column-wise as in R.
* In R arguments passed to a function are always copied. Here the R function behaves differently then the external pointer.
* If using "R" for the *output* argument of *translate* then the function expects *SEXP* objects. These objects can be modified as long as the size is not increased (see **Example 1**).
* If using "XPtr" for the *output* argument of *translate* the variables can be passed by reference. Meaning to only pass the memory address of an object (called a reference). To do this, you have to set the *reference* parameter to *TRUE*. If you pass a function by reference you can modify the object without returning it. Notably, if no *return* is used in the R code translated by *ast2ast* nothing is returned (in R the last object is returned in this case). You see that x is 10 before the call of the function and it is 1 after the call of the function. But the function does not return anything. Thus, the object *x* is modified in the function without copying it.
**Example 1**
```{r modify objects, eval = TRUE}
f <- function(variable) {
variable <- 1
}
library(ast2ast)
fetr <- translate(f)
x <- 10
return_value <- fetr(x)
print(x)
print(return_value)
```
**Caveats:**
* Sometimes large overhead of the containers
* Overhead is generated due to code injection. This is especially true if "R" is used for the output argument.
* Variables which are scalars are represented as vectors of length 1. As in C++ scalar variables are not defined as vectors the speed of the translated R function can be substantially lower compared to a native C++ function.
### Variable declaration
In **Example 2** the various ways of declaring variables are presented. To assign a value to a variable you can use *<-* or *=*. As already mentioned only numeric values are possible.
If you want to assign a vector you can use either the *c* or *vector* function. The *c* function works in the same way as R and can handle any combinations of scalars, vectors or matrices. The function *vector* differs in two ways from the R equivalent. First of all, you cannot use terms such as *vector(length = size)* as this is not possible in C++. In contrast, you just write *vector(size)*. The R function *rep* is not available in *ast2ast* but it is possible to write *vector(value, size)* which in R would be written as *rep(value, size)*. A third way to use the *vector* function is to pass another vector and the size e.g. *vector(other_vector, size)*. The *matrix* function works in the same way as the *vector* function. However, instead of the size, two arguments are needed the number of rows and the number of columns.
**Example 2**
```{r}
f <- function() {
a <- 1
a_db <- 3.14
b <- 2
c <- c(1, 2, 3)
d <- vector_numeric(2)
e <- rep(3.14, 4)
f <- rep(c, 3)
g <- matrix(2, 2)
h <- matrix(6, 2, 2)
i <- matrix(e, 2, 2)
print("a")
print(a)
print(a_db)
print()
print("b")
print(b)
print()
print("c")
print(c)
print()
print("d")
print(d)
print()
print("e")
print(e)
print()
print("f")
print(f)
print()
print("g")
print(g)
print()
print("h")
print(h)
print()
print("i")
print(i)
print()
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Basic arithmetics
As usual in R it is possible to use basic arithmetic operations on scalars, vectors and matrices (**Example 3**).
**Example 3**
```{r}
f <- function() {
a <- 2
b <- 3
print("scalar operations")
print(a + b)
print(a - b)
print(a / b)
print(a * b)
print()
print("vector & scalar operations")
a <- c(1, 2, 3)
b <- 4
print(a + b)
print(b - a)
print()
print("2 vectors (same length)")
a <- 6:8
b <- 1:3
print(a / b)
a <- 1:6
b <- 1:3
print(a / b)
print("2 vectors (different length)")
print("multiple of each other")
a <- 1:6
b <- 1:3
print(a / b)
print("not a multiple of each other")
a <- 1:5
b <- 1:3
print(a / b) # different to R no warning
print()
print("matrix & scalar operations")
a <- 3
b <- matrix(3, 2, 2)
print(a * b)
print(b + 4)
print()
print("matrix & vector operations")
a <- 5:6
b <- matrix(3, 2, 2)
print(b - a)
print(a / b)
print()
print("matrix & matrix operations")
a <- matrix(3, 2, 2)
b <- matrix(4, 2, 1)
print(a + b)
print()
print("mixed operations")
a <- 1
b <- 2:5
c <- matrix(50, 2, 2)
d <- a + b - c / 2
print(d)
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Subsetting
If you want to subset a vector or a matrix object you can use either *[]* or the *at* function. The *[]* is slower than *at* but more powerful (**Example 4**).
The following objects can be passed to *[]* when using a vector or matrix:
* nothing
* numeric scalar
* logical
* vector
* matrix
* result of comparison
In case of a matrix, it is possible to pass one of the above objects to access specific rows or columns respectively ([rows, cols]). \
In contrast to *[]*, the *at* function accepts only a scalar or two scalars for vectors or matrices, respectively. Thus, only a single element is accessed by this function! However, this function works faster. The result of *at* cannot be subsetted further. The *at* function returns the numeric type which is used when a variable is declared with the extension *\_db*.
**Example 4**
```{r}
f <- function() {
print("pass nothing")
a <- 1:8
print(a)
a[] <- 100
print(a)
print()
print("pass logical")
a <- 1:8
print(a)
a[TRUE] <- 100
print(a)
print()
print("pass scalar")
a <- 1:8
print(a)
a[1] <- 100
print(a)
print()
print("pass vector")
a <- 1:8
b <- 2:5
print(a)
a[b] <- 100
print(a)
print()
print("pass result of ==")
a <- 1:8
a[a < 5] <- 100
print(a)
print()
print("pass result of !=")
a <- 1:8
b <- c(1, 2, 3, 0, 0, 0, 0, 8)
a[a != b] <- 100
print(a)
print()
print("pass result of <=")
a <- 1:8
b <- c(1, 2, 3, 0, 0, 0, 0, 8)
a[a <= b] <- 100
print(a)
print()
print("pass result of >=")
a <- 1:8
b <- c(1, 2, 3, 0, 0, 0, 0, 9)
a[a >= b] <- 100
print(a)
print()
print("pass result of >")
a <- 1:8
b <- c(0, 2, 3, 0, 0, 0, 0, 9)
a[a > b] <- 100
print(a)
print()
print("pass result of <")
a <- 1:8
b <- c(0, 2, 3, 0, 0, 0, 0, 9)
a[a < b] <- 100
print(a)
print()
print("pass scalar, scalar")
a <- matrix(3, 4, 4)
a[1, 1] <- 100
print(a)
print()
print("pass vector, vector")
a <- matrix(3, 4, 4)
b <- c(1, 3)
c <- c(2, 4)
a[b, c] <- 100
print(a)
print()
print("pass ==, >=")
a <- matrix(1:16, 4, 4)
b <- 1:4
c <- c(1, 8, 3, 8)
a[b == c, b >= c] <- 100
print(a)
print()
print("at")
a <- 1:16
at(a, 2) <- 100
print(a)
print()
print("at")
a <- matrix(1:16, 4, 4)
at(a, 1, 4) <- 100
print(a)
print()
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Helper functions
There exist three helper function. The *length* function returns the number of elements of a vector or matrix. The *dim* function returns the number of rows and columns of a matrix. The *:* function can be used to create a range of numbers. For example 1:3 creates a vector with the elements 1, 2 and 3 or 1.1:5.3 returns a vector with the elements 1.1, 2.1, 3.1, 4.1 and 5.1. See **Example 5** in order to see how the functions can be applied.
**Example 5**
```{r}
f <- function() {
a <- 1:4
print(a)
a <- 1.1:5.2
print(a)
a <- 1:16
print(length(a))
b <- matrix(1:4, 2, 2)
print(dim(b))
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Comparison functions
As usual in R it is possible to compare two objects using one of the following options (**Example 6**):
* \=\=
* <=
* \>\=
* !=
* \<
* \>
**Example 6**
```{r}
f <- function() {
a <- 1:4
b <- c(1, 2, 3, 5)
c <- 9
print(a == b)
print(a <= b)
print(a >= b)
print(a != b)
print(a < c)
print(a > c)
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Control flow
It is possible to write for-loops and 'if', 'else if', and 'else' branches as in native R (**Example 7**).
for(index in variable){ \
# do whatever \
} \
for(index in 1:length(variable){ \
# do whatever \
} \
**Example 7**
```{r}
f <- function() {
a <- 1:4
for (i in a) {
print(i)
}
for (i in 1:length(a)) {
a[i] <- i + i
}
for (i in 1:length(a)) {
if (i < 4 && i > 1) {
print(i)
}
}
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Printing
Using the function print as common in R (see **Examples 2, 3, 4, 5, 6**):
* print() is different to R
* print("string")
* print(logical)
* print(scalar)
* print(vector) is different to R
* print(matrix)
### Math functions
Following mathematical functions are available (see **Example 8**):
* sin
* asin
* sinh
* cos
* acos
* cosh
* tan
* atan
* tanh
* sqrt
* log
* ^ and exp
* d-, p-, q- and r-unif, -norm, -lnorm and -gamma (for gamma argument *Scale* cannot be defined and is calculated using *1/rate*)
**Example 8**
```{r}
f <- function() {
a <- 1:4
print(sin(a))
print(cos(a))
print(a^2)
print(exp(a))
}
library(ast2ast)
fetr <- translate(f)
fetr()
```
### Interpolation
To interpolate values, the 'cmr' function can be used. The function needs three arguments (see **Example 9**):
* the first argument is the point of the independent variable (x) for which the dependent variable should be calculated (y). This has to be a vector of length one.
* the second argument is a vector defining the points of the independent variable (x). This has to be a vector of at least length four.
* the third argument is a vector defining the points of the dependent variable (y). This has to be a vector of at least length four.
**Example 9**
```{r}
f <- function() {
dep <- c(0, 1, 0.5, 2.5, 3.5, 4.5, 4)
indep <- 1:7
evalpoints <- c(
0.5, 1, 1.5, 2, 2.5,
3, 3.5, 4, 4.5, 5,
5.5, 6, 6.5
)
for (i in evalpoints) {
print(cmr(i, indep, dep))
}
}
library(ast2ast)
fetr <- translate(f, verbose = TRUE)
fetr()
```