Skip to content

Instantly share code, notes, and snippets.

@mike-lawrence
Created October 9, 2012 22:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike-lawrence/3861998 to your computer and use it in GitHub Desktop.
Save mike-lawrence/3861998 to your computer and use it in GitHub Desktop.
Parallel computation of chains for rstan using doMC
library(rstan)
library(plyr)
library(doMC)
options(cores=4) #set this appropriate to your system
registerDoMC()
#This example assumes you have the rats.txt and rats.stan example files in your working directory
# rats.txt: http://wiki.stan.googlecode.com/git/rstangettingstarted/rats.txt
# rats.stan: http://stan.googlecode.com/git/src/models/bugs_examples/vol1/rats/rats.stan
#set up the rats example
y <- read.table('rats.txt', header = TRUE)
x <- c(8, 15, 22, 29, 36)
rats_dat <- list(
N = nrow(y)
, T = ncol(y)
, x = x
, y = y
, xbar = mean(x)
)
#fit once to compile
initial_fit <- stan(
file = 'rats.stan'
, data = rats_dat
, verbose = FALSE
, chains = 1
, iter = 1
)
#set the number of chains to produce in each case
num_chains = 4
#serial case
start <- proc.time()[3]
serial_fit <- stan(
fit = initial_fit
, data = rats_dat
, verbose = FALSE
, chains = num_chains
, iter = 10000
)
proc.time()[3] - start
#prep for parallel case
fun <- function(){
fit <- stan(
fit = initial_fit
, data = rats_dat
, iter = 10000
, chains = 1
, verbose = F
)
return(attr(fit,'sim'))
}
#parallel case
start <- proc.time()[3]
parallel_fit <- foreach(i = 1:num_chains) %dopar% fun()
proc.time()[3] - start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment