Help with transformed parameters error

Hello,

I am new to working in stan, and I’m hoping somebody can help me figure out how to properly use the transformed parameters block.

I started with a very simple model, and I am slowly adding in more complexity. The very first model worked fine (it was simple enough that there wasn’t much room for error), but I am hitting difficulty now that I am trying to add in a transformed parameter.

I am getting the following error when I run

Chain 1: Rejecting initial value:
Chain 1: Error evaluating the log probability at the initial value.
Chain 1: Exception: validate transformed params: B[1] is nan, but must be greater than or equal to 0.01 (in ‘model80ac35e030a7_BM_Buildup_1’ at line 16)

Line 16 is where I declare matrix B. Below is the code that produced the error - can anybody guide me to fix what I am missing? I am hoping the answer will be obvious enough from the info I have provided - I’d prefer not to share the data if possible.

data {
int<lower=0> C;//number of channels
int<lower=0> TT;//time steps
matrix<lower=0>[C,TT] B_o;//observed biomass
}

parameters {
real tau_o;//observation error
matrix<lower=0>[C,TT] mu; // growth
}

transformed parameters {

matrix<lower=0.01>[C,TT] B;//Biomass

for (c in 1:C){
for (t in 2:TT) {
B[c,t] = B[c,t-1] + (mu[c,t] * B[c,t-1]);
}
}
}

model {

for (c in 1:C) {
for (t in 1:TT) {
B_o[c,t] ~ normal(B[c,t], tau_o);
}
}
}

I suspect that the error is obvious, but my naivety is preventing me from seeing it.

Thank you for your help!

1 Like

Hi, welcome to Discourse!

When you fill in the values of B, you never fill the first column. Thus, the first element (which has not been defined) is nan. So Stan constructs the matrix B, but then checks it against its declared constraint and it fails the check. Moreover (though this isn’t the direct source of your error), since all subsequent columns of B are defined in terms of the first column, they won’t have values either.

Thank you so much for your response! I assigned a starting value for the first column, and it worked (now I’ll have a few other things to figure out pertaining to that starting value).
That was a more straightforward error than I feared it might be, so I am pleasantly surprised.

Thanks again!