ソースコードをテキストとして受け取る具体的な並列化関数を次に示します。
library(rstan)
library(parallel)
parallel_stan <- function(code, data, cores=detectCores(), chains=8, iter=2000, seed=1234) {
cat("parallel_stan: cores=", cores, ", chains=", chains, ", iter=", iter, ", seed=", seed, "\n", sep="")
cat("--- Step 1: compile the model (and run it once, very briefly, ignoring its output)\n")
f1 = stan(model_code = code, data = data, iter = 1, seed = seed, chains = 1, chain_id = 1)
cat("--- Step 2: run more chains in parallel\n")
sflist <- mclapply(
1:chains
, mc.cores = cores
, function(i) stan(fit = f1, data = data, iter = iter, seed = seed, chains = 1, chain_id = i)
)
# ... passing the same seed to all chains follows example(sflist2stanfit)
# ... important to use the same seed but different chain_id when executing in parallel
cat("--- Finished.\n")
return(sflist2stanfit(sflist))
}