# Sum to zero constraints and multi-level models - best practise/example code

**URL:** <https://discourse.mc-stan.org/t/sum-to-zero-constraints-and-multi-level-models-best-practise-example-code/39349>\
**Category:** Modeling\
**Created:** [April 25, 2025, 12:08pm UTC](https://discourse.mc-stan.org/t/sum-to-zero-constraints-and-multi-level-models-best-practise-example-code/39349 "2025-04-25T12:08:16Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![Alasdair\_Clarke](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/alasdair_clarke/32/9468_2.png) [@Alasdair\_Clarke](https://discourse.mc-stan.org/u/Alasdair_Clarke)\
**Post date:** [April 28, 2025, 8:39am UTC](https://discourse.mc-stan.org/t/sum-to-zero-constraints-and-multi-level-models-best-practise-example-code/39349/6 "2025-04-28T08:39:06Z")

</div>

Thanks.

I think the missing part of the puzzle is how to integrate this with a variance-covariance matrix.

For example, in my model I have K conditions (usually 2, sometimes 3), and 4 features. Therefore I end up with 4\*K parameters (per person).

At present, I define `matrix[4*K,L] z_u;`:

```no-highlight

parameters {

  array[K] real b_a; // weights for class A compared to B  
  array[K] real b_s; // stick-switch rates 
  array[K] real<lower = 0> rho_delta; // distance tuning
  array[K] real rho_psi; // direction tuning

  // random effect variances: 
  // 4*K as we have four fixed effect parameters x K conditions
  vector<lower=0>[4*K] sigma_u;
  cholesky_factor_corr[4*K] L_u;
  // random effect matrix
  matrix[4*K,L] z_u; 
  
}

transformed parameters {

  // this transform random effects so that they have the correlation
  // matrix specified by the correlation matrix above
  matrix[4*K, L] u = diag_pre_multiply(sigma_u, L_u) * z_u;

  // create empty arrays for everything
  array[K] vector[L] u_a, u_stick, u_delta, u_psi;
  // calculate
  for (kk in 1:K) {
    u_a[kk] = to_vector(b_a[kk] + u[4*(kk-1)+1]);
    u_stick[kk] = to_vector(b_s[kk] + u[4*(kk-1)+2]);
    u_delta[kk] = to_vector(rho_delta[kk] + u[4*(kk-1)+3]);
    u_psi[kk] = to_vector(rho_psi[kk] + u[4*(kk-1)+4]);
  }
}

```

I suppose I could try defining ` array[L] sum_to_zero_vector[4*K] z_u;` but I’m not sure how easy it will be to convert `z_u` to a matrix for the multiplication in `transformed parameters {}`.

Perhaps the best way forward is to simply remove L\_u from the model and skip over estimating all those correlations.

I feel like I am missing something?

---

_[View the full topic](https://discourse.mc-stan.org/t/sum-to-zero-constraints-and-multi-level-models-best-practise-example-code/39349)._
