Algorithm Search⌘K

Algorithmadvanced

Henderson's mixed model equations

Also called best linear unbiased prediction of random effects.

A linear system whose solution gives at once the GLS estimates of the fixed effects and the best linear unbiased predictions of the random effects.

Time
Θ(n^3 + n (p + q)^2 + (p + q)^3) worstΘ(n (p + q)^2 + (p + q)^3) best
Space
Θ(n^2 + n (p + q) + (p + q)^2) extra
Counts
flops n^3/3 + 2 (p + q + 1) n^2 + n (p + q)^2 + (p + q)^3/3 + q^3 worst
Where
n = the number of observations; p = the number of fixed-effect columns; q = the number of random effects
Properties
deterministicexactofflineiterative
Origin
Charles R. Henderson, Oscar Kempthorne, Shayle R. Searle, C. M. von Krosigk, 1959

Henderson's mixed model equations are a linear system of order p+qp + q whose solution gives, for known covariance matrices GG and RR, both the generalized least squares estimate b^\hat b of the fixed effects and the best linear unbiased predictor u~\tilde u of the random effects in the linear mixed model y=Xb+Zu+ey = Xb + Zu + e. On this page bb is the vector of fixed-effect coefficients. The direct route to b^\hat b is generalized least squares with V=ZGZ⊤+RV = ZGZ^\top + R, an n×nn \times n matrix, and u~=GZ⊤V−1(y−Xb^)\tilde u = GZ^\top V^{-1}(y - X\hat b). The equations avoid V−1V^{-1}: they need only R−1R^{-1}, which is often diagonal, and G−1G^{-1}, which is often diagonal or sparse. That made national genetic evaluations of millions of animals possible, and the same system is inside every modern mixed model program. The predictions of the random effects are what the alias "best linear unbiased prediction of random effects" names.

In plain words

Suppose you want to rank bulls by the milk yield of their daughters. Each bull has a few daughters in different herds, and herds differ. A plain average per bull is noisy for bulls with few daughters and mixes in herd effects. The equations solve for the herd effects and the bull effects together. They treat the bull effects as random draws around zero, so a bull with few daughters is pulled toward the average, and a bull with many daughters keeps most of his own average. The amount of pull comes from how much bulls truly differ compared with the noise in single records. One system of equations, about as large as the number of herds plus bulls, gives all of these answers at once.

The problem

Input. y∈Rny \in \mathbb R^n; XX (n×pn \times p) of rank pp; ZZ (n×qn \times q); a symmetric positive definite GG (q×qq \times q), the covariance of uu; a symmetric positive definite RR (n×nn \times n), the covariance of ee.

Output. b^\hat b and u~\tilde u that solve

(X⊤R−1XX⊤R−1ZZ⊤R−1XZ⊤R−1Z+G−1)(b^u~)=(X⊤R−1yZ⊤R−1y),\begin{pmatrix} X^\top R^{-1}X & X^\top R^{-1}Z \\ Z^\top R^{-1}X & Z^\top R^{-1}Z + G^{-1} \end{pmatrix}\begin{pmatrix} \hat b \\ \tilde u \end{pmatrix} = \begin{pmatrix} X^\top R^{-1}y \\ Z^\top R^{-1}y \end{pmatrix},

and on request the blocks of the inverse of the coefficient matrix CC: the top left block is Cov⁡(b^)\operatorname{Cov}(\hat b) and the bottom right block is Cov⁡(u~−u)\operatorname{Cov}(\tilde u - u), the prediction error covariance (PEV).

What the solution is. b^=(X⊤V−1X)−1X⊤V−1y\hat b = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y, the GLS estimate, which is the best linear unbiased estimator of bb and its maximum likelihood estimate for known GG and RR. For every linear combination k⊤b+m⊤uk^\top b + m^\top u with kk in the row space of XX, k⊤b^+m⊤u~k^\top\hat b + m^\top\tilde u is the best linear unbiased predictor (BLUP): it has the smallest mean squared error among linear functions ℓ⊤y\ell^\top y with E[ℓ⊤y−k⊤b−m⊤u]=0E[\ell^\top y - k^\top b - m^\top u] = 0 for all bb.

The algorithm

  1. MIXED-MODEL-EQUATIONS(X[1..n, 1..p], Z[1..n, 1..q], G[1..q, 1..q], R[1..n, 1..n], y[1..n])
  2. 1W ← [X Z] ▷ n × (p + q)
  3. 2F ← R⁻¹W; f ← R⁻¹y ▷ divide rows if R is diagonal, else LDLᵀ of R and solves
  4. 3C ← Wᵀ F ▷ (p + q) × (p + q), symmetric
  5. 4C[p+1..p+q, p+1..p+q] ← C[p+1..p+q, p+1..p+q] + G⁻¹
  6. 5r ← Wᵀ f
  7. 6(L, D) ← LDLᵀ factor of C ▷ every pivot is positive
  8. 7s ← solve L D Lᵀ s = r
  9. 8return b̂ = s[1..p], ũ = s[p+1..p+q]
  10. 9on request: C⁻¹ from p + q solves; Cov(b̂) = top left p × p block, PEV = bottom right q × q block

Line L2 is the only step that touches RR. With independent errors, R=σe2IR = \sigma_e^2I or a diagonal matrix of weights, it costs O(n(p+q))O(n(p + q)). Line L4 needs G−1G^{-1}, which is σu−2I\sigma_u^{-2}I for independent random effects, block diagonal for random slopes, and, for relationship matrices in animal breeding, sparse and written down from the pedigree by Henderson's (1976) rules without forming GG. In large problems CC is sparse, and line L6 is a sparse Cholesky factorization with a fill-reducing order, or lines L6 and L7 are replaced by an iterative solver.

