Unrecoverable error evaluating the log probability at the initial value

Dear all,

I’m trying to implement the following Stan code:(from: Simon Jackman’s Bayesian Model Examples in Stan).

 // polling model
data {
  int N;
  int T;
  vector[N] y;
  vector[N] s;
  int time[N];
  int H;
  int house[N];
  // initial and final values
  real xi_init;
  real xi_final;
  real delta_loc;
  real zeta_scale;
  real tau_scale;
}
parameters {
  vector[T - 1] omega;
  real tau;
  vector[H] delta_raw;
  real zeta;
}
transformed parameters {
  vector[H] delta;
  vector[T - 1] xi;
  vector[N] mu;
  // this is necessary. If not centered the model is unidentified
  delta = (delta_raw - mean(delta_raw)) / sd(delta_raw) * zeta;
  xi[1] = xi_init;
  for (i in 2:(T - 1)) {
    xi[i] = xi[i - 1] + tau * omega[i - 1];
  }
  for (i in 1:N) {
    mu[i] = xi[time[i]] + delta[house[i]];
  }
}
model {
  // house effects
  delta_raw ~ normal(0., 1.);
  zeta ~ normal(0., zeta_scale);
  // latent state innovations
  omega ~ normal(0., 1.);
  // scale of innovations
  tau ~ cauchy(0, tau_scale);
  // final known effect
  xi_final ~ normal(xi[T - 1], tau);
  // daily polls
  y ~ normal(mu, s);
}

To prepare the model fit, i defined the following:

campaign_mod <- stan_model("pollingmodel.stan")

campaign_data <- within(list(), {
  y <- datamoon$good
  s <- datamoon$good_se
  time <- datamoon$time
  house <- datamoon$pollster
  H <- max(datamoon$pollster)
  N <- length(y)
  T <- as.integer(difftime("2021-04-01", "2017-05-12", units = "days")) + 1
  xi_init <- 77.8
  xi_final <- 32.0
  delta_loc <- 0
  tau_scale <- sd(y)
  zeta_scale <- 5
})

campaign_fit <- sampling(campaign_mod, data = campaign_data,
                         chains = 1,
                         init = list(list(xi = rep(mean(campaign_data$y), campaign_data$N))))

And I’m getting the error message:

Chain 1: Unrecoverable error evaluating the log probability at the initial value.
Chain 1: Exception: []: accessing element out of range. index 1421 out of range; expecting index to be between 1 and 1420; index position = 1xi  (in 'model1a4d553a90eb_pollingmodel' at line 34)

dose anyone know how I handle this error?

Assuming that the Stan program you posted is literally the same as the one you’ve run (with the same line numbering), the error suggests that time contains a value larger than 1420, but xi is only 1420 elements long.

Jacob, thank you ! Do you know how do I resolve this problem?