Skip to content

Instantly share code, notes, and snippets.

@khakieconomics
Created April 1, 2017 20:07
Show Gist options
  • Save khakieconomics/ab9907c774c67a5717eff30e040f359a to your computer and use it in GitHub Desktop.
Save khakieconomics/ab9907c774c67a5717eff30e040f359a to your computer and use it in GitHub Desktop.
data {
int N; // number of observations
matrix[N, 6] Y; // a matrix of observations for each measure. I've encoded missing values as -9
vector[6] inits; // a vector of centers for the initial values of the data
}
parameters {
// the state
matrix[N, 6] X;
// cholesky factor of the correlation matrix of the innovations to the state
cholesky_factor_corr[6] L_omega;
// scale vector of the innovations to the state
vector<lower = 0>[6] tau;
// standard deviation of measurement errors
vector<lower = 0>[6] measurement_sd;
}
model {
// priors
// first state is distribued loosely around the initial values
X[1] ~ normal(inits, 5);
// Reasonably loose prior about correlations between parts of the state
L_omega ~ lkj_corr_cholesky(4);
// Want innovations to the state to be fairly small, but not zero (this causes problems)
tau ~ inv_gamma(3.0, .5);
// fat tailed prior on measurement errors' scale
measurement_sd ~ cauchy(0, 1);
// state model (random walk)
for(n in 2:N) {
// This is the same as X[n] ~ mult_normal(X[n-1], Sigma)
// where Sigma = diag(tau)*L_omega*L_omega'*diag(tau)
X[n] ~ multi_normal_cholesky(X[n-1], diag_pre_multiply(tau, L_omega));
}
// measurement model
for(n in 1:N) {
for(p in 1:6) {
// this is how we deal with missing values
if(Y[n,p] >0) {
Y[n,p] ~ normal(X[n,p], measurement_sd[p]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment