R JAGS: invalid parent value in node (combining dcat and dnorm) - r

I am a newbie when it comes to using Jags and Rjags.
modelString = "
model {
for (i in 1:N){
y[i] ~ dt(mu,tau,nu)
}
tau <- nuless2/(sig^2)
nuless2 <- nu / nuless
nuless <- (nu-2)
sig ~ dnorm(0.02045457,10000000)
mu ~ dnorm(0.0013942308,4000000000)
nu ~ dcat(pi[])
pi <- c(0,0,3,3,3,3,3,3,3)
}"
writeLines(modelString,con="model.txt")
line_data = list("y"=ret,"N"=length(ret))
init_value = list("mu"=0.003)
model <- jags.model("model.txt", data=line_data, n.chains=2)
I have been struggling to get this code to work and I have no idea while it is giving me the error.
Error: Error in node nuless2
Invalid parent values
I experienced around to see what the problem lies and read most of discussion but I couldnt see any reason.
It would be great if someone can tell me where my stupid mistake is.
Also, I am quite new to JAGS and would like to know how the flow of the system works. For example, while I define y ~ dt(), I also supply data for y. By doing so, am I telling the system this is what the data is and all the parameter in dt() need to be "verified" using this data? It would be great to have a deeper understanding of such system.

Related

Syntax error when trying to parse Bayesian model using RJAGS