Example

Three groups with y=(10,12,14; 15,17; 18,20,22,24)y = (10, 12, 14;\ 15, 17;\ 18, 20, 22, 24), an intercept (p=1p = 1), one random effect for each group (q=3q = 3), σu2=15\sigma_u^2 = 15 and σe2=3\sigma_e^2 = 3, so G=15I3G = 15I_3 and R=3I9R = 3I_9. Lines L1 to L5 give

C=(312/34/3116/15002/3011/1504/3007/5),r=(152/31232/328).C = \begin{pmatrix} 3 & 1 & 2/3 & 4/3 \\ 1 & 16/15 & 0 & 0 \\ 2/3 & 0 & 11/15 & 0 \\ 4/3 & 0 & 0 & 7/5 \end{pmatrix}, \qquad r = \begin{pmatrix} 152/3 \\ 12 \\ 32/3 \\ 28 \end{pmatrix}.

The first row is X⊤R−1X=9/3X^\top R^{-1}X = 9/3 and the group sizes divided by 3. The diagonal of the lower block is ni/3+1/15n_i/3 + 1/15. Solving in exact arithmetic:

quantity exact decimal
b^0\hat b_0 33852/206933852/2069 16.3615
u~1\tilde u_1 −8460/2069-8460/2069 −4.0889-4.0889
u~2\tilde u_2 −680/2069-680/2069 −0.3287-0.3287
u~3\tilde u_3 9140/20699140/2069 4.4176
Var⁡(b^0)\operatorname{Var}(\hat b_0) 11088/206911088/2069 5.3591
PEV of u1,u2,u3u_1, u_2, u_3 11685/2069, 11985/2069, 11535/206911685/2069,\ 11985/2069,\ 11535/2069 5.6477, 5.7927, 5.5752

The group means are 12, 16 and 21, and the plain mean of the 9 values is 16.889. b^0\hat b_0 is the GLS weighted mean of the group means with weights ni/(σe2+niσu2)n_i/(\sigma_e^2 + n_i\sigma_u^2), which are nearly equal here because σu2\sigma_u^2 is large, so it is close to the unweighted mean 16.33 of the group means. Each u~i\tilde u_i is the deviation yˉi⋅−b^0\bar y_{i\cdot} - \hat b_0 times the shrinkage factor niσu2/(niσu2+σe2)n_i\sigma_u^2/(n_i\sigma_u^2 + \sigma_e^2), which is 15/1615/16, 10/1110/11 and 20/2120/21 for the groups of sizes 3, 2 and 4: the smallest group is shrunk most and has the largest PEV. With the balanced data y=(10,12,14; 15,16,17; 18,20,22)y = (10, 12, 14;\ 15, 16, 17;\ 18, 20, 22) and the same GG and RR, the solution is b^0=16\hat b_0 = 16 and u~=(−15/4,0,15/4)\tilde u = (-15/4, 0, 15/4), the deviations −4,0,4-4, 0, 4 times 15/1615/16, with Var⁡(b^0)=16/3\operatorname{Var}(\hat b_0) = 16/3 and PEV 45/845/8 for each group.

Correctness

The proof in this folder shows four facts in exact arithmetic. First, CC is positive definite when XX has full column rank and GG and RR are positive definite, so every pivot of line L6 is positive and the solution is unique. Second, the push-through identity (Z⊤R−1Z+G−1)−1Z⊤R−1=GZ⊤V−1(Z^\top R^{-1}Z + G^{-1})^{-1}Z^\top R^{-1} = GZ^\top V^{-1} and the matching form of V−1V^{-1} turn the second block row into u~=GZ⊤V−1(y−Xb^)\tilde u = GZ^\top V^{-1}(y - X\hat b) and the first into the GLS normal equations X⊤V−1Xb^=X⊤V−1yX^\top V^{-1}X\hat b = X^\top V^{-1}y. Third, a direct comparison of mean squared errors shows that k⊤b^+m⊤u~k^\top\hat b + m^\top\tilde u is the BLUP. Fourth, the Schur complement formula gives the two diagonal blocks of C−1C^{-1} as (X⊤V−1X)−1(X^\top V^{-1}X)^{-1} and G−GZ⊤PZGG - GZ^\top PZG, which are Cov⁡(b^)\operatorname{Cov}(\hat b) and the PEV.

Proof: Henderson's equations give the GLS estimate of b with V = ZGZ^T + R and the best linear unbiased predictor of ufull

The arithmetic is exact. XX is n×pn \times p of rank pp, ZZ is n×qn \times q, GG (q×qq \times q) and RR (n×nn \times n) are symmetric positive definite, V=ZGZ⊤+RV = ZGZ^\top + R, M=Z⊤R−1Z+G−1M = Z^\top R^{-1}Z + G^{-1}, A=X⊤V−1XA = X^\top V^{-1}X and P=V−1−V−1XA−1X⊤V−1P = V^{-1} - V^{-1}XA^{-1}X^\top V^{-1}. The vector bb holds the fixed-effect coefficients. The coefficient matrix and right-hand side built by lines L1 to L5 are

