datacloning / dclone

Data Cloning and MCMC Tools for Maximum Likelihood Methods
https://github.com/datacloning/dclone
7 stars 2 forks source link

JAGS model must be recompiled #12

Closed zhiiiyang closed 6 years ago

zhiiiyang commented 6 years ago

Hi,

I saved all the mcmc.list while specifying the updated.model to be TRUE. So I can update those unconverged mcmc.list in the future. However, when I load that mcmc.list, it can not be updated anymore and an error message appears saying that JAGS model must be recompiled. I have tried out another package like R2jags which allows me to recompile the object for updating. Are there any functions in dclone recompiling the mcmc.list? Thank you!

psolymos commented 6 years ago

@zhiiyang : I think this is what you are after:

library(dclone)
library(rjags)
jfun <- function() {
    for (i in 1:N) {
        Y[i] ~ dnorm(mu[i], tau)
        mu[i] <- alpha + beta * (x[i] - x.bar)
    }
    x.bar <- mean(x[])
    alpha ~ dnorm(0.0, 1.0E-4)
    beta ~ dnorm(0.0, 1.0E-4)
    sigma <- 1.0/sqrt(tau)
    tau ~ dgamma(1.0E-3, 1.0E-3)
}
set.seed(1234)
N <- 100
alpha <- 1
beta <- -1
sigma <- 0.5
x <- runif(N)
linpred <- crossprod(t(model.matrix(~x)), c(alpha, beta))
Y <- rnorm(N, mean = linpred, sd = sigma)
jdata <- list(N = N, Y = Y, x = x)
jpara <- c("alpha", "beta", "sigma")
mod <- jags.fit(jdata, jpara, jfun, n.chains = 3)
updated.model(mod)
str(updated.model(mod))
state0 <- updated.model(mod)$state()
save(mod, file="jags-model.RData")
rm(mod)

load("jags-model.RData")
update(updated.model(mod)) # this should give error: JAGS model must be recompiled
updated.model(mod)$recompile()
state1 <- updated.model(mod)$state()
data.frame(unlist(state0), unlist(state1)) # same state
update(updated.model(mod)) # this should work now

This is taking advantage of the low level rjags features. updated.model(mod)$state(internal=TRUE) will give you the RNG type and state as well.

zhiiiyang commented 6 years ago

Thank you! This is exactly what I am looking for.