Linear mixed models
Repeated measurements describe both change over time and differences between people. Someone who starts high may still be high at the last visit, even if measurement errors on the two visits are independent. People may also differ in how quickly they change, so a population trend alone gives an incomplete account of their trajectories. The association between a person’s measurements contains information about these differences. A linear mixed model uses it to estimate how starting levels and rates of change vary around the population trajectory, while allowing for measurement error. Using the simulated GROWTH4 sample throughout, the chapter moves from the marginal distribution of a person’s responses to likelihood and restricted likelihood estimation, efficient computation, three fitting routes and the prediction of each person’s trajectory.
8.1 Random intercepts, random slopes, and the marginal distribution
Let $y_i$ collect the responses of person $i$ at the $n_i$ times that person was observed. At time $t$, the population mean follows the line $\beta_0+\beta_1t$. The intercept $\beta_0$ is the mean response at time zero, in response units; $\beta_1$ is the mean change in response per unit of time. Person $i$ has intercept $\beta_0+b_{0i}$ and slope $\beta_1+b_{1i}$. The random intercept $b_{0i}$ is the person’s deviation from the population starting level, and the random slope $b_{1i}$ is the deviation in change per unit of time. Write $\beta=(\beta_0,\beta_1)^\top$ for the fixed coefficients, which are shared population parameters, and $b_i=(b_{0i},b_{1i})^\top$ for the two random effects. Each deviation has the same units as its corresponding fixed coefficient. At each visit, measurement error adds to the value on the person’s line. Stacking the visits gives the linear mixed model
\[y_i=X_i\beta+Z_i b_i+\epsilon_i,\qquad b_i\sim N_2(0,G),\qquad \epsilon_i\sim N_{n_i}(0,R_i).\]The rows of $X_i$ give the observed covariates for the fixed effects and the rows of $Z_i$ give the coefficients multiplying the random effects. For this growth model, both matrices have row $(1,t)$ at time $t$.
The covariance matrix $G$ describes how intercepts and slopes vary across people. Its intercept variance $G_{11}$ is in squared response units, its slope variance $G_{22}$ in squared response units per squared time unit, and their covariance $G_{21}$ in squared response units per time unit. A positive $G_{21}$ means that higher starting levels tend to accompany larger slopes. These are variances and a covariance of people’s deviations, not of the estimates of $\beta$. The matrix $R_i$ describes measurement error within person $i$. Each person is an independent cluster. Here the residual represents measurement error under the stated model; in other applications it can also include within-person variation left unexplained by the specified mean and random effects.
Suppose the errors have common variance $\sigma^2$, are independent across visits, and are independent of $b_i$. Then $R_i=\sigma^2 I_{n_i}$, and $\sigma^2$ is the variance of a visit response around the person’s own line, in squared response units. Given the observed design and a specified value of $b_i$, the conditional mean is $X_i\beta+Z_i b_i$. Averaging over people with the same observed design removes the centered term $Z_i b_i$ from the mean. Its variance still contributes to the spread of the responses. Since $Z_i b_i$ and $\epsilon_i$ are independent normal vectors, their sum is normal and their covariances add. The marginal distribution is therefore
\[y_i\sim N_{n_i}(X_i\beta,V_i),\qquad V_i=Z_iGZ_i^\top+R_i.\]For two distinct times $s$ and $t$, the corresponding off-diagonal entry is $(1,s)G(1,t)^\top=G_{11}+(s+t)G_{21}+stG_{22}$. At times 0 and 3, the slope contributes nothing to the first measurement, but a person’s initial level can covary with that person’s subsequent rate of change. With $G_{11}=1$ and $G_{21}=0.15$, the covariance is $1+3(0.15)=1.45$. Independent errors add $\sigma^2$ only when calculating a response’s own variance.
In the long form of GROWTH4, one row records one response, its person identifier and its time. The time multiplying $b_{1i}$ is known from the visit record even though the individual’s slope is unobserved. Starting in the book directory, the following code loads the responses and a separate file of generating parameters. The generating parameters specify the simulated population line, variation across people and measurement error. They support the checks below, while estimation uses the recorded responses and designs.
1
2
3
4
5
6
7
8
9
10
for (file in c("result", "differentiation", "line_search", "quasi_newton", "dogleg",
"lmm_fast", "lmm_profile", "transforms", "simulation", "em", "factor", "sem")) {
source(paste0("code/lib/", file, ".R"))
}
growth_input <- readRDS("data/source/ch07/GROWTH4.rds")
growth_truth <- readRDS("data/source/ch07/GROWTH4-truth.rds")
growth_long <- growth_input$long
G_true <- growth_truth$G
sigma2_true <- growth_truth$residual_variance
beta_true <- growth_truth$mean
A precision weight changes the error variance of the observation to which it belongs. If $w_{ij}>0$ is the known relative precision for visit $j$ of person $i$, the residual variance is $\sigma^2/w_{ij}$, where $\sigma^2$ is the error variance at unit weight. These weights specify relative error variances, not replicated observations or sampling probabilities. The residual covariance is $R_i=\sigma^2\operatorname{diag}(1/w_{i1},\ldots,1/w_{in_i})$.
The same row indices must select the response and both design rows for each person. The function lmm_design() groups these matched rows in one block for each independent person.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
lmm_design <- function(y, X, Z, id, weights = rep(1, length(y)), keys = NULL) {
X <- as.matrix(X)
Z <- as.matrix(Z)
N <- length(y)
stopifnot(N > ncol(X), nrow(X) == N, nrow(Z) == N, length(id) == N,
length(weights) == N, all(is.finite(c(y, X, Z, weights))), all(weights > 0),
!anyNA(id), qr(X)$rank == ncol(X))
# Group by person and preserve the input order of visits within each person.
groups <- droplevels(as.factor(id))
ids <- levels(groups)
blocks <- lapply(ids, function(label) {
rows <- which(groups == label)
list(y = y[rows], X = X[rows, , drop = FALSE], Z = Z[rows, , drop = FALSE],
weights = weights[rows], rows = rows, id = label,
keys = if (is.null(keys)) NULL else keys[rows, , drop = FALSE])
})
list(blocks = blocks, N = N, p = ncol(X), q = ncol(Z), groups = length(ids),
y = y, X = X, Z = Z, id = groups, weights = weights)
}
In lmm_design(), rows selects observations in their input order, so each person’s time and response remain paired. The optional keys store the person and time alongside those rows. The returned blocks list contains one such group per person. The list follows the levels of the grouping factor, while rows within each person retain their input order; predictions must be matched to people by these identifiers.
The returned design object contains observations and design information, with blocks[[i]]$y, blocks[[i]]$X and blocks[[i]]$Z representing $y_i$, $X_i$ and $Z_i$. The population coefficients $\beta$, random-effect covariance $G$ and residual variance $\sigma^2$ are supplied separately. A block’s marginal mean is block$X %*% beta.
The function below forms each person’s marginal covariance from the random-effect and residual covariances. The default weight of one assigns the same residual variance to each visit.
1
2
3
4
5
6
7
8
9
10
11
lmm_covariance <- function(block, G, sigma2) {
stopifnot(is.matrix(G), nrow(G) == ncol(block$Z), ncol(G) == nrow(G),
isSymmetric(G), sigma2 > 0, is.finite(sigma2))
if (length(G)) stopifnot(min(eigen(G, symmetric = TRUE,
only.values = TRUE)$values) >= -1e-12)
block$Z %*% G %*% t(block$Z) + diag(sigma2 / block$weights, length(block$y))
}
X_growth <- cbind(intercept = 1, time = growth_long$time)
growth_data <- lmm_design(growth_long$response, X_growth, X_growth, growth_long$person,
keys = growth_long[c("person", "time")])
V_true <- lmm_covariance(growth_data$blocks[[1]], G_true, sigma2_true)
For the covariance, lmm_covariance(block, G, sigma2) forms $Z_iGZ_i^\top$ and adds the residual variances to the diagonal. Passing X_growth twice gives the common intercept and time columns their two roles. In the row for time 3, the second column multiplies both the population slope in $X_i\beta$ and the person’s deviation in $Z_i b_i$.
Does this construction describe the same four responses as the latent growth model? In growth_spec(), the loadings on the two latent variables are the intercept and time columns. The arguments to ram_implied() specify four residual variances of 0.49, the three distinct entries of $G$, and the population intercept and slope of 2 and 0.4. Every person has the same four design rows in this dataset, so the model mean and covariance can be compared using the first block. Checking that the data themselves agree in wide and long form requires all the response values.
1
2
3
4
5
6
ram_growth <- ram_implied(c(rep(.49, 4), 1, .15, .25, 2, .4), growth_spec())
print(c(people = growth_data$groups, responses = growth_data$N,
mean_gap = max(abs(growth_data$blocks[[1]]$X %*% beta_true - ram_growth$mean)),
covariance_gap = max(abs(V_true - ram_growth$covariance)),
wide_long_gap = max(abs(matrix(growth_long$response, 200, byrow = TRUE) -
growth_input$wide))))
1
2
people responses mean_gap covariance_gap wide_long_gap
2.000000e+02 8.000000e+02 0.000000e+00 8.881784e-16 0.000000e+00
The four marginal means agreed exactly, and the largest absolute difference between entries of the two model covariances was $8.88\times10^{-16}$. The last comparison filled each row of a matrix with four successive long responses. All 800 responses matched the entries of the wide matrix for the 200 people in their original order.
Unequal visit times and precision weights
When observation times differ, a person contributes only the design rows for the visits observed. To see what changes, the following selection retains three people. Their original row numbers identify the visits. The constructed vector companion_weights assigns relative measurement precisions for this example, treated as known in its calculations.
1
2
3
4
5
6
7
keep <- c(1:3, 5:8, 9, 12)
companion_rows <- growth_long[keep, ]
companion_weights <- c(1, 2, .5, .5, 1, 2, 1, 1, 3)
unequal <- lmm_design(companion_rows$response, X_growth[keep, ], X_growth[keep, ],
companion_rows$person, companion_weights, companion_rows[c("person", "time")])
print(data.frame(person = vapply(unequal$blocks, `[[`, "", "id"),
measurements = vapply(unequal$blocks, function(b) length(b$y), 1L)))
1
2
3
4
person measurements
1 1 3
2 2 4
3 3 2
Person 1 contributes times 0, 1 and 2, and person 2 contributes times 0, 1, 2 and 3. For person 3, rows 9 and 12 correspond to times 0 and 3. The second row of this person’s design is therefore $(1,3)$, although it is only the second retained visit. The response vector has length two and its marginal covariance has two rows and two columns. The model can assign a joint distribution to these observed responses without filling in the intervening visits.
Subtracting $Z_iGZ_i^\top$ from the first person’s marginal covariance isolates that person’s residual covariance.
1
2
print(diag(lmm_covariance(unequal$blocks[[1]], G_true, sigma2_true) -
unequal$blocks[[1]]$Z %*% G_true %*% t(unequal$blocks[[1]]$Z)))
1
[1] 0.490 0.245 0.980
With $\sigma^2=0.49$, the weights 1, 2 and 0.5 give residual variances 0.490, 0.245 and 0.980. The second measurement has twice the precision of the first, so its error variance is half as large. Its marginal variance also includes the variation of personal trajectories at time 1. Changing the precision of that measurement leaves its covariance with the other visits determined by the shared intercept and slope.
8.2 Maximum likelihood and restricted maximum likelihood
For the three people with unequal visit times, what likelihood do the nine measurements give for the population line and the variation around it? Stack the person-specific response vectors in order to form $y$, and stack their fixed-effect design matrices in the same order to form $X$. There are $N=\sum_i n_i$ observed responses and $p$ columns in $X$. Independence across people makes their joint density a product. Equivalently, $y$ is normal with mean $X\beta$ and block-diagonal covariance $V$, whose blocks are the individual marginal covariances $V_i$. With the designs and precision weights fixed, let $\theta$ denote the covariance parameters in $G$ and $\sigma^2$. Suppose $V$ is positive definite and $X$ has full column rank with $p<N$. The normal log likelihood is
\[\ell(\beta,\theta)=-\tfrac12\left\{N\log(2\pi)+\log|V| +(y-X\beta)^\top V^{-1}(y-X\beta)\right\}.\]The block structure makes $\vert V\vert $ the product of the person-specific covariance determinants. The quadratic is a sum over people. Within each person, the inverse covariance weights the residuals and accounts for the association between visits.
At a given $\theta$, only the quadratic varies with the population coefficients. Its derivative with respect to $\beta$ is $-2X^\top V^{-1}(y-X\beta)$. Equating this vector to zero gives the generalized least squares (GLS) estimate. Write $C=X^\top V^{-1}X$. For any nonzero coefficient vector $a$, $Xa$ is nonzero by full column rank, so $a^\top Ca=(Xa)^\top V^{-1}(Xa)>0$. Thus $C$ is invertible and the solution is $\hat\beta=C^{-1}X^\top V^{-1}y$. Let $r=y-X\hat\beta$ be the residual vector. The normal equations give $X^\top V^{-1}r=0$. Substituting $y-X\beta=r-X(\beta-\hat\beta)$ into the quadratic therefore removes its cross term and gives
\[(y-X\beta)^\top V^{-1}(y-X\beta) =r^\top V^{-1}r+(\beta-\hat\beta)^\top C(\beta-\hat\beta).\]The first term is the minimized residual quadratic at this covariance. Evaluating the likelihood at these maximizing coefficients gives the profile likelihood for maximum likelihood (ML) estimation of the covariance parameters. The second term quantifies how the likelihood decreases as the coefficients move away from their maximizing values. Its curvature matters when integrating the likelihood over the coefficients.
Another way to obtain information about $\theta$ is to take combinations of the measurements whose means are zero for every population intercept and slope. For example, the difference between the time-zero responses of people 1 and 2 cancels the population intercept. Both time coefficients are zero, yet the difference still varies across samples because the two people have independent random intercepts and measurement errors. More generally, any coefficient vector orthogonal to the columns of $X$ gives such an error contrast. A complete QR decomposition of $X$ gives an orthonormal basis for the observation space. Take the final $N-p$ columns as the matrix $Q$, so $Q^\top X=0$ and $Q^\top Q=I_{N-p}$. The vector $z=Q^\top y$ then has mean zero and covariance $S=Q^\top VQ$. For the nine measurements and two fixed coefficients, $Q$ has nine rows and seven columns. The seven contrasts can be correlated with one another. Their joint normal density assigns a likelihood to $\theta$ through $S$ without requiring either population coefficient.
How much of the original residual discrepancy do the contrasts capture? Define the symmetric matrix
\[P=V^{-1}-V^{-1}XC^{-1}X^\top V^{-1}.\]Multiplying by $X$ gives $PX=V^{-1}X-V^{-1}XC^{-1}C=0$. Multiplying by $y$ gives $Py=V^{-1}r$, so $y^\top Py=r^\top V^{-1}r$ by the GLS normal equations. Those equations also imply that $V^{-1}r$ is orthogonal to every column of $X$. It must have the form $Qu$ for some vector $u$ of length $N-p$. Then $r=VQu$, and multiplying by $Q^\top$ gives $Su=Q^\top r=Q^\top y=z$. For nonzero $u$, $Qu$ is nonzero and $u^\top Su=(Qu)^\top V(Qu)>0$. Thus $S$ is invertible and $u=S^{-1}z$. Consequently $r^\top V^{-1}r=r^\top Qu=z^\top S^{-1}z$, exactly the quadratic in the contrast density. Each column of the rectangular matrix $Q$ supplies the coefficients for one error contrast. The matrix $P$ is the precision matrix adjusted for the estimated fixed coefficients; it annihilates $X$ but is generally not an ordinary orthogonal projection, for which $P^2=P$ would be required.
The contrast density and the integrated likelihood use this same quadratic. To see how their normalizing terms differ, integrate $\exp\lbrace \ell(\beta,\theta)\rbrace $ over $\mathbb R^p$ with respect to $d\beta$. The part of the likelihood that varies with $\beta$ is $\exp\lbrace -\tfrac12(\beta-\hat\beta)^\top C(\beta-\hat\beta)\rbrace $. Its integral is $(2\pi)^{p/2}\vert C\vert ^{-1/2}$, as follows by integrating the normal density with mean $\hat\beta$ and covariance $C^{-1}$. The resulting negative restricted log likelihood, in the convention used here, is
\[-\ell_R(\theta)=\tfrac12\{(N-p)\log(2\pi)+\log|V|+\log|C|+y^\top Py\}.\]The negative log likelihood of $z$ has $\log\vert S\vert $ in place of $\log\vert V\vert +\log\vert C\vert $. To relate the determinants, write the observed vector uniquely as $y=Xa+Qz$. The change of variables from $(a,z)$ to $y$ has absolute determinant $\vert X^\top X\vert ^{1/2}$ because the Gram matrix of $[X\ Q]$ is block diagonal with blocks $X^\top X$ and $I_{N-p}$. To find the density $f_z$ of the contrasts, integrate over $a$ with $z$ fixed. The response density depends on $a$ and $\beta$ through $a-\beta$, so integrating out $a$ gives the same Gaussian integral as integrating out $\beta$. The Jacobian multiplies that integral, giving
\[f_z(z;\theta)=|X^\top X|^{1/2}\exp\{\ell_R(\theta)\}.\]Equating the normalizing factors gives $\vert S\vert =\vert V\vert \vert C\vert /\vert X^\top X\vert $. Thus the integrated negative log likelihood equals the contrast negative log likelihood plus $\tfrac12\log\vert X^\top X\vert $. This term is constant when varying $\theta$ with $X$ fixed, so the two criteria give the same restricted maximum likelihood (REML) estimates. Changing the fixed-effect space changes which response contrasts enter the density. To compare models with different population mean structures on the same responses, their full ML likelihoods provide a common basis. This integration is with respect to the coefficient measure $d\beta$; it does not introduce a proper probability distribution for the fixed coefficients.
For a numerical comparison, unequal contains the three people’s responses, their observed times and the nine precision weights. Both calls below use the generating covariance parameters in G_true and sigma2_true. The function lmm_dense() assembles the full covariance and evaluates ML or REML. These calls estimate the fixed coefficients at the supplied covariance; they do not optimize the covariance parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
lmm_dense <- function(data, G, sigma2, beta = NULL, REML = FALSE) {
V <- as.matrix(Matrix::bdiag(lapply(data$blocks, lmm_covariance,
G = G, sigma2 = sigma2)))
X <- do.call(rbind, lapply(data$blocks, `[[`, "X"))
y <- unlist(lapply(data$blocks, `[[`, "y"), use.names = FALSE)
# Solve the GLS normal equations at the supplied covariance.
R <- chol(V)
K <- chol2inv(R)
C <- crossprod(X, K %*% X)
H <- chol2inv(chol(C))
beta_gls <- drop(H %*% crossprod(X, K %*% y))
if (is.null(beta)) beta <- beta_gls
if (REML) beta <- beta_gls
residual <- y - X %*% beta
quadratic <- sum(residual * (K %*% residual))
# P removes the fixed-effect design from the quadratic in y.
P <- K - K %*% X %*% H %*% t(X) %*% K
value <- .5 * ((data$N - if (REML) data$p else 0) * log(2 * pi) +
2 * sum(log(diag(R))) + quadratic + if (REML) 2 * sum(log(diag(chol(C)))) else 0)
list(value = value, beta = beta, beta_gls = beta_gls, V = V, K = K, P = P, C = C,
quadratic = quadratic, REML = REML,
constant = "REML includes half log determinant of X'X")
}
dense_ml <- lmm_dense(unequal, G_true, sigma2_true)
dense_reml <- lmm_dense(unequal, G_true, sigma2_true, REML = TRUE)
Inside lmm_dense(), R is the upper Cholesky factor of $V$, K is the square inverse covariance $V^{-1}$, and H is the inverse of $C$. With beta omitted, the function evaluates the residual quadratic at the GLS estimate. The vector beta_true used to check the marginal means plays no part in this estimate. In value, setting REML = TRUE changes the multiplier of $\log(2\pi)$ from $N$ to $N-p$ and adds $\log\vert C\vert $ inside the parentheses. The code obtains this log determinant by summing the logarithms of the diagonal entries of chol(C) and doubling the result. In the REML branch, even an explicitly supplied beta is replaced by the GLS vector. That vector is used in the calculation; the restricted criterion itself estimates covariance parameters and contains no free fixed-effect coefficient.
The complete QR decomposition below uses the same ordered design rows as the likelihood. Its final seven columns give the observed contrasts and their covariance. The signed difference called constant_gap subtracts both the contrast criterion and the design constant from the integrated criterion. The last check measures the largest absolute entry of $PX$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
X_small <- do.call(rbind, lapply(unequal$blocks, `[[`, "X"))
y_small <- unlist(lapply(unequal$blocks, `[[`, "y"), use.names = FALSE)
Q <- qr.Q(qr(X_small), complete = TRUE)[, (unequal$p + 1):unequal$N]
contrast <- drop(crossprod(Q, y_small))
contrast_covariance <- crossprod(Q, dense_ml$V %*% Q)
contrast_nll <- .5 * (length(contrast) * log(2 * pi) +
2 * sum(log(diag(chol(contrast_covariance)))) +
sum(contrast * solve(contrast_covariance, contrast)))
design_constant <- sum(log(diag(chol(crossprod(X_small)))))
print(c(profiled_negative_loglik = dense_ml$value,
negative_restricted_loglik = dense_reml$value,
error_contrast_negative_loglik = contrast_nll,
design_constant = design_constant,
constant_gap = dense_reml$value - contrast_nll - design_constant,
PX_gap = max(abs(dense_ml$P %*% X_small))))
1
2
3
4
profiled_negative_loglik negative_restricted_loglik error_contrast_negative_loglik
1.160014e+01 1.113022e+01 8.789150e+00
design_constant constant_gap PX_gap
2.341066e+00 1.776357e-15 2.636780e-16
At the specified covariance, the profiled negative log likelihood was 11.60014. Only the fixed effects were estimated in that calculation. For the same covariance, the negative log likelihood of the seven contrasts was 8.789150. The observed times sum to 12 and their squares sum to 28, giving $\vert X^\top X\vert =9(28)-12^2=108$. Adding half its log, 2.341066, to the contrast value gave the negative restricted log likelihood of 11.13022 to the printed precision. With the unrounded values, the signed difference was $1.78\times10^{-15}$, and the largest absolute entry of $PX$ was $2.64\times10^{-16}$. Multiplication by $P$ removed both fixed-effect columns to numerical precision.
8.3 Profiling fixed effects and the residual variance
How would the estimated population line change if the variance of every measurement and the covariance of every pair of measurements doubled? Let $s=\sigma^2>0$ be the residual variance at unit observation weight, and express the random-effect covariance in units of that variance as $D=G/s$. The relative marginal covariance $H=V/s$ is block diagonal. For person $i$, its block is
\[H_i=Z_iDZ_i^\top+\operatorname{diag}(1/w_{i1},\ldots,1/w_{in_i}), \qquad V_i=sH_i.\]The known weights $w_{ij}$ specify how measurement precision differs among visits. The entries of $D$ describe how much the intercepts and slopes vary across people and how they covary, relative to the unit-weight residual variance. The ratio $D_{11}$ is dimensionless, but $D_{21}$ retains inverse time units and $D_{22}$ inverse squared time units because the slope is measured per unit of time. Given $D$, the design and the visit weights, every entry of $H$ is known. For instance, a visit with precision weight 2 contributes one half to the residual part of the corresponding diagonal of $H_i$. On the response scale, its residual variance is $s/2$. The covariance between two visits is $s$ times the corresponding off-diagonal entry of $H_i$.
At fixed $D$, let $C_D=X^\top H^{-1}X$. The positive weights and positive semidefinite $D$ make $H$ positive definite, and the full column rank of $X$ makes $C_D$ invertible. Substituting $V^{-1}=H^{-1}/s$ into the generalized least squares (GLS) normal equations puts a factor $1/s$ on both sides. After cancellation, the estimate, the fitted residual vector $e$, and its weighted sum of squares $q_D$ are
\[\hat\beta_D=C_D^{-1}X^\top H^{-1}y,\qquad e=y-X\hat\beta_D,\qquad q_D=e^\top H^{-1}e.\]Thus doubling the whole covariance leaves the GLS estimates of the intercept and slope unchanged. The residual quadratic computed with $V^{-1}$ becomes $q_D/s$. Computing $q_D$ at residual variance $s=1$ gives the discrepancy needed to evaluate any other positive residual variance at this same $D$.
The residual variance enters the likelihood through the normalizing terms as well as the quadratic. Since $V=sH$ has $N$ rows, $\log\vert V\vert =N\log s+\log\vert H\vert $. The integrated restricted criterion also contains the log determinant of $X^\top V^{-1}X=C_D/s$. Because $C_D$ is $p$ by $p$, this log determinant is $\log\vert C_D\vert -p\log s$. Thus the terms that depend on $s$ sum to $(d\log s+q_D/s)/2$, where $d=N$ for ML and $d=N-p$ for REML. Differentiating with respect to the variance $s$ gives
\[\frac{\mathrm{d}}{\mathrm{d}s}\,\frac{d\log s+q_D/s}{2} =\frac{d}{2s}-\frac{q_D}{2s^2} =\frac{d\,s-q_D}{2s^2}.\]If $q_D>0$, the derivative is negative below $q_D/d$ and positive above it. This proves that $\hat s_D=q_D/d$ minimizes the negative log likelihood over positive residual variances. For the same relative covariance, both calculations use the same fitted residuals. The restricted criterion divides their weighted sum of squares by the dimension of the error-contrast space, $N-p$. If $q_D=0$, there is no finite minimizing positive variance: the negative log likelihood decreases without bound as $s$ tends to zero.
At the minimizing residual variance, the quadratic $q_D/\hat s_D$ equals $d$. Substituting the variance estimate into the ML and integrated REML criteria gives the following two profiled negative log likelihoods, each a function of $D$ alone.
\[\begin{aligned} -\ell_{\rm ML,prof}(D) &=\tfrac12\{\log|H|+N[\log(2\pi)+1+\log(q_D/N)]\},\\ -\ell_{\rm R,prof}(D) &=\tfrac12\{\log|H|+\log|C_D| +(N-p)[\log(2\pi)+1+\log(q_D/(N-p))]\}. \end{aligned}\]The function lmm_profile_nll() evaluates these profiled criteria at a proposed relative covariance $D$. It computes the GLS coefficients and either estimates the residual variance or evaluates a supplied positive variance.
1
2
3
4
5
6
7
8
9
10
11
lmm_profile_nll <- function(data, D, REML = FALSE, scale = NULL) {
shape <- lmm_dense(data, D, 1, REML = REML)
df <- data$N - if (REML) data$p else 0
sigma2 <- if (is.null(scale)) shape$quadratic / df else scale
stopifnot(sigma2 > 0, is.finite(sigma2))
value <- shape$value - shape$quadratic / 2 + .5 *
(df * log(sigma2) + shape$quadratic / sigma2)
list(value = value, beta = shape$beta, sigma2 = sigma2, G = sigma2 * D,
relative_covariance = D, quadratic = shape$quadratic, df = df, REML = REML,
scale_fixed = !is.null(scale))
}
The function lmm_profile_nll() obtains the GLS coefficients and the residual quadratic from lmm_dense(data, D, 1, REML = REML). At residual variance one, the covariance of the responses is $H$, so shape$beta is $\hat\beta_D$ and shape$quadratic is $q_D$. The return value shape$value already includes the appropriate normalizing constant and determinant terms. In particular, the REML call with residual variance one includes the log determinant of $C_D$. It varies with $D$ and must enter every REML comparison of proposed relative covariances. The calculation of value replaces the residual quadratic computed at variance one with the quadratic and log determinant terms at the new residual variance.
The local name shape denotes this likelihood calculation at residual variance one. The argument scale, when supplied, is the fixed residual variance $s$, not its square root. With scale omitted, sigma2 is the minimizing variance. The function also returns $G=\hat s_D D$ so that the joint likelihood can be evaluated on the original covariance scale.
In the complete GROWTH4 data, GLS gives the same population line for every choice of $D$. All 200 people share the four-row intercept and time matrix $T=X_i=Z_i$ and have unit weights. Their common covariance block is $V_0=TGT^\top+sI_4$. Multiplying by $T$ gives $V_0T=TB$, where $B=G T^\top T+sI_2$. Since $T$ has full column rank and $V_0$ is invertible, $B$ is invertible too. It follows that $V_0^{-1}T=TB^{-1}$. By symmetry, $T^\top V_0^{-1}=B^{-\top}T^\top$. In the GLS normal equations for all people, the same invertible factor $B^{-\top}$ multiplies each person’s contribution. Cancelling this factor gives $\sum_i T^\top(y_i-T\hat\beta)=0$, exactly the ordinary least squares equations.
To see how the relative covariance can change the coefficients, consider the three people in unequal. Person 1 has times 0, 1 and 2 with weights 1, 2 and 0.5. Person 2 has times 0, 1, 2 and 3 with weights 0.5, 1, 2 and 1. Person 3 has times 0 and 3 with weights 1 and 3. Their covariance blocks no longer yield a common multiplier in the normal equations.
The first ML calculation uses $D=G_{\rm true}/0.49$. The second multiplies $D$ by five without changing the visit weights. This multiplies the random-effect contribution to each $H_i$ by five and leaves the residual diagonal at its original size. A third call uses REML at the first $D$. The first two columns below give the intercept and slope, and the last column gives the profiled residual variance.
1
2
3
4
5
6
7
D_true <- G_true / sigma2_true
profile_small <- lmm_profile_nll(unequal, D_true)
profile_changed <- lmm_profile_nll(unequal, 5 * D_true)
profile_reml <- lmm_profile_nll(unequal, D_true, REML = TRUE)
print(rbind(shape1_ML = c(profile_small$beta, sigma2 = profile_small$sigma2),
shape5_ML = c(profile_changed$beta, sigma2 = profile_changed$sigma2),
shape1_REML = c(profile_reml$beta, sigma2 = profile_reml$sigma2)))
1
2
3
4
sigma2
shape1_ML 1.483354 -0.2939216 0.1998939
shape5_ML 1.433407 -0.2524230 0.1321195
shape1_REML 1.483354 -0.2939216 0.2570064
The larger $D$ moved the ML intercept from 1.48335 to 1.43341 and the slope from $-0.29392$ to $-0.25242$. The fitted residual variance fell from 0.1998939 to 0.1321195. Both ML rows use the divisor nine. Their residual-variance estimates differ because the change in $D$ changes the fitted line and the inverse covariance used to weight its residuals. At the first $D$, ML and REML returned the same coefficients. The ML variance of 0.1998939 used the divisor nine, so the weighted residual sum of squares was approximately $9(0.1998939)=1.7990451$. REML divided the same unrounded sum by seven and gave 0.2570064. The final two calculations both use profile_small, the ML result at the first $D$.
1
2
3
4
print(c(profile_joint_gap = profile_small$value - lmm_dense(unequal, profile_small$G,
profile_small$sigma2, profile_small$beta)$value,
scale_derivative = unequal$N / (2 * profile_small$sigma2) -
profile_small$quadratic / (2 * profile_small$sigma2^2)))
1
2
profile_joint_gap scale_derivative
0 0
Substituting the fixed coefficients, random-effect covariance matrix and residual variance from profile_small into the joint ML criterion reproduced the profiled value, so profile_joint_gap printed zero. The derivative with respect to $s$ also evaluated to zero at that variance, as the variance equation predicts. The remaining numerical minimization can therefore vary the relative covariance while computing the coefficients and residual variance directly at each proposed value. The R package lme4 uses profiled criteria for ML and REML estimation of linear mixed models and supports observation-level precision weights.
8.4 Cluster calculations with the Woodbury identity and determinant lemma
Each evaluation of the profiled likelihood needs a GLS estimate, a residual quadratic and a log determinant. For a person measured at many visits, can the random intercept and slope reduce the size of the system that has to be factored? Let $v$ have one entry per visit for person $i$. Applying the inverse marginal covariance to $v$ means solving $V_i x=v$, where $V_i=R_i+Z_iGZ_i^\top$. Suppose first that both covariance matrices $R_i$ and $G$ are positive definite. Set $a=GZ_i^\top x$. The equation for $x$ now reads $R_i x=v-Z_i a$. Substituting $x=R_i^{-1}(v-Z_i a)$ back into the definition of $a$ gives a system with one equation per random effect.
\[(G^{-1}+Z_i^\top R_i^{-1}Z_i)a=Z_i^\top R_i^{-1}v.\]Solving for $a$ and substituting into $x$ gives the Woodbury identity in the form needed for a response vector or a column of the design matrix.
\[V_i^{-1}v=R_i^{-1}v- R_i^{-1}Z_i(G^{-1}+Z_i^\top R_i^{-1}Z_i)^{-1}Z_i^\top R_i^{-1}v.\]The same inner matrix determines how much the random effects contribute to the determinant. The matrix determinant lemma follows by eliminating either off-diagonal block of the matrix
\[\begin{pmatrix} R_i & Z_i \\ -Z_i^\top & G^{-1} \end{pmatrix}.\]Adding $Z_i^\top R_i^{-1}$ times the first block row to the second gives diagonal blocks $R_i$ and $G^{-1}+Z_i^\top R_i^{-1}Z_i$. Starting again and subtracting $Z_iG$ times the second block row from the first gives $V_i$ and $G^{-1}$. Both operations preserve the determinant, so equating the two products and taking logarithms yields
\[\log|V_i|=\log|R_i|+\log|G|+\log|G^{-1}+Z_i^\top R_i^{-1}Z_i|.\]Near a zero variance, this expression asks for the inverse of a covariance that may become singular. Write $G=LL^\top$, with $q$ rows in $L$ for the $q$ random effects and $r$ columns, and put $U_i=Z_iL$. Now $V_i=R_i+U_iU_i^\top$. Using $U_i$ and $I_r$ in place of $Z_i$ and $G^{-1}$ in the block determinant gives $\vert V_i\vert =\vert R_i\vert \,\vert M_i\vert $, where $M_i=I_r+U_i^\top R_i^{-1}U_i$. For any nonzero $h$, $h^\top M_i h=h^\top h+(U_i h)^\top R_i^{-1}(U_i h)>0$. Even when the supplied matrix $L$ loses rank, $M_i$ therefore has a Cholesky factor.
Which quantities must be combined across people before fitting the population line? Independence makes the joint precision block diagonal, so the GLS equations sum the individual design and response products. Write
\[C=\sum_i X_i^\top V_i^{-1}X_i,\qquad C\hat\beta=\sum_i X_i^\top V_i^{-1}y_i.\]Each person contributes to both sums, even when their numbers of visits differ. Solving the summed equations gives the intercept and slope of one population line. Using these common coefficients in each residual $e_i=y_i-X_i\hat\beta$ gives the joint quadratic $\sum_i e_i^\top V_i^{-1}e_i$. The joint log determinant is $\sum_i\log\vert V_i\vert $ and can be accumulated before the coefficients are known. In the restricted likelihood, the additional $\log\vert C\vert $ uses the information from the combined design.
Implementing the cluster calculations
The function lmm_cluster() builds a solver for one person at a specified positive residual variance. The likelihood calculation uses its inverse products at a fixed variance or at residual variance one when profiling the variance. With known positive precision weights, applying $R_i^{-1}$ amounts to multiplying each row by $w_{ij}/\sigma^2$. Using $U_i=Z_iL$ in the Woodbury identity gives an inverse product that is defined even for singular $G$.
The following solver applies this identity to a response vector or several design columns and returns the person-specific log determinant.
1
2
3
4
5
6
7
8
9
10
11
12
13
lmm_cluster <- function(block, L, sigma2) {
inverse_residual <- block$weights / sigma2
U <- block$Z %*% L
inner <- diag(ncol(U)) + crossprod(U, inverse_residual * U)
R <- chol(inner)
apply_inverse <- function(B) {
B <- as.matrix(B)
RB <- inverse_residual * B
RB - (inverse_residual * U) %*% backsolve(R, forwardsolve(t(R), crossprod(U, RB)))
}
list(solve = apply_inverse, logdet = sum(log(sigma2 / block$weights)) +
2 * sum(log(diag(R))), inner_dimension = ncol(U))
}
For the first person in the weighted example, apply_inverse() multiplies the three ones in the intercept column of $X_i$ by the residual precisions. This gives RB with entries $(1,2,0.5)/\sigma^2$. More generally, for one column $v$ of B, crossprod(U, RB) forms the right-hand side $c=U_i^\top R_i^{-1}v$. With R denoting the upper Cholesky factor of $M_i$, forwardsolve() solves $\mathtt{R}^\top h_1=c$ and backsolve() solves $\mathtt{R}h_2=h_1$. The second solution $h_2$ is $M_i^{-1}U_i^\top R_i^{-1}v$. Multiplication by $R_i^{-1}U_i$ and subtraction from RB give $V_i^{-1}v$. The factorization also gives $\log\vert M_i\vert =2\sum_k\log(\mathtt{R}_{kk})$. Adding the log residual variances $\log(\sigma^2/w_{ij})$ over visits supplies $\log\vert R_i\vert $.
The function lmm_components() combines these person-specific calculations, solves the common GLS equations and computes the residual quadratic and log determinant for the whole sample.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
lmm_components <- function(data, G, sigma2, factor = NULL) {
L <- if (is.null(factor)) t(chol(G)) else factor
blocks <- lapply(data$blocks, function(b) {
op <- lmm_cluster(b, L, sigma2)
list(K = op$solve(diag(length(b$y))), KX = op$solve(b$X), Ky = drop(op$solve(b$y)),
logdet = op$logdet)
})
C <- Reduce(`+`, Map(function(b, a) crossprod(b$X, a$KX), data$blocks, blocks))
d <- Reduce(`+`, Map(function(b, a) drop(crossprod(b$X, a$Ky)), data$blocks, blocks))
H <- chol2inv(chol(C))
beta <- drop(H %*% d)
# Use the common GLS coefficients for every person's residuals.
quadratic <- sum(vapply(seq_along(blocks), function(i) {
b <- data$blocks[[i]]
r <- b$y - drop(b$X %*% beta)
sum(r * drop(blocks[[i]]$K %*% r))
}, 0.0))
list(blocks = blocks, C = C, H = H, beta = beta, quadratic = quadratic,
logdet = sum(vapply(blocks, `[[`, 0.0, "logdet")))
}
By default, lmm_components() takes t(chol(G)), which requires positive definite $G$. A supplied factor can be rectangular or rank deficient, provided its dimensions agree with the design and $LL^\top=G$. The function does not verify this equality when factor is supplied; the caller must ensure that the supplied factor represents the stated covariance.
The solver acts on $X_i$ and $y_i$ to produce KX and Ky. It also acts on all columns of the identity matrix to store the full person-specific inverse in K. The sums in C and d are the coefficient matrix and right-hand side of the GLS equations. After computing the common coefficients, the function uses the stored inverses to weight the residuals.
At a supplied $G$ and $\sigma^2$, lmm_cluster_nll() combines the log determinant, residual quadratic and normalizing constant. For ML, it can also evaluate a specified coefficient vector and return each person’s log likelihood contribution. Its REML calculation uses the GLS coefficients and the determinant of the summed $C$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
lmm_cluster_nll <- function(data, G, sigma2, REML = FALSE, beta = NULL, factor = NULL) {
a <- lmm_components(data, G, sigma2, factor)
if (!is.null(beta) && !REML) {
a$beta <- beta
a$quadratic <- sum(vapply(seq_along(data$blocks), function(i) {
r <- data$blocks[[i]]$y - drop(data$blocks[[i]]$X %*% beta)
sum(r * drop(a$blocks[[i]]$K %*% r))
}, 0.0))
}
df <- data$N - if (REML) data$p else 0
a$value <- .5 * (df * log(2 * pi) + a$logdet + a$quadratic +
if (REML) 2 * sum(log(diag(chol(a$C)))) else 0)
a$loglik_contributions <- if (REML) NULL else vapply(seq_along(data$blocks),
function(i) {
b <- data$blocks[[i]]
r <- b$y - drop(b$X %*% a$beta)
-.5 * (length(b$y) * log(2 * pi) + a$blocks[[i]]$logdet +
sum(r * drop(a$blocks[[i]]$K %*% r)))
}, 0.0)
a
}
The function lmm_fast_profile() uses the cluster likelihood to profile the fixed effects and residual variance at a proposed relative covariance $D$.
1
2
3
4
5
6
7
8
lmm_fast_profile <- function(data, D, REML = FALSE, scale = NULL) {
a <- lmm_cluster_nll(data, D, 1, REML)
df <- data$N - if (REML) data$p else 0
sigma2 <- if (is.null(scale)) a$quadratic / df else scale
list(value = a$value - a$quadratic / 2 + .5 * (df * log(sigma2) + a$quadratic / sigma2),
beta = a$beta, sigma2 = sigma2, G = sigma2 * D, relative_covariance = D,
df = df, REML = REML, scale_fixed = !is.null(scale))
}
The function lmm_fast_profile() evaluates this same calculation at relative covariance $D$ and residual variance one. It then replaces that quadratic with the terms for the chosen residual variance. With scale omitted, it estimates the variance using the ML or REML divisor. Supplying a positive scale fixes the residual variance at that value. Unlike lmm_profile_nll(), this function has no explicit check that the resulting sigma2 is positive and finite; a zero residual quadratic therefore needs separate handling.
For the nine weighted measurements in unequal, the first three comparisons use the generating $G$ and $\sigma^2=0.49$. Their dense reference, dense_ml, used the same visit times and weights in a single covariance matrix. The fourth uses D_true, the generating $G$ divided by 0.49. At that relative covariance, profile_small gives the dense ML criterion evaluated at the profiled residual variance. The final entries record the dimensions of the systems involved.
1
2
3
4
5
6
7
8
9
10
cluster_small <- lmm_cluster_nll(unequal, G_true, sigma2_true)
print(c(quadratic_gap = cluster_small$quadratic - dense_ml$quadratic,
logdet_gap = cluster_small$logdet -
as.numeric(determinant(dense_ml$V, logarithm = TRUE)$modulus),
beta_gap = max(abs(cluster_small$beta - dense_ml$beta)),
profile_gap = lmm_fast_profile(unequal, D_true)$value - profile_small$value,
stacked_dimension = unequal$N,
largest_cluster = max(vapply(unequal$blocks, function(b) length(b$y), 1L)),
inner_dimension =
lmm_cluster(unequal$blocks[[1]], t(chol(G_true)), sigma2_true)$inner_dimension))
1
2
3
4
quadratic_gap logdet_gap beta_gap profile_gap stacked_dimension largest_cluster
2.664535e-15 -8.881784e-16 4.218847e-15 3.552714e-15 9.000000e+00 4.000000e+00
inner_dimension
2.000000e+00
Subtracting the dense result from the person-by-person result gave $2.664535\times10^{-15}$ for the residual quadratic and $-8.881784\times10^{-16}$ for the log determinant. The largest absolute difference across the two GLS coefficients was $4.218847\times10^{-15}$. At the specified relative covariance, the difference in profiled negative log likelihood, again person-by-person minus dense, was $3.552714\times10^{-15}$.
The nine responses give a nine-by-nine stacked covariance. Person 2 contributes the largest block, with four visits. The last entry reads the inner dimension from person 1. All three people use the same two-column matrix $L$ for the random intercept and slope. The two triangular systems have dimension two for each right-hand side, including each column of the four-by-four identity matrix for person 2. The resulting stored inverse is four by four. In general, an $L$ with $r$ columns gives an $r$-by-$r$ inner matrix $M_i$, even if the number of visits differs from person to person. The four differences show that this calculation reproduces the dense likelihood quantities to numerical precision.
8.5 Covariance parameterization and variance components at the boundary
A proposed covariance for a random intercept and slope must give a nonnegative variance to every linear combination of the two effects. The cluster calculation uses a matrix $L$ with $G=LL^\top$. For a search over positive definite covariances, the profile optimizer works with the relative precision. With $D=G/\sigma^2$, it writes $D^{-1}=\Delta^\top\Delta$, where $\Delta$ is upper triangular with positive diagonal entries. For two random effects, the log-Cholesky parameters of the relative precision are $(\log\Delta_{11},\log\Delta_{22},\Delta_{12})$. This parameterization is applied to $D^{-1}$, whereas $L$ factors $G$; they are different matrices. The following helpers report covariance summaries, encode a relative precision matrix in log-Cholesky coordinates and recover its triangular factor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
lmm_covariance_summary <- function(G) {
sd <- sqrt(pmax(diag(G), 0))
denominator <- outer(sd, sd)
correlation <- G / denominator
correlation[denominator == 0] <- NA_real_
list(sd = sd, correlation = correlation,
minimum_eigenvalue = min(eigen(G, symmetric = TRUE)$values))
}
# R is the upper triangular Cholesky factor of the relative precision.
# Its log diagonal entries are followed by the entries above the diagonal.
precision_to_logchol <- function(P) {
R <- chol(P)
c(log(diag(R)), R[upper.tri(R)])
}
logchol_to_factor <- function(u) {
q <- round((sqrt(1 + 8 * length(u)) - 1) / 2)
R <- diag(exp(u[seq_len(q)]), q)
R[upper.tri(R)] <- u[-seq_len(q)]
R
}
In precision_to_logchol(), the local matrix R is $\Delta$. Its off-diagonal entry can take either sign. In exact arithmetic, exponentiating the first two parameters in logchol_to_factor() makes the diagonal positive for every finite input. For positive variances, lmm_covariance_summary() takes square roots of variances and divides each covariance by the product of its two standard deviations.
Consider a starting covariance with intercept variance 1, slope variance 0.25 and covariance 0.1. Dividing it by a reference residual variance of 0.5 gives $D$. Inverting $D$ before taking its Cholesky factor gives the following coordinates.
1
2
3
covariance_start <- matrix(c(1, .1, .1, .25), 2)
u_start <- precision_to_logchol(solve(covariance_start / .5))
print(u_start)
1
[1] -0.3261626 0.3465736 -0.2886751
The first two printed values are the log diagonal entries. The third, $-0.2886751$, enters the upper right corner of $\Delta$ unchanged. To recover the starting covariance, chol2inv() computes $(\Delta^\top\Delta)^{-1}$, which is then multiplied by 0.5.
1
print(lmm_covariance_summary(chol2inv(logchol_to_factor(u_start)) * .5))
1
2
3
4
5
6
7
8
9
10
$sd
[1] 1.0 0.5
$correlation
[,1] [,2]
[1,] 1.0 0.2
[2,] 0.2 1.0
$minimum_eigenvalue
[1] 0.2368956
The resulting standard deviations are 1 and 0.5, so the correlation is $0.1/(1\times 0.5)=0.2$. The smallest eigenvalue, 0.23690, shows that this starting covariance is positive definite. Both effects and every nonzero linear combination have positive variance. The summary function also replaces negative diagonal entries by zero before taking square roots; its reported standard deviations alone cannot establish that an arbitrary input is a valid covariance.
How sensitive is the profiled ML criterion to this choice of relative covariance? Let $a$ and $b$ be starting standard deviations for the random intercept and slope. Together with their correlation $\rho$, they give a covariance matrix with diagonal entries $a^2,b^2$ and off-diagonal entry $\rho ab$. Dividing this matrix by a reference residual variance and taking the Cholesky factor of its inverse gives the optimizer a start for each proposed $(a,b,\rho)$. To inspect the likelihood at selected relative covariance matrices, shape_grid crosses three choices of $a$ with three choices of $b$ for the 200 people in growth_data. Each row fixes $\rho=0.2$ and divides its covariance by 0.5. At that $D$, lmm_fast_profile() estimates the residual variance and returns the profiled negative log likelihood. The covariance at which this likelihood is evaluated is $\hat\sigma^2 D$.
1
2
3
4
5
6
shape_grid <- expand.grid(intercept_sd = c(.6, 1, 1.4), slope_sd = c(.3, .5, .7))
shape_grid$nll <- mapply(function(a, b) {
D <- diag(c(a, b)) %*% matrix(c(1, .2, .2, 1), 2) %*% diag(c(a, b)) / .5
lmm_fast_profile(growth_data, D)$value
}, shape_grid$intercept_sd, shape_grid$slope_sd)
print(shape_grid, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
intercept_sd slope_sd nll
0.6 0.3 1272.033
1.0 0.3 1252.388
1.4 0.3 1265.118
0.6 0.5 1255.942
1.0 0.5 1230.083
1.4 0.5 1236.372
0.6 0.7 1269.229
1.0 0.7 1236.832
1.4 0.7 1237.566
Of the nine relative covariance matrices, the lowest value was 1230.083, at grid labels $a=1$ and $b=0.5$. These grid labels equal the generating marginal standard deviations. After the residual variance is estimated at a grid point, however, the evaluated covariance is $\hat\sigma^2 D$; its standard deviations need not equal the labels $a$ and $b$. The generating correlation was 0.3 and the generating residual variance was 0.49, so the generating relative covariance differs from the one used in that row. A continuous search can also vary the correlation and examine standard deviations between grid points.
Approaching a zero variance component
Can a finite log-Cholesky parameter of the relative precision represent a random-intercept variance of exactly zero? With one random effect of variance $\tau^2>0$ and residual variance $s=\sigma^2>0$, the Cholesky factor of the relative precision is $\Delta=\sqrt{s/\tau^2}$. As $\tau^2$ approaches zero at fixed $s$, the Cholesky factor $L=\sqrt{\tau^2}$ of the covariance tends to zero and $\log\Delta$ grows without bound. Every finite value of $\log\Delta$ corresponds to $\tau^2>0$ in exact arithmetic. The value $\tau^2=0$ is permitted by the random-intercept model but cannot be represented by a finite $\log\Delta$ at fixed $s>0$; a negative variance is not permitted.
Consider four constructed, independent pairs of responses, $(-1,1)$, $(1,-1)$, $(-2,2)$ and $(2,-2)$. The fixed intercept is common to all pairs, and each pair has its own mean-zero random intercept. Its variance $\tau^2$ describes differences in expected response between pairs; $s$ describes variation around a pair’s own mean. Both are in squared response units. At $\tau^2=0$, every pair has the same expected response, while measurement errors still allow the two responses within a pair to differ.
Each covariance block is $sI_2+\tau^2\mathbf1\mathbf1^\top$, where $\mathbf1=(1,1)^\top$. The direction $(1,1)^\top$ has eigenvalue $s+2\tau^2$, and the within-pair contrast $(1,-1)^\top$ has eigenvalue $s$. Since $V_i^{-1}\mathbf1=\mathbf1/(s+2\tau^2)$, each pair contributes its response sum divided by $s+2\tau^2$ to the GLS intercept numerator. The sums are all zero, so the fitted intercept is zero for every $\tau^2$, and all residual variation lies along the contrasts.
For fixed $s$, the residual quadratic is consequently $20/s$ for every $\tau^2$, since the eight squared residuals sum to 20. Each block determinant is $s(s+2\tau^2)$. Relative to zero random-intercept variance, the increase in negative log likelihood across all four pairs is therefore $2\log(1+2\tau^2/s)$. The reduced model has a fixed intercept and a random-effect design with eight rows and zero columns. Fitting it gives the residual variance $20/8=2.5$. The table evaluates the four specified random-intercept variances at this common residual variance.
1
2
3
4
5
6
7
8
9
10
11
12
Y_boundary <- rbind(c(-1, 1), c(1, -1), c(-2, 2), c(2, -2))
boundary_data <- lmm_design(as.vector(t(Y_boundary)), matrix(1, 8, 1),
matrix(1, 8, 1), rep(1:4, each = 2))
reduced_data <- lmm_design(boundary_data$y, boundary_data$X,
matrix(numeric(), 8, 0), boundary_data$id)
reduced <- lmm_profile_nll(reduced_data, matrix(numeric(), 0, 0))
boundary_table <- do.call(rbind, lapply(c(.1, .01, .001, 0), function(tau2) {
a <- lmm_dense(boundary_data, matrix(tau2), reduced$sigma2)
data.frame(random_intercept_variance = tau2,
residual_variance = reduced$sigma2, nll = a$value)
}))
print(boundary_table, row.names = FALSE)
1
2
3
4
5
random_intercept_variance residual_variance nll
0.100 2.5 15.17059
0.010 2.5 15.03261
0.001 2.5 15.01827
0.000 2.5 15.01667
The negative log likelihood fell from 15.17059 at variance 0.1 to 15.03261 at 0.01, 15.01827 at 0.001 and 15.01667 at zero. Differentiating the increase $2\log(1+2\tau^2/s)$ from the right gives $4/s$ at zero. The code computes the same derivative one pair at a time. At zero, $V_i^{-1}=I/s$ and the derivative of $V_i$ in $\tau^2$ is $\mathbf1\mathbf1^\top$. For a cluster of size $n_i$ with residuals $r_{ij}$, the derivative of the log determinant with respect to $\tau^2$ is $n_i/s$ and the derivative of the quadratic is $-(\sum_j r_{ij})^2/s^2$. Combining them gives
\[\left.\frac{\partial(-\ell)}{\partial\tau^2}\right|_{0+} =\frac12\sum_i\left\{\frac{n_i}{s} -\frac{(\sum_j r_{ij})^2}{s^2}\right\}.\]The calculation uses the residuals and variance from the reduced fit.
1
2
3
4
5
6
print(c(reduced_nll = reduced$value, independent_normal_nll = -sum(dnorm(boundary_data$y,
reduced$beta, sqrt(reduced$sigma2), log = TRUE)),
right_variance_derivative = sum(vapply(boundary_data$blocks, function(b) {
r <- b$y - drop(b$X %*% reduced$beta)
(length(r) / reduced$sigma2 - sum(r)^2 / reduced$sigma2^2) / 2
}, 0))))
1
2
reduced_nll independent_normal_nll right_variance_derivative
15.01667 15.01667 1.60000
All four residual sums vanish. With two responses per pair, the right derivative is $4/2.5=1.6$. An increase in the random-intercept variance from zero raises the negative log likelihood.
For the four pairs, the positive-variance rows are likelihood evaluations at a fixed residual variance. The zero-column model fits the boundary directly. Its negative log likelihood of 15.01667 agrees with the sum of the eight independent-normal negative log densities at the fitted intercept and residual variance. For any $s>0$ and $\tau^2>0$, the increase $2\log(1+2\tau^2/s)$ puts the negative log likelihood above its value at $(0,s)$. That boundary value is minimized at $s=2.5$, so $(\tau^2,s)=(0,2.5)$ is the global ML solution for these pairs.
A zero variance also affects how an estimated covariance can be reported. Consider two random effects with covariance matrix $\operatorname{diag}(1,0)$, a separate example from the paired responses. The second effect is constant, so its covariance with the first is zero. Converting that entry to a correlation would divide zero by the product of their standard deviations, $1\times0$.
1
print(lmm_covariance_summary(diag(c(1, 0)))$correlation)
1
2
3
[,1] [,2]
[1,] 1 NA
[2,] NA NA
Only the first effect’s correlation with itself is defined. The missing entries mark correlations involving the second effect, including its diagonal entry. A correlation involving a zero-variance effect is undefined because its standard deviation is zero. A singular covariance can also have positive diagonal entries: for two effects with positive variances, a correlation of $-1$ or $1$ makes one nonzero linear combination have zero variance.
The R package lme4 fits mixed models that allow variance components on the boundary.
8.6 Profile optimization, EM, and Fisher scoring
A trial covariance for the growth curves determines how much unexplained variation to assign to differences between people. With unit weights, write $D=G/\sigma^2$, take the Cholesky factor $\Delta$ with $\Delta^\top\Delta=D^{-1}$, and consider one person’s least-squares problem. For a given population coefficient vector $\beta$, the penalized sum of squares is $\Vert y_i-X_i\beta-Z_i b_i\Vert ^2+\Vert \Delta b_i\Vert ^2$. The first term measures deviations from the person’s line. The second penalizes departures from the population coefficients according to their covariance relative to the residual variance. Both terms fit in one array.
Stack $[Z_i\;\;X_i\;\;y_i]$ above $[\Delta\;\;0\;\;0]$ and use QR to eliminate the $q$ random-effect columns. The resulting upper triangular block $R_{11(i)}$ satisfies $R_{11(i)}^\top R_{11(i)}=Z_i^\top Z_i+D^{-1}$. The determinant identity for $H_i=I+Z_i D Z_i^\top$ then gives $\tfrac12\log\vert H_i\vert =\log\vert \det R_{11(i)}\vert -\log\vert \det\Delta\vert $. The rows below that block describe the sum of squares after minimizing over $b_i$. Stack those rows across people and eliminate the fixed-effect columns to obtain the upper triangular block $R_{00}$. Reducing the last response column gives a scalar $r$ whose square is the minimized residual quadratic in relative covariance units. Define $d=N$ for ML and $d=N-p$ for REML. Up to terms independent of $D$, the negative log likelihood is
\[d\log|r|+\sum_{i=1}^m \log|\det R_{11(i)}|-m\log|\det\Delta| +\mathbf{1}_{\mathrm{REML}}\log|\det R_{00}|.\]The setup below constructs and stores the stacked array for repeated evaluations. With unit weights, an initial reduction saves work when $mq+p+1<N$. Here two columns per person and three additional rows require 403 rows for 800 responses. With specified precision weights, each observation row is multiplied by the square root of its weight, and the determinant calculation includes the sum of the log multipliers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
lmm_profile_setup <- function(data, REML = FALSE, scale = NULL,
variance_function = NULL) {
stopifnot(is.null(scale) || !REML)
rows <- function(b) cbind(b$Z, b$X, b$y)
stacked <- do.call(rbind, lapply(data$blocks, rows))
dims <- lmmp_dims(vapply(data$blocks, function(b) length(b$y), 0L), data$q, data$p)
weights <- unlist(lapply(data$blocks, `[[`, "weights"), use.names = FALSE)
if (identical(variance_function, FALSE) && any(weights != 1))
stop("Nonunit weights require the specified variance function")
weighted <- if (is.null(variance_function)) any(weights != 1) else variance_function
log_weights <- 0
# Apply observation weights before the QR reductions.
if (weighted) {
factor <- 1 / sqrt(abs(1 / weights))
log_weights <- sum(log(factor))
stacked[] <- stacked * factor
} else if (dims$factor_rows < dims$N) {
reduced <- lmmp_decompose(stacked, dims)
stacked <- reduced$stacked
dims <- reduced$dims
}
list(stacked = stacked, dims = dims, weighted = weighted, log_weights = log_weights,
reml_flag = as.integer(REML), sigma = if (is.null(scale)) 0 else sqrt(scale))
}
In code/lib/lmm_profile.R, lmmp_dims() records the block sizes and row and column locations for the random effects, fixed effects and response. Given that layout, lmmp_decompose() returns the initially reduced array together with its updated layout. The orthogonal transformations accumulate logarithms of the absolute diagonal entries of the triangular blocks.
At each trial, the following functions evaluate the QR criterion at the supplied relative precision. By default, weighted fits evaluate it directly, while unit-weight fits use a local quadratic interpolation in the log-Cholesky coordinates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
lmm_precision_nll <- function(setup, Delta) {
if (any(!is.finite(Delta))) return(Inf)
e <- new.env()
e$stacked <- setup$stacked
-(setup$log_weights + lmmp_loglik(e, setup$dims, Delta, setup$reml_flag, setup$sigma))
}
lmm_profile_objective <- function(setup, u) {
if (setup$weighted) return(lmm_precision_nll(setup, logchol_to_factor(u)))
-lmmp_koshal(function(v) {
e <- new.env()
e$stacked <- setup$stacked
lmmp_loglik(e, setup$dims, logchol_to_factor(v), setup$reml_flag, setup$sigma)
}, u)
}
The helper lmmp_loglik() takes the stacked array in a working environment e, its layout and the trial precision factor, then returns the QR log likelihood with the constants omitted above. It overwrites working rows during reduction, so each evaluation starts with a fresh environment and a copy of the stored array. The wrapper lmm_precision_nll() adds the weight adjustment and reverses the sign for minimization.
For unit weights, lmmp_koshal() fits a quadratic through criterion values at the center and nearby points in the log-Cholesky parameters of the relative precision. Three coordinates require ten points. For parameter $u_j$ and machine precision $\varepsilon$, the increment is $\varepsilon^{1/3}u_j$ for nonzero $u_j$ and $\varepsilon^{1/3}$ at zero. The fitted intercept reproduces the center value up to rounding. The name lmmp_koshal identifies this implementation of quadratic interpolation.
For a nonzero final QR residual, the internal field log_absolute_qr_residual stores $\log\vert r\vert $, which is half the logarithm of the residual quadratic $r^2$. Its name should not be read as $\log(r^2)$. A rank failure in lmmp_loglik() returns -.Machine$double.xmax, a finite failure value; a finite returned criterion alone does not establish that the likelihood calculation succeeded.
The starting precision is diagonal, with entry $0.375^2\sum_j Z_{jk}^2/m$ for column $k$, summed over observation rows. For times zero through three its two diagonal entries are 0.5625 and 1.96875.
1
2
3
4
lmm_precision_start <- function(data) {
Z <- do.call(rbind, lapply(data$blocks, `[[`, "Z"))
diag(.375^2 * colSums(Z^2) / data$groups, data$q)
}
The first double-dogleg fit starts at this diagonal precision, minimizes the scalar criterion and allows 50 iterations and 200 evaluations. At the returned coordinates, chol2inv() recovers $D$ from the Cholesky factor of the relative precision. For unweighted ML, $r^2/N$ is the fitted variance. Substituting it in the full normal likelihood adds $N[1+\log(2\pi/N)]/2$ to the QR criterion. The printed nll comes from evaluating the full fit at the returned $D$.
1
2
3
4
5
6
7
8
9
10
growth_setup <- lmm_profile_setup(growth_data)
initial_profile <- dogleg_minimize(precision_to_logchol(lmm_precision_start(growth_data)),
function(u) lmm_profile_objective(growth_setup, u),
control = list(max_iter = 50L, max_evals = 200L))
initial_fit <- lmm_fast_profile(growth_data,
chol2inv(logchol_to_factor(initial_profile$par)))
print(data.frame(nll = initial_fit$value, iterations = initial_profile$iterations,
criterion_evaluations = initial_profile$evaluations[[1]],
numerical_derivative_requests = initial_profile$evaluations[[2]],
converged = initial_profile$convergence == 0L, message = initial_profile$message))
1
2
nll iterations criterion_evaluations numerical_derivative_requests converged message
1 1229.074 10 17 48 TRUE relative convergence (4)
The double-dogleg method reports relative convergence after ten iterations, with 17 recorded criterion evaluations and 48 numerical-derivative requests. The counts describe its calls. A single request can entail several QR reductions. To read the fit in response units, extract the coefficients and covariance components from initial_fit.
1
2
print(c(initial_fit$beta, sigma2 = initial_fit$sigma2, G11 = initial_fit$G[1, 1],
G21 = initial_fit$G[2, 1], G22 = initial_fit$G[2, 2]))
1
2
sigma2 G11 G21 G22
2.0745469 0.4014797 0.4790536 1.1451576 0.1201173 0.2810086
The first two entries estimate the population intercept and slope. Multiplying the fitted $D$ by the residual variance 0.4790536 gives $G$. Its diagonal entries, 1.1451576 and 0.2810086, estimate the between-person variances of the intercept and slope. Their estimated covariance is 0.1201173.
Conditional-moment updates and ECME
The next calculation constructs an ML iteration that updates the covariance from conditional moments of the unobserved intercepts and slopes. Estimating $G$ this way requires their conditional second moments. At specified $\beta,G,\sigma^2$, the centered random effects $b_i$ and responses $y_i$ are jointly normal with cross-covariance $GZ_i^\top$. Subtract $A_i(y_i-X_i\beta)$ from $b_i$, where $A_i=GZ_i^\top V_i^{-1}$. The difference has zero covariance with $y_i$ because $A_i V_i=GZ_i^\top$. Joint normality gives independence, so observing $y_i$ changes only the first term in the decomposition $b_i=A_i(y_i-X_i\beta)+[b_i-A_i(y_i-X_i\beta)]$. The conditional mean, covariance and second moment are therefore
\[m_i=A_i(y_i-X_i\beta),\qquad C_i=G-A_i Z_iG,\qquad E(b_i b_i^\top\mid y_i)=C_i+m_i m_i^\top.\]The vector $m_i$ predicts the person’s intercept and slope deviations. The diagonal entries of $C_i$ describe the remaining uncertainty about those deviations given the responses and the specified parameters. This conditional covariance differs from the between-person covariance $G$ and does not include uncertainty from estimating the population parameters.
The function lmm_conditional() returns these three conditional moments for each person.
1
2
3
4
5
6
7
8
9
lmm_conditional <- function(data, beta, G, sigma2) {
lapply(data$blocks, function(b) {
V <- lmm_covariance(b, G, sigma2)
KZ <- solve(V, b$Z)
C <- G - G %*% crossprod(b$Z, KZ) %*% G
mean <- drop(G %*% t(KZ) %*% (b$y - b$X %*% beta))
list(mean = mean, covariance = (C + t(C)) / 2, second = C + tcrossprod(mean))
})
}
The solve in lmm_conditional() gives $V_i^{-1}Z_i$ for the calculations. Its output contains a vector and two matrices for each person.
At a given relative covariance, lmm_gls() evaluates the GLS coefficients using residual variance one and divides the resulting relative residual quadratic by $N$ for the ML estimate of $\sigma^2$.
1
2
3
4
lmm_gls <- function(data, xi) {
a <- lmm_components(data, xi, 1)
list(beta = a$beta, sigma2 = a$quadratic / data$N)
}
The initialization fits weighted least squares to all responses and divides the weighted residual sum of squares by $N$. Regressing these residuals on $Z_i$ within person $i$, with diagonal precision weights $W_i$, gives starting deviations. Their second moments supply a starting relative covariance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
lmm_ecme_start <- function(data) {
W <- data$weights
beta <- drop(qr.coef(qr(sqrt(W) * data$X), sqrt(W) * data$y))
residual <- data$y - drop(data$X %*% beta)
sigma2 <- sum(W * residual^2) / data$N
# A person contributes a start only if the within-person fit has full rank.
S <- matrix(0, data$q, data$q)
used <- 0L
for (b in data$blocks) {
A <- crossprod(b$Z, b$weights * b$Z)
if (inherits(tryCatch(chol(A), error = identity), "error")) next
used <- used + 1L
S <- S + tcrossprod(solve(A, crossprod(b$Z, b$weights * residual[b$rows])))
}
stopifnot(used > 0)
list(beta = beta, sigma2 = sigma2, xi = S / (used * sigma2))
}
In lmm_ecme_start(), each usable coefficient vector contributes its outer product to S. Dividing the sum by the number of usable fits times the starting residual variance gives the relative covariance. A person contributes only if $Z_i^\top W_i Z_i$ is positive definite. All 200 designs qualify here.
For the first covariance update, let $s_o$ denote the old residual variance. At this residual variance the part of the expected complete-data negative log likelihood that depends on the candidate $D$ is
\[\frac{m}{2}\log|D|+ \frac{1}{2s_o}\operatorname{tr}\!\left(D^{-1}\sum_{i=1}^m [C_i+m_i m_i^\top]\right).\]With respect to $D^{-1}$, the first term has derivative $-mD/2$. The second is linear in $D^{-1}$, so equating the derivatives to zero gives $D_{\rm new}=\sum_i(C_i+m_i m_i^\top)/(m s_o)$. To form this expectation, first obtain $\beta$ by GLS at the starting $D$. Then condition on each person’s responses using that new $\beta$, the starting $D$ and the old residual variance $s_o$. The two parts of the update have the same denominator. The helper vech() defined below reads down the lower triangle: for these two effects, the columns contain the intercept variance, the intercept-slope covariance and the slope variance in relative covariance units.
1
2
3
4
5
6
7
8
9
10
11
12
em_start <- lmm_ecme_start(growth_data)
first_gls <- lmm_gls(growth_data, em_start$xi)
first_moments <- lmm_conditional(growth_data, first_gls$beta,
em_start$sigma2 * em_start$xi,
em_start$sigma2)
vech <- function(A) A[lower.tri(A, diag = TRUE)]
mean_part <- Reduce(`+`, lapply(first_moments, function(e) tcrossprod(e$mean))) /
(growth_data$groups * em_start$sigma2)
uncertainty_part <- Reduce(`+`, lapply(first_moments, `[[`, "covariance")) /
(growth_data$groups * em_start$sigma2)
print(rbind(start = vech(em_start$xi), mean_part = vech(mean_part),
uncertainty_part = vech(uncertainty_part), update = vech(mean_part + uncertainty_part)))
1
2
3
4
5
[,1] [,2] [,3]
start 0.4988060 -0.007951807 0.12695698
mean_part 0.1714831 0.061511732 0.03878957
uncertainty_part 0.2329834 -0.065214230 0.06394840
update 0.4044664 -0.003702498 0.10273797
The intercept entry moves from 0.4988060 to 0.4044664. Treating the conditional means as observed random effects would use just 0.1714831 and discard more than half of the updated intercept entry. For the covariance, the two contributions have opposite signs. The positive 0.061511732 from the pairs of conditional means combines with $-0.065214230$ from their conditional uncertainty to give $-0.003702498$. For the slope, both contributions are positive and give 0.10273797. GLS also produced a new residual variance. The two printed residual variances distinguish that update from the old residual variance used in both conditional-moment terms.
1
2
print(c(start_residual_variance = em_start$sigma2,
gls_residual_variance = first_gls$sigma2))
1
2
start_residual_variance gls_residual_variance
2.968098 1.014674
The starting residual variance 2.968098 comes from the pooled least-squares residuals. GLS at the starting $D$ gives 1.014674. The latter is the residual variance to take forward. Using it to divide the displayed sums would define a different update from the one shown.
Repeating these calculations gives an expectation/conditional maximization either (ECME) algorithm for ML. One conditional maximization uses the observed responses directly to update $\beta$ and $\sigma^2$ at the current $D$. The other updates $D$ using the expected complete-data criterion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
lmm_ecme <- function(data, start = lmm_ecme_start(data), control = list()) {
stopifnot(all(names(control) %in% c("maxit", "tol")))
settings <- modifyList(list(maxit = 1000L, tol = 1e-4), control)
beta <- start$beta
sigma2 <- start$sigma2
xi <- start$xi
upper <- upper.tri(xi, diag = TRUE)
changed <- function(new, old) any(abs(new - old) > settings$tol * abs(old))
iterations <- 0L
converged <- FALSE
reason <- "iteration_limit"
history <- list(list(beta = beta, xi = xi, sigma2 = sigma2))
while (iterations < settings$maxit) {
if (inherits(tryCatch(chol(xi), error = identity), "error")) {
reason <- "relative_covariance_not_positive_definite"
break
}
iterations <- iterations + 1L
old <- list(beta = beta, xi = xi, sigma2 = sigma2)
# Maximize the observed-data likelihood at the current relative covariance.
update <- lmm_gls(data, xi)
beta <- update$beta
sigma2 <- update$sigma2
# Average the conditional second moments using the previous residual variance.
moments <- lmm_conditional(data, beta, old$sigma2 * xi, old$sigma2)
xi <- Reduce(`+`, lapply(moments, `[[`, "second")) / (data$groups * old$sigma2)
xi <- (xi + t(xi)) / 2
history[[length(history) + 1L]] <- list(beta = beta, xi = xi, sigma2 = sigma2)
# Every distinct component must pass its relative-change test.
if (!changed(beta, old$beta) && !changed(xi[upper], old$xi[upper]) &&
!changed(sigma2, old$sigma2)) {
converged <- TRUE
reason <- "small_relative_change"
break
}
}
fit <- list(beta = beta, G = sigma2 * xi, sigma2 = sigma2,
value = lmm_cluster_nll(data, sigma2 * xi, sigma2, beta = beta)$value)
optimizer <- new_result(c(beta, vech(xi), sigma2), fit$value, converged = converged,
reason = reason, iterations = iterations, history = history)
lmm_finish(fit, data, "ECME", FALSE, NULL, optimizer)
}
In lmm_ecme(), the update of xi is $D_{\rm new}$ above, with each second element equal to $C_i+m_im_i^\top$, data$groups equal to $m$ and old$sigma2 equal to $s_o$. Here old saves the residual variance that produced the covariance for the conditional expectation, even after sigma2 takes its new GLS value. Averaging the updated matrix with its transpose removes numerical asymmetry. Each history entry contains all three quantities for the same completed iteration. The coefficients in such an entry were obtained at the preceding relative covariance. Before convergence, they need not equal the GLS coefficients evaluated at the newly updated $D$.
For each fixed coefficient, each distinct entry of $D$ and the residual variance, the stopping rule is $\vert a_{\rm new}-a_{\rm old}\vert \leq 10^{-4}\vert a_{\rm old}\vert $. A previously zero entry must still be zero to pass its test. The function also checks that the current relative covariance has a Cholesky factor and limits the run to 1,000 updates. At return it converts $D$ to $G$ using the current residual variance and evaluates the full normal likelihood at the returned coefficients. The label "ECME" selects this ML routine. A restricted-likelihood update would have to account for estimating the population coefficients in the covariance calculation. Changing the divisor in the GLS residual-variance update alone would omit that contribution.
Derivatives and expected information for the variance components
How close are the fitted variance components to a stationary point on their reported scales? Stack the people, write $K=V^{-1}$, $C=X^\top KX$ and $P=K-KXC^{-1}X^\top K$. At GLS the residual vector in precision units is $u=K(y-X\hat\beta)=Py$. For a free component $\theta_a$, put $V_a=\partial V/\partial\theta_a$. Differentiating $\log\vert V\vert $ gives $\operatorname{tr}(KV_a)$. In the minimized residual quadratic, terms involving the derivative of $\hat\beta$ vanish by $X^\top u=0$. The derivative of the inverse, $-KV_aK$, leaves $-u^\top V_a u$. REML also differentiates $\log\vert C\vert $. Its contribution is $-\operatorname{tr}(C^{-1}X^\top KV_aKX)$, which changes the determinant trace to $\operatorname{tr}(PV_a)$. Thus for the negative log likelihood $L$ and its expected information $\mathcal I$,
\[\partial_a L=\tfrac12\{\operatorname{tr}(M V_a)-u^\top V_a u\},\qquad \mathcal I_{ab}=\tfrac12\operatorname{tr}(M V_a M V_b), \qquad M=\begin{cases}K&\text{ML},\\ P&\text{REML}.\end{cases}\]For ML the information is the variance-component block of Gaussian expected information with unknown fixed coefficients; it is not the observed Hessian of the profiled criterion. For REML the residual contrasts give the projected precision in both positions. Within a person, $V_a=Z_i(\partial_a G)Z_i^\top+\operatorname{diag}(\partial_a\sigma^2/w_{ij})$. Changing $G_{21}$ by one changes both symmetric positions of $G$ by one. Between visits at times $t$ and $v$, the resulting covariance derivative is $t+v$. This explains the two assignments to the same unit value in lmm_G_derivatives().
1
2
3
4
5
6
7
8
lmm_G_derivatives <- function(q) {
index <- which(lower.tri(diag(q), diag = TRUE), arr.ind = TRUE)
lapply(seq_len(nrow(index)), function(a) {
dG <- matrix(0, q, q)
dG[index[a, 1], index[a, 2]] <- dG[index[a, 2], index[a, 1]] <- 1
dG
})
}
The function lmm_nll_derivatives() sums these gradient contributions across people and optionally evaluates expected information. For REML, the fixed-effect projection couples the people, so the information calculation must also combine their contributions before taking the final trace products.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
lmm_nll_derivatives <- function(data, G, sigma2, derivatives, REML = FALSE, information = FALSE) {
a <- lmm_components(data, G, sigma2)
k <- length(derivatives)
gradient <- numeric(k)
Ca <- replicate(k, matrix(0, data$p, data$p), simplify = FALSE)
VA <- vector("list", data$groups)
KA <- VA
for (i in seq_along(data$blocks)) {
b <- data$blocks[[i]]
z <- a$blocks[[i]]
r <- b$y - drop(b$X %*% a$beta)
Kr <- drop(z$K %*% r)
# Form one marginal covariance derivative per free parameter.
VA[[i]] <- lapply(derivatives, function(d) b$Z %*% d$G %*% t(b$Z) +
diag(d$sigma2 / b$weights, length(b$y)))
KA[[i]] <- lapply(VA[[i]], function(Va) z$K %*% Va)
for (j in seq_len(k)) {
# Sum the fixed-effect correction across people for REML.
Cj <- crossprod(z$KX, VA[[i]][[j]] %*% z$KX)
Ca[[j]] <- Ca[[j]] + Cj
gradient[j] <- gradient[j] + .5 * (sum(diag(KA[[i]][[j]])) -
sum(Kr * drop(VA[[i]][[j]] %*% Kr)) - if (REML) sum(a$H * Cj) else 0)
}
}
I <- NULL
if (information) {
I <- matrix(0, k, k)
# Compute one information entry for each pair of free parameters.
for (j in seq_len(k)) for (h in seq_len(j)) {
value <- 0
B <- matrix(0, data$p, data$p)
for (i in seq_along(data$blocks)) {
value <- value + sum(KA[[i]][[j]] * t(KA[[i]][[h]]))
if (REML) {
KX <- a$blocks[[i]]$KX
B <- B + crossprod(VA[[i]][[j]] %*% KX,
a$blocks[[i]]$K %*% VA[[i]][[h]] %*% KX)
}
}
if (REML) value <- value - 2 * sum(a$H * t(B)) +
sum(diag(a$H %*% Ca[[j]] %*% a$H %*% Ca[[h]]))
I[j, h] <- I[h, j] <- value / 2
}
}
list(gradient = gradient, information = I, components = a)
}
In lmm_nll_derivatives(), Kr is the person’s part of $u$, and Cj is the person’s contribution to $X^\top KV_aKX$. The matrix a$H is the inverse of $C$ for the whole sample. Subtracting sum(a$H * Cj) inside the factor of one half supplies the restricted trace correction. For the optional information calculation, Ca sums each derivative matrix across people before the last trace product. This accounts for the common fixed coefficients, which couple the people through $P$. The returned gradient points in the direction of increasing negative log likelihood.
To compare methods, evaluate each fit in the same variance-component coordinates: the distinct lower triangular entries of $G$, followed by $\sigma^2$ when it is free. The objective below evaluates the likelihood at the GLS coefficients and supplies its gradient and expected information in these coordinates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
make_lmm_objective <- function(data, REML = FALSE, scale = NULL) {
q <- data$q
k <- q * (q + 1) / 2
derivatives <- c(lapply(lmm_G_derivatives(q), function(d) list(G = d, sigma2 = 0)),
if (is.null(scale)) list(list(G = matrix(0, q, q), sigma2 = 1)))
unpack <- function(u) {
stopifnot(length(u) == k + is.null(scale))
G <- matrix(0, q, q)
G[lower.tri(G, diag = TRUE)] <- u[seq_len(k)]
list(G = G + t(G) - diag(diag(G), q),
sigma2 = if (is.null(scale)) u[k + 1] else scale)
}
list(fn = function(u) tryCatch({
a <- unpack(u)
lmm_cluster_nll(data, a$G, a$sigma2, REML)$value
}, error = function(e) Inf),
gr = function(u) {
a <- unpack(u)
lmm_nll_derivatives(data, a$G, a$sigma2, derivatives, REML)$gradient
},
expected_information = function(u) {
a <- unpack(u)
lmm_nll_derivatives(data, a$G, a$sigma2, derivatives, REML, information = TRUE)$information
}, unpack = unpack, derivatives = derivatives)
}
In make_lmm_objective(), unpack() fills the lower triangle of $G$, reflects it across the diagonal and subtracts the duplicated diagonal. Given this vector, fn evaluates the criterion at the GLS coefficients, gr returns its analytically derived gradient vector and expected_information returns expected information. fn returns infinity if a covariance matrix prevents evaluation of the negative log likelihood. The derivative and information calculations require positive definite $G$, positive residual variance and finite intermediate calculations.
One fitting function for the three routes
For the profile route, conditional-moment updates prepare the optimizer start. The default fit improves the diagonal starting precision by 25 expectation-maximization (EM) updates before calling the double-dogleg method. These fixed-count updates do not assert convergence. They use unit weights, including when the eventual fit has unequal observation weights.
The triangular matrices from the QR decompositions give the fitted coefficients, person-specific conditional means and a residual standard deviation for rescaling the conditional means. Divide each conditional mean by the residual standard deviation and stack it as a row with the rows of uncertainty from the inverse of that person’s triangular matrix. For REML, that inverse also contributes columns associated with the estimated fixed effects. If $T$ is the upper triangular matrix obtained by QR decomposition of these stacked rows, $T^\top T/m$ is the new $D$. Taking the inverse transpose of $T/\sqrt m$ gives a matrix $\Delta$ with $\Delta^\top\Delta$ equal to the updated relative precision.
1
2
3
4
5
6
7
8
lmm_unweighted <- function(data) {
data$blocks <- lapply(data$blocks, function(b) {
b$weights[] <- 1
b
})
data$weights[] <- 1
data
}
1
2
3
4
5
6
7
8
lmm_precision_em <- function(data, P, iterations, REML = FALSE, scale = NULL) {
stopifnot(is.null(scale) || !REML)
stacked <- do.call(rbind, lapply(data$blocks, function(b) cbind(b$Z, b$X, b$y)))
dims <- lmmp_dims(vapply(data$blocks, function(b) length(b$y), 0L), data$q, data$p)
Delta <- lmmp_em(stacked, dims, logchol_to_factor(precision_to_logchol(P)), iterations,
as.integer(REML), if (is.null(scale)) 0 else sqrt(scale))
crossprod(Delta)
}
In lmm_precision_em(), lmmp_em() carries out the requested number of updates from the supplied precision factor and returns the updated factor. The wrapper converts it back to the relative precision matrix with crossprod().
The completed fits use lmm_finish() to attach derivatives in the reported units and record which likelihood and covariance constraints were used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
lmm_finish <- function(fit, data, method, REML, scale, optimizer) {
derivatives <- c(lapply(lmm_G_derivatives(data$q), function(d) list(G = d, sigma2 = 0)),
if (is.null(scale)) list(list(G = matrix(0, data$q, data$q), sigma2 = 1)))
fit$gradient <- lmm_nll_derivatives(data, fit$G, fit$sigma2, derivatives, REML)$gradient
fit$optimizer <- optimizer
fit$method <- method
fit$data <- data
fit$REML <- REML
fit$scale_fixed <- !is.null(scale)
fit$covariance_summary <- lmm_covariance_summary(fit$G)
fit$criterion <- if (REML) "REML with fixed-design constant" else "full normal ML"
fit$loglik_contributions <- if (REML) NULL else
lmm_cluster_nll(data, fit$G, fit$sigma2, beta = fit$beta)$loglik_contributions
fit$approximation <- "exact normal marginal distribution"
fit$constraints <- list(random_effect_mean = rep(0, data$q),
covariance = "positive definite", residual_scale = scale)
fit
}
When an optimizer returns, lmm_finish() computes the derivative in the original units of $G$ and $\sigma^2$. For ML, the sum of the individual negative log likelihoods equals the criterion when all use the same coefficients and variance parameters. The gradient routine recomputes GLS coefficients at the returned covariance, whereas the individual contributions use fit$beta; this distinction matters if an iteration stops with coefficients from the preceding covariance. For REML the fixed-design determinant involves the whole sample. The result therefore records the restricted criterion with its fixed-design constant and gives individual likelihood contributions only for ML.
The label exact normal marginal distribution refers to analytic integration under the normal model, not to exact numerical maximization. Likewise, constraints$covariance = "positive definite" describes the fitting parameterization here; the model itself also permits positive semidefinite random-effect covariances.
The method argument of lmm_fit() selects profile optimization, ECME or scoring. The common interface returns coefficients, covariance components and numerical diagnostics for comparing the methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
lmm_fit <- function(data, method = "profile", REML = FALSE, scale = NULL,
control = list()) {
stopifnot(method %in% c("profile", "scoring", "ECME"),
is.null(scale) || (is.finite(scale) && scale > 0))
if (method == "ECME") {
stopifnot(!REML, is.null(scale))
return(lmm_ecme(data, control = control))
}
if (method == "profile") {
stopifnot(is.null(scale) || !REML, all(names(control) %in%
c("em_iterations", "optimizer", "max_iter", "max_evals", "maxit", "rel_tol",
"variance_function")))
settings <- modifyList(list(em_iterations = 25L, optimizer = "dogleg", max_iter = 50L,
max_evals = 200L, maxit = 50L, rel_tol = 1e-7, variance_function = NULL), control)
stopifnot(settings$optimizer %in% c("dogleg", "optim"))
# Obtain a precision start from the QR factors of the unweighted data.
em_data <- lmm_unweighted(data)
P <- lmm_precision_em(em_data, lmm_precision_start(em_data),
settings$em_iterations, REML, scale)
start <- precision_to_logchol(P)
# Restore the observation weights for the objective function.
setup <- lmm_profile_setup(data, REML, scale, settings$variance_function)
objective <- function(u) lmm_profile_objective(setup, u)
if (settings$optimizer == "dogleg") {
optimizer <- dogleg_minimize(start, objective,
control = list(max_iter = settings$max_iter, max_evals = settings$max_evals))
optimizer$converged <- optimizer$convergence == 0L
} else {
optimizer <- bfgs(objective, NULL, start, list(maxit = settings$maxit,
rel_tol = settings$rel_tol))
}
optimizer$start <- start
optimizer$em_iterations <- settings$em_iterations
fit <- lmm_fast_profile(data, chol2inv(logchol_to_factor(optimizer$par)), REML, scale)
} else {
stopifnot(is.null(scale), all(data$weights == 1),
all(names(control) %in% c("max_iter", "eps")))
settings <- modifyList(list(max_iter = 50L, eps = 1e-4), control)
# Score in relative-precision coordinates, then evaluate on the reported scale.
scoring <- lmm_fast(data$blocks, REML, settings$max_iter, settings$eps)
final <- lmm_cluster_nll(data, scoring$psi, scoring$sigma2, REML)
fit <- list(value = final$value, beta = final$beta, G = scoring$psi, sigma2 = scoring$sigma2)
optimizer <- new_result(c(vech(fit$G), fit$sigma2), fit$value,
converged = scoring$converged,
reason = if (scoring$converged) "small_relative_change" else "iteration_limit",
iterations = scoring$iterations, loglik = scoring$loglik, reject = scoring$reject,
scoring_matrix_factorization_failed = scoring$scoring_matrix_factorization_failed)
}
lmm_finish(fit, data, method, REML, scale, optimizer)
}
For profile fitting, setup uses the original observation weights after the unweighted EM start. The double-dogleg method receives the log-Cholesky coordinates and calculates numerical derivatives. Selecting optimizer = "optim" calls the book’s bfgs() function, rather than stats::optim(), and uses BFGS with central differences of step $10^{-3}$, at most 50 iterations and relative tolerance $10^{-7}$.
Setting variance_function = TRUE uses the weighted likelihood calculation even if all weights equal one. Here variance_function is a logical switch for the weighted calculation, not a fitted variance-function object. The function rejects variance_function = FALSE when any weight differs from one, so the fitting criterion retains the specified observation precisions. A fixed positive residual variance is an option for profile ML.
The two calls below fit the growth data by profile ML and REML.
1
2
3
4
5
6
ml_profile <- lmm_fit(growth_data)
reml_profile <- lmm_fit(growth_data, REML = TRUE)
print(rbind(ML = c(ml_profile$beta, sigma2 = ml_profile$sigma2, G11 = ml_profile$G[1, 1],
G21 = ml_profile$G[2, 1], G22 = ml_profile$G[2, 2], nll = ml_profile$value),
REML = c(reml_profile$beta, sigma2 = reml_profile$sigma2, G11 = reml_profile$G[1, 1],
G21 = reml_profile$G[2, 1], G22 = reml_profile$G[2, 2], nll = reml_profile$value)))
1
2
3
sigma2 G11 G21 G22 nll
ML 2.074547 0.4014797 0.4790506 1.145172 0.1201129 0.2810109 1229.074
REML 2.074547 0.4014797 0.4790493 1.152613 0.1199894 0.2829068 1232.825
Both profile fits estimate a population intercept of 2.074547 and a slope of 0.4014797 per unit of time. All 200 people have the same times, with $X_i=Z_i$ and unit weights. In this design GLS gives the ordinary least-squares line through the four occasion means for any $D$, which explains the identical fixed effects. The two residual variance estimates differ by about one millionth. The larger REML intercept and slope variances are visible at the displayed precision, while the intercept-slope covariance changes from 0.1201129 to 0.1199894. The latent growth model with a common residual variance gives the same ML problem for these responses. The ML value 1229.074 of the negative log likelihood and the REML value 1232.825 of the negative restricted log likelihood are values of different functions.
The Fisher scoring branch
The scoring branch accepts unit weights and estimates the residual variance. The call lmm_fast(data$blocks, REML, settings$max_iter, settings$eps) uses the routine in code/lib/lmm_fast.R. The implementation details below refer to that source file; its full definition is not repeated here.
From a least-squares start, lmmf_scoring_step() works in $-\log\sigma^2$, the log diagonal entries of the relative precision $D^{-1}$ and its untransformed off-diagonal entries. These are entries of $D^{-1}$ itself, whereas the profile method transforms its triangular factor $\Delta$. At coordinates $v$, the log likelihood score vector $S$ and expected information matrix $I$ give the Fisher scoring proposal $v+I^{-1}S$. Under REML, this matrix approximates expected information: the covariance entries use $D-U_i$, where $U_i=(D^{-1}+Z_i^\top Z_i)^{-1}$, without the fixed-effect correction used in the conditional second moment. It does not transform the exact projected information computed by lmm_nll_derivatives().
Writing $v^\star$ for the complete proposal, the negative log residual variance and the transformed precision entries follow the same line,
\[v(\alpha)=v+\alpha(v^\star-v),\qquad \alpha=1,\tfrac12,\tfrac14,\ldots.\]The routine stores the step matrix in work_gg and its product with $v$ plus $S$ in work_g. After R <- lmmf_cholesky(work_gg) and Tg <- lmmf_upper_inverse(R), the two triangular multiplications apply the inverse of work_gg to this right-hand side. The resulting work_g is a candidate vector of coordinates. The GLS helper also returns negative_half_logdet_XtWX, whose value is $-\tfrac12\log\vert X^\top W X\vert $ because it sums log diagonals of the inverse Cholesky factor.
The line tau <- tau_old + shrink * (work_g[1] - tau_old) interpolates the negative log residual variance, and the same fraction moves each precision coordinate. The assignment w2[i, i] <- exp(w2[i, i]) exponentiates the proposed log diagonal entries. If R <- lmmf_cholesky(w2) fails, shrink <- shrink / 2 halves the move and tries again. A successful factorization gives a relative covariance by inversion and the residual variance by exp(-tau).
The routine also computes an ECME candidate from the same iterate. Under REML, its second moment includes uncertainty in the fixed coefficients through the additional a[i, j] term. Failure to factor work_gg returns code 11. The outer branch if (step$status == 11L) then assigns xi <- xi_fallback and sigma2 <- sigma2_cm immediately.
A different decision comes after evaluating a scoring proposal. If ll_path[iter] < ll_path[iter - 1L] and the previous move has yet to be rejected, the routine restores sigma2 <- sigma2_cm_old and xi <- xi_fallback, marks that move rejected and reevaluates the likelihood. A positive definite proposed precision can therefore still produce a rejected scoring step.
The variable shrink is the fraction of the proposed numerical step; it does not describe shrinkage of random-effect predictions. The flag scoring_matrix_factorization_failed records a failed Cholesky factorization of work_gg, not a test of the observed likelihood Hessian.
Starting with the second iteration, the stopping rule requires, for every distinct pair $j,k$,
\[|D_{jk}^{\rm new}-D_{jk}^{\rm old}|\leq 10^{-4}|D_{jk}^{\rm old}|.\]The test abs(xi[i, j] - xi_old[i, j]) > eps * abs(xi_old[i, j]) checks each distinct entry of $D$. The inner evaluation has already executed sigma2_old <- sigma2, so the residual-variance difference in the following test is zero. With the defaults, the stopping decision depends on relative changes in $D$ of at most $10^{-4}$, with a limit of 50 iterations.
The returned beta, psi and sigma2 give the population coefficients, $G$ and residual variance. The iteration count, likelihood history and rejection indicators describe the path to them. At the iteration limit, the routine can return covariance parameters after a final step while retaining the coefficients and last likelihood from before that step. The enclosing lmm_fit() therefore evaluates lmm_cluster_nll() at the returned covariance parameters and reports the resulting GLS coefficients and criterion at that same point.
Comparing the fitted routes
Do the fitting methods agree when they optimize the same likelihood? The route table records EM updates and subsequent optimizer iterations in separate columns. For each returned fit, lmm_finish() has computed four derivatives with respect to $G_{11},G_{21},G_{22},\sigma^2$. The largest absolute derivative measures the steepest coordinate slope in those variance-component units.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ml_ecme <- lmm_fit(growth_data, method = "ECME")
ml_scoring <- lmm_fit(growth_data, method = "scoring")
reml_scoring <- lmm_fit(growth_data, method = "scoring", REML = TRUE)
fit_routes <- list(ML_profile = ml_profile, ML_scoring = ml_scoring, ML_ECME = ml_ecme,
REML_profile = reml_profile, REML_scoring = reml_scoring)
route_table <- do.call(rbind, lapply(names(fit_routes), function(name) {
fit <- fit_routes[[name]]
em <- if (fit$method == "ECME") fit$optimizer$iterations else
if (fit$method == "profile") fit$optimizer$em_iterations else 0L
data.frame(route = name, nll = fit$value, em_iterations = em,
optimizer_iterations = if (fit$method ==
"ECME") NA_integer_ else fit$optimizer$iterations,
maximum_absolute_nll_derivative = max(abs(fit$gradient)),
converged = fit$optimizer$converged)
}))
print(route_table, row.names = FALSE)
1
2
3
4
5
6
route nll em_iterations optimizer_iterations maximum_absolute_nll_derivative converged
ML_profile 1229.074 25 7 3.282353e-04 TRUE
ML_scoring 1229.074 0 7 6.475376e-10 TRUE
ML_ECME 1229.074 55 NA 4.452325e-02 TRUE
REML_profile 1232.825 25 6 1.735567e-03 TRUE
REML_scoring 1232.825 0 7 1.579306e-05 TRUE
All three ML fits give 1229.074 to three decimal places. The profile route uses 25 EM updates and seven double-dogleg iterations, scoring takes seven iterations, and ECME takes 55. Their largest absolute derivatives are about $3.3\times10^{-4}$, $6.5\times10^{-10}$ and 0.0445, respectively. ECME can take short steps while the likelihood still slopes appreciably along one component. Its convergence flag certifies that the changes met its tolerance. For REML, the profile route takes 25 EM updates and six double-dogleg iterations, and scoring takes seven iterations. Both give 1232.825, with largest absolute derivatives about $1.7\times10^{-3}$ and $1.6\times10^{-5}$. Criterion values can agree at the printed precision even when endpoint derivatives distinguish the fits.
A separate check asks whether the analytic derivative differentiates the specified likelihood. For each scoring fit, add 0.1 to each of its four original-scale coordinates. At that displaced point compare each analytic component with a central difference using the same likelihood and the same fixed-effect design. If the two derivatives are $g_a$ and $d_a$, compute $\vert g_a-d_a\vert /\max(1,\vert g_a\vert ,\vert d_a\vert )$, then take the largest ratio across components. Displacement makes this a check at a point where the derivatives can be appreciable.
1
2
3
4
5
6
7
8
nll_gradient_checks <- do.call(rbind, lapply(c(FALSE, TRUE), function(REML) {
obj <- make_lmm_objective(growth_data, REML)
u <- (if (REML) reml_scoring else ml_scoring)$optimizer$par + 0.1
do.call(rbind, lapply(c(1e-3, 1e-4, 1e-5), function(step) data.frame(REML = REML,
step = step, largest_scaled_error = max(check_grad(obj$fn, obj$gr, u,
step)$scaled_error))))
}))
print(nll_gradient_checks, row.names = FALSE)
1
2
3
4
5
6
7
REML step largest_scaled_error
FALSE 1e-03 7.750222e-06
FALSE 1e-04 7.751880e-08
FALSE 1e-05 8.103415e-09
TRUE 1e-03 7.757407e-06
TRUE 1e-04 7.764817e-08
TRUE 1e-05 3.106844e-09
Reducing the absolute step from $10^{-3}$ to $10^{-4}$ reduces the largest scaled error from about $7.8\times10^{-6}$ to $7.8\times10^{-8}$ for each criterion. At $10^{-5}$ the two errors are about $8.1\times10^{-9}$ for ML and $3.1\times10^{-9}$ for REML. These differences assess the derivative formulas at the displaced points. The stationarity checks used the analytic derivatives at the fitted points themselves.
An illustrative model for the same 200 people uses unequal precision weights and fixes the residual variance at one. Only derivatives with respect to the three free entries of $G$ remain in that calculation.
1
2
3
4
5
6
7
8
working_weights <- rep(c(1, 2, .5, 1.5), growth_data$groups)
working_data <- lmm_design(growth_data$y, growth_data$X, growth_data$Z, growth_data$id,
working_weights)
fixed_scale_fit <- lmm_fit(working_data, scale = 1)
print(c(fixed_residual_variance = fixed_scale_fit$sigma2,
first_residual_diagonal = fixed_scale_fit$sigma2 / working_weights[1],
second_residual_diagonal = fixed_scale_fit$sigma2 / working_weights[2],
maximum_absolute_nll_derivative = max(abs(fixed_scale_fit$gradient))))
1
2
3
4
fixed_residual_variance first_residual_diagonal second_residual_diagonal
1.0000000000 1.0000000000 0.5000000000
maximum_absolute_nll_derivative
0.0006841843
The profile method estimates $G$ with $\sigma^2$ fixed at the specified value one. Repeating weights 1, 2, 0.5 and 1.5 for every person gives residual variances $1/w_{ij}$, including 1 and 0.5 on the first two occasions. Omitting scale would estimate the unit-weight residual variance. The largest absolute derivative here is 0.0006841843 over the three free entries of $G$. Fixing the residual variance removes it from the set of directions along which the fitted likelihood must be stationary. The supplied profile route is translated from internal routines of nlme, and lmm_fast() from the Fortran routines of lmm (code/NOTICE.md); the nlme package provides profile fitting, and the lmm package provides ECME and Fisher scoring.
8.7 Henderson’s equations, BLUP, and empirical Bayes prediction
How steep is one person’s growth curve given only four measurements? A slope fitted separately to those four responses reflects both the person’s rate of change and the measurement errors. The mixed model gives a prediction of the person’s deviation from the population slope. At specified $\beta,G,\sigma^2$, the conditional mean of the random effects and their conditional covariance are
\[m_i=GZ_i^\top V_i^{-1}(y_i-X_i\beta),\qquad C_i=G-GZ_i^\top V_i^{-1}Z_iG.\]The residuals in this expression are measured from the population line. If its coefficients are unknown but the variance components are known, a joint system can estimate the population line by GLS and predict the deviations. Stack the $m$ vectors $b_i$ in $b$, form the block-diagonal design $Z$ from the $Z_i$, and let $\mathcal G$ be the block-diagonal covariance of $b$, with one copy of $G$ per person. The measurement-error covariance $R$ is block diagonal with blocks $R_i$. Assume $G$ and $R$ are positive definite. Conditional on $b$, the response errors are $y-X\beta-Zb$ with covariance $R$. The centered effects themselves have covariance $\mathcal G$. Multiplying the two normal densities and taking minus twice their logarithm gives, up to constants, the joint quadratic
\[Q(\beta,b)=(y-X\beta-Zb)^\top R^{-1}(y-X\beta-Zb) +b^\top\mathcal G^{-1}b.\]A person’s deviations can improve the fit to that person’s measurements, but the second term charges a larger penalty for a deviation in a direction with little between-person variation.
Differentiating $Q$ with respect to the population coefficients gives $X^\top R^{-1}(y-X\beta-Zb)=0$. Differentiation with respect to the random effects gives $Z^\top R^{-1}(y-X\beta-Zb)=\mathcal G^{-1}b$. Collecting the unknowns gives Henderson’s mixed-model equations,
\[\begin{pmatrix} X^\top R^{-1}X & X^\top R^{-1}Z\\ Z^\top R^{-1}X & Z^\top R^{-1}Z+\mathcal G^{-1} \end{pmatrix} \begin{pmatrix}\hat\beta\\ \hat b\end{pmatrix} = \begin{pmatrix}X^\top R^{-1}y\\ Z^\top R^{-1}y\end{pmatrix}.\]To read the solution, let $g=R^{-1}(y-X\hat\beta-Z\hat b)$. The second equation gives $\hat b=\mathcal G Z^\top g$, so $y-X\hat\beta=(R+Z\mathcal GZ^\top)g=Vg$. The first equation now reads $X^\top V^{-1}(y-X\hat\beta)=0$, the GLS equation for the first $p$ entries. Substituting its solution into the equation for $\hat b$ gives $GZ_i^\top V_i^{-1}(y_i-X_i\hat\beta_{\rm GLS})$ for person $i$. Thus separate conditional-mean calculations at the GLS population line give the same predictions.
With known variance components, this solution gives the best linear unbiased predictor (BLUP). It is linear in the responses and its error has mean zero under the joint distribution of random effects and residual errors for every $\beta$. This does not assert unbiasedness conditional on a particular person’s realized random effect. Among linear predictors unbiased in this sense, it has the smallest mean squared prediction error.
To see why its mean squared prediction error is smallest among linear unbiased predictors, write $A=\mathcal G Z^\top V^{-1}$. Any competing linear unbiased predictor differs from $\hat b$ by a vector $Hy$ with $HX=0$. The error $b-A(y-X\beta)$ at the true coefficients is independent of $y$. Substitution of GLS adds $AX(\hat\beta-\beta)$ to this error. Its covariance with $Hy$ is also zero, since
\[\operatorname{Cov}(\hat\beta,Hy)=(X^\top V^{-1}X)^{-1}X^\top H^\top=0.\]Using the competing predictor therefore adds $\operatorname{Var}(Hy)$ to the prediction-error covariance.
Estimating the variance components from the data and substituting them yields an empirical BLUP (EBLUP). The function blup() uses the conditional-mean expression at the parameters in a fit, returns these empirical predictions and attaches the person identifiers to the result.
1
2
3
4
5
6
blup <- function(fit) {
moments <- lmm_conditional(fit$data, fit$beta, fit$G, fit$sigma2)
list(random_effects = do.call(rbind, lapply(moments, `[[`, "mean")),
conditional_covariance = lapply(moments, `[[`, "covariance"),
ids = vapply(fit$data$blocks, `[[`, "", "id"))
}
For comparison with these separate conditional means, henderson() solves the joint system for the population coefficients and all random effects at supplied variance components.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
henderson <- function(data, G, sigma2) {
X <- do.call(rbind, lapply(data$blocks, `[[`, "X"))
Z <- as.matrix(Matrix::bdiag(lapply(data$blocks, `[[`, "Z")))
y <- unlist(lapply(data$blocks, `[[`, "y"), use.names = FALSE)
# Residual precision is the known precision weight divided by residual variance.
w <- unlist(lapply(data$blocks, `[[`, "weights"), use.names = FALSE) / sigma2
G_inverse <- as.matrix(Matrix::bdiag(rep(list(solve(G)), data$groups)))
# Assemble the two block equations in fixed-then-random order.
left <- rbind(cbind(crossprod(X, w * X), crossprod(X, w * Z)),
cbind(crossprod(Z, w * X), crossprod(Z, w * Z) + G_inverse))
right <- c(crossprod(X, w * y), crossprod(Z, w * y))
solution <- drop(solve(left, right))
list(beta = head(solution, data$p),
random_effects = matrix(tail(solution, data$groups * data$q),
data$groups, data$q, byrow = TRUE))
}
In henderson(), w contains the diagonal entries of $R^{-1}$, so multiplying each row of a design matrix by its weight applies the residual precision. The final $mq$ entries of solution come in $m$ consecutive blocks of $q$. Filling the prediction matrix by row puts each person’s deviations together.
The nine unequally weighted measurements from three people give a check with known variance components. Only $G$ and $\sigma^2$ take their generating values. The joint system has eight unknowns, two population coefficients followed by three intercept-slope pairs. Compare its first two entries with dense_ml$beta, the GLS coefficients estimated from the nine responses. Use those same GLS coefficients to compute the conditional means for the second comparison.
1
2
3
4
5
henderson_small <- henderson(unequal, G_true, sigma2_true)
conditional_small <- lmm_conditional(unequal, dense_ml$beta, G_true, sigma2_true)
print(c(fixed_effect_gap = max(abs(henderson_small$beta - dense_ml$beta)),
random_effect_gap = max(abs(henderson_small$random_effects -
do.call(rbind, lapply(conditional_small, `[[`, "mean"))))))
1
2
fixed_effect_gap random_effect_gap
2.220446e-15 1.207368e-15
The two ways of estimating the population coefficients differ by at most $2.22\times10^{-15}$. For the six entries of the three-by-two prediction matrix, the greatest absolute difference is $1.21\times10^{-15}$. Thus each person’s predicted intercept and slope agree to numerical precision despite the unequal visit patterns and weights.
Shrinkage toward the population line
How much of a person’s observed deviation should enter the prediction? Consider a single random intercept with between-person variance $\tau^2$, independent within-person errors with common variance $\sigma^2$, and $n$ measurements of the person. For a specified population line, the mean residual $\bar r_i=\mathbf 1^\top(y_i-X_i\beta)/n$ equals the person’s random intercept plus an average measurement error of variance $\sigma^2/n$. Its covariance with the random intercept is $\tau^2$. Normal conditioning therefore gives
\[\hat b_i=\frac{\tau^2}{\tau^2+\sigma^2/n}\,\bar r_i =\frac{n\tau^2}{n\tau^2+\sigma^2}\,\bar r_i.\]If the population line is unknown, using GLS to form the residuals gives the BLUP with the same multiplier. This movement toward the population mean is called shrinkage: the predicted random-effect deviation is reduced toward zero by a multiplier determined by the variance components and the number of measurements. For residual variance 1 and intercept variance 0.25, the multiplier is $n/(n+4)$.
1
2
3
4
5
tau2 <- .25
sigma2 <- 1
n <- c(1, 2, 10)
print(data.frame(cluster_size = n,
weight_on_mean_residual = n * tau2 / (n * tau2 + sigma2)))
1
2
3
4
cluster_size weight_on_mean_residual
1 1 0.2000000
2 2 0.3333333
3 10 0.7142857
One measurement gives the person’s mean residual a weight of 0.2, two give it one third, and ten give it about 0.714. For the same observed mean residual, more visits reduce the measurement-error variance in the average and reduce the shrinkage of the prediction toward zero.
Predictions for the GROWTH4 people
Return now to the random intercept and slope for the 200 people in GROWTH4. The call blup(ml_profile) uses the population coefficients, random-effect covariance and residual variance estimated by ML. Each row of random_effects predicts two deviations. The simulation also provides the pair that generated each person’s responses.
The rows of growth_truth$random_effects follow the same person order, so subtracting the two matrices compares corresponding people and effects. Squaring and averaging down a column, then taking the square root, gives the root mean squared error (RMSE) for that effect. Correlation measures how closely the predictions track variation between people on the corresponding simulated effect. These RMSEs summarize the 200 realized prediction errors in this one simulated dataset; they do not summarize errors across 200 independently generated datasets.
1
2
3
4
5
6
7
8
growth_predictions <- blup(ml_profile)
effect_names <- c("random_intercept", "random_slope")
predicted_effects <- growth_predictions$random_effects
colnames(predicted_effects) <- effect_names
truth_effects <- growth_truth$random_effects
print(rbind(RMSE = sqrt(colMeans((predicted_effects - truth_effects)^2)),
correlation = vapply(1:2, function(j) cor(predicted_effects[, j], truth_effects[, j]),
0.0)))
1
2
3
random_intercept random_slope
RMSE 0.4469341 0.2225608
correlation 0.8999573 0.9056235
The intercept RMSE is 0.447 response units and the slope RMSE is 0.223 response units per unit of time. The correlations are 0.900 and 0.906, respectively. To interpret the signs on the original time scale, inspect the first three pairs.
1
2
colnames(predicted_effects) <- paste0("predicted_", effect_names)
print(predicted_effects[1:3, ])
1
2
3
4
predicted_random_intercept predicted_random_slope
[1,] 0.1602701 -0.8125897
[2,] -0.8519334 -0.5186159
[3,] -1.4482471 -0.9495238
The first person’s predicted starting level is 0.160 units above the population intercept. The slope deviation is $-0.81259$ units per unit time. Adding it to the population slope estimate of 0.40148 gives this person a fitted slope of about $-0.411$, even though the population line rises. The next two people have negative deviations for both coefficients.
How uncertain is an individual prediction? Empirical Bayes prediction substitutes the estimated population parameters into the conditional distribution of $b_i$ given $y_i$. Its mean gives the predictions just examined. Its covariance describes the remaining uncertainty about the deviations when those parameter estimates are treated as fixed. Extract that matrix for the first person.
1
2
3
first_person_covariance <- growth_predictions$conditional_covariance[[1]]
dimnames(first_person_covariance) <- list(effect_names, effect_names)
print(first_person_covariance)
1
2
3
random_intercept random_slope
random_intercept 0.20852167 -0.07678901
random_slope -0.07678901 0.05862683
The diagonal gives an intercept variance of 0.20852 and a slope variance of 0.05863. The off-diagonal covariance of $-0.07679$ means that, given the four responses and fitted parameters, a higher plausible intercept tends to accompany a lower plausible slope. All 200 people share the same designs and precision weights, so they have the same $C_i$ even though their conditional means differ.
The conditional standard deviations, 0.457 and 0.242, are close to the RMSEs of 0.447 and 0.223 computed across the 200 simulated people. The RMSEs use the realized prediction errors. A full assessment of prediction-error variance must also account for estimating the population line and the variance components that govern shrinkage.
8.8 Checking ML and REML fits and their equivalence to latent growth models
Would arranging each person’s four responses in one row for a latent growth model change the estimated population trajectory? In the wide model the latent intercept and slope have mean $\beta$ and covariance $G$. Their loadings at time $t$ are $1$ and $t$. In the long model the same two numbers form a row of $Z$, the coefficients have population value $\beta$, and each person has a centered deviation with covariance $G$. Constrain the four measurement-error variances in the wide model to the same $\sigma^2$ and use unit weights in the long model. For either representation the marginal distribution of one person’s response vector is
\[y_i\sim N_4(Z\beta,\;ZGZ^\top+\sigma^2 I_4).\]This identity is true for every coefficient vector $\beta$, positive semidefinite $G$ and positive $\sigma^2$ under the common residual-variance restriction. Since the same 200 people contribute independently in both fits, the product of their densities gives the same full ML criterion. The stored wide growth fit used the double-dogleg method to estimate its constrained parameters. The long fit ml_profile profiled out the fixed coefficients and residual variance before optimizing the three log-Cholesky parameters of the relative precision. Each person’s design is the same, so one design block suffices to compare the two fitted mean vectors and covariance matrices.
1
2
3
4
5
6
7
saved_growth_fit <- readRDS("data/derived/ch07/growth-fit.rds")
print(c(mean_gap = max(abs(growth_data$blocks[[1]]$X %*% ml_profile$beta -
saved_growth_fit$model$mean)),
covariance_gap = max(abs(lmm_covariance(growth_data$blocks[[1]], ml_profile$G,
ml_profile$sigma2) -
saved_growth_fit$model$covariance)), full_nll_gap = ml_profile$value -
saved_growth_fit$value))
1
2
mean_gap covariance_gap full_nll_gap
1.442153e-08 2.498618e-06 3.724381e-10
The maximum differences are $1.44\times10^{-8}$ across the four means and $2.50\times10^{-6}$ across the covariance entries. The last subtraction has a direction. The full negative log likelihood at the mixed-model fit exceeds the value at the growth fit by $3.72\times10^{-10}$. These numbers describe the two returned estimates. The equality of the model likelihoods follows from the distribution above.
Reference fits and optimizer records
Do other mixed-model implementations recover the same estimates and predictions? The book’s profiled likelihood is translated from internal routines of nlme (code/NOTICE.md), so agreement with lme() checks that translation, while lmer() uses a different mixed-model fitting implementation and provides a further comparison (Section E.3). For each of ML and REML, give lme4::lmer() and nlme::lme() the long responses, the population intercept and time slope, and a correlated intercept and slope by person.
The first comparison concerns the returned estimates and predictions. The calculation also records how lme() reached its fit: nlme_traced() captures the starting coordinates and optimizer result around its call to nlminb(), and iteration_row() puts the two implementations’ counters and coordinate differences in a common row.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
.libPaths(c(".R-library", .libPaths()))
reference_rows <- list()
iteration_rows <- list()
nlme_capture <- new.env()
nlme_traced <- function(expr) {
suppressMessages(trace("nlminb", quote({
assign("start",start,envir=nlme_capture)
assign("state",serialize(get("lmeSt",environment(objective)),NULL),envir=nlme_capture)
assign("control",control,envir=nlme_capture)
}),
exit = quote(assign("run", returnValue(), envir = nlme_capture)), print = FALSE,
where = asNamespace("stats")))
on.exit(suppressMessages(untrace("nlminb", where = asNamespace("stats"))))
fit <- expr
list(fit = fit, start = nlme_capture$start, run = nlme_capture$run,
state=nlme_capture$state,control=nlme_capture$control)
}
iteration_row <- function(label, own, traced) data.frame(fit = label,
iterations = own$optimizer$iterations, reference_iterations = traced$run$iterations,
criterion_calls = own$optimizer$evaluations[[1]],
reference_criterion_calls = traced$run$evaluations[[1]],
difference_requests = own$optimizer$evaluations[[2]],
reference_difference_requests = traced$run$evaluations[[2]],
start_gap = max(abs(own$optimizer$start - traced$start)),
par_gap = max(abs(own$optimizer$par - traced$run$par)))
For the estimates, extract the fixed coefficients and the random-effect covariance on the response scale. Squaring each package’s residual standard deviation converts it to the variance returned by lmm_fit(). Match the rows of the predicted intercepts and slopes by person identifier before subtracting them. The first four gap columns give absolute differences or their maxima. Adding the package log likelihood to the book’s negative log likelihood gives nll_gap, the signed difference between negative log likelihoods. The REML comparison uses the same fixed design throughout and includes the fixed-design constant.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
for (restricted in c(FALSE, TRUE)) {
label <- if (restricted) "REML" else "ML"
own <- if (restricted) reml_profile else ml_profile
ref <- lme4::lmer(response ~ time + (1 + time | person), data = growth_long,
REML = restricted)
traced <- nlme_traced(nlme::lme(response ~ time, random = ~ time | person,
data = growth_long, method = label))
ref_nlme <- traced$fit
iteration_rows[[label]] <- iteration_row(label, own, traced)
for (package in c("lme4", "nlme")) {
reference_fit <- if (package == "lme4") ref else ref_nlme
beta <- if (package ==
"lme4") lme4::fixef(reference_fit) else nlme::fixef(reference_fit)
G <- if (package == "lme4") as.matrix(lme4::VarCorr(reference_fit)$person) else
as.matrix(nlme::getVarCov(reference_fit, type = "random.effects"))
predicted <- if (package == "lme4") as.matrix(lme4::ranef(reference_fit)$person) else
as.matrix(nlme::ranef(reference_fit))
# Put both prediction matrices in the same person order.
predicted <- predicted[match(blup(own)$ids, rownames(predicted)), , drop = FALSE]
reference_rows[[paste(label, package)]] <- data.frame(criterion = label,
package = package,
beta_gap = max(abs(own$beta - beta)), G_gap = max(abs(own$G - G)),
sigma2_gap = abs(own$sigma2 - sigma(reference_fit)^2),
prediction_gap = max(abs(blup(own)$random_effects - predicted)),
nll_gap = own$value + as.numeric(logLik(reference_fit)))
}
}
reference_table <- do.call(rbind, reference_rows)
print(reference_table, row.names = FALSE)
1
2
3
4
5
criterion package beta_gap G_gap sigma2_gap prediction_gap nll_gap
ML lme4 2.273737e-13 1.498180e-05 2.720892e-06 1.516473e-05 -4.367394e-09
ML nlme 3.108624e-15 4.397037e-06 5.225867e-09 6.379094e-06 -4.286221e-09
REML lme4 8.548717e-14 3.823707e-05 7.687778e-06 4.887710e-05 -2.885781e-08
REML nlme 1.154632e-14 1.630954e-09 2.168837e-10 1.128654e-09 6.821210e-13
Across the ML and REML fits from lmer(), the largest discrepancies are about $2.3\times10^{-13}$ for the fixed coefficients, $3.8\times10^{-5}$ for $G$, $7.7\times10^{-6}$ for the residual variance and $4.9\times10^{-5}$ for the predictions. The criterion gaps have magnitudes $4.4\times10^{-9}$ under ML and $2.9\times10^{-8}$ under REML.
For ML, lmm_fit() gives a residual variance of 0.4790505634 and lme() gives 0.4790505686 after squaring its residual standard deviation. The difference is $5.23\times10^{-9}$. The corresponding maximum differences in $G$ and the predictions are $4.40\times10^{-6}$ and $6.38\times10^{-6}$. Under REML the largest $G$ difference is $1.63\times10^{-9}$ and the criterion gap is $6.82\times10^{-13}$.
The optimizer comparisons are on a different scale. Their three coordinates are the two log diagonals and the off-diagonal entry of the upper triangular Cholesky factor of the relative precision.
1
print(do.call(rbind, iteration_rows), row.names = FALSE)
1
2
3
4
5
6
fit iterations reference_iterations criterion_calls reference_criterion_calls difference_requests
ML 7 6 11 10 45
REML 6 6 10 10 33
reference_difference_requests start_gap par_gap
33 1.665335e-16 1.102416e-05
33 5.551115e-17 9.377367e-10
The ML runs start within $1.67\times10^{-16}$ in these coordinates and finish with a maximum coordinate difference of $1.10\times10^{-5}$. The book fit takes one more ML iteration, while both REML fits take six. After the weighted-fit comparisons, recorded evaluation paths are used to investigate this difference in ML stopping counts.
The scoring and ECME methods also provide a check in which the iteration history can be compared directly. Stack the responses in person order, give every row the appropriate subject ID, and select both columns of X_sorted for the fixed effects and for the random effects. The functions fastml(), fastrml() and ecmeml() in lmm then use the same observations and designs as the corresponding book fits. The book’s scoring fits use lmm_fast(), which is translated from the Fortran routines of lmm (code/NOTICE.md), so their agreement, including the iteration counts, checks that translation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
sizes <- vapply(growth_data$blocks, function(b) length(b$y), 0L)
subject <- rep(seq_along(sizes), sizes)
y_sorted <- unlist(lapply(growth_data$blocks, `[[`, "y"), use.names = FALSE)
X_sorted <- do.call(rbind, lapply(growth_data$blocks, `[[`, "X"))
# Compare each scoring method at its own returned estimates.
scoring_reference <- do.call(rbind, lapply(c(FALSE, TRUE), function(restricted) {
own <- if (restricted) reml_scoring else ml_scoring
invisible(capture.output(ref <- if (restricted)
lmm::fastrml(y_sorted, subject, X_sorted, 1:2, 1:2) else
lmm::fastml(y_sorted, subject, X_sorted, 1:2, 1:2)))
data.frame(route = if (restricted) "REML scoring" else "ML scoring",
iterations = own$optimizer$iterations, reference_iterations = ref$iter,
beta_gap = max(abs(own$beta - ref$beta)), G_gap = max(abs(own$G - ref$psi)),
sigma2_gap = abs(own$sigma2 - ref$sigma2),
loglik_gap = max(abs(own$optimizer$loglik - ref$loglik)))
}))
invisible(capture.output(ecme_reference <- lmm::ecmeml(y_sorted, subject, X_sorted, 1:2,
1:2)))
scoring_reference <- rbind(scoring_reference, data.frame(route = "ML ECME",
iterations = ml_ecme$optimizer$iterations, reference_iterations = ecme_reference$iter,
beta_gap = max(abs(ml_ecme$beta - ecme_reference$beta)), G_gap = max(abs(ml_ecme$G -
ecme_reference$psi)),
sigma2_gap = abs(ml_ecme$sigma2 - ecme_reference$sigma2), loglik_gap = NA_real_))
print(scoring_reference, row.names = FALSE)
1
2
3
4
route iterations reference_iterations beta_gap G_gap sigma2_gap loglik_gap
ML scoring 7 7 5.329071e-15 1.332268e-15 1.942890e-15 1.762146e-12
REML scoring 7 7 1.199041e-14 2.398082e-14 2.553513e-15 2.785328e-12
ML ECME 55 55 1.776357e-14 5.329071e-15 2.220446e-16 NA
Scoring takes seven iterations in each implementation under both criteria. Both ML ECME fits take 55. The largest difference in a reported parameter is about $2.4\times10^{-14}$. The scoring log likelihood histories agree within $2.8\times10^{-12}$. For ECME the history comparison is unavailable, as indicated by NA.
Precision weights and a fixed residual variance
Assigning weights 1, 2, 0.5 and 1.5 to each person’s four visits checks how the implementations interpret residual precision. In a weighted fit, the observation precisions enter the measurement-error covariance $R_i$. In lmm_fit() a known weight $w_{ij}$ gives visit $j$ of person $i$ a residual variance of $\sigma^2/w_{ij}$. For lmer(), use working_weights and estimate the residual variance by ML.
1
2
3
4
5
weighted_fit <- lmm_fit(working_data)
weighted_reference <- lme4::lmer(response ~ time + (1 + time | person),
data = growth_long, weights = working_weights, REML = FALSE)
print(c(weighted_nll_gap = weighted_fit$value + as.numeric(logLik(weighted_reference)),
weighted_variance_gap = abs(weighted_fit$sigma2 - sigma(weighted_reference)^2)))
1
2
weighted_nll_gap weighted_variance_gap
-6.409664e-09 2.336863e-06
The weighted negative log likelihood difference is $-6.41\times10^{-9}$ and the residual variances differ by $2.34\times10^{-6}$.
In lme(), varFixed() takes a covariate proportional to residual variance, so its input is the reciprocal of the precision weight. Make one comparison estimating the residual variance at unit weight and another fixing it at one. The latter pairs fixed_scale_fit with lmeControl(sigma = 1). The sigma argument of lmeControl() is a residual standard deviation, while scale in lmm_fit() is a variance. For a fixed variance $s$, the corresponding nlme setting is sigma = sqrt(s); using one in this example conceals that difference in units.
1
2
3
4
5
6
7
8
9
growth_weighted <- transform(growth_long, inverse_weight = 1 / working_weights)
weighted_traced <- nlme_traced(nlme::lme(response ~ time, random = ~ time | person,
data = growth_weighted, method = "ML", weights = nlme::varFixed(~ inverse_weight)))
fixed_traced <- nlme_traced(nlme::lme(response ~ time, random = ~ time | person,
data = growth_weighted, method = "ML", weights = nlme::varFixed(~ inverse_weight),
control = nlme::lmeControl(sigma = 1)))
print(rbind(iteration_row("weighted ML", weighted_fit, weighted_traced),
iteration_row("weighted ML, residual variance 1", fixed_scale_fit, fixed_traced)),
row.names = FALSE)
1
2
3
4
5
6
fit iterations reference_iterations criterion_calls reference_criterion_calls
weighted ML 11 11 20 20
weighted ML, residual variance 1 11 11 16 16
difference_requests reference_difference_requests start_gap par_gap
57 57 1.665335e-16 1.876645e-08
45 45 4.440892e-16 8.644383e-09
Within each weighted comparison, the two implementations report identical optimizer counts. In the order iterations, recorded criterion calls and numerical-derivative requests, the triples are (11, 20, 57) for the estimated residual variance and (11, 16, 45) for the fixed residual variance.
Differences between the recorded optimization paths
Why did the unweighted ML profile fit take seven iterations while lme() took six to reach nearly the same likelihood? The full ML triples were (7, 11, 45) and (6, 10, 33). For REML both were (6, 10, 33). An iteration can require multiple evaluations. A numerical-derivative request and a call recorded in the optimizer’s criterion counter also describe different parts of the calculation.
Eight recorded ML optimizations locate where their evaluation paths first differ. In the section script code/practice/8.8.R, each row of settings chooses a source for the starting vector, an implementation of the profiled likelihood criterion and a solver. The two choices for each setting give eight combinations. The following block reads those saved comparisons. In the table, reference identifies the corresponding package calculation and book the calculation implemented in this chapter.
The criterion values use the QR form of the profiled negative log likelihood, with its omitted constant. Restoring $N[1+\log(2\pi/N)]/2$ with $N=800$ gives the full normal ML negative log likelihood near 1229.074.
1
2
3
comparison <- readRDS("data/derived/ch08/dogleg-ml-comparison.rds")
settings <- comparison$settings
print(settings, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
starting_coordinates likelihood_implementation solver iterations
book book book 7
reference book book 7
book reference book 6
reference reference book 6
book book reference 7
reference book reference 7
book reference reference 6
reference reference reference 6
criterion_calls numerical_derivative_requests function_evaluations
11 45 57
12 39 52
10 33 44
10 33 44
11 45 57
12 39 52
10 33 44
10 33 44
reason book_at_end reference_at_end
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
relative convergence (4) 2767.768 2767.768
Runs 1 and 8 reproduce the counts for the original book and package fits. The function_evaluations column counts actual calls to the recorded profiled likelihood function, including numerical differentiation. There are 57 such calls for run 1 and 44 for run 8. Each row of a path contains all three trial log-Cholesky parameters and the value returned for them. Inspect the first call in every path.
1
2
3
4
5
6
7
evaluations <- do.call(rbind, lapply(seq_along(comparison$paths), function(i) {
path <- comparison$paths[[i]]
data.frame(run = i, evaluation = seq_len(nrow(path)), log_diagonal_1 = path[, 1],
log_diagonal_2 = path[, 2], off_diagonal = path[, 3], criterion = path[, 4],
row.names = NULL)
}))
print(subset(evaluations, evaluation == 1), row.names = FALSE)
1
2
3
4
5
6
7
8
9
run evaluation log_diagonal_1 log_diagonal_2 off_diagonal criterion
1 1 -0.4127072 0.266801 -0.2830423 2767.768
2 1 -0.4127072 0.266801 -0.2830423 2767.768
3 1 -0.4127072 0.266801 -0.2830423 2767.768
4 1 -0.4127072 0.266801 -0.2830423 2767.768
5 1 -0.4127072 0.266801 -0.2830423 2767.768
6 1 -0.4127072 0.266801 -0.2830423 2767.768
7 1 -0.4127072 0.266801 -0.2830423 2767.768
8 1 -0.4127072 0.266801 -0.2830423 2767.768
The starts look identical at this print precision. The terminal coordinates reveal some variation, particularly in the off-diagonal. The next extract puts each terminal vector alongside the two values obtained by evaluating it under both likelihood implementations.
1
2
3
ends <- data.frame(run = seq_len(nrow(settings)), comparison$endpoints,
book_criterion = settings$book_at_end, reference_criterion = settings$reference_at_end)
print(ends, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
run log_diagonal_1 log_diagonal_2 off_diagonal book_criterion
1 -0.4128184 0.2667063 -0.2828665 2767.768
2 -0.4128174 0.2667058 -0.2828631 2767.768
3 -0.4128199 0.2667056 -0.2828555 2767.768
4 -0.4128199 0.2667059 -0.2828555 2767.768
5 -0.4128184 0.2667063 -0.2828665 2767.768
6 -0.4128174 0.2667058 -0.2828631 2767.768
7 -0.4128199 0.2667056 -0.2828555 2767.768
8 -0.4128199 0.2667059 -0.2828555 2767.768
reference_criterion
2767.768
2767.768
2767.768
2767.768
2767.768
2767.768
2767.768
2767.768
All eight terminal criteria round to 2767.768 in both columns. To distinguish paths that happen to end at nearly the same value, compare two runs that differ in just one setting. Search the common part of the paths for the first row where any coordinate or the criterion differs. If one path ends before the other, its first missing row is a difference as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
first_differences <- do.call(rbind, lapply(seq_len(nrow(comparison$first_differences)),
function(i) {
pair <- comparison$first_differences[i, ]
left <- comparison$paths[[pair$a]]
right <- comparison$paths[[pair$b]]
common <- seq_len(min(nrow(left), nrow(right)))
# A difference in the criterion or any coordinate changes the recorded path.
differences <- which(rowSums(left[common, , drop = FALSE] != right[common, ,
drop = FALSE]) > 0)
first <- NA_integer_
if (length(differences)) {
first <- differences[1]
} else if (nrow(left) != nrow(right)) {
first <- length(common) + 1L
}
stopifnot(identical(as.integer(first), as.integer(pair$first)))
data.frame(left_run = pair$a, right_run = pair$b, first_evaluation = first)
}))
print(first_differences, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
left_run right_run first_evaluation
1 2 1
1 3 2
2 4 2
3 4 1
1 5 NA
2 6 NA
5 6 1
3 7 NA
5 7 2
4 8 NA
6 8 2
7 8 1
Changing the start alone in runs 1 and 2 gives a difference at evaluation 1. Changing the likelihood implementation alone in runs 1 and 3 gives the first difference at evaluation 2. With only the solver changed, runs 1 and 5 have identical recorded paths, including their lengths. The extra digits for the first pair show what the shorter display concealed.
1
2
3
pair <- first_differences[which(!is.na(first_differences$first_evaluation))[1], ]
print(subset(evaluations, run %in% c(pair$left_run, pair$right_run) &
evaluation == pair$first_evaluation), row.names = FALSE, digits = 17)
1
2
3
4
5
6
run evaluation log_diagonal_1 log_diagonal_2 off_diagonal
1 1 -0.41270720901354724 0.26680099475228991 -0.28304234104044296
2 1 -0.41270720901354707 0.26680099475228991 -0.28304234104044307
criterion
2767.7682159192004
2767.7682159192018
The first and third coordinates already differ in their last digits before an iteration is taken. With a common start, the choice of likelihood implementation can instead change a subsequent evaluation. On these data those differences suffice to change the stopping counts while leaving the printed endpoint likelihood the same.
Random-intercept models for chicks and plants
Two observed animal and plant datasets distributed with R extend the comparison to other repeated measurements. ChickWeight records body weight in grams at recorded ages within each chick. The R dataset documentation describes the experiment. Dividing age in days by ten gives day10; denote this time in ten-day units by $t$. For diet $d$, write the population mean as $\alpha_d+\delta_d t+\gamma t^2$. Here $\alpha_d$ is mean weight at birth, and $\delta_d$ is the initial rate of change in grams per ten days. The common quadratic coefficient $\gamma$ is in grams per squared ten-day unit; the growth rate at time $t$ is $\delta_d+2\gamma t$, so it need not remain constant. Under treatment coding, day10 * Diet represents these diet-specific intercepts and linear coefficients by a reference diet and differences from it. The I(day10^2) term adds the common curvature.
A chick’s mean-zero random intercept shifts its whole diet-specific curve by the same number of grams. Its variance describes between-chick differences after accounting for diet and age, while $\sigma^2$ describes response variation around that chick’s curve. Both variances are in squared grams.
CO2 records carbon dioxide uptake rates in grass plants at several concentrations, not repeated ages. The R dataset documentation describes the experiment. Uptake is measured in $\mu\mathrm{mol}\,\mathrm{m}^{-2}\mathrm{s}^{-1}$. The mean uses factor(conc) to give each concentration its own effect and Type * Treatment to allow the chilling difference to depend on geographic origin. Under treatment coding, the intercept is the mean at the reference concentration, origin and treatment. Each concentration coefficient is a mean difference from the reference concentration at the same origin and treatment. The origin coefficient compares origins under the reference treatment; the treatment coefficient compares treatments for the reference origin. Their interaction is the difference between the two origins’ treatment differences. All these coefficients are in uptake units.
A plant’s mean-zero random intercept shifts its expected uptake equally at every concentration. Its variance describes between-plant variation remaining after the fixed effects, and $\sigma^2$ describes variation around a plant’s own expected uptake. Both are in squared uptake units.
Both models assume independent groups, normal random intercepts and independent normal residuals of common variance within groups, independent of the random intercepts. The REML comparisons use lmer() for chicks and statmod::mixedModel2() for plants, whose single random grouping factor and residual error give the two variance components it supports. The mixedModel2() documentation allows its block component varcomp[2] to be negative, whereas the random-intercept model here requires a nonnegative intercept variance. Its parameter space is therefore broader; the positive plant estimate below permits comparison at the reported fit, but does not make the constraints identical in general.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
chick <- as.data.frame(datasets::ChickWeight)
chick$day10 <- chick$Time / 10
chick_formula <- weight ~ day10 * Diet + I(day10^2)
X_chick <- model.matrix(chick_formula, chick)
chick_data <- lmm_design(chick$weight, X_chick, matrix(1, nrow(chick), 1), chick$Chick)
chick_fit <- lmm_fit(chick_data, REML = TRUE)
chick_ref <- lme4::lmer(weight ~ day10 * Diet + I(day10^2) + (1 | Chick),
data = chick, REML = TRUE)
co2 <- as.data.frame(datasets::CO2)
co2_formula <- uptake ~ factor(conc) + Type * Treatment
X_co2 <- model.matrix(co2_formula, co2)
co2_data <- lmm_design(co2$uptake, X_co2, matrix(1, nrow(co2), 1), co2$Plant)
co2_fit <- lmm_fit(co2_data, REML = TRUE)
co2_ref <- statmod::mixedModel2(co2_formula, random = Plant, data = co2)
secondary_table <- rbind(
data.frame(data = "ChickWeight", N = chick_data$N, groups = chick_data$groups,
fixed_rank = chick_data$p, sigma2 = chick_fit$sigma2,
random_intercept_variance = chick_fit$G[1, 1],
residual_gap = abs(chick_fit$sigma2 - sigma(chick_ref)^2),
random_gap = abs(chick_fit$G[1, 1] - lme4::VarCorr(chick_ref)$Chick[1, 1])),
data.frame(data = "CO2", N = co2_data$N, groups = co2_data$groups,
fixed_rank = co2_data$p, sigma2 = co2_fit$sigma2,
random_intercept_variance = co2_fit$G[1, 1],
residual_gap = abs(co2_fit$sigma2 - co2_ref$varcomp[1]),
random_gap = abs(co2_fit$G[1, 1] - co2_ref$varcomp[2])))
print(secondary_table, row.names = FALSE)
1
2
3
data N groups fixed_rank sigma2 random_intercept_variance residual_gap random_gap
ChickWeight 578 50 9 608.88217 545.61129 1.358449e-06 1.538969e-05
CO2 84 12 10 11.75749 3.37092 6.654755e-09 2.453433e-08
The chick fit uses 578 observations on 50 chicks and nine fixed coefficients. Its residual variance is 608.88217 and its between-chick intercept variance is 545.61129, within about $1.36\times10^{-6}$ and $1.54\times10^{-5}$ of the lmer() estimates. With 84 observations on 12 plants and ten fixed coefficients, the corresponding plant variances are 11.75749 and 3.37092. The differences from mixedModel2() are about $6.65\times10^{-9}$ and $2.45\times10^{-8}$. For a comparison of optimizer counts on these designs, fit each model with lme().
1
2
3
4
5
6
chick_traced <- nlme_traced(nlme::lme(chick_formula, random = ~ 1 | Chick, data = chick,
method = "REML"))
co2_traced <- nlme_traced(nlme::lme(co2_formula, random = ~ 1 | Plant, data = co2,
method = "REML"))
print(rbind(iteration_row("ChickWeight REML", chick_fit, chick_traced),
iteration_row("CO2 REML", co2_fit, co2_traced)), row.names = FALSE)
1
2
3
4
5
6
fit iterations reference_iterations criterion_calls reference_criterion_calls
ChickWeight REML 1 1 2 2
CO2 REML 2 2 4 4
difference_requests reference_difference_requests start_gap par_gap
1 1 2.081668e-16 2.081668e-16
5 5 2.220446e-16 8.801715e-11
Both chick fits in this table use one iteration, two criterion calls and one numerical-derivative request. Both plant fits use two iterations, four calls and five requests. These counts compare the book profile fits with the traced lme() fits. Because the book’s profile route is translated from nlme, agreement checks that translation under the specified models. Human longitudinal responses can share this grouping structure, but their mean trajectories and residual covariance require assumptions appropriate to their measurements and visit schedules.
ML and REML across simulated samples
How much does estimating the population mean change the variance estimates across independent growth samples? For the balanced study every person has the same full-rank design $X_i=Z_i=Z$, unit weights and residual covariance $\sigma^2 I_4$. Put $A=(Z^\top Z)^{-1}$ and $a_i=AZ^\top y_i$. These two least-squares coefficients for person $i$ have mean $\beta$ and covariance $B=G+\sigma^2 A$.
Project the person’s responses onto the two orthogonal directions perpendicular to the columns of $Z$, using an orthonormal basis. The resulting contrasts have mean zero and covariance $\sigma^2 I_2$. Their covariance with $a_i$ vanishes, so the normal contrasts are independent of the person coefficients. The sum of squared contrasts divided by $2m$ is the unconstrained estimate of $\sigma^2$ under either criterion, where $m$ is the number of people.
The formulas below describe mixed-model optima when this estimate is positive and the resulting $\hat G$ is positive definite for both ML and REML. If a candidate violates the covariance constraint, the constrained fit requires a separate calculation at a singular $G$.
All information about the population mean lies in the $a_i$. Let $\bar a$ be the mean vector across people and $T=\sum_i(a_i-\bar a)(a_i-\bar a)^\top$ their centered sum of products. ML estimates $B$ by $T/m$. For REML, take $m-1$ orthonormal contrasts of the $m$ person vectors across people. Each contrast has mean zero and covariance $B$, the contrasts are independent, and their outer products sum to $T$. Their normal likelihood therefore gives $T/(m-1)$ for $B$. Subtracting the common $\hat\sigma^2 A$ gives
\[\hat G_{\rm ML}=T/m-\hat\sigma^2 A,\qquad \hat G_{\rm REML}=T/(m-1)-\hat\sigma^2 A,\qquad \hat G_{\rm REML}-\hat G_{\rm ML}= \frac{\hat G_{\rm ML}+\hat\sigma^2 A}{m-1}.\]This is a relation between fits in one sample. To gauge its magnitude, substitute the generating values on the right. At times zero through three, $A_{11}=0.7$ and $A_{22}=0.2$. For 200 people the intercept-variance change is on the scale of $(1+0.49\times0.7)/199=0.00675$ and the slope-variance change on the scale of $(0.25+0.49\times0.2)/199=0.00175$, both rounded.
The next calculation reads saved results for 200 simulated datasets, each fit by ML and REML scoring, giving 400 fits. For each method, the mean estimate minus its generating value estimates bias. The Monte Carlo standard error (MCSE) of that mean is the sample standard deviation divided by the square root of the number of contributing datasets.
For the paired comparison, order the REML rows to match the ML replication identifiers before forming any differences. The summaries retain fits marked converged, and the paired summary retains datasets for which both methods meet their stopping rule. If some fits are excluded, the reported means describe the retained fits and must be read with the failure counts; the near-boundary flag is recorded but is not an exclusion condition.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
lmm_study_results <- read.csv("data/derived/ch08/recovery-replications.csv")
recovery_truth <- c(G11 = 1, G21 = .15, G22 = .25, sigma2 = .49)
recovery <- do.call(rbind, lapply(c("ML", "REML"), function(method) {
rows <- subset(lmm_study_results, criterion == method)
do.call(rbind, lapply(names(recovery_truth), function(name) {
estimates <- rows[[name]][rows$converged]
data.frame(criterion = method, parameter = name, valid = length(estimates),
bias = mean(estimates) - recovery_truth[name], MCSE = sd(estimates) /
sqrt(length(estimates)), row.names = NULL)
}))
}))
ml_rows <- subset(lmm_study_results, criterion == "ML")
reml_rows <- subset(lmm_study_results, criterion == "REML")
stopifnot(!anyDuplicated(ml_rows$replication), !anyDuplicated(reml_rows$replication))
reml_rows <- reml_rows[match(ml_rows$replication, reml_rows$replication), , drop = FALSE]
stopifnot(identical(ml_rows$replication, reml_rows$replication))
# Subtract the two estimates only for pairs with both fits converged.
paired <- ml_rows$converged & reml_rows$converged
paired_summary <- do.call(rbind, lapply(names(recovery_truth), function(name) {
d <- reml_rows[[name]][paired] - ml_rows[[name]][paired]
data.frame(parameter = name, pairs = length(d), REML_minus_ML = mean(d),
MCSE = sd(d) / sqrt(length(d)))
}))
print(c(replications = 200, failed_fits = sum(!lmm_study_results$converged),
near_boundary = sum(lmm_study_results$boundary, na.rm = TRUE),
distinct_replicates = length(unique(lmm_study_results$replication))))
1
2
replications failed_fits near_boundary distinct_replicates
200 0 0 200
All 400 fits in the 200 pairs met the scoring stopping rule. No fit met the near-boundary condition that the smallest eigenvalue of $\hat G$ was at most $10^{-7}$. Each bias therefore uses 200 estimates. This eigenvalue threshold is a numerical diagnostic in the present parameter units. It is not a scale-independent definition of a boundary fit or the same test as lme4::isSingular().
1
print(recovery, row.names = FALSE)
1
2
3
4
5
6
7
8
9
criterion parameter valid bias MCSE
ML G11 200 0.0029841876 0.010237823
ML G21 200 -0.0017631234 0.003556156
ML G22 200 -0.0032104605 0.002521971
ML sigma2 200 0.0001180115 0.002348985
REML G11 200 0.0097483723 0.010287754
REML G21 200 -0.0017570887 0.003572970
REML G22 200 -0.0014777234 0.002534087
REML sigma2 200 0.0001180202 0.002348985
All eight estimated biases have magnitude below twice their respective MCSEs. Pairing answers a different question. Match by replication ID, subtract ML from REML within each dataset and calculate the MCSE from the standard deviation of those 200 differences.
1
print(paired_summary, row.names = FALSE)
1
2
3
4
5
parameter pairs REML_minus_ML MCSE
G11 200 6.764185e-03 5.058352e-05
G21 200 6.034731e-06 1.714831e-05
G22 200 1.732737e-03 1.233062e-05
sigma2 200 8.759801e-09 3.809380e-10
The REML estimate of the intercept variance exceeds the ML estimate by 0.006764185 on average (MCSE 0.00005058352), and that of the slope variance by 0.001732737 (MCSE 0.00001233062). Both means are close to the magnitudes suggested by the between-person divisor. For the covariance the mean change is $6.03\times10^{-6}$ (MCSE $1.71\times10^{-5}$). At these times $A_{21}=-0.3$, so the generating terms $0.15+0.49(-0.3)$ nearly cancel in the covariance change, while the two diagonal changes add positive contributions.
The mean residual-variance change is $8.76\times10^{-9}$ (MCSE $3.81\times10^{-10}$). The within-person contrasts give exactly the same residual variance when the positive residual-variance estimate and both positive definite covariance estimates satisfy the conditions just derived. The tiny difference in the study summarizes the numerically stopped fits. The reported MCSE describes variation of the paired mean across repeated samples. Scoring stops on a relative change in $D$ of at most $10^{-4}$, which gives no error bound in residual-variance units.
For the simulated growth data, the four responses per person supply the same marginal ML information whether expressed through a latent intercept and slope in wide form or shared random effects in long form. Switching from ML to REML changes how the between-person covariance is estimated. Iteration counts describe how a particular calculation reached its estimates.