C=(X⊤R−1XX⊤R−1ZZ⊤R−1XM),r=(X⊤R−1yZ⊤R−1y).C = \begin{pmatrix} X^\top R^{-1}X & X^\top R^{-1}Z \\ Z^\top R^{-1}X & M \end{pmatrix}, \qquad r = \begin{pmatrix} X^\top R^{-1}y \\ Z^\top R^{-1}y \end{pmatrix}.

Lemma 1 (C is positive definite). CC is symmetric positive definite, so every pivot of the LDL⊤LDL^\top factor in line L6 is positive, line L7 returns the unique solution, and the algorithm stops after a fixed number of steps.

Proof. With W=[X Z]W = [X\ Z], C=W⊤R−1W+diag⁡(0,G−1)C = W^\top R^{-1}W + \operatorname{diag}(0, G^{-1}). For v=(v1,v2)≠0v = (v_1, v_2) \ne 0, v⊤Cv=w⊤R−1w+v2⊤G−1v2v^\top Cv = w^\top R^{-1}w + v_2^\top G^{-1}v_2 with w=Xv1+Zv2w = Xv_1 + Zv_2. Both terms are at least 0. If v2≠0v_2 \ne 0 the second is positive. If v2=0v_2 = 0 then v1≠0v_1 \ne 0, w=Xv1≠0w = Xv_1 \ne 0 because XX has rank pp, and the first is positive. The pivots of LDL⊤LDL^\top are ratios of consecutive leading principal minors of CC, which are positive for a positive definite matrix. VV is positive definite too, as the sum of the positive semidefinite ZGZ⊤ZGZ^\top and the positive definite RR, and MM is positive definite, as G−1G^{-1} plus a positive semidefinite matrix; so V−1V^{-1}, M−1M^{-1} and A−1A^{-1} below exist. □\square

Lemma 2 (push-through and the inverse of V). M−1Z⊤R−1=GZ⊤V−1M^{-1}Z^\top R^{-1} = GZ^\top V^{-1} and V−1=R−1−R−1ZM−1Z⊤R−1V^{-1} = R^{-1} - R^{-1}ZM^{-1}Z^\top R^{-1}.

Proof. Z⊤R−1V=Z⊤R−1ZGZ⊤+Z⊤=(Z⊤R−1Z+G−1)GZ⊤=MGZ⊤Z^\top R^{-1}V = Z^\top R^{-1}ZGZ^\top + Z^\top = (Z^\top R^{-1}Z + G^{-1})GZ^\top = MGZ^\top. Multiplying on the left by M−1M^{-1} and on the right by V−1V^{-1} gives the first identity. For the second, (R−1−R−1ZM−1Z⊤R−1)V=R−1V−R−1ZM−1(MGZ⊤)=(R−1ZGZ⊤+I)−R−1ZGZ⊤=I(R^{-1} - R^{-1}ZM^{-1}Z^\top R^{-1})V = R^{-1}V - R^{-1}ZM^{-1}(MGZ^\top) = (R^{-1}ZGZ^\top + I) - R^{-1}ZGZ^\top = I. This is the Woodbury identity for this VV. □\square

Theorem 1 (the fixed effects are GLS). The solution (b^,u~)(\hat b, \tilde u) of Cs=rCs = r satisfies Ab^=X⊤V−1yA\hat b = X^\top V^{-1}y, so b^=(X⊤V−1X)−1X⊤V−1y\hat b = (X^\top V^{-1}X)^{-1}X^\top V^{-1}y, and u~=GZ⊤V−1(y−Xb^)\tilde u = GZ^\top V^{-1}(y - X\hat b).

Proof. The second block row is Z⊤R−1Xb^+Mu~=Z⊤R−1yZ^\top R^{-1}X\hat b + M\tilde u = Z^\top R^{-1}y, so u~=M−1Z⊤R−1(y−Xb^)=GZ⊤V−1(y−Xb^)\tilde u = M^{-1}Z^\top R^{-1}(y - X\hat b) = GZ^\top V^{-1}(y - X\hat b) by Lemma 2. Put u~=M−1Z⊤R−1(y−Xb^)\tilde u = M^{-1}Z^\top R^{-1}(y - X\hat b) into the first block row X⊤R−1Xb^+X⊤R−1Zu~=X⊤R−1yX^\top R^{-1}X\hat b + X^\top R^{-1}Z\tilde u = X^\top R^{-1}y and collect terms:

X⊤(R−1−R−1ZM−1Z⊤R−1)Xb^=X⊤(R−1−R−1ZM−1Z⊤R−1)y.X^\top(R^{-1} - R^{-1}ZM^{-1}Z^\top R^{-1})X\hat b = X^\top(R^{-1} - R^{-1}ZM^{-1}Z^\top R^{-1})y.

By Lemma 2 the matrix in parentheses is V−1V^{-1}, which gives Ab^=X⊤V−1yA\hat b = X^\top V^{-1}y. □\square

So b^\hat b is the generalized least squares estimate for Cov⁡(y)=V\operatorname{Cov}(y) = V, which is the best linear unbiased estimator of bb by Aitken's theorem. Note also that V−1(y−Xb^)=PyV^{-1}(y - X\hat b) = Py, so u~=GZ⊤Py\tilde u = GZ^\top Py.

Theorem 2 (BLUP). Let k∈Rpk \in \mathbb R^p lie in the row space of XX and m∈Rqm \in \mathbb R^q. Among all linear predictors ℓ⊤y\ell^\top y with E[ℓ⊤y−k⊤b−m⊤u]=0E[\ell^\top y - k^\top b - m^\top u] = 0 for every bb, the one with the smallest mean squared error E[(ℓ⊤y−k⊤b−m⊤u)2]E[(\ell^\top y - k^\top b - m^\top u)^2] is k⊤b^+m⊤u~k^\top\hat b + m^\top\tilde u, and it is unique.

