I am trying to fit a GP spatial model over T time points (years) where there is spatial dependence within each year, but across years independence is assumed and the spatial parameters do not vary. Thus, the covariance matrix is block diagonal (D \otimes Identity matrix). The spatial structure and parameters are the same across years, so I am trying to just have to take the inverse of the covariance matrix once for all T years.
I have fit the model for individual years in Stan, but when I try and estimate the parameters over all T, I'm getting long source code/compiler errors. I initially tried to separate the T time points using an array for the model matrix, but ran into trouble so I created an ID variable instead for each T.
Below is my Rstan code, and I can attach the data file if that would be helpful. The data set is not terribly large (180 observations). I am wondering if the way I am separating the years is causing the issue, but I am not sure. Any insight would be much appreciated.
data{
int<lower=1> N; //total obs (L*T)
int<lower=1> L; // total number of locations per year
int<lower=1> T; //number of years, assume independence across years
int<lower=1> p; //number of covariates
int <lower=1> id[N]; // ID By T (year)
vector [N] Y; // response vector
matrix[N,p] X;// Model Matrix
matrix [L,L] d; //distance matrix, same across all years so only need to define once
}
parameters {
vector[p] beta; # coefficient
real<lower=0> sigma; # error sd
real<lower=0> tau; # sd spatial process
real<lower=0> phi; # range/decay parameter
}
transformed parameters {
real<lower=0> sigma2;
real<lower=0> tau2;
sigma2 = sigma^2;
tau2 = tau^2;
}
model {
vector[N] mu;
matrix[L,L] H; // Same Spatial Parameters for Each Year
matrix[L,L] Hinv;
for (i in 1:(L-1)) {
for (j in (i+1):L) {
H[i,j] = tau2 * exp(-d[i,j]/ phi);
H[j,i] = H[i,j]; // do not calculate twice, utilize symmetry
}
}
for (k in 1:L) {
H[k, k] = sigma2 + tau2; //diagonal of covariance matrix
}
Hinv = inverse_spd(H); //inverse of covariance matrix, should just have to do this once
target += -.5*log_determinant(H); // this step only has to be done once across all years
//calculate the mean for each year using index variable
for (n in 1:N){
mu[n] = Y[id[n]] - X[id[n]]*beta;
}
// increment the likelihood for each T (year)
for (t in 1:T){
target += -.5*(mu[id[t]])'*Hinv*(mu[id[t]]); //MVN is block diagonal so likelihood is incremented by year
}
//priors
//inproper prios on betas.
sigma ~ cauchy(0,1);
tau ~ cauchy(0,1);
phi ~ gamma(0.5,0.5);
}