Thanks! I’ll try to go through each suggestion more carefully to fully understand each possibility. I implement the forward algorithm as described in the manual.

Here’s one model for the earthquake data example in “HMMs for time series, an intro using R”.

dat <- read.table(“http://www.hmms-for-time-series.de/second/data/earthquakes.txt”)

stan.data <- list(K=dim(dat)[1], N=3, obs=dat$V2)

// Fitting an HMM to the earthquake data

```
data {
int<lower=0> K; // length of the time series
int<lower=0> obs[K]; // data
int<lower=1> N; // number of states
}
parameters {
simplex[N] theta[N]; // tpm
positive_ordered[N] mu; // mean of poisson - ordered
}
model {
vector[N] log_theta_tr[N]; // log, transposed tpm
vector[N] lp; // for forward variables
vector[N] lp_p1; // for forward variables
mu ~ gamma(0.1, 0.01); // assigning exchangeable priors
//(mus are ordered for sampling purposes)
// transposing tpm and taking the log of each entry
for (n_from in 1:N)
for (n in 1:N)
log_theta_tr[n, n_from] = log(theta[n_from, n]);
lp = rep_vector(-log(N), N); //
for (k in 1:K) {
for (n in 1:N)
lp_p1[n] = log_sum_exp(log_theta_tr[n] + lp) + poisson_lpmf(obs[k] | mu[n]);
lp = lp_p1;
}
target += log_sum_exp(lp);
}
```

[edit: escaped model code]

fit <- stan(file=“earthquakeHMM.stan”,data=stan.data,

iter=5000,chains=3)

As we’ll be fitting HMMs using a variety of state-dependent distributions for different problems/data sets, sometimes spline-based densities, incorporating covariates into both the state process and observation process, I focused on the forward algorithm, rather than ask a specific question about one model. I assume (and have discovered) that different formulations will have their own problems, so thought that maybe increasing evaluation speed of forward algorithm could at least help in general. I appreciate all of your suggestions!

I’ve run into loads of issues not uncommon for mixture models, perhaps related to not specifying initial values or good enough priors(?), and I frequently get the warning that I should increase adapt_delta, increase max_treedepth.