// This Stan block defines a Negative Binomial model with groups, by Sean van der Merwe, UFS
data {
  int<lower=1> n;   			        // number of observations
  int<lower=0> y[n];              // observations
  int<lower=1> ng;   			        // number of groups
  int<lower=1, upper=ng> g[n];    // group membership
  int<lower=1> nv;   			        // number of variance groups
  int<lower=1, upper=nv> v[n];    // variance group membership
  real x[n];                      // explanatory variable
}
// The parameters of the model
parameters {
  real alpha[ng];                 // group intercepts
  real beta[ng];                  // group slopes
  real<lower=0> phi[nv];                   // group variances
}
transformed parameters {
  vector[n] etas;
  vector[n] phis;
  for (i in 1:n) {
    etas[i] = alpha[g[i]] + beta[g[i]]*x[i];
    phis[i] = phi[v[i]];
  }
}
model {
  y ~ neg_binomial_2_log(etas, phis);       // likelihood
}
generated quantities {
  vector[n] log_lik;
  for (i in 1:n) {
    log_lik[i] = neg_binomial_2_log_lpmf(y[i] | etas[i], phis[i]);
  }
}

CXXFLAGS = -O2 -Wall $(DEBUGFLAG) -mfpmath=sse -msse2 -mstackrealign $(LTO)