Update
I thought about my first attempt in Stan and now understand why I get a linear decline in k rather than the expected exponential decay. It is because r
is not coded as a dynamic but a fixed parameter, meaning that k[i]
always has the same difference to k[i - 1]
, resulting in a linear trend. Inspired by this answer I rewrote my Stan code so that the random walk is specified in the model block:
stan_code <- "
data {
int n; // Number of observations
vector[n] y; // Response variable
vector[n] x; // Predictor variable
}
parameters {
real<lower=0> sigma; // Standard deviation
real<lower=0> a; // Intercept
real<lower=0> ks; // Initial decay rate
real<lower=0> tau; // Precision of random step
}
model {
// Priors
sigma ~ exponential( 1 );
a ~ lognormal( log(2) , 0.05 );
ks ~ lognormal( log(0.08) , 0.1 );
tau ~ lognormal( log(0.01) , 0.1 );
// Random walk
vector[n] k; // Decay rate
k[1] = ks; // Set starting value of random walk
for ( i in 2:n ) {
k[i] ~ normal(k[i - 1], tau);
}
// Prediction function
vector[n] mu; // Mean prediction for y
for( i in 1:n ) {
mu[i] = a * exp(-k[i] * x[i]); // Calculate mu using updated k
}
// Likelihood
y ~ normal(mu, sigma);
}
"
Unfortunately, the model does not compile this time and throws errors Error evaluating the log probability at the initial value.
, normal_lpdf: Random variable is nan, but must be not nan!
and Initialization failed.
. The suggestion: Try specifying initial values, reducing ranges of constrained values, or reparameterizing the model.
Any help with such reparameterisation would be greatly appreciated!