Running bayesnec

The bayesnec package makes use of the R package brms (Paul Christian Bürkner 2017; Paul-Christian Bürkner 2018) (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

  1. Install Rtools from https://cran.r-project.org/bin/windows/Rtools/

  2. Go to the install location and check that the following usr\bin and mingw64\bin directories exist:

    • C:\usr\bin
    • C:\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.

  1. 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)
  1. 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
  2. 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

  1. If git is not already on your system, install it here: https://git-scm.com/download/win

  2. 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

  1. 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

  1. Install the R package cmdstanr following the instructions at: https://mc-stan.org/cmdstanr/articles/cmdstanr.html
# 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")))
  1. Make sure all these packages are installed and loaded.
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
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
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
color_scheme_set("brightblue")
  1. Manually set the following options.

Make sure the path points to the cmdstan installation

cmdstan_path()
## [1] "/Users/dbarneche/.cmdstan/cmdstan-2.33.1"

If not, manually set it

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.

options(brms.backend = "cmdstanr")

Setting the path and backend may be required each time you use cmdstan

  1. Check that your toolchain is set up properly.
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:

file <- file.path(cmdstan_path(), "examples", "bernoulli", "bernoulli.stan")
mod <- cmdstan_model(file)
## Model executable is up to date!
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:

# 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

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

require(cmdstanr)
set_cmdstan_path("C:/cmdstan")
## Warning: Path not set. Can't find directory: C:/cmdstan
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.
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

Bürkner, Paul Christian. 2017. brms: An R package for Bayesian multilevel models using Stan.” Journal of Statistical Software 80 (1): 1–28. https://doi.org/10.18637/jss.v080.i01.
Bürkner, Paul-Christian. 2018. “Advanced Bayesian Multilevel Modeling with the R Package brms.” The R Journal 10 (1): 395–411. https://doi.org/10.32614/RJ-2018-017.