I'm running the following code to attempt Bayesian modelling using rjags but coming up with the syntax error below.
Error in jags.model(file = "RhoModeldef.txt", data = ModelData, inits
= ModelInits, : Error parsing model file: syntax error on line 4 near "~"
RhoModel.def <- function() {
for (s in 1:S) {
log(rhohat[s]) ~ dnorm(log(rho[s]),log(rhovar[s]))
rho[s] ~ dgamma(Kappa,Beta)
}
Kappa ~ dt(0,2.5,1) # dt(0, pow(2.5,-2), 1) https://stackoverflow.com/questions/34935606/cauchy-prior-in-jags https://arxiv.org/pdf/0901.4011.pdf
sig.k <- abs(Kappa)
Beta ~ dt(0,2.5,1)
sig.b <- abs(Beta)
}
S <- length(africasad21)-1 # integer
Rhohat <- afzip30$Rho # vector
Rhovar <- afzip30$RhoVar # vector
ModelData <-list(S=S,rhohat=Rhohat,rhovar=Rhovar)
ModelInits <- list(list(rho = rep(1,S),Kappa=0.1,Beta=0.1))
Model.1 <- jags.model(file = 'RhoModeldef.txt',data = ModelData,inits=ModelInits,
n.chains = 4, n.adapt = 100)
Does anyone have any ideas how I might be able to fix this? I'm thinking it might have something to do with my attempts to fit a logged model? Please let me know if more details are needed.
Thanks!
Line 4 of the file 'RhoModeldef.txt' is most likely this one:
log(rhohat[s]) ~ dnorm(log(rho[s]),log(rhovar[s]))
JAGS does not allow log transformations on the left hand side of stochastic relations, only deterministic ones. Given that you are providing rhohat as data, the easiest solution is to do the log transformation in R and drop that part in JAGS i.e.:
log_rhohat[s] ~ dnorm(log(rho[s]), log(rhovar[s]))
ModelData <-list(S=S, log_rhohat=log(Rhohat), rhovar=Rhovar)
Alternatively, you could use dlnorm rather than dnorm in JAGS.
Does that solve your problem? Your example is not self-contained so I can't check myself, but I guess it should work now.

JAGS: variable number of clusters

I am trying to run a Bayesian clustering model where the number of clusters is random with binomial distribution.
This is my Jags model:
model{
for(i in 1:n){
y[ i ,1:M] ~ dmnorm( mu[z[i] , 1:M] , I[1:M, 1:M])
z[i] ~ dcat(omega[1:M])
}
for(j in 1:M){
mu[j,1:M] ~ dmnorm( mu_input[j,1:M] , I[1:M, 1:M] )
}
M ~ dbin(p, Mmax)
omega ~ ddirich(rep(1,Mmax))
}
to run it, we need to define the parameters anche the initial values for the variables, which is done in this R script
Mmax=10
y = matrix(0,100,Mmax)
I = diag(Mmax)
y[1:50,] = mvrnorm(50, rep(0,Mmax), I)
y[51:100,] = mvrnorm(50, rep(5,Mmax), I)
plot(y[,1:2])
z = 1*((1:100)>50) + 1
n = dim(y)[1]
M=2
mu=matrix(rnorm(Mmax^2),nrow=Mmax)
mu_input=matrix(2.5,Mmax,Mmax) ### prior mean
p=0.5
omega=rep(1,Mmax)/Mmax
data = list(y = y, I = I, n = n, mu_input=mu_input, Mmax = Mmax, p = p)
inits = function() {list(mu=mu,
M=M,
omega = omega) }
require(rjags)
modelRegress=jags.model("cluster_variabile.txt",data=data,inits=inits,n.adapt=1000,n.chains=1)
however, running the last command, one gets
Error in jags.model("cluster_variabile.txt", data = data, inits = inits,
: RUNTIME ERROR: Compilation error on line 6.
Unknown variable M Either supply values
for this variable with the data or define it on the left hand side of a relation.
which for me makes no sense, since the error is at line 6 even if M already appears at line 4 of the model! What is the actual problem in running this script?
So JAGS is not like R or other programming procedural languages in that it doesn't actually run line by line, it is a declarative language meaning the order of commands doesn't actually matter at least in terms of how the errors pop up. So just because it didn't throw an error on line 4 doesn't mean something isn't also wrong there. Im not positive, but I believe the error is occuring because JAGS tries to build the array first before inputting values, so M is not actually defined at this stage, but nothing you can do about that on your end.
With that aside, there should be a fairly easy work around for this, it is just less efficient. Instead of looping from 1:M make the loop iterate from 1:MMax that way the dimensions don't actually change, it is always an MMax x MMax. Then line 7 just assigns 1:M of those positions to a value. The downside of this is that it will require you to do some processing after the model is fit. So on each iteration, you will need to pull the sampled M and filter the matrix mu to be M x M, but that shouldn't be too tough. Let me know if you need more help.
So, I think the main problem is that you can't change the dimensionality of the stochastic node you're updating. This seems like a problem for reversible jump MCMC, though I don't think you can do this in JAGS.

R error message in my bootstrapping & regression code

I wanted to use bootstrapping & run a regression, but for some reason, it doesn't work. I always get the error message "Anzahl der zu ersetzenden Elemente ist kein Vielfaches der Ersetzungslänge" (in English: apparently I have two sets of elements & I want to change one to the other but they do not match).
Does anyone see what could have gone wrong here:
bootReg <- function(formula,data,indices)
{
d <- data[indices,]
fit <- lm(formula, data=d)
return(coef(fit))
}
results <- boot(statistic = bootReg,
formula = RT ~ Code + Situation + Block, data = reg_df, R = 2000)
#RT = reaction times (--> numeric)
#Situation = "lab" or "online"
#Block = either 0,1,2 or 3 (--> as characters)
#Code = each subject's individual code
The data in the groups are dependent (= there are RTs from each subject in each situation X block combination)
Thanks in advance!
P.S.: I googled the error message & compared my code with other people's (working) approaches, but don't know what happened here anyway.
This is what worked for me, you have to add the lm() in the formula in boot().
bootReg <- function(formula,
data,
indices)
{
d <- data[indices,]
fit <- lm(formula, data=d)
return(coef(fit))
}
results <- boot(statistic = bootReg, formula = lm(RT ~ Code + Situation + Block, data = df), data = df, R = 2000)
( I recognize that this is a comment at this point, but I'd like to keep it up as an answer for How-To solve the problem. I'll add specific diagnosis if the OP provides more source info)
A general tutorial for debugging:
First, try traceback() to see if an internal call threw the error or boot itself did.
Next, take a look at the class and the size of the object returned from your bootReg function. Is it exactly what boot will accept for the statistic input? Does your formula return what you expect it to return (again, class and length)? Are you certain that data and indices inputs are getting fed in the right order to your formula?

rjags model negative binomial likelihood and gamma prior

I read in my data. I make the model string. I hand it JAGS. I get "Error in node y[1] - Node inconsistent with parents".
Y=read.table("data.txt",header=T)
Y=Y$Y
model_string <- "model{
# Likelihood:
for( i in 1 : N ) {
y[i] ~ dnegbin( l , r )
}
# Prior:
r ~ dgamma(1,1)
l ~ dgamma(.1,.1)
}"
model <- jags.model(textConnection(model_string),
data = list(y=Y,N=200))
First off all, I have no clue if my model is right. I cannot find even basic documentation for JAGS. I'm actually ashamed to admit it, because this should be as simple as an internet search, but I cannot find any document to tell me 1) how a JAGS model is set up or 2) what kinds of functions/distribution/parameters are available in JAGS. I only got this far because I found someone doing a similar model. If anyone knows of a JAGS wiki or documentation, that would be great.
Edit: If someone could even just tell me what the parameters for dnegbin are that would be a huge help. When I plug in random numbers for l and r in dnegbin(l,r) it 'works' as in it draws numbers for l and r, but I have no clue if it means anything.
You can find some info about dnegbin in the JAGS user manual.
The first parameter of dnegbin must be between and 0 and 1. You can assign e.g. a uniform distribution:
library(rjags)
model_string <- "model{
# Likelihood:
for( i in 1 : N ) {
y[i] ~ dnegbin( l , r )
}
# Prior:
r ~ dgamma(1,1)
l ~ dunif(0,1)
}"
y <- rpois(200, 10)
model <- jags.model(textConnection(model_string),
data = list(y=y, N=length(y)))
You also have to be sure that the values of y are non-negative integers.