Proof. Since E[y]=XbE[y] = Xb and E[u]=0E[u] = 0, the unbiasedness condition is (X⊤ℓ−k)⊤b=0(X^\top\ell - k)^\top b = 0 for every bb, that is X⊤ℓ=kX^\top\ell = k; this set is not empty because kk is in the row space of XX. For such ℓ\ell the error has mean 0, and with Cov⁡(y,u)=Cov⁡(Zu+e,u)=ZG\operatorname{Cov}(y, u) = \operatorname{Cov}(Zu + e, u) = ZG,

MSE(ℓ)=Var⁡(ℓ⊤y−m⊤u)=ℓ⊤Vℓ−2ℓ⊤ZGm+m⊤Gm.\mathrm{MSE}(\ell) = \operatorname{Var}(\ell^\top y - m^\top u) = \ell^\top V\ell - 2\ell^\top ZGm + m^\top Gm.

Let ℓ∗=V−1ZGm+V−1XA−1(k−X⊤V−1ZGm)\ell^* = V^{-1}ZGm + V^{-1}XA^{-1}(k - X^\top V^{-1}ZGm). Then X⊤ℓ∗=X⊤V−1ZGm+(k−X⊤V−1ZGm)=kX^\top\ell^* = X^\top V^{-1}ZGm + (k - X^\top V^{-1}ZGm) = k, so ℓ∗\ell^* is unbiased, and Vℓ∗−ZGm=XλV\ell^* - ZGm = X\lambda with λ=A−1(k−X⊤V−1ZGm)\lambda = A^{-1}(k - X^\top V^{-1}ZGm). Any other unbiased ℓ\ell is ℓ∗+δ\ell^* + \delta with X⊤δ=0X^\top\delta = 0, and

MSE(ℓ∗+δ)−MSE(ℓ∗)=2δ⊤(Vℓ∗−ZGm)+δ⊤Vδ=2(X⊤δ)⊤λ+δ⊤Vδ=δ⊤Vδ,\mathrm{MSE}(\ell^* + \delta) - \mathrm{MSE}(\ell^*) = 2\delta^\top(V\ell^* - ZGm) + \delta^\top V\delta = 2(X^\top\delta)^\top\lambda + \delta^\top V\delta = \delta^\top V\delta,

which is positive unless δ=0\delta = 0, because VV is positive definite. So ℓ∗\ell^* is the unique best predictor. Finally,

ℓ∗⊤y=m⊤GZ⊤V−1y+(k−X⊤V−1ZGm)⊤A−1X⊤V−1y=m⊤GZ⊤V−1y+k⊤b^−m⊤GZ⊤V−1Xb^,\ell^{*\top}y = m^\top GZ^\top V^{-1}y + (k - X^\top V^{-1}ZGm)^\top A^{-1}X^\top V^{-1}y = m^\top GZ^\top V^{-1}y + k^\top\hat b - m^\top GZ^\top V^{-1}X\hat b,

using A−1X⊤V−1y=b^A^{-1}X^\top V^{-1}y = \hat b from Theorem 1, and this is k⊤b^+m⊤GZ⊤V−1(y−Xb^)=k⊤b^+m⊤u~k^\top\hat b + m^\top GZ^\top V^{-1}(y - X\hat b) = k^\top\hat b + m^\top\tilde u. □\square

With k=0k = 0 and mm a unit vector, each coordinate u~j\tilde u_j is the BLUP of uju_j; with m=0m = 0, k⊤b^k^\top\hat b is the BLUE of k⊤bk^\top b.

Theorem 3 (the blocks of the inverse). Write C−1C^{-1} in blocks C11C^{11} (p×pp \times p) and C22C^{22} (q×qq \times q). Then C11=A−1=Cov⁡(b^)C^{11} = A^{-1} = \operatorname{Cov}(\hat b) and C22=G−GZ⊤PZG=Cov⁡(u~−u)C^{22} = G - GZ^\top PZG = \operatorname{Cov}(\tilde u - u).

Proof. By the block inverse formula with the Schur complement of the lower block MM,

C11=(X⊤R−1X−X⊤R−1ZM−1Z⊤R−1X)−1=(X⊤V−1X)−1=A−1C^{11} = (X^\top R^{-1}X - X^\top R^{-1}ZM^{-1}Z^\top R^{-1}X)^{-1} = (X^\top V^{-1}X)^{-1} = A^{-1}

by Lemma 2, and C22=M−1+M−1Z⊤R−1XA−1X⊤R−1ZM−1C^{22} = M^{-1} + M^{-1}Z^\top R^{-1}XA^{-1}X^\top R^{-1}ZM^{-1}. By Lemma 2, M−1Z⊤R−1X=GZ⊤V−1XM^{-1}Z^\top R^{-1}X = GZ^\top V^{-1}X, so the second term is GZ⊤V−1XA−1X⊤V−1ZGGZ^\top V^{-1}XA^{-1}X^\top V^{-1}ZG. Also M−1=G−GZ⊤V−1ZGM^{-1} = G - GZ^\top V^{-1}ZG, because G−GZ⊤V−1ZG=G−M−1Z⊤R−1ZG=M−1(M−Z⊤R−1Z)G=M−1G−1G=M−1G - GZ^\top V^{-1}ZG = G - M^{-1}Z^\top R^{-1}ZG = M^{-1}(M - Z^\top R^{-1}Z)G = M^{-1}G^{-1}G = M^{-1}. Adding, C22=G−GZ⊤(V−1−V−1XA−1X⊤V−1)ZG=G−GZ⊤PZGC^{22} = G - GZ^\top(V^{-1} - V^{-1}XA^{-1}X^\top V^{-1})ZG = G - GZ^\top PZG.

