Hi Guys, I am using rstan
to fit the model where the residual term is AR1\otimes AR1. Well, the problem is that the computing speed is extremely slow even if I put the term in a simple model.
stanmodelcode <- "
functions {
// cholesky decomposition of an AR matrix
matrix chol_AR_matrix(real rho,int d){
matrix[d,d] MatAR;
MatAR = rep_matrix(0,d,d);
for(i in 1:d){
for(j in i:d){
if(j>=i && i==1) MatAR[j,i] = rho^(j-1);
else if(i>=2 && j>=i) MatAR[j,i] = rho^(j-i)*sqrt(1-rho^2);
}
}
return MatAR;
}
// Kronecker product of cholesky decompistions of two matrices
matrix chol_kronecker_product(matrix matA, matrix matB) {
matrix[rows(matA)*rows(matB),rows(matA)*rows(matB)] matC;
matC = rep_matrix(0,rows(matA)*rows(matB),rows(matA)*rows(matB));
for (k in 1:rows(matA)){
for (l in 1:k){
for (m in 1:rows(matB)){
for (n in 1:m){
matC[rows(matB)*(k-1)+m, cols(matB)*(l-1)+n] = matA[k,l] * matB[m,n];
}
}
}
}
return matC;
}
}
data {
int<lower=0> N;
real y[N];
int n1;
int n2;
}
parameters {
real mu;
real<lower=0,upper=1> rho_c; // rho columns
real<lower=0,upper=1> rho_r; // rho rows
}
transformed parameters {
matrix[n1*n2,n1*n2] ar1byar1;
ar1byar1 = chol_kronecker_product(chol_AR_matrix(rho_c,n1),chol_AR_matrix(rho_r,n2));
}
model {
target += normal_lpdf(mu | 0, 10);
target += normal_lpdf(y | mu, 1);
}
"
y <- rnorm(20)
dat <- list(N = 20, y = y,n1=98,n2=13);
fit <- stan(model_code = stanmodelcode, model_name = "example",
data = dat, iter = 100, chains = 1)
print(fit)
As you can see that I didn’t estimate the two parameters, but only put them in the stan code to test the computing speed.
With unknown \rho s, the computing speed is extremely slow (350 seconds). However, if I give \rho_1=0.5 and \rho_2=0.6, for example, in the data chunk, the speed is much faster and runs as a normal simple model (1.5 seconds).
Alternatively, if I only calculate AR1 matrices without calculating Korenecher product, the computing speed is still okay to estimate unknown \rho s.
I don’t know why it is so slow if I put AR1 and Korenecher product together.
Thank you all in advance for your help and time.
R version 3.6.3 (2020-02-29)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)
Matrix products: default
Random number generation:
RNG: Mersenne-Twister
Normal: Inversion
Sample: Rounding
locale:
[1] LC_COLLATE=English_Australia.1252
[2] LC_CTYPE=English_Australia.1252
[3] LC_MONETARY=English_Australia.1252
[4] LC_NUMERIC=C
[5] LC_TIME=English_Australia.1252
Update:
I have put print("chains")
somewhere in the code to monitor the process and noticed that rstan
is still running but didn’t achieve any valid chains.