/
example5.Rmd
608 lines (426 loc) · 16.7 KB
/
example5.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
---
title: "Running `bayesnec`"
output:
rmarkdown::html_vignette:
vignette: >
%\VignetteIndexEntry{Running `bayesnec`}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: bayesnec.bib
---
[e1]: https://open-aims.github.io/bayesnec/articles/example1.html
[e2]: https://open-aims.github.io/bayesnec/articles/example2.html
[e2b]: https://open-aims.github.io/bayesnec/articles/example2b.html
[e3]: https://open-aims.github.io/bayesnec/articles/example3.html
[e4]: https://open-aims.github.io/bayesnec/articles/example4.html
The `bayesnec` package makes use of the R package `brms` [@Burkner2017; @Burkner2018] (https://cran.r-project.org/package=brms) which relies on `stan` (https://mc-stan.org/). You will need to have either `RStan` (https://mc-stan.org/users/interfaces/rstan.html) or `cmdstanr`(https://mc-stan.org/cmdstanr/) installed and configured on your computer to run `bayesnec`.
Quick start guides can be found for both `RStan` https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started and `cmdstanr` https://mc-stan.org/cmdstanr/articles/cmdstanr.html. However, in our experience getting either package to work can be a bit fiddly, particularly on Windows machines.
We have prepared an installation workflow for `cmdstanr` specifically for Windows 10 that may resolve issues if the above Quick start links fail to result in a working version of `brms`. Note that this workflow has also been known to resolve some issues with `RStan`, although it was not developed with that intention.
# `cmdstanr` installation workflow
These instructions are derived from the instructions at <https://mc-stan.org/docs/2_24/cmdstan-guide/cmdstan-installation.html>
The high level steps are:
1. Install `Rtools`, this is what `cmdstan` will use to make the executables
2. Install `git`, this is will be used to get the `cmdstan` code
3. Install `cmdstan`
4. Test `cmdstan` and run a model
These instructions assume you have R and Rstudio installed already.
## 1. Install `Rtools`
a. Install `Rtools` from <https://cran.r-project.org/bin/windows/Rtools/>
b. Go to the install location and check that the following usr\\bin and mingw64\\bin directories exist:
- C:\rtools40\\usr\\bin
- C:\rtools40\\mingw64\\bin
Check that a **mingw32-make.exe** file is in one of those directories.
`RTools` may not always install **mingw32-make.exe** but it can be installed manually if needed by the following instructions:
Open `RTools Bash`, which comes with `RTools` (hit Windows Key, type rtools bash, and hit enter). In the `RTools Bash` console window, type:
`pacman -Sy mingw-w64-x86_64-make`
Check that the `mingw32-make.exe` file is in one of the `RTools` folders listed in 1b.
c. Add the directories to to the Windows Path using the "Edit the system environment variables" tool in Windows' Control Panel. A step by step guide on adding directories to the windows path can be found at <https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/>. Note that you will need administrator privileges on your computer to edit the environment variables.
- Put the path in the system paths section (bottom section)
- Note that you can also add the path `C:\cmdstan\stan\lib\stan_math\lib\tbb` to save having to do it later (in the later install `cmdstan` step below)
d. Test the paths are set correctly
- Reboot your computer
- Start up R studio
- Navigate to the terminal (a tab co-located in the R console panel)
- Type `echo %PATH%`
- The paths you added should be in the output from that command. They should look something like:
- `\c\RTools\RTools40\usr\bin`
e. Final check to see if it installed properly.
In the terminal type:
`g++ --version`
and
`mingw32-make --version`
Check that it both return a version number. If they produce an error there is a problem with the installation.
## 2. Install `git`
a. If git is not already on your system, install it here: <https://git-scm.com/download/win>
b. To check that git is installed. In RStudio:
- Navigate to the terminal
- type `git --version`
- Check that it returns a version number. If it produces an error there is a problem with the installation
## 3. Intall `cmdstan`
In R studio
a\. Navigate to the terminal
b\. change directory to c:\\ drive using the code: `cd \c`
c\. download latest version of cmdstan from githup - this may take a few minutes: `git clone https://github.com/stan-dev/cmdstan.git --recursive`
d\. change directory to where `cmdstan` is downloaded: `cd cmdstan`
e\. clean up the space (just to be sure): `mingw32-make clean-all`
f\. compile the code: `mingw32-make build`
This will take a few minutes and should end with similar phrase as """--- CmdStan v2.23.0 built ---"""
g\. Add `cmdstan` library to system environment path by adding `C:\cmdstan\stan\lib\stan_math\lib\tbb` to the path (using the same instructions as 1.c.)
h\. Reboot your computer
i\. `cmdstan` is missing a file that must be manually added to the `C:\cmdstan\make` folder. Open notepad and copy paste the following two lines of text:
`CXXFLAGS += -Wno-nonnull`
`TBB_CXXFLAGS= -U__MSVCRT_VERSION__ -D__MSVCRT_VERSION__=0x0E00`
k. Save the file with the name `local` and ensure that it has no file extension. For example, if you used notepad the default file extension is .txt which can be deleted by right clicking the file and selecting rename. If you can't see the file extensions, click the view tab in your folder ribbon and make sure the `file name extension` box is checked. Instructions for how to remove a file extension can be found at: <https://www.computerhope.com/issues/ch002089.htm>
## 4. Test cmdstan in R studio
a. Install the R package `cmdstanr` following the instructions at: <https://mc-stan.org/cmdstanr/articles/cmdstanr.html>
```r
# we recommend running this is a fresh R session or restarting your current session
install.packages("cmdstanr", repos = c("https://mc-stan.org/r-packages/", getOption("repos")))
```
b. Make sure all these packages are installed and loaded.
```r
library(cmdstanr)
```
```
## This is cmdstanr version 0.5.3
```
```
## - CmdStanR documentation and vignettes: mc-stan.org/cmdstanr
```
```
## - CmdStan path: /Users/dbarneche/.cmdstan/cmdstan-2.33.1
```
```
## - CmdStan version: 2.33.1
```
```r
library(posterior)
```
```
## This is posterior version 1.4.1
```
```
##
## Attaching package: 'posterior'
```
```
## The following objects are masked from 'package:stats':
##
## mad, sd, var
```
```
## The following objects are masked from 'package:base':
##
## %in%, match
```
```r
library(bayesplot)
```
```
## This is bayesplot version 1.10.0
```
```
## - Online documentation and vignettes at mc-stan.org/bayesplot
```
```
## - bayesplot theme set to bayesplot::theme_default()
```
```
## * Does _not_ affect other ggplot2 plots
```
```
## * See ?bayesplot_theme_set for details on theme setting
```
```
##
## Attaching package: 'bayesplot'
```
```
## The following object is masked from 'package:posterior':
##
## rhat
```
```
## The following object is masked from 'package:brms':
##
## rhat
```
```r
color_scheme_set("brightblue")
```
c. Manually set the following options.
Make sure the path points to the `cmdstan` installation
```r
cmdstan_path()
```
```
## [1] "/Users/dbarneche/.cmdstan/cmdstan-2.33.1"
```
If not, manually set it
```r
set_cmdstan_path("C:/cmdstan")
```
```
## Warning: Path not set. Can't find directory: C:/cmdstan
```
To use `cmdstan` as a backend for `brms` call the relevant options.
```r
options(brms.backend = "cmdstanr")
```
Setting the path and backend may be required each time you use `cmdstan`
d. Check that your toolchain is set up properly.
```r
check_cmdstan_toolchain()
```
```
## The C++ toolchain required for CmdStan is setup properly!
```
This should return the message `The C++ toolchain required for CmdStan is setup properly!`
### Compile a model
If `cmdstan` is installed, the following example model should work.
Set up data:
```r
file <- file.path(cmdstan_path(), "examples", "bernoulli", "bernoulli.stan")
mod <- cmdstan_model(file)
```
```
## Model executable is up to date!
```
```r
mod$print()
```
```
## data {
## int<lower=0> N;
## array[N] int<lower=0,upper=1> y;
## }
## parameters {
## real<lower=0,upper=1> theta;
## }
## model {
## theta ~ beta(1,1); // uniform prior on interval 0,1
## y ~ bernoulli(theta);
## }
```
Run a Monte Carlo Markov Chain:
```r
# names correspond to the data block in the Stan program
data_list <- list(N = 10, y = c(0,1,0,0,0,0,0,0,0,1))
fit <- mod$sample(
data = data_list,
seed = 123,
chains = 4,
parallel_chains = 4,
refresh = 500
)
```
```
## Running MCMC with 4 parallel chains...
##
## Chain 1 Iteration: 1 / 2000 [ 0%] (Warmup)
## Chain 1 Iteration: 500 / 2000 [ 25%] (Warmup)
## Chain 1 Iteration: 1000 / 2000 [ 50%] (Warmup)
## Chain 1 Iteration: 1001 / 2000 [ 50%] (Sampling)
## Chain 1 Iteration: 1500 / 2000 [ 75%] (Sampling)
## Chain 1 Iteration: 2000 / 2000 [100%] (Sampling)
## Chain 2 Iteration: 1 / 2000 [ 0%] (Warmup)
## Chain 2 Iteration: 500 / 2000 [ 25%] (Warmup)
## Chain 2 Iteration: 1000 / 2000 [ 50%] (Warmup)
## Chain 2 Iteration: 1001 / 2000 [ 50%] (Sampling)
## Chain 2 Iteration: 1500 / 2000 [ 75%] (Sampling)
## Chain 2 Iteration: 2000 / 2000 [100%] (Sampling)
## Chain 3 Iteration: 1 / 2000 [ 0%] (Warmup)
## Chain 3 Iteration: 500 / 2000 [ 25%] (Warmup)
## Chain 3 Iteration: 1000 / 2000 [ 50%] (Warmup)
## Chain 3 Iteration: 1001 / 2000 [ 50%] (Sampling)
## Chain 3 Iteration: 1500 / 2000 [ 75%] (Sampling)
## Chain 3 Iteration: 2000 / 2000 [100%] (Sampling)
## Chain 4 Iteration: 1 / 2000 [ 0%] (Warmup)
## Chain 4 Iteration: 500 / 2000 [ 25%] (Warmup)
## Chain 4 Iteration: 1000 / 2000 [ 50%] (Warmup)
## Chain 4 Iteration: 1001 / 2000 [ 50%] (Sampling)
## Chain 4 Iteration: 1500 / 2000 [ 75%] (Sampling)
## Chain 4 Iteration: 2000 / 2000 [100%] (Sampling)
## Chain 1 finished in 0.0 seconds.
## Chain 2 finished in 0.0 seconds.
## Chain 3 finished in 0.0 seconds.
## Chain 4 finished in 0.0 seconds.
##
## All 4 chains finished successfully.
## Mean chain execution time: 0.0 seconds.
## Total execution time: 0.2 seconds.
```
Check that the model has successfully fitted by examining the model parameters
```r
fit$summary()
```
```
## # A tibble: 2 × 10
## variable mean median sd mad q5 q95 rhat ess_bulk ess_tail
## <chr> <num> <num> <num> <num> <num> <num> <num> <num> <num>
## 1 lp__ -7.26 -6.99 0.695 0.331 -8.70 -6.75 1.00 1661. 1619.
## 2 theta 0.249 0.233 0.119 0.122 0.0816 0.468 1.00 1494. 1630.
```
### Run a model using brms
```r
require(cmdstanr)
set_cmdstan_path("C:/cmdstan")
```
```
## Warning: Path not set. Can't find directory: C:/cmdstan
```
```r
options(brms.backend = "cmdstanr")
require(brms)
fit <- brm(count ~ zAge + zBase * Trt + (1|patient),
data = epilepsy, family = poisson(), silent = 2, refresh = 0)
```
```
## Compiling Stan program...
```
```
## -\|/-\|/-\|/-
```
```
## In file included from /var/folders/80/x2f5bfts2_n9g_2h7w8rx3jm0000gn/T/RtmpGymuJf/model-5a0b7979b3af.hpp:1:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/src/stan/model/model_header.hpp:4:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/stan/math.hpp:19:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/stan/math/rev.hpp:10:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/stan/math/rev/fun.hpp:200:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/stan/math/prim/functor.hpp:16:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/stan/math/prim/functor/integrate_ode_rk45.hpp:6:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/stan/math/prim/functor/ode_rk45.hpp:9:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/numeric/odeint.hpp:76:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/numeric/odeint/integrate/observer_collection.hpp:23:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/function.hpp:30:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/function/detail/prologue.hpp:17:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/function/function_base.hpp:21:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/type_index.hpp:29:
## In file included from /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/type_index/stl_type_index.hpp:47:
## /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/container_hash/hash.hpp:132:33: warning: 'unary_function<const std::error_category
```
```
## \
```
```
## *, unsigned long>' is deprecated [-Wdeprecated-declarations]
## struct hash_base : std::unary_function<T, std::size_t> {};
## ^
## /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/container_hash/hash.hpp:692:18: note: in instantiation of template class 'boost::hash_detail::hash_base<const std::error_category *>' requested here
## : public boost::hash_detail::hash_base<T*>
## ^
## /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/container_hash/hash.hpp:420:24: note: in instantiation of template class 'boost::hash<const std::error_category *>' requested here
## boost::hash<T> hasher;
## ^
## /Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/boost_1.78.0/boost/container_hash/hash.hpp:551:9: note: in instantiation of function template specialization 'boost::hash_combine<const std::error_category *>' requested here
## hash_combine(seed, &v.category());
## ^
## /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__functional/unary_function.h:23:29: note: 'unary_function<const std::error_category *, unsigned long>' has been explicitly marked deprecated here
## struct _LIBCPP_TEMPLATE_VIS _LIBCPP_DEPRECATED_IN_CXX11 unary_function
## ^
## /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__config:850:41: note: expanded from macro '_LIBCPP_DEPRECATED_IN_CXX11'
## # define _LIBCPP_DEPRECATED_IN_CXX11 _LIBCPP_DEPRECATED
## ^
## /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__config:835:49: note: expanded from macro '_LIBCPP_DEPRECATED'
## # define _LIBCPP_DEPRECATED __attribute__((deprecated))
## ^
```
```
## |/-\|/-\|/-\|/-\|/-\|/-\|
```
```
## 1 warning generated.
```
```
## /-
```
```
## ld: warning: duplicate -rpath '/Users/dbarneche/.cmdstan/cmdstan-2.33.1/stan/lib/stan_math/lib/tbb' ignored
```
```
## \|/- Running MCMC with 4 chains, at most 10 in parallel...
##
## Chain 4 finished in 1.7 seconds.
## Chain 1 finished in 1.8 seconds.
## Chain 2 finished in 1.7 seconds.
## Chain 3 finished in 1.7 seconds.
##
## All 4 chains finished successfully.
## Mean chain execution time: 1.7 seconds.
## Total execution time: 1.9 seconds.
```
```r
summary(fit)
```
```
## Family: poisson
## Links: mu = log
## Formula: count ~ zAge + zBase * Trt + (1 | patient)
## Data: epilepsy (Number of observations: 236)
## Draws: 4 chains, each with iter = 2000; warmup = 1000; thin = 1;
## total post-warmup draws = 4000
##
## Group-Level Effects:
## ~patient (Number of levels: 59)
## Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## sd(Intercept) 0.58 0.07 0.46 0.73 1.01 793 1694
##
## Population-Level Effects:
## Estimate Est.Error l-95% CI u-95% CI Rhat Bulk_ESS Tail_ESS
## Intercept 1.77 0.12 1.54 2.00 1.00 941 1752
## zAge 0.09 0.09 -0.08 0.26 1.01 825 1493
## zBase 0.70 0.12 0.46 0.93 1.01 723 1202
## Trt1 -0.27 0.17 -0.58 0.06 1.00 847 1774
## zBase:Trt1 0.05 0.17 -0.27 0.39 1.01 759 1316
##
## Draws were sampled using sample(hmc). For each parameter, Bulk_ESS
## and Tail_ESS are effective sample size measures, and Rhat is the potential
## scale reduction factor on split chains (at convergence, Rhat = 1).
```
# References