Learn R Programming

dclone (version 1.3-2)

jags.parfit: Parallel computing with JAGS

Description

Do the same job as jags.fit, but parallel chanis are run on parallel workers, thus computations can be faster (up to 1/n.chains) for long MCMC runs.

Usage

jags.parfit(cl, data, params, model, inits = NULL, n.chains = 3, ...)

Arguments

cl
A cluster object created by makeCluster.
data
A named list or environment containing the data. If an environment, data cloning might not work properly (has to be done manually).
params
Character vector of parameters to be sampled.
model
Character string (name of the model file), a function containing the model, or a or custommodel object (see Examples).
inits
Specification of initial values in the form of a list or a function, can be missing if n.chains <= 4<="" code="">. inits must contain RNG seed information, too (see Initialization at jags.model<
n.chains
Number of chains to generate, must be higher than 1. Ideally, this is equal to the number of parallel workers in the cluster.
...
Other arguments passed to jags.fit.

Value

  • An mcmc.list object.

encoding

UTF-8

Details

Chains are run on parallel workers, and the results are combined in the end.

See Also

jags.fit

Examples

Run this code
set.seed(1234)
n <- 20
x <- runif(n, -1, 1)
X <- model.matrix(~x)
beta <- c(2, -1)
mu <- X %*% beta
Y <- rpois(n, exp(mu))
glm.model <- function() {
    for (i in 1:n) {
        Y[i] ~ dpois(lambda[i])
        log(lambda[i]) <- inprod(X[i,], beta[1,])
    }
    for (j in 1:np) {
        beta[1,j] ~ dnorm(0, 0.001)
    }
}
dat <- list(Y=Y, X=X, n=n, np=ncol(X))
m <- jags.fit(dat, "beta", glm.model)
cl <- makeCluster(3, type = "SOCK")
pm <- jags.parfit(cl, dat, "beta", glm.model)
## chains are not identical -- this is good
pm[1:2,]
summary(pm)
## examples on how to use initial values
## fixed initial values
inits <- list(list(beta=matrix(c(0,1),1,2)), 
    list(beta=matrix(c(1,0),1,2)), 
    list(beta=matrix(c(0,0),1,2)))
pm2 <- jags.parfit(cl, dat, "beta", glm.model, inits)
## random numbers generated prior to jags.parfit
inits <- list(list(beta=matrix(rnorm(2),1,2)), 
    list(beta=matrix(rnorm(2),1,2)), 
    list(beta=matrix(rnorm(2),1,2)))
pm3 <- jags.parfit(cl, dat, "beta", glm.model, inits)
## self contained function
inits <- function() list(beta=matrix(rnorm(2),1,2))
pm4 <- jags.parfit(cl, dat, "beta", glm.model, inits)
## function pointing to the global environment
fun <- function() list(beta=matrix(rnorm(2),1,2))
inits <- function() fun()
clusterExport(cl, "fun")
pm4 <- jags.parfit(cl, dat, "beta", glm.model, inits)
stopCluster(cl)

Run the code above in your browser using DataLab