-
Notifications
You must be signed in to change notification settings - Fork 0
/
README.rmd
190 lines (151 loc) · 7.16 KB
/
README.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
---
title: "macroStan"
output:
github_document: default
---
```{r setup, echo=FALSE, cache = FALSE, message = FALSE}
library(macroStan)
library(rstan)
knitr::opts_chunk$set(echo = TRUE)
wd = "."
stan_to_chunk = function(i, .list) {
# browser()
invisible(knitr::read_chunk(.list[[i]], label = names(.list)[i]))
}
import_stan_chunks = function(...) {
.l = list(...)
lapply(seq_along(.l), stan_to_chunk, .list = .l)
.l
}
macros = import_stan_chunks(
macro_ncp_simple = file.path(wd, "inst/macros/ncp_simple.stan"),
macro_hs = file.path(wd, "inst/macros/horseshoe.stan"),
macro_ncp = file.path(wd, "inst/macros/ncp_mv.stan"),
macro_ncp_lp = file.path(wd, "inst/macros/ncp_mv_linpred.stan"))
scaffolds = import_stan_chunks(
scaffold_ncp_simple = file.path(wd,
"inst/stan_scaffolds/ncp_simple.stan"),
scaffold_hs = file.path(wd,
"inst/stan_scaffolds/horseshoe.stan"),
scaffold_ncp = file.path(wd,
"inst/stan_scaffolds/ncp_mv.stan"),
scaffold_ncp_hs = file.path(wd,
"inst/stan_scaffolds/ncp_mv_hs.stan")
)
```
R package for defining text macros in Stan for flexible code reuse.
macroStan provides a method to define reuseable, parameterized chunks of code and insert them into the appropriate locations of a stan file. The package was inspired by (and uses) the `glue` package.
## Example: Varying intercept non-centered parameterization
Macros are defined as a stan file with an extra `macro args` block at the top. Each argument is declared on a separate line ending with a semicolon; default values can be optionally provided. To use a macro, a `use macros` block is included with a stan file, with each listing a macro and defining its arguments.
Here's a macro for the non-centered parameterization of a varying intercept model, paired with a simple "scaffold" model to use it with.
**Macro:**
```{stan macro_ncp_simple, output.var = "m_ncp_s", eval = FALSE}
```
This macro has the arguments `N_group`, `location`, `scale`, and `value`. Code in the remaining blocks has been written with argument tags (e.g., `{|N_group|}`), which are replaced with the argument's value when parsed.
**Scaffold:**
```{stan scaffold_ncp_simple, output.var = "junk2", eval = FALSE}
```
The macro is invoked with `alpha = ncp_simple(N_groups, mu, tau);`.
The parser will match the provided arguments by name or position. If the macro is called as part of an assignment, the left hand side is treated as the `value` argument (if the macro has one). In the macros I've included in this document, the `value` argument corresponds to a transformed parameter or local model variable that is primary output of the macro; the assignment syntax highlights that the value should be useable in other parts of the stan program.
This call thus defines the arguments `N_group` as `N_groups`, `location` as `mu`, `scale` as `tau`, and `value` as `alpha`. Once the arguments are defined, argument tags are replaced with their new definitions (e.g., `z_{|value|} * {|scale|}` becomes `z_alpha * tau`).
The parsed macro code is inserted into the calling stan file in the appropriate program blocks. For blocks that can contain both declarations and other statements, the macro is inserted after the last declaration. If multiple macros are defined, they are inserted in the order they appear in the `use macros` block.
**Parsing the macro in R:**
```{r, eval = TRUE, echo = TRUE }
# macros$macro_ncp_simple and
# scaffolds$scaffold_ncp_simple are filepaths
# to the above stan files
out_file = tempfile(fileext = ".stan")
ncp_simple = macroStan::parse_stan_macros(
input = scaffolds$scaffold_ncp_simple,
output = out_file,
macro_files = list(ncp_simple = macros$macro_ncp_simple))
```
```{r, echo = FALSE, eval = TRUE}
knitr::read_chunk(out_file, labels = "out_ncp_simple")
# import_stan_chunks(list(out_ncp_simple = out_file))
```
**Output:**
```{stan out_ncp_simple, output.var = "junk", eval = FALSE}
```
## Example: Horseshoe prior
As a more complicated example, here is the regularized horseshoe prior, adapted from the implementation in `brms`.
**Macro:**
```{stan macro_hs, output.var = "junk", eval = FALSE}
```
**Scaffold:**
```{stan scaffold_hs, output.var = "m_ncp_s", eval = FALSE}
```
Note that the macro was called with `value = beta`, and that `beta` is used in the model block to connect the assembled horseshoe prior coefficients to the linear predictor.
**Parsing:**
```{r, eval = TRUE, echo = TRUE }
# once again, input and macro_files are paths that link to
# the above definitions
out_file = tempfile(fileext = ".stan")
horseshoe = macroStan::parse_stan_macros(
input = scaffolds$scaffold_hs,
output = out_file,
macro_files = list(horseshoe = macros$macro_hs))
```
**Output:**
```{r, echo = FALSE, eval = TRUE}
knitr::read_chunk(out_file, labels = "out_hs")
# import_stan_chunks(list(out_ncp_simple = out_file))
```
```{stan out_hs, output.var = "junk", eval = FALSE}
```
## Multivariate Noncentered Parameterizations:
This is a version of the multivariate NCP (see the [Stan User's Guide 21.7](https://mc-stan.org/docs/2_18/stan-users-guide/reparameterization-section.html) for more details). In this example, we use two macros: The first defines coefficients:
**Primary Macro:**
```{stan macro_ncp, output.var = "junk", eval = FALSE}
```
The second combines the coefficients with the data into a linear predictor.
**Helper Macro:**
```{stan macro_ncp_lp, output.var = "junk", eval = FALSE}
```
The helper macro could easily be combined with the primary one (or used as an independent function in the scaffold), but it allowed for an easy way to demonstrate combining macros.
**Scaffold:**
```{stan scaffold_ncp, output.var = "m_ncp_s", eval = FALSE}
```
Note that the `value` argument of the first macro is a different argument for the second macro.
**Parsing:**
```{r, eval = TRUE, echo = TRUE }
# once again, input and macro_files are paths that link to
# the above definitions
out_file = tempfile(fileext = ".stan")
ncp_mv = macroStan::parse_stan_macros(
input = scaffolds$scaffold_ncp,
output = out_file,
macro_files = list(ncp_mv = macros$macro_ncp,
ncp_mv_linpred = macros$macro_ncp_lp))
```
**Output:**
```{r, echo = FALSE, eval = TRUE}
knitr::read_chunk(out_file, labels = "out_ncp_mv")
# import_stan_chunks(list(out_ncp_simple = out_file))
```
```{stan out_ncp_mv, output.var = "junk", eval = FALSE}
```
## Horseshoe + NCP
Finally, let's combine the horseshoe and the multivariate NCP together. The macro files are already defined, but we need a new scaffold.
**Scaffold:**
```{stan scaffold_ncp_hs, output.var = "tmp", eval = FALSE}
```
**Parsing:**
```{r, eval = TRUE, echo = TRUE }
# once again, input and macro_files are paths that link to
# the above definitions
out_file = tempfile(fileext = ".stan")
ncp_mv_hs = macroStan::parse_stan_macros(
input = scaffolds$scaffold_ncp_hs,
output = out_file,
macro_files = list(horseshoe = macros$macro_hs,
ncp_mv = macros$macro_ncp,
ncp_mv_linpred = macros$macro_ncp_lp))
```
**Output:**
```{r, echo = FALSE, eval = TRUE}
knitr::read_chunk(out_file, labels = "out_ncp_hs")
# import_stan_chunks(list(out_ncp_simple = out_file))
```
```{stan out_ncp_hs, output.var = "junk", eval = FALSE}
```