Yes, here it is. It is just a linear regression with hierarchical \beta and I wrote the log_lik as you suggested
data {
int<lower=0> n_group;
int<lower=0> n_indiv;
int<lower=0> n_obs;
int<lower=0> n_des;
int<lower=1, upper=n_group> idx_group[n_indiv];
int<lower=1, upper=n_indiv> idx_indiv[n_indiv];
array[n_indiv] vector[n_obs] Y;
matrix[n_obs, n_des] X;
}
parameters {
vector[n_des] mu;
matrix[n_group, n_des] z_group;
matrix[n_indiv, n_des] z_indiv;
real<lower=0> sigma[n_indiv];
real<lower=0> sigma_group;
real<lower=0> sigma_indiv;
}
model {
mu ~ normal(0,10);
to_vector(z_group) ~ std_normal();
to_vector(z_indiv) ~ std_normal();
sigma_group ~ normal(0,10);
sigma_indiv ~ normal(0,10);
sigma ~ normal(0, 10);
for (n in 1:n_indiv) {
Y[n] ~ normal_id_glm(X, 0,
mu + sigma_group * z_group[idx_group[n]]' + sigma_indiv * z_indiv[idx_indiv[n]]',
sigma[idx_indiv[n]]);
}
}
generated quantities{
vector[n_indiv * n_obs] log_lik;
matrix[n_indiv, n_obs] temp;
for(n in 1:n_indiv) {
for(t in 1:n_obs) {
temp[n, t] = normal_lpdf(Y[n, t] | X[t, ] *
(mu + sigma_group * z_group[idx_group[n]]' + sigma_indiv * z_indiv[idx_indiv[n]]'),
sigma[idx_indiv[n]]);
}
}
log_lik = to_vector(temp);
}
This is silly but I wonder if I can write log_lik as below, it’s like calculating only one log_lik for each variate (one row of the data matrix Y) instead of two for loops calculating one log_lik per element of Y
generated quantities{
vector[n_indiv] log_lik;
vector[n_indiv] temp;
for(n in 1:n_indiv) {
temp[n] = normal_id_glm_lpdf(Y[n, ] | X, 0,
(mu + sigma_group * z_group[idx_group[n]]' + sigma_indiv * z_indiv[idx_indiv[n]]'),
sigma[idx_indiv[n]]);
}
}