For the covariances: b^=A−1X⊤V−1y\hat b = A^{-1}X^\top V^{-1}y has Cov⁡(b^)=A−1X⊤V−1VV−1XA−1=A−1\operatorname{Cov}(\hat b) = A^{-1}X^\top V^{-1}VV^{-1}XA^{-1} = A^{-1}. For the prediction error, u~−u=GZ⊤Py−u\tilde u - u = GZ^\top Py - u. Direct multiplication gives PVP=PPVP = P, and Cov⁡(Py,u)=PZG\operatorname{Cov}(Py, u) = PZG, so

Cov⁡(u~−u)=GZ⊤PVPZG−GZ⊤PZG−GZ⊤PZG+G=G−GZ⊤PZG.□\operatorname{Cov}(\tilde u - u) = GZ^\top PVPZG - GZ^\top PZG - GZ^\top PZG + G = G - GZ^\top PZG. \qquad \square

Lines L8 and L9 return exactly these quantities. The implementation checks Theorems 1 and 3 with rational arithmetic against the direct formulas with V−1V^{-1} on random problems.

Complexity

For dense RR, the LDL⊤LDL^\top factor costs n3/3n^3/3 flops and the p+q+1p + q + 1 solves 2(p+q+1)n22(p + q + 1)n^2; the product of line L3 costs about n(p+q)2n(p + q)^2 and the factor of CC (p+q)3/3(p + q)^3/3. Inverting a dense GG adds O(q3)O(q^3). Extra space is Θ(n2)\Theta(n^2) for the factor of RR, Θ(n(p+q))\Theta(n(p + q)) for FF and Θ((p+q)2)\Theta((p + q)^2) for CC. With diagonal RR and GG, the time is Θ(n(p+q)2+(p+q)3)\Theta(n(p + q)^2 + (p + q)^3) and the n×nn \times n matrices are never formed; the GLS route instead costs Θ(n3)\Theta(n^3) for VV, which is dense within each group. Line L9 adds Θ((p+q)3)\Theta((p + q)^3).

Properties

  • Exact. In exact arithmetic the result equals GLS and BLUP exactly; the implementation checks this with rational numbers on random problems.
  • The ridge view. The equations are the normal equations of the penalized least squares problem min⁡b,u(y−Xb−Zu)⊤R−1(y−Xb−Zu)+u⊤G−1u\min_{b, u}(y - Xb - Zu)^\top R^{-1}(y - Xb - Zu) + u^\top G^{-1}u. This is how Henderson et al. (1959) found them, as the maximum of the joint density of yy and uu over bb and uu. With G=σu2IG = \sigma_u^2I and R=σe2IR = \sigma_e^2I it is ridge regression on the ZZ columns with penalty σe2/σu2\sigma_e^2/\sigma_u^2 and no penalty on XX.
  • Shrinkage. u~\tilde u is pulled toward 0 compared with a fit that treats uu as fixed; the pull grows with σe2/σu2\sigma_e^2/\sigma_u^2 and shrinks with the amount of data on each effect. As σu2→∞\sigma_u^2 \to \infty the equations become the normal equations of the fixed effects fit.
  • Bayes. For known GG and RR and a flat prior on bb, u~\tilde u is the posterior mean of uu and C−1C^{-1} is the posterior covariance of (b,u)(b, u).
  • Boundary. A variance component equal to 0 makes GG singular, and line L4 cannot form G−1G^{-1}; the implementation raises an error. The limit σu2→0\sigma_u^2 \to 0 sets u~=0\tilde u = 0 and b^\hat b to the GLS fit without that effect, so the effect can be dropped. A form of the equations that multiplies the second block by GG instead of using G−1G^{-1} handles a singular GG directly.

Variants and improvements

  • Estimated variance components (EBLUP). In practice G=G(θ^)G = G(\hat\theta) and R=R(θ^)R = R(\hat\theta) with θ^\hat\theta from restricted maximum likelihood. The result is the empirical BLUP. EM and average information REML algorithms reuse CC and the blocks of C−1C^{-1} at every iteration.
  • Animal models. With G=σa2AG = \sigma_a^2\mathcal A, A−1\mathcal A^{-1} has at most a few nonzeros for each animal and is written down from the pedigree (Henderson 1976), so CC stays sparse even with millions of animals; the system is solved by Gauss-Seidel or preconditioned conjugate gradients.
  • Penalized least squares with a Cholesky factor of the relative covariance. lme4 (Bates et al. 2015) writes u=Λθvu = \Lambda_\theta v with v∼N(0,σ2I)v \sim N(0, \sigma^2I) and solves a sparse Cholesky system in Λθ⊤Z⊤ZΛθ+I\Lambda_\theta^\top Z^\top Z\Lambda_\theta + I, which stays well defined when a variance component is 0.
  • Absorption. When qq is large and the lower block is diagonal, as for one random factor, eliminate uu first: the Schur complement X⊤V−1XX^\top V^{-1}X is computed cheaply, then u~\tilde u follows group by group.

