Simple harmonic oscillator ODE stan model from the Stan docs says function is not defined

Hi all,

I’m trying to reproduce the Stan model from here:

I’ve saved the model as model.stan:

functions {
  vector sho(real t,
             vector y,
             real theta) {
    vector[2] dydt;
    dydt[1] = y[2];
    dydt[2] = -y[1] - theta * y[2];
    return dydt;
data {
  int<lower=1> T;
  vector[2] y[T];
  real t0;
  real ts[T];
parameters {
  vector[2] y0;
  vector<lower=0>[2] sigma;
  real theta;
model {
  vector[2] mu[T] = ode_rk45(sho, y0, t0, ts, theta);
  sigma ~ normal(0, 2.5);
  theta ~ std_normal();
  y0 ~ std_normal();
  for (t in 1:T)
    y[t] ~ normal(mu[t], sigma);

In R, the code I’m running to run the model is:


fit <- stan(
  data = list(
    T = 10,
    y0 = c(0,0),
    t0 = 0,
    ts = 1:10,
    theta = .1
  chains = 1,
  iter = 500)

And the error I’m getting is this:

Variable "sho" does not exist.
 error in 'model10f3714c306f_model' at line 23, column 32
    21: }
    22: model {
    23:   vector[2] mu[T] = ode_rk45(sho, y0, t0, ts, theta);
    24:   sigma ~ normal(0, 2.5);

Error in stanc(file = file, model_code = model_code, model_name = model_name,  :
  failed to parse Stan model 'model' due to the above error.

It’s been driving me a little crazy since it seems like I’m defining sho all of 20 lines up from where it’s being passed to ode_rk45, but maybe I’m doing something wrong?

Any advice would be appreciated. Thanks in advance.

This ODE uses a new feature(variadic ODE solver) from 2.24 release, and latest rstan is at 2.21 IIRC.


For this model you’ll need to use cmdstanR, which has the latest Stan version (and this feature) available. Instructions on installing and using cmdstanR are up here: