#invent some data
x1 <- seq(1,10)*0.005
x2 <- seq(1,10)*0.005
x <- cbind(x1,x2)
y <- 1 + x1*2 + x2*2.5 + rnorm(10,0,sd=0.005)
K <- 2
#create the nimble model
lmCode <- nimbleCode({
A <- chol(A)
mMean <- c(0,0)
intercept ~ dnorm(0, sd=1000)
slope[1:K] ~ dmnorm(mean=mMean, prec=A)
sigma ~ dunif(0, 100)
for (j in 1:N){
predicted.y[j] <- intercept + t(slope[1:K]) %*% x[j,1:K]
y[j] ~ dnorm(predicted.y[j], sd=sigma)
}
})
#create precision matrix
A <- solve(diag(rep(1000,K)))
#data to be passed to nimbleModel()
lmData <- list(y=y,
x=x,
A=A)
#constants to be passed to nimbleModel()
lmConsts <- list(N=length(y),
K=ncol(x))
#initial paramter settings to be passed to nimbleModel()
lmInits <- list(intercept=1,slope=matrix(c(1,1)),sigma=1)
#create nimble model
lmModel <- nimbleModel(code=lmCode,data=lmData,inits=lmInits,constants=lmConsts)
#compile nimble model to C++ code—much faster runtime
C_lmModel <- compileNimble(lmModel)
#configure the MCMC
lmModel_conf <- configureMCMC(lmModel,print=T)
#select the variables that we want to monitor in the MCMC chain
lmModel_conf$addMonitors(c("intercept","slope","sigma"))
#build the MCMC model
lmModelMCMC <- buildMCMC(lmModel_conf)
#compile MCMC to C++—much faster
C_lmModelMCMC <- compileNimble(lmModelMCMC,project=lmModel)
#number of MCMC iterations
niter=10000
#set seed for replicability
set.seed(1)
#call the C++ compiled MCMC model
C_lmModelMCMC$run(niter)
#save the MCMC chain (monitored variables) as a matrix
samples <- as.matrix(C_lmModelMCMC$mvSamples)