Binomial model - "Target can only be accessed in the model block or in definitions of functions with the suffix _lp

Hi,

I wrote the following model:

data {
  int<lower=0> N;
  array[N] int<lower=0> success;  
  array[N] int<lower=0> trials;  
}
parameters {
  real p;
}
model {
  success ~ binomial(trials,p);
}
generated quantities{
  vector[N] pred;
  for(i in 1:N){
  pred[i]~binomial_rng(trials,p);
  }
 }

but when I try to compile it I get:

library(cmdstanr)
mod_prior<-cmdstan_model("test.stan")
Target can only be accessed in the model block or in definitions of functions with the suffix _lp.

make: *** [make/program:50: /tmp/RtmpEBxEl8/model-974c54bf3493.hpp] Error 1

Error: An error occured during compilation! See the message above for more information.

I tracked down the problem to the generated quantities section, but I have no idea what I am doing wrong.

I think you need

pred[i] = binomial_rng(trials, p);

The tilde statement is shorthand for

target = target + binomial_lupmf(success | trials, p). 

which is not allowed with a random number generator ending in _rng

See for instance here

1 Like

Thanks. If there was a facepalm emoji I would add it here.

1 Like