I’d like to ask about the use of curly braces in stan.
My understanding is that for example, when we want to write a for loop with more than one arguments in the loop, we’d want to use {}
. However, I’ve seen multiple times that these braces get used in the middle of a function, or in the model block for no apparent reason. Below is an example.
vector theta_pred_rng(array[] vector x, array[] vector x_pred, matrix LK,
vector theta, real alpha, real l, real epsilon) {
int n = size(x);
int n_pred = size(x_pred);
vector[n_pred] theta_pred;
{
matrix[n,n_pred] K12 = gp_matern32_cov(x,x_pred,alpha,l);
matrix[n,n_pred] LKinv_K12 = mdivide_left_tri_low(LK,K12);
vector[n_pred] LKinv_theta0 = mdivide_left_tri_low(LK,theta);
vector[n_pred] theta_pred_mu = LKinv_K12' * LKinv_theta0;
matrix[n_pred,n_pred] K22 = add_diag(gp_matern32_cov(x_pred,alpha,l), epsilon);
matrix[n_pred,n_pred] theta_pred_cov = K22 - LKinv_K12'*LKinv_K12;
theta_pred = multi_normal_rng(theta_pred_mu, theta_pred_cov);
}
return theta_pred;
}
At first, I thought this is only for clarify/ ease to read of the codes. However, later I realized that the braces have actual impacts on the execution of the codes … E.g., I noticed that if instead of declaring theta_pred before the braces, I put vector[n_pred] theta_pred=multi_normal_rng()
in the braces, then I wouldn’t be able to return this variable. I’d get an error message saying “Identifier ‘theta_pred’ not in scope.”.
So I wonder, are the braces explicitly creating a local environment? What are the pros and cons of using these braces and when should I use them? I couldn’t find any documentation on this. Would appreciate if someone points me to some references of could explain a bit more.
Thanks!