Preface

Software Configuration

Going through the Preface, we need to do some preliminary configuration to prepare ourselves to use the software in the book. I’m running a 16 inch MacBook Pro (Nov 2023) Apple M3 Pro chip, and macOS Sonoma 14.6.1.

Steps to get setup

As the book suggests:

“You will need to install both a C++ compiler (also called a”tool chain”) and the rstan package. Instructions for doing both are at mc-stan.org

1. Installing the C++ toolchain

From the main web page, we go to the instructions for installing RStan.

a. Install macrtools

We can use this R package to help setup the C++ toolchain.

# install.packages("remotes")
remotes::install_github("coatless-mac/macrtools")

Then we run the following command:

macrtools::macos_rtools_install()

I was prompted to enter a password (my computer’s password) in RStudio. After it installed, I received this message in the R console:

Congratulations! 
Xcode CLI, Gfortran, and R developer binaries have been installed successfully.
b. Optimize compiler

We run the R code here to “enable some compiler optimizations to improve the estimation speed of the model”:

dotR <- file.path(Sys.getenv("HOME"), ".R")
if (!file.exists(dotR)) dir.create(dotR)
M <- file.path(dotR, "Makevars")
if (!file.exists(M)) file.create(M)
arch <- ifelse(R.version$arch == "aarch64", "arm64", "x86_64")
cat(paste("\nCXX17FLAGS += -O3 -mtune=native -arch", arch, "-ftemplate-depth-256"),
    file = M, sep = "\n", append = FALSE)

It ran without error (though I don’t really know what it did).

2. Install rstan

Going back to the RStan page, we can run the following installation:

install.packages("rstan", repos = "https://cloud.r-project.org/", dependencies = TRUE)

This worked.

Test some examples

Running the following example:

example(stan_model, package = "rstan", run.dontrun = TRUE)

I received a lot of output in the console (compilation and sampling).

Import package
## Load the package
library("rstan") # observe startup messages

# Set cores
options(mc.cores = parallel::detectCores()) # 12

# Auto write compiled stan code
# rstan_options(auto_write = TRUE) # <-- Not doing it here, but would be useful

It says, “You will need to run these commands each time you load the rstan library.”

Run an example model

We saved an example Stan file in stan/schools.stan, and then run the example:

# Data to input into model
schools_dat <- 
  list(
    J = 8, 
    y = c(28,  8, -3,  7, -1,  1, 18, 12),
    sigma = c(15, 10, 16, 11,  9, 11, 10, 18)
  )

# Fit the model
fit <- stan(file = 'stan/schools.stan', data = schools_dat)

It fit with this message:

Warning messages:
1: There were 11 divergent transitions after warmup. See
https://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
to find out why this is a problem and how to eliminate them. 
2: Examine the pairs() plot to diagnose sampling problems
print(fit)
plot(fit)
pairs(fit, pars = c("mu", "tau", "lp__"))

la <- extract(fit, permuted = TRUE) # return a list of arrays 
mu <- la$mu 

### return an array of three dimensions: iterations, chains, parameters 
a <- extract(fit, permuted = FALSE) 

### use S3 functions on stanfit objects
a2 <- as.array(fit)
m <- as.matrix(fit)
d <- as.data.frame(fit)

Install book packages

install.packages(c("coda", "mvtnorm", "devtools", "dagitty"))
devtools::install_github("rmcelreath/rethinking")

Had issues with cmdstanr, so I’m following instructions here.

# we recommend running this is a fresh R session or restarting your current session
install.packages("cmdstanr", repos = c('https://stan-dev.r-universe.dev', getOption("repos")))

Now try again

devtools::install_github("rmcelreath/rethinking")

Success!

At this point, I don’t know what is better: rstan or cmdstanr