R2OpenBUGS Error: node not stochastic - r

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)

Related

Possible directed cycle in JAGS

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

JAGS and R: Obtain posterior predictive distribution for specific x

I am trying to obtain a posterior predictive distribution for specified values of x from a simple linear regression in Jags. I could get the regression itself to work by adapting this example (from https://biometry.github.io/APES//LectureNotes/StatsCafe/Linear_models_jags.html) to my own data. I have supplied a smal chunk of this data here so that the code works here also.
library(rjags)
library(R2jags)
#create data
dw=c(-15.2,-13.0,-10.0,-9.8,-8.5,-8.5,-7.7,-7.5,-7.2,-6.1,-6.1,-6.1,-5.5,-5.0,-5.0,-5.0,-4.5,-4.0,-2.0,-1.0,1.3)
phos=c(11.8,12.9,15.0,14.4,17.3,16.1,20.8,16.6,16.2,18.2,18.8,19.2,15.6,17.0,18.9,22.1,18.9,22.8,21.6,20.5,21.1)
#convert to list
jagsdwphos=list(dw=dw,phos=phos,N=length(phos))
#write model function for linear regression
lm1_jags <- function(){
# Likelihood:
for (i in 1:N){
phos[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
mu[i] <- intercept + slope * dw[i]
}
# Priors:
intercept ~ dnorm(0, 0.01)
slope ~ dnorm(0, 0.01)
sigma ~ dunif(0, 100) # standard deviation
tau <- 1 / (sigma * sigma)
}
#specifiy paramters of MCMC sampler, choose posteriors to be reported and run the jags model
#set initial values for MCMC
init_values <- function(){
list(intercept = rnorm(1), slope = rnorm(1), sigma = runif(1))
}
#choose paramters to report on
params <- c("intercept", "slope", "sigma")
#run model in jags
lm_dwphos <- jags(data = jagsdwphos, inits = init_values, parameters.to.save = params, model.file = lm1_jags,
n.chains = 3, n.iter = 12000, n.burnin = 2000, n.thin = 10, DIC = F)
In addition to this regression, I would like to have an output of the posterior predictive distributions of particular phos values, but I cannot get it to work with this simple example I have written. I found a tutorial here https://doingbayesiandataanalysis.blogspot.com/2015/10/posterior-predicted-distribution-for.html and tried to implement it like this:
#create data
dw=c(-15.2,-13.0,-10.0,-9.8,-8.5,-8.5,-7.7,-7.5,-7.2,-6.1,-6.1,-6.1,-5.5,-5.0,-5.0,-5.0,-4.5,-4.0,-2.0,-1.0,1.3)
phos=c(11.8,12.9,15.0,14.4,17.3,16.1,20.8,16.6,16.2,18.2,18.8,19.2,15.6,17.0,18.9,22.1,18.9,22.8,21.6,20.5,21.1)
#specifiy phos values to use for posterior predictive distribution
phosprobe=c(14,18,22)
#convert to list
jagsdwphos=list(dw=dw,phos=phos,N=length(phos),xP=phosprobe)
#write model function for linear regression
lm1_jags <- function(){
# Likelihood:
for (i in 1:N){
phos[i] ~ dnorm(mu[i], tau) # tau is precision (1 / variance)
mu[i] <- intercept + slope * dw[i]
}
# Priors:
intercept ~ dnorm(0, 0.01) # intercept
slope ~ dnorm(0, 0.01) # slope
sigma ~ dunif(0, 100) # standard deviation
tau <- 1 / (sigma * sigma) # sigma^2 doesn't work in JAGS
nu <- nuMinusOne+1
nuMinusOne ~ dexp(1/29.0)
#prediction
for(i in 1:3){
yP ~ dt(intercept+slope*xP[i],tau,nu)
}
}
#specifiy paramters of MCMC sampler, choose posteriors to be reported and run the jags model
#set initial values for MCMC
init_values <- function(){
list(intercept = rnorm(1), slope = rnorm(1), sigma = runif(1))
}
#choose paramters to report on
params <- c("intercept", "slope", "sigma","xP","yP")
#run model in jags
lm_dwphos <- jags(data = jagsdwphos, inits = init_values, parameters.to.save = params, model.file = lm1_jags,
n.chains = 3, n.iter = 12000, n.burnin = 2000, n.thin = 10, DIC = F)
But I get the following error message:
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, : RUNTIME ERROR: Compilation error on line 14. Attempt to redefine node yP[1]
I confess I don't quite understand exactly how the prediction was implemented in that example I used and could not find an explanation on what exactly nu is or where those numbers come from. So I presume that is where I made some mistake adapting to my example, but it was the only tutorial in Jags that I could find that gives the whole distribution of y values for the probed x instead of just the mean.
I would appreciate any help or explanation.
Thanks!
This error occurs because you are not indexing yP. You have written this loop like this:
#prediction
for(i in 1:3){
yP ~ dt(intercept+slope*xP[i],tau,nu)
}
As i moves from 1 to 3 the element yP is being written over. You need to index it like you have done with xP.
#prediction
for(i in 1:3){
yP[i] ~ dt(intercept+slope*xP[i],tau,nu)
}

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

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.

Resources