When to use it

Use the equations whenever bb and uu are wanted for given covariance parameters and R−1R^{-1} and G−1G^{-1} are cheap: clustered and longitudinal data with independent errors, genetic evaluation, small area estimation and penalized spline fits. If VV is small and dense, or RR is a dense matrix with no structure, GLS with VV directly is as fast. If only bb is wanted and nn is small, GLS is simpler.

Pitfalls

  • Unknown covariance treated as known. The blocks of C−1C^{-1} assume the true GG and RR; with estimated values they understate the uncertainty, most with few groups.
  • Collinear XX. If XX is not of full column rank, CC is singular. Only estimable functions k⊤bk^\top b have a BLUE; drop or constrain columns first.
  • Dense G−1G^{-1}. Inverting a dense GG that has no structure loses the main advantage; then GLS or a factor of VV may be cheaper.
  • Selection. BLUP stays unbiased under selection on yy only when the data used for the selection are in the model (Henderson 1975); otherwise the ranking of animals or schools is biased.
  • Rounding. Large differences in scale between G−1G^{-1} and Z⊤R−1ZZ^\top R^{-1}Z make CC badly conditioned; scale the columns or use the Λθ\Lambda_\theta form.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

henderson_mixed_model_equations.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/henderson-mixed-model-equations/. The authors are listed in prov/3AX196.jsonl.
"""Henderson's mixed model equations for the linear mixed model y = X b + Z u + e.

u ~ N(0, G) and e ~ N(0, R) are independent, with G (q x q) and R (n x n)
known and positive definite. The equations

    [ X^T R^-1 X    X^T R^-1 Z          ] [b]   [ X^T R^-1 y ]
    [ Z^T R^-1 X    Z^T R^-1 Z + G^-1   ] [u] = [ Z^T R^-1 y ]

have order p + q, not n. Their solution b is the generalized least squares
estimate with V = Z G Z^T + R, and u is the best linear unbiased predictor
(BLUP) of the random effects. The inverse of the coefficient matrix gives
Cov(b-hat) in its top-left block and the prediction error covariance
Cov(u-hat - u) in its bottom-right block.

The solver is a symmetric LDL^T factorization without square roots, so the
arithmetic is generic: Fraction input gives exact results.
"""

from typing import NamedTuple


def transpose(a):
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def ldl(a):
    """Unit lower triangular L and diagonal d with A = L diag(d) L^T. Raises ValueError unless A is positive definite."""
    n = len(a)
    l = [[0] * n for _ in range(n)]
    d = [0] * n
    for j in range(n):
        dj = a[j][j] - sum(l[j][k] * l[j][k] * d[k] for k in range(j))
        if not dj > 0:
            raise ValueError("matrix is not positive definite")
        d[j] = dj
        l[j][j] = 1
        for i in range(j + 1, n):
            l[i][j] = (a[i][j] - sum(l[i][k] * l[j][k] * d[k] for k in range(j))) / dj
    return l, d


def ldl_solve(l, d, b):
    """Solve L diag(d) L^T x = b by forward substitution, a diagonal scaling and back substitution."""
    n = len(d)
    z = [0] * n
    for i in range(n):
        z[i] = b[i] - sum(l[i][k] * z[k] for k in range(i))
    w = [z[i] / d[i] for i in range(n)]
    x = [0] * n
    for i in reversed(range(n)):
        x[i] = w[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))
    return x


def inverse_spd(a):
    """The inverse of a symmetric positive definite matrix, by LDL^T."""
    l, d = ldl(a)
    n = len(a)
    cols = [ldl_solve(l, d, [1 if i == j else 0 for i in range(n)]) for j in range(n)]
    return transpose(cols)


def _is_diagonal(a):
    return all(a[i][j] == 0 for i in range(len(a)) for j in range(len(a)) if i != j)


class MMEFit(NamedTuple):
    b: list     # fixed effects, length p (the GLS estimate)
    u: list     # predicted random effects, length q (the BLUP)
    c: list     # the (p + q) x (p + q) coefficient matrix
    rhs: list   # the right-hand side


def mixed_model_equations(x, z, g, r, y):
    """Build and solve Henderson's mixed model equations."""
    n, p, q = len(y), len(x[0]), len(z[0])
    if len(x) != n or len(z) != n or len(r) != n or len(g) != q:
        raise ValueError("dimensions do not match")
    w = [xr + zr for xr, zr in zip(x, z)]  # @line L1
    if _is_diagonal(r):
        for i in range(n):
            if not r[i][i] > 0:
                raise ValueError("R is not positive definite")
        rinv_w = [[row[j] / r[i][i] for j in range(len(row))] for i, row in enumerate(w)]  # @line L2
        rinv_y = [y[i] / r[i][i] for i in range(n)]  # @line L2
    else:
        l, d = ldl(r)
        cols = [ldl_solve(l, d, [w[i][j] for i in range(n)]) for j in range(p + q)]  # @line L2
        rinv_w = transpose(cols)
        rinv_y = ldl_solve(l, d, list(y))  # @line L2
    wt = transpose(w)
    c = matmul(wt, rinv_w)  # @line L3
    if _is_diagonal(g):
        if not all(g[i][i] > 0 for i in range(q)):
            raise ValueError("G is not positive definite")
        ginv = [[1 / g[i][i] if i == j else 0 for j in range(q)] for i in range(q)]
    else:
        ginv = inverse_spd(g)
    for i in range(q):
        for j in range(q):
            c[p + i][p + j] += ginv[i][j]  # @line L4
    rhs = [sum(wt[i][k] * rinv_y[k] for k in range(n)) for i in range(p + q)]  # @line L5
    l, d = ldl(c)  # @line L6
    sol = ldl_solve(l, d, rhs)  # @line L7
    return MMEFit(sol[:p], sol[p:], c, rhs)  # @line L8


