model='''
data{
int<lower=0> N; //nr of subjects
int<lower=0> S; //nr of sessions
vector[2] y[N,S]; // bivariate gaussian outcome
real x[S]; // predictor
}parameters{
vector<lower=0>[2] sigma; // standard deviation
corr_matrix[2] r;
vector[2] offset;
vector[2] slope;
}transformed parameters{
vector[2] mu[S]; // mean for each session
for (s in 1:S){
// Here comes the crucial idea
// 2d matrix multiplication in two lines follows
// in matrix notation mu[s]= sigma*U*sqrt(lambda)*(offset+slope*x[s])
// where lambda has eigenvectors on diagonal and U is eigenvalue matrix of the correlation matrix r, ie r=U*lambda*U^T
mu[s][1]<-sigma[1]*cos(pi()/4)*sqrt(1+r[1,2])*(offset[1]+slope[1]*x[s])-sigma[1]*sin(pi()/4)*sqrt(1-r[1,2])*(offset[2]+slope[2]*x[s]);
mu[s][2]<-sigma[2]*sin(pi()/4)*sqrt(1+r[1,2])*(offset[1]+slope[1]*x[s])+sigma[2]*cos(pi()/4)*sqrt(1-r[1,2])*(offset[2]+slope[2]*x[s]);
}
}model{
matrix[2,2] tempSigma; // covariance matrix
r~lkj_corr(1);
tempSigma<-quad_form_diag(r,sigma);
for (n in 1:N)
for (s in 1:S)
y[n,s]~multi_normal(mu[s],tempSigma);
}'''