JAGS - apply function to all parameter nodes

I'm new to JAGS and I'm running a model in R via R2jags package.
The model code is based on a code taken from Kéry & Schaub 2012 ('Bayesian Population Analysis using WinBUGS"), pg 399.
Chi-square discrepancy measure is computed
model {
....
for(g in 1:G) {
for (t in 1:T) {
...
E[g,t] <- pow((y[g,t] - eval[g,t]),2) / eval[g,t]
...
}#t
}#g
fit <- sum(E[,])
}#model
where g and t are site and time indices and G and T are then the number of sites and the number of years
I get an error though
Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains, :
RUNTIME ERROR:
Compilation error on line 140.
Cannot evaluate subset expression for fit
Is it caused by different syntax used by JAGS relative to WinBUGS? The code is the same used in the book, except for I have 2 dimensions instead of three as in the book example.
To answer the last part of your question, no that error isn't caused by different syntax in JAGS (although the error message might look different in BUGS).
In fact I can't see anything wrong with the code snippet that you have posted, and the following reproducible example shows that it works at least when y and eval are given in data:
m <- 'model {
for(g in 1:G) {
for (t in 1:T) {
E[g,t] <- pow((y[g,t] - eval[g,t]),2) / eval[g,t]
}#t
}#g
fit <- sum(E[,])
#data# G, T, y, eval
#monitor# fit
}#model
'
library('runjags')
G=T <- 10
y <- matrix(rnorm(100), nrow=G, ncol=T)
eval <- matrix(rnorm(100), nrow=G, ncol=T)
results <- run.jags(m)
Have you verified what line 140 refers to? Either line 140 is something that you haven't shown, or maybe you have specified either fit or E somewhere else in the model with a different number of dimensions?
If this isn't the case and you still get an error then please add a minimal reproducible example to your question that shows the problem (preferably underneath an ---EDIT--- line below what you have already written) and we can try to help with that.
Matt

Resources