def mme_inverse_blocks(fit, p):
    """(Cov(b-hat), Cov(u-hat - u)) from the inverse of the coefficient matrix: its top-left and bottom-right blocks."""
    ci = inverse_spd(fit.c)  # @line L9
    return [row[:p] for row in ci[:p]], [row[p:] for row in ci[p:]]  # @line L9


def one_way_design(groups):
    """X (a column of ones) and Z (group indicators) for a one-way random effects layout given as lists of responses."""
    x, z, y = [], [], []
    for gi, values in enumerate(groups):
        for v in values:
            x.append([1])
            z.append([1 if k == gi else 0 for k in range(len(groups))])
            y.append(v)
    return x, z, y
test_henderson_mixed_model_equations.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/henderson-mixed-model-equations/. The authors are listed in prov/3AX196.jsonl.

import random
from fractions import Fraction as Fr

import pytest

from henderson_mixed_model_equations import (
    matmul, mixed_model_equations, mme_inverse_blocks, one_way_design, transpose,
)


def inverse_gj(a):
    """Gauss-Jordan inverse in exact rational arithmetic (independent of the LDL^T code)."""
    n = len(a)
    m = [[Fr(v) for v in row] + [Fr(int(i == j)) for j in range(n)] for i, row in enumerate(a)]
    for c in range(n):
        piv = next(r for r in range(c, n) if m[r][c] != 0)
        m[c], m[piv] = m[piv], m[c]
        m[c] = [v / m[c][c] for v in m[c]]
        for r in range(n):
            if r != c and m[r][c] != 0:
                f = m[r][c]
                m[r] = [u - f * v for u, v in zip(m[r], m[c])]
    return [row[n:] for row in m]


def add(a, b):
    return [[u + v for u, v in zip(r, s)] for r, s in zip(a, b)]


def random_spd(rng, k):
    """A random symmetric positive definite rational matrix: M M^T + I."""
    m = [[Fr(rng.randint(-2, 2)) for _ in range(k)] for _ in range(k)]
    return add(matmul(m, transpose(m)), [[Fr(int(i == j)) for j in range(k)] for i in range(k)])


def gls_and_blup(x, z, g, r, y):
    """Reference: b = (X^T V^-1 X)^-1 X^T V^-1 y and u = G Z^T V^-1 (y - X b), with V = Z G Z^T + R."""
    v = add(matmul(matmul(z, g), transpose(z)), r)
    vi = inverse_gj(v)
    xt = transpose(x)
    a = matmul(matmul(xt, vi), x)
    ai = inverse_gj(a)
    col = [[v] for v in y]
    b = [row[0] for row in matmul(ai, matmul(matmul(xt, vi), col))]
    resid = [[y[i] - sum(x[i][j] * b[j] for j in range(len(b)))] for i in range(len(y))]
    u = [row[0] for row in matmul(matmul(matmul(g, transpose(z)), vi), resid)]
    return b, u, v, vi, ai


def test_henderson_equals_gls_and_blup_exactly():
    rng = random.Random(20261114)
    for _ in range(12):
        n, p, q = rng.randint(5, 9), rng.randint(1, 3), rng.randint(1, 4)
        x = [[Fr(1)] + [Fr(rng.randint(-3, 3)) for _ in range(p - 1)] for _ in range(n)]
        z = [[Fr(rng.randint(0, 1)) for _ in range(q)] for _ in range(n)]
        g = random_spd(rng, q)
        r = random_spd(rng, n) if rng.random() < 0.5 else [[Fr(rng.randint(1, 4)) if i == j else Fr(0) for j in range(n)] for i in range(n)]
        y = [Fr(rng.randint(-9, 9)) for _ in range(n)]
        try:
            want_b, want_u, v, vi, ai = gls_and_blup(x, z, g, r, y)
        except StopIteration:
            continue  # X^T V^-1 X singular: X has dependent columns
        fit = mixed_model_equations(x, z, g, r, y)
        assert fit.b == want_b
        assert fit.u == want_u
        cb, cu = mme_inverse_blocks(fit, p)
        assert cb == ai
        # C^22 = G - G Z^T P Z G with P = V^-1 - V^-1 X (X^T V^-1 X)^-1 X^T V^-1.
        vix = matmul(vi, x)
        proj = add(vi, [[-t for t in row] for row in matmul(matmul(vix, ai), transpose(vix))])
        gz = matmul(g, transpose(z))
        pev = add(g, [[-t for t in row] for row in matmul(matmul(gz, proj), transpose(gz))])
        assert cu == pev


def test_balanced_one_way_shrinkage():
    groups = [[10, 12, 14], [15, 16, 17], [18, 20, 22]]
    x, z, y = one_way_design([[Fr(v) for v in grp] for grp in groups])
    g = [[Fr(15) if i == j else Fr(0) for j in range(3)] for i in range(3)]
    r = [[Fr(3) if i == j else Fr(0) for j in range(9)] for i in range(9)]
    fit = mixed_model_equations(x, z, g, r, y)
    assert fit.b == [Fr(16)]
    assert fit.u == [Fr(-15, 4), Fr(0), Fr(15, 4)]  # shrinkage 15/16 of the group mean deviations -4, 0, 4


