I'm rather new to JAGS.
My data consists of larval counts of 5 streams during 15 weeks (two observations / week and stream). For this I work with an array with 150 rows, 2 columns and 15 entries (y). My goal is to estimate omega for each week with help of an open N-mixture model.
I also tried it with the unmarked package but could not figure it out how this would work with pcountopen().
sink("model1.txt")
cat("
model {
# Priors
lambda ~ dunif(0, 5)
omega ~ dunif(0, 1)
p ~ dunif(0, 1)
# Likelihood
# Biological (ecological) model for true abundance (State model)
for (i in 1:R) { #loop over R sites (150)
N[i,1] ~ dpois(lambda) #Abundance
for (k in 2:15) { #loop over weeks (15)
N[i,k] ~ dpois(omega[k] * N[i, k-1])
# Observation model for replicated counts
for (j in 1:T){ #loop over temporal reps (2)
y[i,j,k-1] ~ dbin(p, N[i,k-1]) #Detection
} #j
} #k
} #i
}
",fill = TRUE)
sink()
# Bundle and summarize data set
R = nrow(y) #sites = 150
T = ncol(y) #replications per observation day = 2
win.data <- list(y = y, R = R, T = T)
# Initial values
Nst <- apply(y, c(1,3), max) +1
inits <- function() {list(N = Nst)}
# Parameters monitored
params1 <- c("omega", "lambda", "p")
# MCMC settings
ni <- 20 ; nt <- 1 ; nb <- 0 ; nc <- 8
# Call JAGS (ART 1 min) and summarize posteriors
library(jagsUI)
fm1 <- jags(win.data, inits, params1,
"model1.txt",
n.chains = nc, n.thin = nt, n.iter = ni, n.burnin = nb)
This gives me the following error:
Error in jags.model(file = model.file, data = data, inits = inits, n.chains = n.chains, :
RUNTIME ERROR:
Compilation error on line 12.
Index out of range taking subset of omega
Thanks for any help!
Related
I am trying to adjust a model in jags. I have a syntax error, but I've been trying to find it for hours. Please, any help is welcome. Here is the model
library(jagsUI)
nyears<-8
ad<-c(707,768,149,221,329, 222,869,445)
an<-c(327,257,18,10,49,56,323,211)
# Specify model in BUGS language
cat(file ="recipm.bug","
model {
#-------------------------------------------------------------------------
# define the priors of the unknown parameters
#-------------------------------------------------------------------------
tau.juv <- pow(sigma.y, -2)
sigma.juv ~ dunif(0, 20)
sigma2.juv <- pow(sigma.an, 2)
#initial population sizes
Njuv ~ (300,0.0001) I (0,) #tamanio inicial de la poblacion de aniales
Nad ~ (700, 0.0001)I(0,) #tamanio inicial de la poblacion de adultos
#survival probabilities and productivity
for (t in 1:(nyears-1)){
sjuv[t] <- mean.sjuv
sad[t] <- mean.sad
f[t] <- mean.fec
}
mean.sjuv ~ dunif(0, 0.6)
mean.sad ~ dunif(0.85,0.95 )
mean.fec ~ dunif(0, 1)
#---------------------------------------------------------------------------
# derived parameters
#---------------------------------------------------------------------------
# Population recruitment traditional way
for (t in 1:(nyears-1)){
rec [t]<-an[t]/ad[t]*0.5
}
# ---------------------------------------------------------------------------
# The likelihoods of the single data sets
# ---------------------------------------------------------------------------
# 3.1. Likelihood for population population count data (state-space
#model)
# 3.1.1 System process
for (t in 2:nyears){
mean.juv[t] <- f[t-1] / 2 * sjuv[t-1] * Nad[t]
Njuv[t] ~ dpois(mean1[t])
}
# 3.1.2 Observation process
for (t in 1:nyears){
an[t] ~ dpois (mean(Njuv))
ad[t] ~ dbin(Nad[t], tauy)
}
}
",fill = TRUE)
# Bundle data
bugs.data <- list( ad=ad,an=an,nyears = 8)
# Initial values
inits <- function(){list(mean.sjuv = runif(1, 0, 1), mean.sad = runif
(1, 0, 1), mean.fec = runif(1, 0, 10),
Njuv = rpois(1,5), Nad = rpois(1,20), sigma.juv = runif
(1, 0, 10))}
parameters<-c("mean.sjuv","mean.sad","mean.fec", "N1","Njuv")
# MCMC settings
ni <- 20000
nt <- 6
nb <- 5000
nc <- 3
# Call jags from R
ipm <- jags(data = bugs.data, inits, n.chains = nc,parameters.to.save = parameters,
model.file = "recipm.bug", n.thin = nt, n.iter = ni, n.burnin = nb)
I am getting the following error `
Error in jags.model(file = model.file, data = data, inits = inits, n.chains = n.chains, :
Error parsing model file:
syntax error on line 18 near "("
I know that JAGS is a declarative language and consequently, to position indicated in the warning may not be the position of the error, any idea of strategies to find this kind of error?
Regards
I am trying to figure out how to sample from a custom density in rJAGS but am running into issues. having searched the site, I saw that there is a zeroes (or ones) trick that can be employed based on BUGS code but am having a hard time with its implementation in rJAGS. I think I am doing it correctly but keep getting the following error:
Error in jags.model(model1.spec, data = list(x = x, N = N), n.chains = 4, :
Error in node dpois(lambda)
Length mismatch in Node::setValue
Here is my rJAGS code for reproducibility:
library(rjags)
set.seed(4)
N = 100
x = rexp(N, 3)
L = quantile(x, prob = 1) # Censoring point
censor = ifelse(x <= L, 1, 0) # Censoring indicator
x[censor == 1] <- L
model1.string <-"
model {
for (i in 1:N){
x[i] ~ dpois(lambda)
lambda <- -N*log(1-exp(-(1/mu)))
}
mu ~ dlnorm(mup, taup)
mup <- log(.0001)
taup <- 1/49
R <- 1 - exp(-(1/mu) * .0001)
}
"
model1.spec<-textConnection(model1.string)
jags <- jags.model(model1.spec,
data = list('x' = x,
'N' = N),
n.chains=4,
n.adapt=100)
Here, my negative log likelihood of the density I am interested in is -N*log(1-exp(-(1/mu))). Is there an obvious mistake in the code?
Using the zeros trick, the variable on the left-hand side of the dpois() relationship has to be an N-length vector of zeros. The variable x should show up in the likelihood somewhere. Here is an example using the normal distribution.
set.seed(519)
N <- 100
x <- rnorm(100, mean=3)
z <- rep(0, N)
C <- 10
pi <- pi
model1.string <-"
model {
for (i in 1:N){
lambda[i] <- pow(2*pi*sig2, -0.5) * exp(-.5*pow(x[i]-mu, 2)/sig2)
loglam[i] <- log(lambda[i]) + C
z[i] ~ dpois(loglam[i])
}
mu ~ dnorm(0,.1)
tau ~ dgamma(1,.1)
sig2 <- pow(tau, -1)
sumLL <- sum(log(lambda[]))
}
"
model1.spec<-textConnection(model1.string)
set.seed(519)
jags <- jags.model(model1.spec,
data = list('x' = x,
'z' = z,
'N' = N,
'C' = C,
'pi' = pi),
inits = function()list(tau = 1, mu = 3),
n.chains=4,
n.adapt=100)
samps1 <- coda.samples(jags, c("mu", "sig2"), n.iter=1000)
summary(samps1)
Iterations = 101:1100
Thinning interval = 1
Number of chains = 4
Sample size per chain = 1000
1. Empirical mean and standard deviation for each variable,
plus standard error of the mean:
Mean SD Naive SE Time-series SE
mu 4.493 2.1566 0.034100 0.1821
sig2 1.490 0.5635 0.008909 0.1144
2. Quantiles for each variable:
2.5% 25% 50% 75% 97.5%
mu 0.6709 3.541 5.218 5.993 7.197
sig2 0.7909 0.999 1.357 1.850 2.779
I am attempting to call the following jags model in R:
model{
# Main model level 1
for (i in 1:N){
ficon[i] ~ dnorm(mu[i], tau)
mu[i] <- alpha[country[i]]
}
# Priors level 1
tau ~ dgamma(.1,.1)
# Main model level 2
for (j in 1:J){
alpha[j] ~ dnorm(mu.alpha, tau.alpha)
}
# Priors level 2
mu.alpha ~ dnorm(0,.01)
tau.alpha ~ dgamma(.1,.1)
sigma.1 <- 1/(tau)
sigma.2 <- 1/(tau.alpha)
ICC <- sigma.2 / (sigma.1+sigma.2)
}
This is a hierarchical model, where ficon is a continuous variable 0-60, that may have a different mean or distribution by country. N = number of total observations (2244) and J = number of countries (34). When I run this model, I keep getting the following error message:
Compilation error on line 5.
Subset out of range: alpha[35]
This code worked earlier, but it's not working now. I assume the problem is that there are only 34 countries, and that's why it's getting stuck at i=35, but I'm not sure how to solve the problem. Any advice you have is welcome!
The R code that I use to call the model:
### input files JAGS ###
data <- list(ficon = X$ficon, country = X$country, J = 34, N = 2244)
inits1 <- list(alpha = rep(0, 34), mu.alpha = 0, tau = 1, tau.alpha = 1)
inits2 <- list(alpha = rep(1, 34), mu.alpha = 1, tau = .5, tau.alpha = .5)
inits <- list(inits1, inits2)
# call empty model
eqlsempty <- jags(data, inits, model.file = "eqls_emptymodel.R",
parameters = c("mu.alpha", "sigma.1", "sigma.2", "ICC"),
n.chains = 2, n.iter = itt, n.burnin = bi, n.thin = 10)
To solve the problem you need to renumber your countries so they only have the values 1 to 34. If you only have 34 countries and yet you are getting the error message you state then one of the countries must have the value 35. To solve this one could call the following R code before bundling the data:
x$country <- factor(x$country)
x$country <- droplevels(x$country)
x$country <- as.integer(x$country)
Hope this helps
I'm working on a binomial mixture model using OpenBUGS and R package R2OpenBUGS. I've successfully built simpler models, but once I add another level for imperfect detection, I consistently receive the error variable X is not defined in model or in data set. I've tried a number of different things, including changing the structure of my data and entering my data directly into OpenBUGS. I'm posting this in the hope that someone else has experience with this error, and perhaps knows why OpenBUGS is not recognizing variable X even though it is clearly defined as far as I can tell.
I've also gotten the error expected the collection operator c error pos 8 - this is not an error I've been getting previously, but I am similarly stumped.
Both the model and the data-simulation function come from Kery's Introduction to WinBUGS for Ecologists (2010). I will note that the data set here is in lieu of my own data, which is similar.
I am including the function to build the dataset as well as the model. Apologies for the length.
# Simulate data: 200 sites, 3 sampling rounds, 3 factors of the level 'trt',
# and continuous covariate 'X'
data.fn <- function(nsite = 180, nrep = 3, xmin = -1, xmax = 1, alpha.vec = c(0.01,0.2,0.4,1.1,0.01,0.2), beta0 = 1, beta1 = -1, ntrt = 3){
y <- array(dim = c(nsite, nrep)) # Array for counts
X <- sort(runif(n = nsite, min = xmin, max = xmax)) # covariate values, sorted
# Relationship expected abundance - covariate
x2 <- rep(1:ntrt, rep(60, ntrt)) # Indicator for population
trt <- factor(x2, labels = c("CT", "CM", "CC"))
Xmat <- model.matrix(~ trt*X)
lin.pred <- Xmat[,] %*% alpha.vec # Value of lin.predictor
lam <- exp(lin.pred)
# Add Poisson noise: draw N from Poisson(lambda)
N <- rpois(n = nsite, lambda = lam)
table(N) # Distribution of abundances across sites
sum(N > 0) / nsite # Empirical occupancy
totalN <- sum(N) ; totalN
# Observation process
# Relationship detection prob - covariate
p <- plogis(beta0 + beta1 * X)
# Make a 'census' (i.e., go out and count things)
for (i in 1:nrep){
y[,i] <- rbinom(n = nsite, size = N, prob = p)
}
# Return stuff
return(list(nsite = nsite, nrep = nrep, ntrt = ntrt, X = X, alpha.vec = alpha.vec, beta0 = beta0, beta1 = beta1, lam = lam, N = N, totalN = totalN, p = p, y = y, trt = trt))
}
data <- data.fn()
And here is the model:
sink("nmix1.txt")
cat("
model {
# Priors
for (i in 1:3){ # 3 treatment levels (factor)
alpha0[i] ~ dnorm(0, 0.01)
alpha1[i] ~ dnorm(0, 0.01)
}
beta0 ~ dnorm(0, 0.01)
beta1 ~ dnorm(0, 0.01)
# Likelihood
for (i in 1:180) { # 180 sites
C[i] ~ dpois(lambda[i])
log(lambda[i]) <- log.lambda[i]
log.lambda[i] <- alpha0[trt[i]] + alpha1[trt[i]]*X[i]
for (j in 1:3){ # each site sampled 3 times
y[i,j] ~ dbin(p[i,j], C[i])
lp[i,j] <- beta0 + beta1*X[i]
p[i,j] <- exp(lp[i,j])/(1+exp(lp[i,j]))
}
}
# Derived quantities
}
",fill=TRUE)
sink()
# Bundle data
trt <- data$trt
y <- data$y
X <- data$X
ntrt <- 3
# Standardise covariates
s.X <- (X - mean(X))/sd(X)
win.data <- list(C = y, trt = as.numeric(trt), X = s.X)
# Inits function
inits <- function(){ list(alpha0 = rnorm(ntrt, 0, 2),
alpha1 = rnorm(ntrt, 0, 2),
beta0 = rnorm(1,0,2), beta1 = rnorm(1,0,2))}
# Parameters to estimate
parameters <- c("alpha0", "alpha1", "beta0", "beta1")
# MCMC settings
ni <- 1200
nb <- 200
nt <- 2
nc <- 3
# Start Markov chains
out <- bugs(data = win.data, inits, parameters, "nmix1.txt", n.thin=nt,
n.chains=nc, n.burnin=nb, n.iter=ni, debug = TRUE)
Note: This answer has gone through a major revision, after I noticed another problem with the code.
If I understand your model correctly, you are mixing up the y and N from the simulated data, and what is passed as C to Bugs. You are passing the y variable (a matrix) to the C variable in the Bugs model, but this is accessed as a vector. From what I can see C is representing the number of "trials" in your binomial draw (actual abundances), i.e. N in your data set. The variable y (a matrix) is called the same thing in both the simulated data and in the Bugs model.
This is a reformulation of your model, as I understand it, and this runs ok:
sink("nmix1.txt")
cat("
model {
# Priors
for (i in 1:3){ # 3 treatment levels (factor)
alpha0[i] ~ dnorm(0, 0.01)
alpha1[i] ~ dnorm(0, 0.01)
}
beta0 ~ dnorm(0, 0.01)
beta1 ~ dnorm(0, 0.01)
# Likelihood
for (i in 1:180) { # 180 sites
C[i] ~ dpois(lambda[i])
log(lambda[i]) <- log.lambda[i]
log.lambda[i] <- alpha0[trt[i]] + alpha1[trt[i]]*X[i]
for (j in 1:3){ # each site sampled 3 times
y[i,j] ~ dbin(p[i,j], C[i])
lp[i,j] <- beta0 + beta1*X[i]
p[i,j] <- exp(lp[i,j])/(1+exp(lp[i,j]))
}
}
# Derived quantities
}
",fill=TRUE)
sink()
# Bundle data
trt <- data$trt
y <- data$y
X <- data$X
N<- data$N
ntrt <- 3
# Standardise covariates
s.X <- (X - mean(X))/sd(X)
win.data <- list(y = y, trt = as.numeric(trt), X = s.X, C= N)
# Inits function
inits <- function(){ list(alpha0 = rnorm(ntrt, 0, 2),
alpha1 = rnorm(ntrt, 0, 2),
beta0 = rnorm(1,0,2), beta1 = rnorm(1,0,2))}
# Parameters to estimate
parameters <- c("alpha0", "alpha1", "beta0", "beta1")
# MCMC settings
ni <- 1200
nb <- 200
nt <- 2
nc <- 3
# Start Markov chains
out <- bugs(data = win.data, inits, parameters, "nmix1.txt", n.thin=nt,
n.chains=nc, n.burnin=nb, n.iter=ni, debug = TRUE)
Overall, the results from this model looks ok, but there are long autocorrelation lags for beta0 and beta1. The estimate of beta1 also seems a bit off(~= -0.4), so you might want to recheck the Bugs model specification, so that it is matching the simulation model (i.e. that you are fitting the correct statistical model). At the moment, I'm not sure that it does, but I don't have the time to check further right now.
I got the same message trying to pass a factor to OpenBUGS. Like so,
Ndata <- list(yrs=N$yrs, site=N$site), ... )
The variable "site" was not passed by the "bugs" function. It simply was not in list passed
to OpenBUGS
I solved the problem by passing site as numeric,
Ndata <- list(yrs=N$yrs, site=as.numeric(N$site)), ... )
I have only 2 core CPU so logically I want to set only two parallel threads/clusters for jags.parallel. unfortunatelly, when I try it and the number of chains is 3 or 4, jags fails with an error:
Error in res[[ch]] : subscript out of bounds
Is lower number of threads (than chains) not allowed?
I have not encountered such statement in the documentation. Anyway, it doesn't make sense to run 4 chains in 4 threads/clusters, when your CPU only has 2 cores! Threads will fight for CPU, caches won't be used optimally and the result will be much slower than using 2 threads only.
Full code:
set.seed(123)
### 14.1.2. Data generation
n.site <- 10
x <- gl(n = 2, k = n.site, labels = c("grassland", "arable"))
eps <- rnorm(2*n.site, mean = 0, sd = 0.5)# Normal random effect
lambda.OD <- exp(0.69 +(0.92*(as.numeric(x)-1) + eps) )
lambda.Poisson <- exp(0.69 +(0.92*(as.numeric(x)-1)) ) # For comparison
C.OD <- rpois(n = 2*n.site, lambda = lambda.OD)
C.Poisson <- rpois(n = 2*n.site, lambda = lambda.Poisson)
### 14.1.4. Analysis using WinBUGS
# Define model
sink("Poisson.OD.t.test.txt")
cat("
model {
# Priors
alpha ~ dnorm(0,0.001)
beta ~ dnorm(0,0.001)
sigma ~ dunif(0, 10)
tau <- 1 / (sigma * sigma)
maybe_overdisp <- mean(exp_eps[])
# Likelihood
for (i in 1:n) {
C.OD[i] ~ dpois(lambda[i])
log(lambda[i]) <- alpha + beta *x[i] #+ eps[i]
eps[i] ~ dnorm(0, tau)
exp_eps[i] <- exp(eps[i])
}
}
",fill=TRUE)
sink()
# Bundle data
x = as.numeric(x)-1
n = length(x)
win.data <- list(C.OD = C.OD, x = as.numeric(x)-1, n = length(x))
# Inits function
inits <- function(){ list(alpha=rlnorm(1), beta=rlnorm(1), sigma = rlnorm(1))}
# Parameters to estimate
params <- c("lambda","alpha", "beta", "sigma", "maybe_overdisp")
# MCMC settings
nc <- 3 # Number of chains
ni <- 3000 # Number of draws from posterior per chain
nb <- 1000 # Number of draws to discard as burn-in
nt <- 5 # Thinning rate
require(R2jags)
# THIS WORKS FINE
out <- R2jags::jags(win.data, inits, params, "Poisson.OD.t.test.txt",
nc, ni, nb, nt);
# THIS PRODUCES ERROR
out <- do.call(jags.parallel, list(names(win.data), inits, params, "Poisson.OD.t.test.txt",
nc, ni, nb, nt, n.cluster = 2));