R OpenBugs Model Error - r

I am looking to run a hierarchical poisson model to hockey goal tending data. here is the model as set up in bugs:
modelString <- "model {
for(i in 1:n_obs){
hockey_goals[i] ~ dpois(p[i])
log(p[i]) <- p_inter + p_age * age[i] + p_sv_pct * sv_pct[i] + p_team * team[i] + p_win_pct * win_pct[i] + log(n_mins[i])
}
p_inter ~ dnorm(0,0.00001)
p_age ~ dnorm(0, 0.00001)
p_sv_pct ~ dnorm(0, 0.00001)
p_team ~ dnorm(0, 0.00001)
p_win_pct ~ dnorm(0, 0.00001)
}"
I then compile and load the data:
season_goals <- data$GA
n_mins <- data$MIN
age <- data$Age
sv_pct <- data$SV.
team <- data$Tm
win_pct <- data$W/data$GP
data <- list(n_obs=length(season_goals),n_mins=n_mins,hockey_goals=season_goals,age=age,
sv_pct=sv_pct,team=team,win_pct=win_pct)
# Get the data into BUGS:
modelData( bugsData( data ) )
#------------------------------------------------------------------------------
# INTIALIZE THE CHAINS.
nchain = 1
modelCompile( numChains=nchain )
modelGenInits()
#------------------------------------------------------------------------------
# RUN THE CHAINS.
samplesSet( c("p_age","p_sv_pct","p_team","p_win_pct") )
# R command defines a new variable that specifies an arbitrary chain length:
chainLength = 10000
# BRugs tells BUGS to generate a MCMC chain:
modelUpdate( chainLength )
At this point I get an error:
Error in handleRes(res) : NA
Any ideas on where I went wrong...?

I wish I could just comment but I don't have enough reputation. Anyway, I made up some data and ran a simplified version of your model (i.e. with only age and minutes played). I ran it in the GUI version of OpenBUGS and it didn't work. I then changed the priors on you coefficients to dnorm(0,0.01) and it updated.
So I would suggest changing the priors. The ones you have are very, very vague. Changing them as suggested will not effect your inference and you may get the model to run.

Related

"empty slot not allowed in variable name" (OpenBUGS, R2OpenBUGS)

I'm a beginner with OpenBUGS which I use through the R2OpenBUGS R package. I try to set state space model for identifying a lognormal signal in very noisy data. After many trials and errors, I managed to get this code but I still get the following error message: "empty slot not allowed in variable name error pos 664" which I don't understand. Can anyone knows what is wrong with the code ?
Disclaimer:
alt = measured altitude
true_alt = what I try to assess
nbird = number of individuals
nobs = number of observations (this number is not the same for every bird)
nstate = 'flight state', which is the way the birds behave (nstate = 3 because there are 3 different behaviours)
I try to determine the lognormal distribution of true_alt for each state.
model <- function(){
## MODEL SPECIFICATION
for(j in 1:nbird){
for(i in 1:nobs[j]){
alt[i,j] ~ dnorm(true_alt[i,j], tau.obs)
log(true_alt[i,j]) <- log_true_alt[i,j]
log_true_alt[i,j] ~ dnorm(mean.alt[i,j], tau[state[i,j]])
mean.alt[i,j] <- alt1[state[i,j]] + ind.re[j]
}
}
for(i in 1:nstate){ tau[i] <- 1/(sig[i]) }
# Random Effects:
tau.re <- 1/sig.re
for(j in 1:nbird) { ind.re[j] ~ dnorm(0, tau.re) }
## PRIORS
for(i in 1:nstate) {
alt1[i] ~ dnorm(0, 0.01)
sig[i] ~ dunif(0, 200)
}
sig.re ~ dunif(0, 200)
state ~ dunif(1,3)
## POSTERIOR PREDICTIVE DISTRIBUTIONS FOR EACH STATE
for(s in 1:nstate){
log_alt_pred[s] ~ dnorm(alt1[s], tau[s])
log(alt_pred[s]) <- log_alt_pred[s]
}
}
Thank you!!!
It could be because in your priors you're trying to set a distribution for "alt1[i]" but in your model you've used "alt[i,j]".

How to set up bayesian linear regression with mixture modelling in rjags?