def test_unbalanced_one_way_closed_form():
    groups = [[Fr(v) for v in grp] for grp in ([10, 12, 14], [15, 17], [18, 20, 22, 24])]
    su, se = Fr(15), Fr(3)
    x, z, y = one_way_design(groups)
    g = [[su if i == j else Fr(0) for j in range(3)] for i in range(3)]
    r = [[se if i == j else Fr(0) for j in range(len(y))] for i in range(len(y))]
    fit = mixed_model_equations(x, z, g, r, y)
    w = [len(grp) / (se + len(grp) * su) for grp in groups]
    means = [sum(grp) / len(grp) for grp in groups]
    b = sum(wi * m for wi, m in zip(w, means)) / sum(w)
    assert fit.b == [b]
    assert fit.u == [len(grp) * su / (len(grp) * su + se) * (m - b) for grp, m in zip(groups, means)]


def test_float_input_agrees_with_exact():
    groups = [[10.0, 12.0, 14.0], [15.0, 17.0], [18.0, 20.0, 22.0, 24.0]]
    x, z, y = one_way_design(groups)
    g = [[15.0 if i == j else 0.0 for j in range(3)] for i in range(3)]
    r = [[3.0 if i == j else 0.0 for j in range(len(y))] for i in range(len(y))]
    fit = mixed_model_equations(x, z, g, r, y)
    xf, zf, yf = one_way_design([[Fr(int(v)) for v in grp] for grp in groups])
    exact = mixed_model_equations(xf, zf, [[Fr(int(v)) for v in row] for row in g], [[Fr(int(v)) for v in row] for row in r], yf)
    assert abs(fit.b[0] - float(exact.b[0])) < 1e-12
    assert all(abs(a - float(b)) < 1e-12 for a, b in zip(fit.u, exact.u))


def test_bad_input():
    x, z, y = one_way_design([[1.0, 2.0], [3.0]])
    with pytest.raises(ValueError):
        mixed_model_equations(x, z, [[1.0, 0.0], [0.0, 0.0]], [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)], y)
    with pytest.raises(ValueError):
        mixed_model_equations(x, z, [[1.0, 0.0], [0.0, 1.0]], [[0.0 if i == j else 0.0 for j in range(3)] for i in range(3)], y)
    with pytest.raises(ValueError):
        mixed_model_equations(x, z, [[1.0]], [[1.0 if i == j else 0.0 for j in range(3)] for i in range(3)], y)

History

Henderson stated the equations in a 1950 abstract, for the evaluation of dairy sires. Henderson, Kempthorne, Searle and von Krosigk (1959) derived them by maximizing the joint density of the records and the random effects, without a proof that the result was best. Goldberger (1962) gave the best linear unbiased predictor in a regression with correlated errors. Henderson (1963, 1975) proved that the solutions are the BLUE and the BLUP, and the 1975 paper treated data subject to selection. Henderson (1976) found the direct rules for the inverse of the relationship matrix, which made evaluations with whole pedigrees possible. Harville (1976) put BLUP in the form of a Gauss-Markov theorem, and Robinson (1991) reviewed the many derivations and uses of BLUP.

References

  1. C. R. Henderson, Best linear unbiased estimation and prediction under a selection model, Biometrics 31(2), 1975, pp. 423 to 447, The mixed model equations, the proof that they give the BLUE of estimable functions of b and the BLUP of u, and the inverse of the coefficient matrix as the error covariance
  2. C. R. Henderson, Oscar Kempthorne, S. R. Searle and C. M. von Krosigk, The estimation of environmental and genetic trends from records subject to culling, Biometrics 15(2), 1959, pp. 192 to 218, The derivation of the equations from the joint density of y and u
  3. C. R. Henderson, Estimation of genetic parameters (abstract), Annals of Mathematical Statistics 21(2), 1950, pp. 309 to 310, The first statement of the equations
  4. C. R. Henderson, A simple method for computing the inverse of a numerator relationship matrix used in prediction of breeding values, Biometrics 32(1), 1976, pp. 69 to 83, The rules that write down the inverse of the relationship matrix directly from a pedigree
  5. David Harville, Extension of the Gauss-Markov theorem to include the estimation of random effects, Annals of Statistics 4(2), 1976, pp. 384 to 395, The whole paper (BLUP of linear combinations of fixed and random effects as a Gauss-Markov theorem)
  6. Arthur S. Goldberger, Best linear unbiased prediction in the generalized linear regression model, Journal of the American Statistical Association 57(298), 1962, pp. 369 to 375, The whole paper (the BLUP of a future observation with correlated errors)
  7. G. K. Robinson, That BLUP is a good thing: the estimation of random effects, Statistical Science 6(1), 1991, pp. 15 to 32, Sections 2 to 5 (derivations of the equations and of BLUP, and the links to Bayes, kriging and credibility)
  8. Douglas Bates, Martin Mächler, Ben Bolker and Steve Walker, Fitting linear mixed-effects models using lme4, Journal of Statistical Software 67(1), 2015, pp. 1 to 48, Section 3 (the penalized least squares form of the equations solved by a sparse Cholesky factor)
  9. Shayle R. Searle, George Casella and Charles E. McCulloch, Variance Components, Wiley, 1992, Chapter 7 (prediction of random variables, BLUP and the mixed model equations)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
  • a full proof of flops.worst
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example