Possible directed cycle in JAGS - r

I am trying to fit a space state model, and I am getting this error message:
Error in jags.model(file = model.file, data = data, inits = inits, n.chains = n.chains, :
RUNTIME ERROR:
Possible directed cycle involving some or all
of the following nodes:
t[2]
t[3]
t[4]
t[5]
t[6]
t[7]
t[8]
t[9]
v[2]
v[3]
v[4]
v[5]
v[6]
v[7]
v[8]
v[9]
I`ve found here JAGS error - Possible directed cycle involving some or all of the following nodes that it might be due to the term t[i] which is in both sides of the equation but I have done this before in other space states models and I have no problem with this, any idea of what can be causing this problem???
Here is the model:
o<-c(22.77619, 19.07782, 22.08817, 16.32168, 32.57081, 10.48027, 15.93440, 27.54557, 33.39933)
cat(file="pop.din","
model {
t[1] <- n0
o[1] ~ dlnorm(log(t[1]),tau.obs)
for (i in 2:9) {
v[i] <- lambda*t[i] #valor esperado
t[i] ~ dpois(v[i]) #t valor verdadero
o[i] ~ dlnorm(log(t[i]),tau.obs)
}
lambda ~ dunif(0.1,0.00001)
tau.obs ~ dgamma(1,10)
n0 ~ dlnorm(1,0.0001)
}")
pop.din.data<-c("o")
#initial values for the parameters stored as a list
inits<-function()list(lambda=runif(0.01,1),tau.obs=rlnorm(1,1,1),n0=rlnorm(1,1,1))
params<- c("lambda","n0","tau.obs")
ni <- 10000
nt <- 1
nb <- 5000
nc <- 3
library(jagsUI)
j.model <- jags (model.file = "pop.din", data = pop.din.data,parameters.to.save = params,
inits=inits, n.burnin=nb,n.chains = nc,n.iter = ni)
print(j.model)
Regards

Here is the solution to my problem: the space state model relates the value of a variable with its value a time before, in this case, so the process model should be written:
cat(file="pop.din","
model{
#### Data Model
for(i in 1:n){
o[i] ~ dlnorm(x[i],tau_obs)
}
#### Process Model
for(i in 2:n){
v[i]<-lambda*x[i-1] ###not x[i]
x[i]~dpois(v[i])
}
#### Priors
x[1] ~ dlnorm(x_ic,tau_ic)
lambda ~dunif(mu,tau_lambda)
tau_obs ~ dgamma(1,1)
}")
Regards

Related

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!

Error: Attempt to redefine node in linear regression

I have fitted following simple linear regression Bayesian model using rjags.
I was able to run the model by specifying all the predictors separately(like for a lm object). Now I want to learn how to specify the predictors by introducing them as a matrix instead of specifying them separately.
So I ran the following code, but it gave some errors.
I used tobbaco data set in rrr package to provide a reproducible example.
library(rrr)
require(dplyr)
library(rjags)
tobacco <- as_data_frame(tobacco)
N1 = length(tobacco$Y1.BurnRate)
x1 = model.matrix(Y1.BurnRate~X2.PercentChlorine+X3.PercentPotassium ,data = tobacco)
bayes_model_mul1=
"model {
for(i in 1:N1){
Y1.BurnRate[i]~dnorm(mu1[i],tau1)
for(j in 1:3){
mu1[i]=beta1[j]*x1[i,j]
}
}
for (l in 1:3) { beta1[l] ~dnorm(0, 0.001) }
tau1 ~ dgamma(.01,.01)
sigma_tau1 = 1/tau1
}"
model3 <- jags.model(textConnection(bayes_model_mul1),
data = list(Y1.BurnRate=tobacco$Y1.BurnRate, x1=x1, N1=N1),
n.chains=1)
After I run model3 , I got following error.
Error in jags.model(textConnection(bayes_model_mul1), data = list(Y1.BurnRate = tobacco$Y1.BurnRate, :
RUNTIME ERROR:
Compilation error on line 6.
Attempt to redefine node mu1[1]
Can anyone help me figure this out ?
Does this due to introducing predictors as a matrix ?
There are a few ways to do this, here are two:
Use matrix multiplication outside of the likelihood loop
m1 =
"model {
mu1 = x1 %*% beta1 # ---> this
for(i in 1:N1){
Y1.BurnRate[i] ~ dnorm(mu1[i], tau1)
}
for (l in 1:3) { beta1[l] ~ dnorm(0, 0.001) }
tau1 ~ dgamma(.01,.01)
sigma_tau1 = 1/tau1
}"
Use inprod to multiply the parameters with the design matrix
m2 =
"model {
for(i in 1:N1){
mu1[i] = inprod(beta1, x1[i,]) #----> this
Y1.BurnRate[i] ~ dnorm(mu1[i], tau1)
}
for (l in 1:3) { beta1[l] ~ dnorm(0, 0.001) }
tau1 ~ dgamma(.01,.01)
sigma_tau1 = 1/tau1
}"
You received an error with for(j in 1:3){ mu1[i] = beta1[j]* x1[i,j] } as every time you loop though the parameter index j you overwrite mu1[i]. It also doesn't sum up the individual terms. You may be able to index mu1 with j as well and then sum but untested ...

R2Winbugs - error in inits specification?

While attempting to adapt a working WinBUGS model and mitigate it to R using R2WinBUGS, I got several error messages.
I believe is related to the specification of the inits, but have been unable resolve the issue.
The first was error message was using inits1:
list(A=1, d=c(NA,0,0,0,0), mu=c(0,0,0,0))
Error in bugs(mydata, inits = inits1, model.file = "mtcfe.txt", parameters = c("or"), :
Number of initialized chains (length(inits)) != n.chains
After reading the suggested fix by Uwe Liggers "List containing lists solution" I modified the the inits1 to inits2:
inits2 <- list(list(A=1, d=c(NA,0,0,0,0), mu=c(0,0,0,0)))
And received the error:
Error in bugs.run(n.burnin, bugs.directory, WINE = WINE, useWINE = useWINE, : Look at the log file and try again with 'debug=TRUE' to figure out what went wrong within Bugs.
I have also attempted the fix suggested by AndyC at this post "getting-winbugs-leuk-example-to-work-from-r-using-r2winbugs". By changing the inits to:
inits4 <- function(){list(list(A=1, d=c(NA,0,0,0,0), mu=c(0,0,0,0)))}
And received the error:
Error in bugs.run(n.burnin, bugs.directory, WINE = WINE, useWINE = useWINE, : Look at the log file and try again with 'debug=TRUE' to figure out what went wrong within Bugs.
This is my attempt on R2WinBUGS.
Note, I have included several inits in the code that did not work:
work.dir <- "removed from example"
setwd(work.dir)
getwd() # check working directory
# Load Package
library(R2WinBUGS)
# Read data
mydata <- list(nt=5,
ns=4,
r=structure(
.Data = c(2506,7834,6729,2139,
2548,7860,6710,4418),
.Dim = c(4,2)),
n=structure(
.Data = c(2697, 8212, 7266, 2333,
2701,8280,7257,4687),
.Dim= c(4,2)),
t=structure(
.Data = c( 1,1,1,1,
2,3,4,5),
.Dim = c(4,2)),
na=structure(
.Data = c(2,2,2,2))
)
bugs.data(mydata)
# Set initial values
inits <- function(){list(A=1, d=c(NA,0,0,0,0), mu=c(0,0,0,0))}
#inits2 <- list(A=1, d=c(NA,0,0,0,0), mu=c(0,0,0,0))
#inits3 <- function(){list(inits2,inits2)}
#inits4 <- function(){list(inits,inits)}
#inits5 <- list(inits,inits)
# CALL WinBUGS AND SAVE RESULTS IN VARIABLE out.re
out.re <- bugs(mydata,inits=inits1, # load data and initial values
model.file="mtcfe.txt", # file with model to run
parameters=c("or"),
n.thin=1,
n.chains=1, n.iter=1500, n.burnin=500,
bugs.directory=bd,
working.directory=work.dir,
debug=TRUE)
print(out.re,digits=4) #lists all results as in WinBUGS stats(*)
And this is the working WinBUGS code, adapted from a WinBUGS course held by the universities of Bristol and Leicester:
# Binomial likelihood, logit link, MTC
# Fixed effect model
model{ # *** PROGRAM STARTS
for(i in 1:ns){ # LOOP THROUGH STUDIES
mu[i] ~ dnorm(0,.0001) # vague priors for all trial baselines
for (k in 1:na[i]) { # LOOP THROUGH ARMS
r[i,k] ~ dbin(p[i,k],n[i,k]) # binomial likelihood
logit(p[i,k]) <- mu[i] + d[t[i,k]]-d[t[i,1]] # model for linear predictor
rhat[i,k] <- p[i,k] * n[i,k] # expected value of the numerators
dev[i,k] <- 2 * (r[i,k] * (log(r[i,k])-log(rhat[i,k])) #Deviance contribution
+ (n[i,k]-r[i,k]) * (log(n[i,k]-r[i,k]) - log(n[i,k]-rhat[i,k])))
}
resdev[i] <- sum(dev[i,1:na[i]]) # summed residual deviance contribution for this trial
}
totresdev <- sum(resdev[]) #Total Residual Deviance
d[1]<- 0 # treatment effect is zero for reference treatment
for (k in 2:nt) { d[k] ~ dnorm(0,.0001) } # vague priors for treatment effects
# pairwise ORs and LORs for all possible pair-wise comparisons
for (c in 1:(nt-1)) { for (k in (c+1):nt) {
or[c,k] <- exp(d[k] - d[c])
lor[c,k] <- (d[k]-d[c])
}
}
# ranking
for (k in 1:nt) {
rk[k] <- nt+1-rank(d[],k) # assumes events are “good”
# rk[k] <- rank(d[],k) # assumes events are “bad”
best[k] <- equals(rk[k],1) #calculate probability that treat k is best
}
# Absolute effects
A ~ dnorm(-2.6,precA)
precA <- pow(0.38,-2) # prior precision for Treatment A, sd=0.38 on logit scale
for (k in 1:nt) { logit(T[k]) <- A + d[k] }
} # *** PROGRAM ENDS
#Inits
list(A=1, d=c(NA,0,0,0,0), mu=c(0,0,0,0))
#Data
list(nt=5.00000E+00, ns=4.00000E+00, r= structure(.Data= c(2.50600E+03, 2.54800E+03, 7.83400E+03, 7.86000E+03, 6.72900E+03, 6.71000E+03, 2.13900E+03, 4.41800E+03), .Dim=c(4, 2)), n= structure(.Data= c(2.69700E+03, 2.70100E+03, 8.21200E+03, 8.28000E+03, 7.26600E+03, 7.25700E+03, 2.33300E+03, 4.68700E+03), .Dim=c(4, 2)), t= structure(.Data= c(1.00000E+00, 2.00000E+00, 1.00000E+00, 3.00000E+00, 1.00000E+00, 4.00000E+00, 1.00000E+00, 5.00000E+00), .Dim=c(4, 2)), na=c(2.00000E+00, 2.00000E+00, 2.00000E+00, 2.00000E+00))

Intro to JAGS analysis

I am a student studying bayesian statistics and have just begun to use JAGS using a intro script written by my lecturer, with us (the students) having to only enter the data and the number of iterations. The following is the script with my data added into it:
setwd("C:\\Users\\JohnSmith\\Downloads")
rawdata = read.table("bwt.txt",header=TRUE)
Birthweight = rawdata$Birthweight
Age = rawdata$Age
model = "model
{
beta0 ~ dnorm(0, 1/1000^2)
beta1 ~ dnorm(0, 1/1000^2)
log_sigma ~ dunif(-10, 10)
sigma <- exp(log_sigma)
for(i in 1:N)
{
mu[i] <- beta0 + beta1 * Age[i]
Birthweight[i] ~ dnorm(mu[i], 1/sigma^2)
}
}
"
data = list(x=Birthweight, y=Age, N=24)
# Variables to monitor
variable_names = c('beta0','beta1')
# How many burn-in steps?
burn_in = 1000
# How many proper steps?
steps = 100000
# Thinning?
thin = 10
# Random number seed
seed = 2693795
# NO NEED TO EDIT PAST HERE!!!
# Just run it all and use the results list.
library('rjags')
# Write model out to file
fileConn=file("model.temp")
writeLines(model, fileConn)
close(fileConn)
if(all(is.na(data)))
{
m = jags.model(file="model.temp", inits=list(.RNG.seed=seed, .RNG.name="base::Mersenne-Twister"))
} else
{
m = jags.model(file="model.temp", data=data, inits=list(.RNG.seed=seed, .RNG.name="base::Mersenne-Twister"))
}
update(m, burn_in)
draw = jags.samples(m, steps, thin=thin, variable.names = variable_names)
# Convert to a list
make_list <- function(draw)
{
results = list()
for(name in names(draw))
{
# Extract "chain 1"
results[[name]] = as.array(draw[[name]][,,1])
# Transpose 2D arrays
if(length(dim(results[[name]])) == 2)
results[[name]] = t(results[[name]])
}
return(results)
}
results = make_list(draw)
However, when I run the following code I get the following error message:
Error in jags.model(file = "model.temp", data = data, inits = list(.RNG.seed = seed, :
RUNTIME ERROR:
Compilation error on line 11.
Unknown parameter Age
In addition: Warning messages:
1: In jags.model(file = "model.temp", data = data, inits = list(.RNG.seed = seed, :
Unused variable "x" in data
2: In jags.model(file = "model.temp", data = data, inits = list(.RNG.seed = seed, :
Unused variable "y" in data
But as far as I can see, line 11 is blank, which leaves me stumped as to where the error is coming from. If anyone can give me some tips as to solve this, it will be greatly appreciated.
The names of the elements of your list of data (data) should match the names of the variables in your model.
You have:
data = list(x=Birthweight, y=Age, N=24)
so JAGS is looking for variables called x and y in your model. However, in your model, you have:
mu[i] <- beta0 + beta1 * Age[i]
Birthweight[i] ~ dnorm(mu[i], 1/sigma^2)
That is, your variables are called Age and Birthweight.
So, either change your list to:
data <- list(Birthweight=Birthweight, Age=Age, N=24)
or change your model to:
mu[i] <- beta0 + beta1 * y[i]
x[i] ~ dnorm(mu[i], 1/sigma^2)
Had you done readLines('model.temp') (or opened model.temp in a text editor), you would have seen that line 11 of that file refers to the line that contains mu[i] <- beta0 + beta1 * Age[i], which is the first error that JAGS encountered due to the reference to Age, for which neither data nor a prior was provided.

R2OpenBUGS Error: node not stochastic

I have a specific problem in Running R2OpenBUGS in R. But it runs perfectly well in OpenBUGS.
I want to understand what the problem is.
Here is my code:
model volatility;
const n=180;
{
# likelihood: joint distribution of ys
for (t in 1:n) { yisigma2[t] <- 1/exp(theta[t]);
y[t] ~ dnorm(0,yisigma2[t]);
}
prior distributions
mu ~ dnorm(0,0.1);
phistar ~ dbeta(20,1.5);
itau2 ~ dgamma(2.5,0.025);
beta <- exp(mu/2);
phi <- 2*phistar-1;
tau <- sqrt(1/itau2);
theta0 ~ dnorm(mu,itau2);
thmean[1] <- mu + phi*(theta0-mu);
theta[1] ~ dnorm(thmean[1],itau2);
for (t in 2:n)
{
thmean[t] <- mu + phi*(theta[t-1]-mu);
theta[t] ~ dnorm(thmean[t],itau2);
}
}
R Code:
svm.sim <- bugs(data, inits, model.file = "C:/Documents and Settings/code.txt",
parameters = c("mu", "phi", "tau"),
n.chains = 1, n.iter = 1000, codaPkg = TRUE,debug=TRUE)
and here is the error shown in log of OpenBUGS when I run it from R:
model is syntactically correct
data loaded
model compiled
this component of node is not stochastic phi error pos 25
unable to generate initial values for node of type UpdaterNormal.StdUpdater
model must be initialized before updating
model must be initialized before monitors used
model must be initialized before monitors used
model must be initialized before monitors used
model must be initialized before monitors used
model must be initialized before DIC can be monitored
model must be initialized before updating
model must be initialized before monitors used
DIC monitor not set
Any help will be greatly appreciated
Thank You and Regards
Dinakar
I ran your code with a slight modification (see below) and it seemed to work fine. I did specify the value n as data, and let OpenBUGS generate initial values itself. Is it an issue with how you specified your inits?
sink("stack_model.txt")
cat("
model{
# likelihood: joint distribution of ys
for (t in 1:n)
{
yisigma2[t] <- 1/exp(theta[t])
y[t] ~ dnorm(0,yisigma2[t])
}
mu ~ dnorm(0,0.1)
phistar ~ dbeta(20,1.5)
itau2 ~ dgamma(2.5,0.025)
beta <- exp(mu/2)
phi <- 2*phistar-1
tau <- sqrt(1/itau2)
theta0 ~ dnorm(mu,itau2)
thmean[1] <- mu + phi*(theta0-mu)
theta[1] ~ dnorm(thmean[1],itau2)
for (t in 2:n)
{
thmean[t] <- mu + phi*(theta[t-1]-mu)
theta[t] ~ dnorm(thmean[t],itau2)
}
}",fill=TRUE)
sink()
win.data<-list(n=180)
svm.sim <- bugs(win.data, inits=NULL, model.file = "stack_model.txt", parameters = c("mu", "phi", "tau"), n.chains = 2, n.iter = 1000, DIC=F, debug=TRUE, codaPkg =TRUE)

Resources