Hi Chris,
thanks for your email, here is the code:
#'## CJS models constant detection survival varying with treatment
##--------------------CJS trat-------------------------------------------------------------------
hmm.phitrat <- nimbleCode({
delta[1] <- 1 # Pr(alive t = 1) = 1
delta[2] <- 0 # Pr(dead t = 1) = 0
for (t in 1:(T-1)){
logit(phi[t]) <- beta[1] + beta[2] * trat[t]
gamma[1,1,t] <- phi[t] # Pr(alive t -> alive t+1)
gamma[1,2,t] <- 1 - phi[t] # Pr(alive t -> dead t+1)
gamma[2,1,t] <- 0 # Pr(dead t -> alive t+1)
gamma[2,2,t] <- 1 # Pr(dead t -> dead t+1)
}
p ~ dunif(0, 1) # prior detection
omega[1,1] <- 1 - p # Pr(alive t -> non-detected t)
omega[1,2] <- p # Pr(alive t -> detected t)
omega[2,1] <- 1 # Pr(dead t -> non-detected t)
omega[2,2] <- 0 # Pr(dead t -> detected t)
beta[1] ~ dnorm(0, 1.5) # prior intercept
beta[2] ~ dnorm(0, 1.5) # prior slope
# likelihood
for (i in 1:N){
z[i,first[i]] ~ dcat(delta[1:2])
for (j in (first[i]+1):T){
z[i,j] ~ dcat(gamma[z[i,j-1], 1:2, j-1])
y[i,j] ~ dcat(omega[z[i,j], 1:2])
}
}
})
#'
#' Constants in a list.
## ---------------------------------------------------------------
first <- apply(y, 1, function(x) min(which(x !=0)))
trat <- (data1$trat)
trat
my.constants <- list(N = nrow(y),
T = ncol(y),
first = first,
trat= trat)
#'
#' Data in a list.
## ---------------------------------------------------------------
my.data <- list(y = y + 1)
#'
#' Initial values.
## ---------------------------------------------------------------
zinits <- y
zinits[zinits == 0] <- 1
initial.values <- function() list(beta = rnorm(2,0,5),
p = runif(1,0,1),
z = zinits)
#'
#' Parameters to be monitored.
## ---------------------------------------------------------------
parameters.to.save <- c("phi", "p", "z", "beta")
parameters.to.save
#'
#' MCMC details.
## ---------------------------------------------------------------
n.iter <- 5000
n.burnin <- 2500
n.chains <- 2
#'
#' Run nimble.
## ---------------------------------------------------------------
mcmc.phitrat <- nimbleMCMC(code = hmm.phitrat,
constants = my.constants,
data = my.data,
inits = initial.values,
monitors = parameters.to.save,
niter = n.iter,
nburnin = n.burnin,
nchains = n.chains,
WAIC = TRUE)
Matt already suggested to subset the MCMC object to refer to the sample, so mcmcphitrat$samples and it worked.
Nonetheless, it gives a Phi for every sample in the graph (see attached). Iraida suggested using set.seed() to say how many phi I want to represent in the graph, but for the moment it didn't work, probably I did something wrong, I'll keep trying.
thanks a lot,
cheers
Cecilia
|
Remitente notificado con
Mailtrack
| 11/02/22 09:01:38 |
|