I'm trying to make a bayesian mixture model using rjags. This is an attempt to map a dose-response relationship for experiments conducted in 19 labs. As such, the model that I produced has intercepts for all the labs. I want to cluster the lab effects using mixture modelling but my code does not work. Here is a copy of my model followed by the error :-
mod_string2 <- "
model{
# Likelihood
for(i in 1:n){
Y[i] ~ dnorm(mu[i],inv.var)
mu[i] <- a[lab[i]] + b[1]*ld1[i] + b[2]*ld2[i] + b[3]*sqld1[i] + b[4]*sqld2[i] + b[5]*lbody[i] + b[6]*B[i]*ld1[i] + b[7]*C[i]*ld1[i] + b[8]*D[i]*ld1[i] + b[9]*B[i]*ld2[i] + b[10]*C[i]*ld2[i] + b[11]*D[i]*ld2[i]
a[lab[i]] ~ dnorm(muOfClust[clust[lab[i]]], tau)
clust[i] ~ dcat( pClust[1:Nclust] )
}
# Prior for labs (intercepts)
for (clustIdx in 1: Nclust) {
muOfClust[clustIdx] ~ dnorm( 0 , 1/100000 )
}
pClust[1:Nclust] ~ ddirch(onesRepNclust) # so (pi1,pi2) follow Dir(1,1) which implies pi1 follows Beta(1,1)
tau ~ dgamma(0.01 , 0.01)
# Prior for beta
for(j in 1:11){
b[j] ~ dnorm(0,0.0001)
}
# Prior for the inverse variance
inv.var ~ dgamma(0.01, 0.01)
sigma <- 1/sqrt(inv.var)
}
"
My error is :-
Error in jags.model(textConnection(mod_string2), data = d2) :
RUNTIME ERROR:
Compilation error on line 7.
Attempt to redefine node a[3]
What am I doing wrong?

Constrain order of parameters in R JAGS

I am puzzled by a simple question in R JAGS. I have for example, 10 parameters: d[1], d[2], ..., d[10]. It is intuitive from the data that they should be increasing. So I want to put a constraint on them.
Here is what I tried to do but it give error messages saying "Node inconsistent with parents":
model{
...
for (j in 1:10){
d.star[j]~dnorm(0,0.0001)
}
d=sort(d.star)
}
Then I tried this:
d[1]~dnorm(0,0.0001)
for (j in 2:10){
d[j]~dnorm(0,0.0001)I(d[j-1],)
}
This worked, but I don't know if this is the correct way to do it. Could you share your thoughts?
Thanks!
If you are ever uncertain about something like this, it is best to just simulate some data to determine if the model structure you suggest works (spoiler alert: it does).
Here is the model that I used:
cat('model{
d[1] ~ dnorm(0, 0.0001) # intercept
d[2] ~ dnorm(0, 0.0001)
for(j in 3:11){
d[j] ~ dnorm(0, 0.0001) I(d[j-1],)
}
for(i in 1:200){
y[i] ~ dnorm(mu[i], tau)
mu[i] <- inprod(d, x[i,])
}
tau ~ dgamma(0.01,0.01)
}',
file = "model_example.R")```
And here are the data I simulated to use with this model.
library(run.jags)
library(mcmcplots)
# intercept with sorted betas
set.seed(161)
betas <- c(1,sort(runif(10, -5,5)))
# make covariates, 1 for intercept
x <- cbind(1,matrix(rnorm(2000), nrow = 200, ncol = 10))
# deterministic part of model
y_det <- x %*% betas
# add noise
y <- rnorm(length(y_det), y_det, 1)
data_list <- list(y = as.numeric(y), x = x)
# fit the model
mout <- run.jags('model_example.R',monitor = c("d", "tau"), data = data_list)
Following this, we can plot out the estimates and overlay the true parameter values
caterplot(mout, "d", reorder = FALSE)
points(rev(c(1:11)) ~ betas, pch = 18,cex = 0.9)
The black points are the true parameter values, the blue points and lines are the estimates. Looks like this set up does fine so long as there are enough data to estimate all of those parameters.
It looks like there is an syntax error in the first implementation. Just try:
model{
...
for (j in 1:10){
d.star[j]~dnorm(0,0.0001)
}
d[1:10] <- sort(d.star) # notice d is indexed.
}
and compare the results with those of the second implementation. According to the documentation, these are both correct, but it is advised to use the function sort.

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