error message JAGS subset out of range - r

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

Related

How can I find a syntax error in JAGS considering that the position indicated is not the real error position?

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

Error: Index out of range taking subset of variable

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!

Winbugs to Rjags beta binomial model translation

I am working through the textbook "Bayesian Ideas and Data Analysis" by Christensen et al.
There is a simple exercise in the book that involves cutting and pasting the following code to run in Winbugs:
model{ y ~ dbin(theta, n) # Model the data
ytilde ~ dbin(theta, m) # Prediction of future binomial
theta ~ dbeta(a, b) # The prior
prob <- step(ytilde - 20) # Pred prob that ytilde >= 20 }
list(n=100, m=100, y=10, a=1, b=1) # The data
list(theta=0.5, ytilde=10) # Starting/initial values
I am trying to translate the following into R2jags code and am running into some trouble. I thought I could fairly directly write my R2Jags code in this fashion:
model {
#Likelihoods
y ~ dbin(theta,n)
yt ~ dbin(theta,m)
#Priors
theta ~ dbeta(a,b)
prob <- step(yt - 20)
}
with the R code:
library(R2jags)
n <- 100
m <- 100
y <- 10
a <- 1
b <- 1
jags.data <- list(n = n,
m = m,
y = y,
a = a,
b = b)
jags.init <- list(
list(theta = 0.5, yt = 10), #Chain 1 init
list(theta = 0.5, yt = 10), #Chain 2 init
list(theta = 0.5, yt = 10) #Chain 3 init
)
jags.param <- c("theta", "yt")
jags.fit <- jags.model(data = jags.data,
inits = jags.inits,
parameters.to.save = jags.param,
model.file = "hw21.bug",
n.chains = 3,
n.iter = 5000,
n.burnin = 100)
print(jags.fit)
However, calling the R code brings about the following error:
Error in jags.model(data = jags.data, inits = jags.inits, parameters.to.save = jags.param, :
unused arguments (parameters.to.save = jags.param, model.file = "hw21.bug", n.iter = 5000, n.burnin = 100)
Is it because I am missing a necessary for loop in my R2Jags model code?
The error is coming from the R function jags.model (not from JAGS) - you are trying to use arguments parameters.to.save etc to the wrong function.
If you want to keep the model as similar to WinBUGS as possible, there is an easier way than specifying the data and initial values in R. Put the following into a text file called 'model.txt' in your working directory:
model{
y ~ dbin(theta, n) # Model the data
ytilde ~ dbin(theta, m) # Prediction of future binomial
theta ~ dbeta(a, b) # The prior
prob <- step(ytilde - 20) # Pred prob that ytilde >= 20
}
data{
list(n=100, m=100, y=10, a=1, b=1) # The data
}
inits{
list(theta=0.5, ytilde=10) # Starting/initial values
}
And then run this in R:
library('runjags')
results <- run.jags('model.txt', monitor='theta')
results
plot(results)
For more information on this method of translating WinBUGS models to JAGS see:
http://runjags.sourceforge.net/quickjags.html
Matt
This old blog post has an extensive example of converting BUGS to JAGS accessed via package rjags not R2jags. (I like the package runjags even better.) I know we're supposed to present self-contained answers here, not just links, but the post is rather long. It goes through each logical step of a script, including:
loading the package
specifying the model
assembling the data
initializing the chains
running the chains
examining the results

Data file seemingly too large with wine and openBUGS

I have recently started trying to do some bayesian modelling with OpenBUGS and R using R2OpenBUGS.
I followed a great link for installing wine and OpenBUGS by David Eagles and the schools example posted there worked fine.
I then tried to run some code I had and kept getting an error after the the model is syntactically correct telling me the data was not loading properly.
After a few days of troubleshooting this it seems that when the datafile is above a certain length the top bit (where you traditionally highlight list in OpenBUGS to load data) is lost and the data cannot be loaded by OpenBUGS.
A screenshot of my OpenBUGS program with the loaded data where the list section has been cut off
This picture shows that at the top of my data.txt file there is no longer a list{ which is basically stopping all of my attempts to run the model.
To confirm this I have ran the example of a simple linear regression where I set the number of points to 1000 and then to 100:
# Load in paths for running OpenBUGS through wine
source("/Users/dp323/Desktop/R/scripts/Where_is_my_OpenBUGS.R")
# set up model
linemodel <- function() {
for (j in 1:N) {
Y[j] ~ dnorm(mu[j], tau) ## Response values Y are Normally distributed
mu[j] <- alpha + beta * (x[j] - xbar) ## linear model with x values centred
}
## Priors
alpha ~ dnorm(0, 0.001)
beta ~ dnorm(0, 0.001)
tau ~ dgamma(0.001, 0.001)
sigma <- 1/sqrt(tau)
}
# set up data ####
linedata <- list(Y = c(1:100), x = c(1:100), N = 100, xbar = 3)
# set initial values ####
lineinits <- function() {
list(alpha = 1, beta = 1, tau = 1)
}
# run bugs ####
lineout <- bugs(data = linedata, inits = lineinits, parameters.to.save = c("alpha", "beta", "sigma"), model.file = linemodel, n.chains = 1, n.iter = 10000, OpenBUGS.pgm = OpenBUGS.pgm, WINE = WINE, WINEPATH = WINEPATH, useWINE = T, debug = T)
The model runs great when linedata <- list(Y = c(1:100), x = c(1:100), N = 100, xbar = 3) but falls apart at the loading in data stage when linedata <- list(Y = c(1:1000), x = c(1:1000), N = 1000, xbar = 3).
I have exhausted a google search of limits of data file size on wine and OpenBUGS and not found anything helpful.
Anyone have any suggestions of what to try/where to start/experience of this before?

OpenBUGS error undefined variable

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)), ... )

Resources