Semantic error

Hello, I am getting the following error message, “Semantic error… Ill-typed arguments supplied to function ‘neg_binomial’: The first argument must be int but got real”. The model is shown below:


// Model including Shuswap Lake elevation -> restricts analysis to 11 years
data {
  int<lower=0> N;         //number of days
  int<lower=0> K;         //number of years
  int year[N];         //years
  vector[N] s_elev;       //shuswap lake elevation
  vector[N] dop;        //julian day
  vector[N] s_mt;  //infilled mean daily stream temperature
  vector[N] s_cumics;       //stream flow
  vector[N] f_rem;        //daily abundance of fish remaining below the fence
  vector[N] f_pass;       //daily abundance of fish that passed the fence
}

parameters {
  vector[5] beta;
  real intercept;
  real u[K]; //random effect of year
  real<lower=0> sigma_u; //standard deviation of random effects
  real<lower=0, upper=1> B1; //negative binomial dispersion parameter
  real<lower=0, upper=1> B2; //negative binomial dispersion parameter
}

transformed parameters{
  vector[N] res;
  res[1] = 0;
  for(n in 2:N){
    res[n] = f_pass[n-1] - (beta[1] * s_elev[n-1] + beta[2] * dop[n-1] + beta[3] * dop[n-1]^2 + beta[4] * s_mt[n-1] + beta[5] * s_cumics[n-1] + u[year[n-1]] + res[n-1] + f_rem[n-1] + intercept);
  }
}


model {
  f_pass[1] ~ neg_binomial(beta[1] * s_elev[1] + beta[2] * dop[1] + beta[3] * dop[1]^2 + beta[4] * s_mt[1] + beta[5] * s_cumics[1] + u[year[1]] + f_rem[1] + intercept, B1);
  for(i in 2:N){
    f_pass[i] ~ neg_binomial(beta[1] * s_elev[i] + beta[2] * dop[i] + beta[3] * dop[i]^2 + beta[4] * s_mt[i] + beta[5] * s_cumics[i] + u[year[i]] + res[i] + f_rem[i] + intercept, B2);
  }
  beta ~ normal(0, 5);
  intercept ~ normal(0,5);
  u ~ normal(0, sigma_u);
  B1 ~ beta(2,2);
  B2 ~ beta(2,2);
  sigma_u ~ cauchy(0,2);
}

generated quantities {
  vector[N] log_lik;
  log_lik[1] = neg_binomial_lpmf(f_pass[1] | beta[1] * s_elev[1] + beta[2] * dop[1] + beta[3] * dop[1]^2 + beta[4] * s_mt[1] + beta[5] * s_cumics[1] + u[year[1]] + f_rem[1] + intercept, B1);
  for(i in 2:N){
    log_lik[i] = neg_binomial_lpmf(f_pass[i] | beta[1] * s_elev[i] + beta[2] * dop[i] + beta[3] * dop[i]^2 + beta[4] * s_mt[i] + beta[5] * s_cumics[i] + u[year[i]] + res[i] + f_rem[i] + intercept, B2);
  } 
}

The error code is specifically referencing model and generated quantities sections. I’m sure its a relatively small error but hours of staring at it hasn’t lead to a solution.

The neg_binomial expects the random variable to be integers.

You defined these as vectors, and hence real datatypes. You should define these an array of integers instead, array[N] int f_pass

Thanks very much! I have never had this issue before but I am assuming it’s because this is my first time using a negative binomial distribution in rstan, and because it’s a count distribution it requires whole numbers (hence integer vs real).