Bayesian – Dealing with Multiple Definitions of a Node in WinBUGS

bayesianbugsmarkov chainwinbugs

So this question is about the BUGS modeling language. So you either know it or have no clue. I'm a newbie to this so it's been driving me mad. I want to define a simple two-state hidden Markov model (HMM) where the emission of each state follows a Normal distribution. I have an array data of Nxl dimension where each row is a subject and column is a continuous variable Time associated with the subject. So in WinBUGS, I would define the model as:

 for(i in 1:N) { # for each subject
    # Sample the initial observation
    Time[i, 1] ~ dnorm(mu[State[1]], tau[State[1]])

    for(j in 2:l[i]) { # for each observation
        # Sample the observed variables
        Time[i, j] ~ dnorm(mu[State[j]], tau[State[j]])
        # Sample the hidden states
        State[j] ~ dcat(P[State[j-1], ])
    }
}

# P is the transition matrix of the hidden Markov chain
P[1, 1:2] ~ ddirch(Pinit)
P[2, 1:2] ~ ddirch(Pinit)

# Set the initial states
State[1] ~ dcat(Pinit)

# Sample the initial params
mu[1] ~ dnorm(200, 1.0E-6)
mu[2] ~ dnorm(400, 1.0E-6)

# The precision params
tau[1] ~ dgamma(0.001, 0.001)
tau[2] ~ dgamma(0.001, 0.001)

Initial values have also been provided via R2WinBUGS. The model is syntactically correct. But when I run, I got this error: "multiple definitions of node State[2]"

Can you please tell me why and how to solve this?
I've searched around on the error but each has their own specific case and there's not a generic solution or explanation as to why this arises.

Best Answer

I don't know about HMM, but I can see that in every loop of i you are defining State[j]. This is causing the error in WinBUGS as it can not sample from each node (such as State[2]) more than once in each iteration in the MCMC.

You need to either somehow define State[j] out of the i loop (as you did for State[1]) in its own loop or switch to a [i,j] index for State. (Without knowing HMM, I am not sure which of these is the correct solution).

Related Question