I am using an ODE to model a toy logistic growth system. I know, however, that the model is persistently wrong, because it fails to account for certain aspects of the system.

One way to model this model discrepancy is to use an autoregressive error. For an AR1 error, the system has the following governining equations,

y(t) ~ normal(y*(t),sigma)

residual(t) = y(t) - y*(t)

residual(t) ~ normal(rho*residual(t-1),sigma1)

where rho measures how persistent the errors are from one period to the next.

I have coded this up in Stan as shown below. My issue is the following, since residuals are a non-linear function of parameters, then I need to do some sort of Jacobian transformation. It is not clear to me, however, how to do this with an ODE model (perhaps here, it is possible because the ODE has an analytic solution but I want to make this work for more general systems).

Does anyone know how to do this here?

Best,

Ben

```
functions {
real[] bacteria_deriv(real t,real[] y,real[] theta,real[] x_r,int[] x_i) {
real dydt[1];
dydt[1] = theta[1] * y[1] * (1 - theta[2] * y[1]);
return dydt;
}
}
data {
int<lower=1> T;
real t0;
real ts[T];
vector[T] y;
}
transformed data {
real x_r[0];
int x_i[0];
}
parameters {
real<lower=0,upper=2> theta[2];
real<lower=0> sigma;
real<lower=0> sigma1;
real<lower=0,upper=10> y0[1];
real<lower=0> rho;
}
transformed parameters{
vector[T] vResiduals;
real y_hat[T,1];
y_hat = integrate_ode_rk45(bacteria_deriv, y0, t0, ts, theta, x_r, x_i);
for(t in 1:T)
vResiduals[t] = y[t] - y_hat[t,1];
}
model {
sigma ~ cauchy(0,1);
y0 ~ normal(5,2);
for (t in 2:T) {
y[t] ~ normal(y_hat[t,1],sigma);
vResiduals[t] ~ normal(rho*vResiduals[t-1],sigma1);
}
theta[1] ~ normal(0.5,1);
theta[2] ~ normal(50,10);
rho ~ normal(0.8,0.5);
}
```