Post

Inference, diagnosis, and model comparison

A researcher may want to know whether an item distinguishes clearly between examinees of different abilities. In a simulated sample of 800 examinees, this relationship is summarized by an estimated discrimination, the slope of the log odds of a correct answer with respect to ability. With another sample, both the answers and the estimate could change, so the size of the slope alone cannot establish how precisely it is known. Its interpretation also depends on whether the model accounts for the response patterns. Systematic departures from the model can weaken a substantive conclusion even when the estimate is precise. The chapter takes up these questions in turn: standard errors, tests and their calibration, residuals and local dependence, identification, and comparisons between models, ending with simulation checks of the procedures themselves.

15.1 Standard errors from observed, expected, and missing information, Louis’s formula, and supplemented EM

If another 800 examinees from the same population answered the same eight items, their answers would give a new estimate of the same population slope. One independent observation here is a person’s vector of eight answers. Write $\theta$ for the vector of free item parameters, $\ell_i(\theta)$ for the log probability of person $i$’s vector after integration over ability, and $\ell(\theta)$ for the sum over the $n$ people. As the number of independent people increases, a consistent maximum likelihood (ML) estimator is asymptotically normal under a correctly specified, sufficiently smooth and identifiable model, provided the population parameter permits small changes in every free direction and the expected information per person is positive definite. A first-order expansion of the score at the population parameter expresses estimation error as inverse information times the sum of person scores. Since their summed variance equals the expected information, the inverse estimates the sampling covariance. If $I_1$ denotes expected information for one person, the covariance is approximately $I_1^{-1}/n$. Inverting the information calculated from the full $\ell$ already accounts for all $n$ people.

Which curvature measures the information in those answers? The observed information $I_o$ is the negative Hessian of $\ell$ evaluated at the fitted parameters. Expected information averages this negative Hessian over response samples drawn from the fitted model. Both calculations integrate out ability before assessing the information in the responses. A different expectation arises if the answers are fixed and only ability varies. For the joint log density of answers and ability, let $s_c$ and $H_c$ denote its score and Hessian in the same item coordinates. The marginal score is the conditional mean of $s_c$ given the answers. Differentiating that mean differentiates both $s_c$ and the conditional density of ability given the answers. Differentiating the score contributes the conditional mean Hessian. Differentiating that density contributes the conditional covariance of the score. On changing signs to obtain information, Louis’s formula therefore subtracts this covariance from the conditional mean of $-H_c$. The missing information in this identity concerns the unobserved abilities even when every item response was recorded.

For one distinct answer pattern $y$ occurring $f$ times, let $z_q$ be the ability value at integration point $q$ and $w_q$ its posterior probability under the quadrature approximation, given all eight answers. The two-parameter logistic (2PL) model gives item $j$ success probability $p_j(z_q)$ with log odds $a_j z_q+d_j$, where $a_j$ is the slope and $d_j$ the intercept. Responses are independent conditional on the same ability. Ability has mean zero and variance one under the standard normal distribution. Thus $d_j$ is the log odds at mean ability, and $a_j$ is the change in log odds for an increase of one ability standard deviation.

At this point the two score components are $z_q[y_j-p_j(z_q)]$ and $y_j-p_j(z_q)$. Stacking the pairs across items gives the column vector $s_q$. Its posterior mean is $\bar s=\sum_q w_qs_q$. With $H_{c,q}$ the complete-data Hessian for this pattern at point $q$, the $f$ independent examinees with this pattern contribute the following term to the observed information

\[I_o(y)= f\sum_q w_q(-H_{c,q}) - f\left(\sum_q w_q s_qs_q^\top-\bar s\bar s^\top\right).\]

Even for identical answers, plausible abilities can give different derivatives of the complete-data log likelihood with respect to an item slope. Their disagreement contributes to the subtracted covariance.

To obtain a standard error for the slope, invert the information for the fitted vector of slopes and intercepts, then take the square root of the slope’s diagonal entry in the covariance. Taking the reciprocal of a single diagonal information entry would treat the other coefficients as known.

These calculations are carried out for the eight-item test described at the start of the chapter. From the book directory, load the IRT8-2 responses into Y and fit the items with a standard normal ability distribution. The accelerated and ordinary EM fits below start the item slopes at $0.5\times1.702$ and set the intercepts from each item’s observed proportion of zeros. Integration uses 61 equally spaced points from $-6$ to $6$ with weights proportional to the standard normal density.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

Y <- readRDS("data/source/ch10/IRT8-2.rds")

multidim_em() fits the items by EM. The equally spaced, truncated grid is distinct from Gauss-Hermite quadrature.

Here SEM means supplemented EM for standard-error calculation, whereas Chapter 14 also used SEM for stochastic EM. Near a fixed point, part of a perturbation to the input coefficients persists after one ordinary EM cycle. The derivative of the EM map measures this persistence.

Write $M(\theta)$ for one ordinary EM cycle and $D$ for its derivative at a fixed point, with $D_{kj}=\partial M_j/\partial\theta_k$. Input coordinates index rows and output coordinates index columns. Let $I_c$ be the complete-data information at that same point and $I$ the identity matrix. For an exact, differentiable EM map at a regular interior fixed point, this row convention gives missing information $D I_c$ and observed information $I_o=(I-D)I_c$. Its inverse is therefore $I_c^{-1}(I-D)^{-1}$. This order of multiplication matters: the full map derivative and complete-data information determine the covariance, not the diagonal persistence rates alone. The numerical calculation below estimates this relation using finite perturbations and a numerically optimized M step.

To compare supplemented-EM standard errors with the complete-data and Louis results, fit the same responses a second time with acceleration off and a tighter tolerance. multidim_sem_information() uses this second fit to estimate observed information from the EM updates. The fit’s design retains the response layout and the fixed/free parameter positions, while par_vec contains the fitted values in that layout. Selecting par_vec[design$is_free] removes the fixed asymptote and group entries and leaves $(a_1,d_1,\ldots,a_8,d_8)$. The information matrices use this same order, so their diagonal entries correspond to the printed item coordinates.

1
2
3
4
5
6
7
# Accelerated EM supplies both complete-data and Louis information.
irt_fit <- multidim_em(Y,1L)
complete_information <- -multidim_complete_hessian(irt_fit)
louis_information <- multidim_louis_information(irt_fit)
# Use an ordinary EM history to estimate the derivative of its map.
sem_fit <- multidim_em(Y,1L,conv_tol=1e-5,n_cycles=1000L,accelerate=FALSE)
sem <- multidim_sem_information(sem_fit)

At the accelerated fit, multidim_complete_hessian() uses the final E-step counts saved with the returned coefficients and grid. The Louis score calculation evaluates the posterior probabilities at these same coefficients and nodes. The two information terms therefore refer to the same fitted conditional distribution. Both functions are in code/lib/multidim_items.R.

1
2
3
4
5
6
7
8
9
10
11
multidim_complete_hessian <- function(fit) {
  design <- fit$design
  L <- design$item_length
  H <- matrix(0, length(fit$par_vec), length(fit$par_vec))
  for (j in seq_len(design$J)) {
    index <- (j - 1L) * L + seq_len(L)
    H[index, index] <- multidim_item_derivatives(fit$par_vec[index], fit$grid$Theta,
      fit$final_expected_counts[, 2L * j - 1L:0L, drop = FALSE], TRUE)$hess
  }
  H[design$is_free, design$is_free]
}

For each item, multidim_item_derivatives() (Section 14.4) evaluates the Hessian of the expected complete-data log likelihood at the grid points fit$grid$Theta, using the expected category counts of the final E step; the function returns the block for the free coordinates.

Inside the imported multidim_louis_information() function, w contains the node probabilities for one occurrence. Row $q$ of S gives the components of $s_q$. Across patterns, info_grad_p adds the frequency-weighted means of the outer products, and info_grad adds the frequency-weighted outer products of the means. The function subtracts info_grad_p and adds info_grad to the complete-data information.

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
multidim_louis_information <- function(fit) {
  design <- fit$design
  is_free <- design$is_free
  L <- design$item_length
  Theta <- fit$grid$Theta
  prior <- fit$grid$Prior
  item_probs <- multidim_category_probabilities(fit$par_vec, design, Theta)
  tab <- fit$patterns$tab
  freq <- fit$patterns$freq
  p <- sum(is_free)
  pairs <- p * p
  inner <- matrix(0, nrow(tab) * nrow(Theta), pairs)
  outer_rows <- matrix(0, nrow(tab), pairs)
  for (pat in seq_len(nrow(tab))) {
    one <- list(tab = tab[pat, , drop = FALSE], freq = 1)
    w <- multidim_estep(item_probs, prior, one)$r1[, which(tab[pat, ] == 1)[1]]
    S <- matrix(0, nrow(Theta), length(fit$par_vec))
    for (j in seq_len(design$J)) {
      index <- (j - 1L) * L + seq_len(L)
      par <- fit$par_vec[index]
      n_dim <- ncol(Theta)
      g <- multidim_inverse_logit(par[n_dim + 2L])
      u <- multidim_inverse_logit(par[n_dim + 3L])
      z <- rep(par[n_dim + 1L], nrow(Theta))
      for (k in seq_len(n_dim)) z <- z + par[k] * Theta[, k]
      z <- pmin(pmax(z, -35), 35)
      p_core <- 1 / (1 + exp(-z))
      P <- g + (u - g) * p_core
      q_core <- 1 - p_core
      score_core <- tab[pat, 2L * j] / P - tab[pat, 2L * j - 1L] / (1 - P)
      S[, index[n_dim + 1L]] <- (u - g) * p_core * q_core * score_core
      for (k in seq_len(n_dim)) S[, index[k]] <- Theta[, k] * p_core * q_core * (u - g) * score_core
    }
    S <- S[, is_free, drop = FALSE]
    rows <- (pat - 1L) * nrow(Theta) + seq_len(nrow(Theta))
    weight <- freq[pat] * w
    inner[rows, ] <- (S[, rep(seq_len(p), times = p), drop = FALSE] *
      S[, rep(seq_len(p), each = p), drop = FALSE]) * weight
    grad <- drop(crossprod(S, w))
    outer_rows[pat, ] <- (grad[rep(seq_len(p), times = p)] * grad[rep(seq_len(p), each = p)]) *
      freq[pat]
  }
  info_grad_p <- matrix(drop(crossprod(inner, rep(1, nrow(inner)))), p, p)
  info_grad <- matrix(drop(crossprod(outer_rows, rep(1, nrow(outer_rows)))), p, p)
  -multidim_complete_hessian(fit) - info_grad_p + info_grad
}

For each response pattern, w contains the posterior probabilities of the grid points from multidim_estep() (Section 14.4). At each point the columns of S contain the derivatives of the pattern’s log probability with respect to the intercepts and slopes: for item $j$ with asymptotes $g$ and $u$, logistic core $p$ and probability $P=g+(u-g)p$, the intercept component is $(u-g)p(1-p)\lbrace y_j/P-(1-y_j)/(1-P)\rbrace $ and each slope component multiplies it by the trait coordinate. The rows of inner are the weighted outer products $s_qs_q^\top$, and outer_rows contains the outer product of each pattern’s posterior mean score.

Row $k$ of the returned delta_mat estimates row $k$ of $D$: the changes across output coordinates per unit change in input $k$. Its diagonal describes persistence along each coordinate during one EM update. The output name fraction_missing stores these diagonal derivatives; with several jointly estimated parameters, they are not the fractions by which each reported variance increases. That interpretation requires the full information and derivative matrices.

The function vcov_information() of Section 14.6 inverts each information matrix after its checks; a matrix that fails them gives unavailable covariance and standard-error entries with its eigenvalues and a reason. The next call prints all 16 item coordinates. The two displays below excerpt item 1, separating the last column.

1
2
3
4
5
6
7
item_coordinate <- paste0(rep(c("a","d"),ncol(Y)),rep(seq_len(ncol(Y)),each=2))
print(data.frame(coordinate=item_coordinate,estimate=irt_fit$par_vec[irt_fit$design$is_free],
  complete_data_SE=vcov_information(complete_information)$se,
  Louis_SE=vcov_information(louis_information)$se,
  SEM_estimate=sem_fit$par_vec[sem_fit$design$is_free],
  SEM_SE=vcov_information(sem$information)$se,
  fraction_missing=diag(sem$delta_mat)))
1
2
3
4
   coordinate   estimate complete_data_SE   Louis_SE SEM_estimate     SEM_SE
1          a1  0.7589228       0.09202025 0.13092849    0.7589177 0.12440043
2          d1  1.0460907       0.08649372 0.09402221    1.0460824 0.09567677

1
2
3
4
   fraction_missing
1        0.51009232
2        0.07996868

The Louis calculation subtracts missing information from complete-data information at the same fitted coefficients. The complete-data standard errors omit uncertainty about the unobserved abilities and serve as comparison values. Supplemented EM uses the separately fitted, unaccelerated solution. Compare the returned coordinates and cycle counts before comparing its standard errors with the Louis calculation. The eigenvalues below describe the missing-information matrix in the stated parameter coordinates.

1
2
3
4
print(c(EM_cycles=irt_fit$cycles,SEM_EM_cycles=sem_fit$cycles,window_from=sem$window[1],
  window_to=sem$window[2],unsettled_rates=sem$unsettled))
print(eigen(complete_information-louis_information,
  symmetric=TRUE,only.values=TRUE)$values)
1
2
3
4
5
6
7
      EM_cycles   SEM_EM_cycles     window_from       window_to unsettled_rates 
             16              31               1              12               0
 [1] 9.647767e+01 7.150631e+01 6.916788e+01 6.058648e+01 5.782591e+01
 [6] 5.705362e+01 5.227149e+01 4.660415e+01 3.932667e+01 3.060089e+00
[11] 4.720050e-01 7.943069e-02 2.074007e-03 5.415310e-05 2.607268e-05
[16] 3.546345e-07

The accelerated fit stopped after 16 cycles when every coefficient changed by less than $10^{-4}$. The eigenvalues of the missing information range from 96.48 down to about $3.5\times10^{-7}$ in these coordinates. These are absolute curvatures on the stated parameter scale, not unit-free proportions of information lost; rescaling coordinates changes their values.

For a symmetric positive definite information matrix $A$, its upper triangular Cholesky factor $R$ satisfies $R^\top R=A$. Solving successively with $R^\top$ and $R$ gives the columns of the inverse without using a determinant. If the optimization used coordinates $u$ and the reported parameters are $\theta=g(u)$, let $J$ be the full matrix of derivatives of $g$ at the estimate. The first-order change in the reported vector is $J$ times the change in $u$, so its covariance is $JA^{-1}J^\top$. For example, item difficulty $-d_j/a_j$ is the ability at which the success probability is one half and depends on both coordinates. The variance of its estimate therefore includes the covariance between the slope and intercept estimates as well as their two variances. For the printed slopes and intercepts, $J$ is the identity. The difficulty transformation requires a nonzero slope; division by a slope near zero can also make this first-order approximation unreliable.

Supplemented EM from the unaccelerated fit

To estimate the EM-map derivative, acceleration must be off, so use sem_fit, which stopped at tolerance $10^{-5}$ after 31 ordinary cycles. Its returned item 1 slope was 0.7589177. The derivative is defined at an ordinary EM fixed point, where a further update leaves the coefficients unchanged to the required accuracy. The function uses earlier EM iterates to perturb one input coordinate at a time, applies an ordinary EM update, and measures the changes in all output coordinates. Read the three blocks below as the definition of the supplemented-EM function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
multidim_sem_information <- function(fit, se_tol = .001) {
  # Select a window from the fitted log likelihoods: from the last cycle whose likelihood
  # ratio is not positive (or the first) to the first whose ratio exceeds 1 - se_tol.
  ratio <- exp(c(NA, fit$ll_path) - c(fit$ll_path, NA))
  from <- suppressWarnings(max(which(ratio <= 0)))
  if (!is.finite(from)) from <- 1L
  to <- min(which(ratio >= 1 - se_tol))
  if (fit$cycles <= 5L) stop("SEM can not be computed due to short EM history")
  design <- fit$design; is_free <- design$is_free
  # The last stored EM vector is the reference of the difference quotients.
  history <- fit$em_path; ml_estimates <- history[nrow(history), ]
  est_index <- which(is_free)
  delta_mat <- t(vapply(est_index, function(k) {
    rij <- 1
    rate_path <- rep(NA_real_, length(est_index))
    converged <- FALSE
    for (cycles in from:to) {
      par_vec <- ml_estimates
      # Displace input k only. Recalculate the expected response counts.
      par_vec[k] <- history[cycles, k]
      e <- multidim_estep(multidim_category_probabilities(par_vec, design, fit$grid$Theta),
        fit$grid$Prior,
        fit$patterns)

The returned parameter vector, also saved as the last row of em_path, supplies the reference ml_estimates. For this fit the window from row 1 to row 12 begins with the starting vector and ends at the first likelihood ratio $\exp(\ell_{t-1}-\ell_t)$ reaching 0.999, where $\ell_t$ is the log likelihood at the start of cycle $t$. For input coordinate $k$, the first block substitutes its value in one window row for its reference value. With all other inputs at the reference, it takes one E step.

The M step minimizes the negative expected complete-data log likelihood using these counts and its gradient while all free item coefficients vary. The derivative calculation inherits the numerical precision of this BFGS minimization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
      fn <- function(p) {
        lp <- par_vec
        lp[is_free] <- p
        value <- sum(e$r1 *
          suppressWarnings(log(multidim_category_probabilities(lp, design, fit$grid$Theta))))
        -ifelse(is.finite(value), value, -1e100)
      }
      # Differentiate with respect to each free item coefficient.
      gr <- function(p) {
        lp <- par_vec
        lp[is_free] <- p
        g <- numeric(length(lp))
        L <- design$item_length
        for (j in seq_len(design$J)) {
          index <- (j - 1L) * L + seq_len(L)
          g[index] <- multidim_item_derivatives(lp[index], fit$grid$Theta,
            e$r1[, 2L * j - 1L:0L, drop = FALSE],
            FALSE)$grad
        }
        -g[is_free]
      }
      par_vec[is_free] <- bfgs(fn, gr, par_vec[is_free], list(maxit = 50L))$par

For each output coordinate, divide its change from the reference by the signed displacement of input $k$. Follow that ratio across the window. The calculation accepts a ratio when its change falls below 0.001 and uses its latest value if it never settles. Here unsettled_rates = 0 means that each displaced input had all its ratios accepted by this rule. The acceptance flags retain an earlier agreement even if later ratios move again. A zero displacement leaves the ratio undefined; unsettled ratios leave the corresponding derivative estimates unresolved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
      rate_last <- rij
      denom <- history[cycles, k] - ml_estimates[k]
      if (denom == 0) {
        converged <- FALSE
        break
      }
      # Each output change has the same input displacement in its denominator.
      rij <- (par_vec[is_free] - ml_estimates[is_free]) / denom
      converged <- converged | abs(rij - rate_last) < se_tol
      newly <- converged & is.na(rate_path)
      rate_path[newly] <- rij[newly]
      if (!anyNA(rate_path)) break
    }
    # Use the last ratio for any output still missing in this row.
    unset <- is.na(rate_path); rate_path[unset] <- rij[unset]
    c(rate_path, all(converged))
  }, numeric(length(est_index) + 1L)))
  settled <- delta_mat[, ncol(delta_mat)] == 1
  delta_mat <- delta_mat[, -ncol(delta_mat), drop = FALSE]
  # Form information with input coordinates indexing the rows of DM.
  info <- solve(-solve(multidim_complete_hessian(fit)) %*% solve(diag(ncol(delta_mat)) - delta_mat))
  list(information = (info + t(info)) / 2, delta_mat = delta_mat, window = c(from, to),
    unsettled = sum(!settled))
}

For item 1 the slope and intercept diagonal entries of delta_mat are 0.510 and 0.080. The final block uses the complete-data information at the unaccelerated fit and the estimated $D$ in the covariance product $I_c^{-1}(I-D)^{-1}$ derived above. The function inverts that product and averages the resulting information with its transpose. The item 1 slope estimates from the two fits agree to four decimal places, but the supplemented standard error depends on these estimated rates.

Expected and observed information in a structural equation model

The full structural equation model from Chapter 7 permits a different information comparison at one complete-data ML fit. Nine responses measure three latent variables. Responses 1–3 measure $\xi$, responses 4–6 measure $\eta_1$, and responses 7–9 measure $\eta_2$. For the factor $f_{k(j)}$ measured by response $j$, the measurement equation is $Y_j=\nu_j+\lambda_j f_{k(j)}+\varepsilon_j$. The structural equations are

\[\xi=u,\qquad \eta_1=a\xi+\zeta_1,\qquad \eta_2=c'\xi+b\eta_1+\zeta_2.\]

The normal variables $u,\zeta_1,\zeta_2$ have means zero and variances $\phi,\psi_1,\psi_2$, respectively, and are mutually independent. The nine normal measurement errors have means zero and separate variances, and are independent of the latent disturbances and one another. The marker loadings for responses 1, 4 and 7 are fixed to one. These constraints give each latent variable the unit of its marker response; they do not fix all latent variances to one. The covariance between latent variables follows from the structural paths and disturbance variances.

There are 30 free parameters: six remaining loadings, three structural coefficients, nine measurement-error variances, three latent disturbance variances and nine response intercepts. In the saved fit, a, b and cprime name the structural coefficients, phi names the variance of $\xi$, and psi1 and psi2 name the disturbances of the two endogenous variables. The prefixes loading, residual and intercept identify the measurement parameters. A structural coefficient describes a conditional linear relation in the specified latent-variable units. A causal interpretation requires assumptions beyond these equations.

Read the saved complete-data fit of FULLSEM9 from Chapter 7. The likelihood and derivatives use the generic Gaussian reticular action model (RAM) functions already introduced. Run code/examples/ch15-application.R from the book directory. Its setup loads those functions, reads data/derived/ch07/full-fits.rds and saves the comparison under data/derived/ch15. This calculation reuses the fitted parameter vector; it does not estimate a replacement model or use the incomplete-data fit.

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
# start_application() loads the functions, sets the random-number methods and creates the folders.
# record_check() and record_review() save checks and review flags; neither changes an estimate.
source("code/lib/application_run.R", local = TRUE)
application <- start_application(15L)
record_check <- application$record_check
record_review <- application$record_review

full_sem_path <- file.path("data/derived/ch07", "full-fits.rds")
full_sem_fit <- readRDS(full_sem_path)$full
full_sem_theta <- full_sem_fit$optimizer$par
stopifnot(length(full_sem_theta) == 30L,
  all(c("a", "b", "cprime", "phi", "psi1", "psi2") %in% names(full_sem_fit$theta)),
  max(abs(full_sem_theta - full_sem_fit$theta)) < 1e-12)
full_sem_objective <- make_ram_objective(full_sem_fit$spec, full_sem_fit$data, "ML",
                                         ram_identity(full_sem_fit$spec))
full_sem_expected <- ram_information(full_sem_theta, full_sem_fit$spec, full_sem_fit$data$n)
full_sem_observed <- num_hess(full_sem_objective$fn, full_sem_theta,
                              gr = full_sem_objective$gr, step = .001)$hessian
full_sem_observed_half <- num_hess(full_sem_objective$fn, full_sem_theta,
                                   gr = full_sem_objective$gr, step = .0005)$hessian
full_sem_expected_cov <- vcov_information(full_sem_expected)
full_sem_observed_cov <- vcov_information(full_sem_observed)
full_sem_half_cov <- vcov_information(full_sem_observed_half)
stopifnot(full_sem_expected_cov$valid, full_sem_observed_cov$valid, full_sem_half_cov$valid)
full_sem_labels <- sub("^residual([0-9]+)$", "residual_variance\\1", names(full_sem_fit$theta))
full_sem_se_table <- data.frame(parameter = full_sem_labels,
  estimate = unname(full_sem_fit$theta), expected_SE = full_sem_expected_cov$se,
  observed_SE = full_sem_observed_cov$se,
  relative_SE_difference = full_sem_observed_cov$se / full_sem_expected_cov$se - 1)
print(full_sem_se_table, 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
28
29
30
31
          parameter    estimate expected_SE observed_SE relative_SE_difference
           loading2  0.85838266  0.05313104  0.05396050           1.561168e-02
           loading3  0.71333815  0.04743240  0.04778377           7.407751e-03
           loading5  0.93482131  0.05136734  0.05106115          -5.960774e-03
           loading6  0.73830896  0.04446951  0.04447026           1.684916e-05
           loading8  0.80241012  0.05193982  0.05158639          -6.804692e-03
           loading9  0.68375804  0.04839527  0.04867750           5.831762e-03
                  a  0.62854208  0.05570631  0.05485455          -1.529016e-02
                  b  0.48462486  0.06541238  0.06558309           2.609668e-03
             cprime  0.25291744  0.06483669  0.06469781          -2.141986e-03
 residual_variance1  0.57236989  0.05743332  0.05812980           1.212675e-02
 residual_variance2  0.44198925  0.04324430  0.04361255           8.515662e-03
 residual_variance3  0.47724725  0.03875045  0.03872280          -7.135944e-04
 residual_variance4  0.42399444  0.04672416  0.04659067          -2.856963e-03
 residual_variance5  0.51780422  0.04754638  0.04738243          -3.448334e-03
 residual_variance6  0.50166282  0.03934328  0.03939144           1.224100e-03
 residual_variance7  0.49853508  0.05609018  0.05597476          -2.057800e-03
 residual_variance8  0.48422636  0.04360114  0.04342091          -4.133499e-03
 residual_variance9  0.54718824  0.04243240  0.04254565           2.668848e-03
                phi  0.98336417  0.10177899  0.10217348           3.875988e-03
               psi1  0.63253044  0.06864119  0.06939183           1.093576e-02
               psi2  0.52817058  0.06409594  0.06405686          -6.096588e-04
         intercept1  0.14944473  0.05578054  0.05578054          -4.440892e-16
         intercept2  0.21600108  0.04830222  0.04830222          -5.551115e-16
         intercept3 -0.09872463  0.04421840  0.04421840          -6.661338e-16
         intercept4  0.51086665  0.05375905  0.05375905          -8.881784e-16
         intercept5  0.33951479  0.05310494  0.05310494          -8.881784e-16
         intercept6  0.11602442  0.04600484  0.04600484          -5.551115e-16
         intercept7 -0.02104470  0.05442289  0.05442289           2.220446e-16
         intercept8  0.51933028  0.04725992  0.04725992          -3.330669e-16
         intercept9  0.32754421  0.04486603  0.04486603          -6.661338e-16

full_sem_fit$spec contains the measurement and structural restrictions, while data contains the complete-sample Gaussian summaries and sample size. The identity map makes the optimizer coordinates equal to the reported parameters. Expected information is computed analytically at that fitted vector. Observed information differences the analytic negative log likelihood gradient with steps of 0.001, and the second calculation halves that step to examine sensitivity. Each inverse information matrix estimates the covariance of all 30 coordinates together. Inverting a smaller structural block by itself would omit uncertainty shared with the measurement parameters.

The table gives each estimate and both standard errors on its reported scale. The last column is the observed-information standard error divided by the expected-information standard error, minus one. It therefore measures a relative difference, not a percentage-point change in the parameter. For example, a value of 0.02 would indicate a standard error two percent larger. The largest absolute relative difference is about 1.56 percent, for loading2: its standard error changes from 0.05313 to 0.05396. For the structural path $a$, the two standard errors are 0.05571 and 0.05485, a decrease of about 1.53 percent. All nine intercept pairs agree to the displayed precision.

The nine response means are freely estimated, while the latent means are fixed to zero. At the Gaussian ML solution, the information block for these free means is $n\Sigma^{-1}$ for both expected and observed information. Their cross-information with covariance parameters vanishes when the mean residual is zero. The resulting agreement of intercept standard errors is a consequence of that structure, rather than a general equality of the two information matrices.

The structural paths also define direct, indirect and total effects from $\xi$ to $\eta_2$:

\[h(\theta)=\begin{pmatrix}c'\\ ab\\ c'+ab\end{pmatrix}, \qquad \widehat{\operatorname{Cov}}\{h(\hat\theta)\} =H\widehat{\operatorname{Cov}}(\hat\theta)H^\top, \quad H=\left.\frac{\partial h}{\partial\theta^\top}\right|_{\hat\theta}.\]

For the indirect effect, the derivatives with respect to $a$ and $b$ are $b$ and $a$, respectively. Thus its variance includes $2ab\operatorname{Cov}(\hat a,\hat b)$ as well as the two individual variance terms. The total effect also involves the covariances of $\hat c^{\prime}$ with those path estimates. Constructing the full gradient matrix preserves these terms.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
full_sem_effect_gradient <- matrix(0, 3L, length(full_sem_theta),
  dimnames = list(c("direct", "indirect", "total"), names(full_sem_fit$theta)))
full_sem_effect_gradient["direct", "cprime"] <- 1
full_sem_effect_gradient["indirect", c("a", "b")] <- full_sem_fit$theta[c("b", "a")]
full_sem_effect_gradient["total", ] <- colSums(full_sem_effect_gradient[c("direct", "indirect"), , drop = FALSE])
full_sem_effect <- c(direct = unname(full_sem_fit$theta["cprime"]),
  indirect = unname(full_sem_fit$theta["a"] * full_sem_fit$theta["b"]),
  total = unname(full_sem_fit$theta["cprime"] + full_sem_fit$theta["a"] * full_sem_fit$theta["b"]))
full_sem_effects <- data.frame(effect = names(full_sem_effect), estimate = unname(full_sem_effect),
  expected_SE = sqrt(diag(full_sem_effect_gradient %*% full_sem_expected_cov$covariance %*%
                           t(full_sem_effect_gradient))),
  observed_SE = sqrt(diag(full_sem_effect_gradient %*% full_sem_observed_cov$covariance %*%
                           t(full_sem_effect_gradient))))
print(full_sem_effects, row.names = FALSE)
saveRDS(list(source = full_sem_path, parameters = full_sem_se_table, effects = full_sem_effects,
  expected_information = full_sem_expected, observed_information = full_sem_observed,
  observed_information_half_step = full_sem_observed_half),
  file.path("data/derived/ch15", "ch15-full-sem-information.rds"))
1
2
3
4
   effect  estimate expected_SE observed_SE
   direct 0.2529174  0.06483669  0.06469781
 indirect 0.3046071  0.04665936  0.04676638
    total 0.5575246  0.05623567  0.05579597

The estimated direct, indirect and total effects are 0.25292, 0.30461 and 0.55752, respectively. Their observed-information standard errors are 0.06470, 0.04677 and 0.05580. The three estimates have units of $\eta_2$ per unit of $\xi$. The two standard-error columns apply the same delta-method calculation to the two covariance estimates. They concern repeated-sample uncertainty in the estimated effects, conditional on the model. They do not represent variation in individual latent scores. A product such as $\hat a\hat b$ can also have an asymmetric sampling distribution, so this first-order standard error does not establish the adequacy of a symmetric interval in a small sample.

Outside the displayed code, the application script records three further checks. With record_check(), it compares the recomputed expected standard errors with those saved in Chapter 7 and compares the observed standard errors at the two differentiation steps; with record_review(), it checks the complete-data score. The recomputed expected standard errors equal those saved in Chapter 7. Halving the differentiation step changes the observed standard errors by at most about $3.28\times10^{-6}$ relative to their first values, and the maximum absolute score is $3.40\times10^{-5}$. These checks connect the chapters to the same numerical fit. Agreement between expected and observed standard errors at this sample does not establish nominal interval coverage; that question requires the repeated-sample evidence considered elsewhere in the book.

Returning to the eight-item test

In the eight-item IRT example, the posterior node probabilities also quantify uncertainty about one examinee’s ability for a given response pattern. With the eight answers fixed and the item parameters set to their ML estimates, the expected a posteriori (EAP) estimate is the posterior mean $\bar z=\sum_q w_qz_q$. Its posterior variance is $\sum_q w_q(z_q-\bar z)^2$. Two examinees with the same pattern have the same spread of plausible abilities under this model. The sampling covariance of the item estimates concerns new calibration samples, with new patterns and new frequencies. The posterior standard deviation beside a person’s EAP score thus omits the sampling uncertainty in the fitted items.

Wald standard errors require identified parameters, an adequately located likelihood maximum, and information that is positive definite on the free coordinates. The usual large-sample approximation also assumes that sufficiently small changes in every free direction remain admissible. The supplied multidim_louis_information() follows the Louis calculation in mirt; the source correspondence is recorded in code/NOTICE.md.

15.2 Sandwich covariance estimates and cluster contributions

A positive definite information matrix describes the curvature of the fitted log likelihood. Another way to estimate sampling variation is to measure how much the score varies from one independent group to the next. In the binary random-intercept model, each of $G$ independent groups contributes a vector $y_i$ of eight responses. Let $\theta$ contain the fixed coefficients and the parameter for the random-intercept scale. The contribution $\ell_i(\theta)$ of group $i$ to the marginal log likelihood is the logarithm of the joint probability of $y_i$ after integrating over the group’s random intercept. Differentiating this contribution gives the column score vector $U_i(\theta)$. At the fitted point $\hat\theta$, the group scores sum to zero up to numerical error, although a change in a coefficient that increases one group’s log likelihood can decrease another’s. Define the summed sensitivity $A$ as the negative derivative of the total score at this point,

\[A=-\left.\sum_{i=1}^G \frac{\partial U_i(\theta)}{\partial\theta^\top}\right|_{\hat\theta}.\]

For a likelihood score, this is the observed information for all the groups together.

Let $\theta_0$ be the parameter at which the expected total score is zero. A first-order expansion of the sample equation around $\theta_0$ gives $\hat\theta-\theta_0\approx A^{-1}\sum_i U_i(\theta_0)$. Suppose the independent groups have mean-zero scores with finite second moments, no group dominates the sum, and the limiting sensitivity per group is nonsingular. The variance of the sum then adds the group variances. Estimate it by $B=\sum_i U_i U_i^\top$, now evaluating each score at $\hat\theta$. The resulting sandwich covariance is $A^{-1}BA^{-\top}$, where $A^{-\top}$ is the transpose of the inverse. Under these conditions it estimates variation around $\theta_0$ despite a misspecified working covariance. It does not ensure that $\theta_0$ equals the intended population parameter when misspecification changes the mean score equation. The outer factors convert changes in the score into changes in the parameter estimate; $B$ estimates the variance of the summed score. Statistical software calls these factors the bread and meat of the sandwich, respectively. No additional division by the number of groups is needed with these sums. To see why the order of addition matters, let $r_{ij}$ be response $j$’s contribution to the score for group $i$. Its score outer product expands as

\[U_iU_i^\top = \sum_j r_{ij}r_{ij}^\top+ \sum_{j\ne k}r_{ij}r_{ik}^\top,\qquad U_i=\sum_j r_{ij}.\]

For each pair of distinct responses, both orders enter the second sum. If U is the matrix with one group score per row, crossprod(U) includes both sums. Applying the same operation to the matrix of response contributions $r_{ij}$ omits the second sum even when every contribution was computed correctly.

For the binary model, let $z$ have a standard normal distribution and write the random intercept as $b=\exp(\lambda)z$, with $\lambda$ the log standard deviation. For response $j$ in group $i$, let $x_{ij}$ contain an intercept and the observed covariate. The conditional log odds are $x_{ij}^\top\beta+b$, where $\beta$ contains the two fixed coefficients. The fixed intercept is the log odds at covariate zero and $b=0$. The fixed slope changes the log odds per covariate unit with $b$ fixed. The variance $\exp(2\lambda)$ measures between-group variation in the shared log-odds shift. Responses are independent conditional on their group intercept.

At quadrature node $z_q$, write $b_q=\exp(\lambda)z_q$ and let $p_{ijq}$ be the corresponding success probability. The Bernoulli log probability has derivative $y_{ij}-p_{ijq}$ with respect to the log odds. The derivative of the log odds is $x_{ij}$ for $\beta$ and $b_q$ for $\lambda$, since $z_q$ remains fixed. If $w_{iq}$ is the posterior probability of node $q$ given the group’s eight responses, the contribution of response $j$ to the score of group $i$ is

\[r_{ij}=\sum_q w_{iq}(y_{ij}-p_{ijq}) \begin{pmatrix}x_{ij}\\ b_q\end{pmatrix}.\]

To obtain $w_{iq}$, multiply the quadrature weight by the eight conditional response probabilities and normalize over nodes. All eight rows use the same posterior node probabilities. Their sum gives the derivative of the group’s marginal log likelihood in all three coordinates. Each row therefore depends on all eight responses. These rows are contributions to a joint group score, not scores of independent one-response marginal likelihoods.

Group and row sums in a binary random-intercept fit

Use the binary GLMM80 data to compare the two sums at one fitted point. From the book directory, load the grouped observations and the saved seven-node adaptive quadrature fit. The responses and identifiers also appear in data/source/ch09/GLMM80-binary.rds. At seven adaptive nodes, the estimated slope was 0.7212408. The variance calibration$G[1] is the square of the estimated random-intercept standard deviation, 0.6057595. Half the log variance gives $\lambda$. Use normal_rule() to construct a fixed 61-node Gauss-Hermite rule for the standard normal distribution for the score calculation. At the same nodes, glmm_scalar() supplies the negative marginal log likelihood in scalar$fn and its gradient in scalar$gr. Start the BFGS minimization at the adaptive fit. The local object name calibration refers to that previously fitted model; it does not name another calibration procedure.

1
2
3
4
5
6
7
8
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/integration.R")
source("code/lib/glmm.R")
source("code/lib/inference.R")
rule <- normal_rule(61L)
1
2
3
4
5
6
gl <- readRDS("data/derived/ch09/fits.rds")
grouped <- gl$binary; calibration <- gl$adaptive
u_fit <- c(calibration$beta,.5*log(calibration$G[1]))
scalar <- glmm_scalar(grouped,61L,"GHQ")
root <- bfgs(scalar$fn,scalar$gr,u_fit)
u <- root$par

Treat the returned coefficients root$par as a candidate. To check the score equation, divide the largest absolute component of the total score by 80. If it exceeds $10^{-8}$, try the Newton step and successively halved steps, choosing the one that gives the smallest residual and improves on the current point.

1
2
3
4
5
6
7
8
9
10
11
12
13
norm_score <- function(v) max(abs(scalar$gr(v)))/grouped$groups
for (iteration in seq_len(12L)) {
  if (norm_score(u)<=1e-8) break
  # Use the Hessian of the negative log likelihood for the Newton direction.
  direction <- solve(num_hess(scalar$fn,u,gr=scalar$gr)$hessian,scalar$gr(u))
  candidates <- lapply(2^-(0:15),function(step) u-step*direction)
  best <- which.min(vapply(candidates,norm_score,0.0))
  if (!length(best) || norm_score(candidates[[best]])>=norm_score(u)) break
  u <- candidates[[best]]
}
print(list(bfgs_stop=root$reason,score=rbind(at_9.3=-scalar$gr(u_fit),
  at_root=-scalar$gr(u)),
  maximum_per_group=norm_score(u)))
1
2
3
4
5
6
7
8
9
10
$bfgs_stop
[1] "converged"

$score
                 [,1]          [,2]          [,3]
at_9.3   5.065706e-04 -1.973607e-03 -1.204220e-01
at_root -1.018916e-13  2.702905e-14  2.981979e-13

$maximum_per_group
[1] 3.727474e-15

At the adaptive estimate, the fixed-rule score was approximately $(0.000507,-0.001974,-0.120422)$. The largest component in absolute value was the derivative with respect to the log standard deviation. BFGS reported convergence, and at the final checked point the largest absolute component divided by 80 was $3.73\times10^{-15}$. Now calculate the response contributions at that point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (!is.finite(norm_score(u)) ||
  norm_score(u)>1e-8) stop("15.2 needs repair: 61-node score residual")
marginal_scores <- function(data,u,rule) {
  p <- ncol(data$X)
  b <- exp(u[p+1])*rule$nodes
  rows <- matrix(0,data$N,p+1L)
  for(block in data$blocks) {
    eta <- outer(drop(block$X%*%u[seq_len(p)])+block$offset,b,"+")
    terms <- glmm_response(block$y,eta,data$family)
    # Normalize over nodes after adding all eight conditional log probabilities.
    w <- normalize_logweights(log(rule$weights)+colSums(terms$log_density))
    # The first two columns refer to fixed effects. The third refers to log SD.
    rows[block$rows,] <- cbind(block$X*drop(terms$residual%*%w),
      drop(terms$residual%*%(w*b)))
  }
  rows
}

In marginal_scores() the rows of terms$residual index observations and its columns index nodes. The product with w*b gives the third score coordinate.

unit_scores() adds the response-score rows with the same group identifier and returns one row per group, in order of first appearance. vcov_sandwich() multiplies the assembled covariance by $G/(G-1)$ when finite_correction is true. Thus the group calculation uses $80/79$ and the calculation treating all 640 rows as independent uses $640/639$. The square root of this multiplier applies to a standard error.

1
2
3
4
5
6
7
8
9
10
row_score <- marginal_scores(grouped,u,rule)
U <- unit_scores(row_score,grouped$id)
# Compare with the negative gradient of the minimized function.
stopifnot(max(abs(colSums(U)+scalar$gr(u)))<1e-7)
bread_sum <- num_hess(scalar$fn,u,gr=scalar$gr)$hessian
stopifnot(min(eigen(bread_sum,symmetric=TRUE,only.values=TRUE)$values)>0)
print(data.frame(parameter=c("intercept","slope","log SD"),
  sum_of_cluster_scores=colSums(U), marginal_log_likelihood_derivative=-scalar$gr(u),
  model=vcov_information(bread_sum)$se,clusters=vcov_sandwich(bread_sum,U)$se,
  rows_treated_independently=vcov_sandwich(bread_sum,row_score)$se))
1
2
3
4
5
6
7
8
  parameter sum_of_cluster_scores marginal_log_likelihood_derivative     model
1 intercept         -1.059153e-13                      -1.018916e-13 0.1081658
2     slope          2.975398e-14                       2.702905e-14 0.1329494
3    log SD          2.989831e-13                       2.981979e-13 0.2311427
   clusters rows_treated_independently
1 0.1084116                  0.1350984
2 0.1210251                  0.1293706
3 0.2523205                  0.1948512

For the slope, the inverse observed information gives a standard error of 0.13295, the group sandwich gives 0.12103, and the row sandwich gives 0.12937. The intercept and log standard deviation use the same three calculations. The same coefficients and sensitivity underlie all three columns. Treating rows as independent increases the sandwich standard errors for the intercept and slope here and decreases the one for the log standard deviation. Within-group products can have either sign, and the inverse sensitivity combines score coordinates. The choice of unit follows the sampling design. In a hidden Markov model with independently sampled sequences, form one score vector by differentiating the log marginal probability of each entire sequence before taking its outer product.

The first group’s eight rows show how a single group score entered the total. Read the columns as the intercept, slope and log standard deviation.

1
print(row_score[grouped$blocks[[1]]$rows,,drop=FALSE]); print(U[1,])
1
2
3
4
5
6
7
8
9
           [,1]        [,2]          [,3]
[1,] -0.2677061  0.26770611 -0.0028646146
[2,] -0.3080950  0.22006788 -0.0005439647
[3,] -0.3515201  0.15065148  0.0027025180
[4,] -0.3974370  0.05677672  0.0069708448
[5,]  0.5548494  0.07926421 -0.1315616861
[6,]  0.5061499  0.21692137 -0.1251738921
[7,]  0.4573405  0.32667178 -0.1178191186
[8,] -0.5906952 -0.59069521  0.0342216138
1
[1] -0.3971137  0.7273643 -0.3340683

For the first observation, the covariate is $-1$, so multiplying its contribution of $-0.2677061$ to the intercept component by $-1$ gives a positive contribution to the slope component. The eight slope entries in the middle column sum to 0.7273643 for this group. Summing again across all groups gives a slope component of $2.98\times10^{-14}$, compared with $2.70\times10^{-14}$ from the negative of the minimized function’s gradient. The other coordinates also agree to numerical precision. Differencing the negative marginal log likelihood gradient at this root gives bread_sum. Its positive eigenvalues verify positive local curvature. These checks concern a stationary point and local curvature of the 61-node approximation in these coordinates. They establish neither a global maximum nor the accuracy of the underlying integral.

The following definitions show how the response contributions are assembled into group scores and how these scores and the sensitivity produce the covariance. In vcov_sandwich(), multiplying each group score by the inverse sensitivity and then forming the sum of outer products gives the sandwich directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
unit_scores <- function(rows,unit) {
  stopifnot(is.matrix(rows),nrow(rows)==length(unit),!anyNA(unit))
  rowsum(rows,unit,reorder=FALSE)
}

vcov_sandwich <- function(A,U,finite_correction=TRUE) {
  inverse <- solve(A)
  G <- nrow(U)
  if(finite_correction && G<=1L) stop("At least two independent units are required")
  # Transform each independent score before summing its outer product.
  V <- tcrossprod(inverse%*%t(U))
  if(finite_correction) V <- V*G/(G-1)
  list(covariance=V,se=sqrt(diag(V)),units=G,
    meat=crossprod(U),finite_correction=finite_correction)
}

The returned meat is the unadjusted crossprod(U). The cluster-count adjustment cannot restore omitted within-group products. With few independent groups, the estimated score variance can itself vary considerably across samples, even after the adjustment. The factor is a cluster-count adjustment, separate from the HC0–HC3 choices in sandwich::vcovCL(). It does not make normal-reference intervals exact with few groups. Also, when the group scores sum to zero, their outer-product matrix has rank at most $G-1$; finite individual standard errors do not establish that every joint Wald test is computable.

Within-group cross products in a Gaussian study

A balanced Gaussian random-intercept study makes one of those cross terms visible. Its response model is $Y_{ij}=\beta_0+\beta_1x_j+b_i+e_{ij}$. The fixed intercept is the population mean at $x=0$, and the slope is its change in response units per covariate unit. The independent groups have centered normal intercepts $b_i$, each shifting all responses in its group. The variance of $b_i$ measures between-group variation in that shared shift. The independent centered normal errors $e_{ij}$ are independent of $b_i$, and their variances describe response variation conditional on the group’s intercept and covariate. Both variance components are in squared response units.

Generate 200 independent samples with 40 groups each and five covariate values per group. The population intercept is one, the true slope is 0.5, the random-intercept standard deviation is 0.5, and the residual standard deviation $\exp(0.3x)$ varies with the covariate $x$. Assign each sample its own random-number stream. Fit each sample by closed-form ML under a common residual variance. Because the same centered covariates occur in every group, the slope is the sum of their products with the responses divided by the sum of squared covariates over all 40 groups. The fit also gives the random-intercept variance and the common residual variance used to construct the fitted group covariance $V$. The calculation below uses replicate_streams() and balanced_variance_fit(), shown in Sections 15.5 and 15.4.

1
2
3
4
5
6
7
8
9
source("code/lib/boundary_test.R", local = TRUE)
source("code/lib/inference.R", local = TRUE)
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(101511L)
streams <- replicate_streams(200L, .Random.seed)
G <- 40L
x <- seq(-1, 1, length.out = 5L)
X <- cbind(1, x)
rows <- vector("list", length(streams))

With $X$ the five-row design and $\hat\beta$ the fitted intercept and slope, set $v_i=V^{-1}(y_i-X\hat\beta)$. Row $j$ contributes to the group score its design vector times component $j$ of $v_i$. Their summed sensitivity across groups is $A=G X^\top V^{-1}X$. Thus even the row calculation uses the joint covariance of the five observations. In the first sample, U in the loop contains the five contributions from group one. Compare the square of their summed slope component with the sum of its five squares. The samples are drawn by balanced_variance_simulate() in code/lib/boundary_test.R.

1
2
3
4
5
6
7
8
balanced_variance_simulate <- function(groups, x, beta, sigma, tau = 0) {
  stopifnot(groups >= 1L, length(beta) == 2L, all(is.finite(c(beta, sigma, tau, x))),
    all(sigma > 0), length(sigma) %in% c(1L, length(x)), tau >= 0)
  effect <- if (tau == 0) numeric(groups) else rnorm(groups, sd = tau)
  errors <- matrix(rnorm(groups * length(x)), groups, length(x))
  matrix(beta[1] + beta[2] * x, groups, length(x), byrow = TRUE) + effect +
    sweep(errors, 2, rep_len(sigma, length(x)), "*")
}

Each of the groups rows contains the responses at the covariate values x: the line $\beta_0+\beta_1x$, one group effect drawn from $N(0,\tau^2)$ (zero when $\tau=0$), and independent normal errors whose standard deviation can differ by column.

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
for (id in seq_along(streams)) {
  assign(".Random.seed", streams[[id]], envir = .GlobalEnv)
  Y <- balanced_variance_simulate(G, x, c(1, .5), exp(.3 * x), tau = .5)
  fit <- balanced_variance_fit(Y, x)
  V <- matrix(fit$tau2, length(x), length(x)) + diag(fit$sigma2, length(x))
  A <- G * crossprod(X, solve(V, X))
  # One row per group. Multiply its residual vector by the inverse covariance.
  weighted <- sweep(Y, 2L, drop(X %*% fit$beta)) %*% solve(V)
  row_scores <- do.call(rbind, lapply(seq_len(G), function(g) X * weighted[g, ]))
  group_scores <- weighted %*% X
  if (id == 1L) {
    # For this display, the five rows belong to the first group.
    U <- row_scores[seq_along(x), , drop = FALSE]
    group_outer <- tcrossprod(colSums(U))
    row_outers <- crossprod(U)
    one_group <- data.frame(term = c("group_outer", "row_outers", "cross_terms"),
      slope = c(group_outer[2, 2], row_outers[2, 2],
        group_outer[2, 2] - row_outers[2, 2]))
    print(one_group, row.names = FALSE)
  }
  # Use the same group-count correction for both covariances.
  rows[[id]] <- data.frame(id = id, slope = unname(fit$beta[2L]),
    group_SE = vcov_sandwich(A, group_scores)$se[2L],
    row_SE = vcov_sandwich(A, row_scores, FALSE)$se[2L] * sqrt(G / (G - 1L)))
}
1
2
3
4
        term      slope
 group_outer  1.2309267
  row_outers  1.7238124
 cross_terms -0.4928857

The group square is 1.23093 and the sum of squares is 1.72381. Subtracting before rounding gives $-0.49289$ for the sum of the within-group slope cross products. Its sign in this group does not determine their sum over 40 groups or their behavior in a new sample. Both covariance estimates in this study use the same multiplier $40/39$. Count the normal 95 percent intervals that include the generating slope 0.5.

The empirical standard deviation describes how a slope estimate changes across samples. The average fitted standard error describes the uncertainty a method reports within a sample. The Monte Carlo standard error describes how precisely these replications estimate a performance measure. Here the average standard error is the arithmetic mean across the fits. For coverage $\hat p$ from $B$ independent usable datasets, its estimated Monte Carlo standard error is $\sqrt{\hat p(1-\hat p)/B}$. The denominator counts datasets, rather than the observations within each dataset.

For each method, retain replications with a finite slope estimate and a positive finite standard error. Compute all summaries on that same subset, report its size as eligible, and record the assigned count separately.

1
2
3
4
5
6
7
8
9
10
estimates <- do.call(rbind, rows)
coverage <- do.call(rbind, lapply(c("group_SE", "row_SE"), function(method) {
  eligible <- is.finite(estimates$slope) & is.finite(estimates[[method]]) & estimates[[method]] > 0
  covers <- abs(estimates$slope[eligible] - .5) <= qnorm(.975) * estimates[[method]][eligible]
  p <- if (length(covers)) mean(covers) else NA_real_
  data.frame(method = method, assigned = nrow(estimates), eligible = sum(eligible),
    empirical_SD = sd(estimates$slope[eligible]), mean_SE = mean(estimates[[method]][eligible]),
    covered = sum(covers), coverage = p, MCSE = if (length(covers)) sqrt(p * (1 - p) / length(covers)) else NA_real_)
}))
print(coverage, row.names = FALSE)
1
2
3
   method assigned eligible empirical_SD   mean_SE covered coverage       MCSE
 group_SE      200      200    0.1123641 0.1061627     186     0.93 0.01804162
   row_SE      200      200    0.1123641 0.1023001     184     0.92 0.01918333

Across 200 samples the fitted slopes had standard deviation 0.11236. Group and row standard errors averaged 0.10616 and 0.10230. The corresponding intervals covered in 186 and 184 samples, with Monte Carlo standard errors of 0.018 and 0.019 for the two proportions. Here, summing within the independent groups brought the average reported slope uncertainty closer to its observed sampling variation. A difference of two covered intervals is not enough to establish superior coverage; a comparison should use the paired coverage decisions and their Monte Carlo uncertainty. The sandwich package provides cluster-robust covariance estimates.

15.3 Wald, likelihood ratio, and score tests

Does the mean response change with time when people can differ in both their starting levels and their rates of change? Write the population slope as $\beta_1$. Its unrestricted maximum likelihood (ML) estimate and standard error already give one way to test $\beta_1=0$. More generally, let $\theta$ collect the free model parameters and let the null hypothesis impose $r$ smooth restrictions $h(\theta)=0$. At the unrestricted estimate $\hat\theta$, write $J$ for the Jacobian of $h$, with a row for each restriction, and $\widehat V$ for the estimated sampling covariance of $\hat\theta$. A small change $d\theta$ changes the restriction vector by approximately $J\,d\theta$. The delta method therefore estimates the covariance of $h(\hat\theta)$ by $J\widehat VJ^\top$. The squared distance of the fitted departure from zero on that scale gives the Wald statistic

\[W=h(\hat\theta)^\top (J\widehat VJ^\top)^{-1}h(\hat\theta).\]

The chi-square reference with $r$ degrees of freedom requires that the population value under the null allow small changes in every direction of the unrestricted model, with identifiable parameters, a full-row-rank restriction Jacobian and positive definite information. Under a correctly specified smooth likelihood with increasing numbers of independent people, the Wald, likelihood ratio and score tests then have the same limiting null distribution.

For one slope, $J$ selects its coordinate and $W$ is the squared ratio of the estimate to its standard error.

1
2
3
4
5
wald_test <- function(h,J,V) {
  covariance <- J%*%V%*%t(J)
  value <- drop(crossprod(h,solve(covariance,h)))
  df <- length(h); c(statistic=value,df=df,p=pchisq(value,df,lower.tail=FALSE))
}

In wald_test(), h contains the evaluated departures and covariance their estimated covariance. Solving with covariance accounts for correlations when several restrictions are tested together. Using $r$ degrees of freedom requires $r$ independent restrictions and a nonsingular covariance for their estimated departures; length(h) alone cannot check this.

How much fit is lost when the population slope is fixed at zero and the other parameters can adjust? Let $\ell$ be the sum of the individual log likelihood contributions, each formed after integrating over one person’s random effects. Write $\tilde\theta$ for the ML estimate subject to the restriction. The likelihood ratio divides the maximized likelihood under the null by the maximized likelihood in the unrestricted model. Taking minus twice its logarithm gives

\[\mathrm{LR}=2\{\ell(\hat\theta)-\ell(\tilde\theta)\}.\]

Both maxima use the same observed responses, marginal likelihood and normalizing constants. Since every restricted parameter vector is also allowed in the larger model, the difference is nonnegative at the two maxima. The value passed first to lr_test() is the unrestricted log likelihood. The function checks the ordering, allowing for numerical roundoff. The function uses the number of independent restrictions as the degrees of freedom and returns the upper-tail chi-square probability.

1
2
3
4
5
lr_test <- function(unrestricted,restricted,df) {
  value <- 2*(unrestricted-restricted)
  if(value< -1e-8) stop("Unrestricted likelihood below the restricted likelihood")
  statistic <- max(0,value); c(statistic=statistic,df=df,p=pchisq(statistic,df,lower.tail=FALSE))
}

At the restricted fit, the log likelihood can still rise in the direction of the omitted slope. To measure that rise while allowing the other parameters to vary, split the score into a tested block $U_t$ and a nuisance block $U_n$. At $\tilde\theta$, differentiate the negative marginal log likelihood twice in all coordinates. Partition this observed information matrix $I$ into matching blocks. For local parameter displacements $d_t$ and $d_n$, the quadratic approximation gives the nuisance score as $U_n-I_{nt}d_t-I_{nn}d_n$. Setting this expression to zero gives $d_n=I_{nn}^{-1}(U_n-I_{nt}d_t)$. Substitute it into the tested score $U_t-I_{tt}d_t-I_{tn}d_n$. The constant term is the nuisance-adjusted score and the negative coefficient of $d_t$ is its adjusted curvature. Using expected information yields the usual efficient-score construction; the observed-information version here is a local quadratic approximation at the restricted fit. In block notation these are

\[U_{t\cdot n}=U_t-I_{tn}I_{nn}^{-1}U_n,\qquad I_{t\cdot n}=I_{tt}-I_{tn}I_{nn}^{-1}I_{nt}.\]

The second expression is the Schur complement of the nuisance block. At an exact restricted optimum where the nuisance parameters can vary in both directions, $U_n=0$, but the information adjustment can be nonzero even then. With numerical derivatives, retain the computed nuisance score in the subtraction, but also check that the restricted fit is adequately optimized. The subtraction cannot repair a failed null fit. The score statistic is $U_{t\cdot n}^\top I_{t\cdot n}^{-1}U_{t\cdot n}$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
score_test <- function(U,I,tested) {
  others <- setdiff(seq_along(U),tested)
  efficient <- I[tested,tested,drop=FALSE]
  score <- U[tested]
  if(length(others)) {
    projection <- I[tested,others,drop=FALSE]%*%solve(I[others,others,drop=FALSE])
    # Allow nuisance coefficients to adjust when the tested coordinates move.
    efficient <- efficient-projection%*%I[others,tested,drop=FALSE]
    # Apply the same projection to the numerical nuisance score.
    score <- score-drop(projection%*%U[others])
  }
  df <- length(tested); value <- drop(crossprod(score,solve(efficient,score)))
  c(statistic=value,df=df,p=pchisq(value,df,lower.tail=FALSE))
}

The object named projection is the coefficient matrix $I_{tn}I_{nn}^{-1}$ used for nuisance adjustment; it need not be square or idempotent.

Testing the mean growth slope

In the simulated GROWTH4 data, 200 independent people each have a response at times 0, 1, 2 and 3. At time $x_j$, person $i$’s response is $Y_{ij}=\beta_0+\beta_1x_j+b_{0i}+b_{1i}x_j+\varepsilon_{ij}$. The personal intercept and slope deviations are jointly normal with mean zero and covariance matrix $G$. The independent normal errors have mean zero and variance $\sigma^2$ and are independent of those deviations. The population intercept $\beta_0$ is the mean response at time zero; $\beta_1$ is the change in that mean per time unit. The diagonal entries of $G$ measure variation among people in starting level and rate of change, in squared response units and squared response-per-time units, respectively. Their covariance, in squared response units per time unit, describes how the two personal deviations vary together; a positive value associates higher starting levels with faster increases. The residual variance $\sigma^2$ describes variation around each person’s trajectory in squared response units. Setting $\beta_1=0$ gives a constant population mean while allowing individual trajectories to rise or fall.

The restricted and unrestricted fits are computed as follows. From the book directory, load the long data and the unrestricted profile ML fit. Its stored design growth_data contains the responses, time values and person identifiers used in estimation. To fit growth_null, replace the fixed-effect design by a column of ones. Passing the original random-effect design preserves both the random slope and its covariance with the random intercept.

1
2
3
4
5
6
7
source("code/lib/transforms.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/lmm_profile.R")
source("code/lib/lmm.R")
source("code/lib/inference.R")
growth <- readRDS("data/source/ch07/GROWTH4.rds")$long
1
2
3
4
5
6
growth_full <- readRDS("data/derived/ch08/fits.rds")$routes$ML_profile
growth_data <- growth_full$data
X0 <- matrix(1,nrow(growth_data$X),1)
# Only the fixed design loses its time column.
reduced_data <- lmm_design(growth_data$y,X0,growth_data$Z,growth_data$id)
growth_null <- lmm_fit(reduced_data)

Both fits maximize the normal marginal likelihood by profiling the fixed coefficients and residual variance for each candidate relative covariance. The restricted fit reestimates the covariance parameters. For the derivatives, express both fits in the same six coordinates. The fixed intercept and slope come first, followed by three coordinates for the random-effects covariance and the log residual variance. If $L$ is the lower Cholesky factor of that covariance, the middle three entries are $\log L_{11}, L_{21}, \log L_{22}$ in that order. The function joint_fn() evaluates the negative marginal log likelihood at all six supplied values. Specifying beta lets the slope vary away from zero when differentiating at the null.

1
2
3
4
5
6
joint_fn <- function(u) lmm_cluster_nll(growth_data,logchol_to_cov(u[3:5]),
  exp(u[6]),beta=u[1:2])$value
# Insert the fixed slope of zero in the full coordinate vector.
u0 <- c(growth_null$beta,0,cov_to_logchol(growth_null$G),log(growth_null$sigma2))
u1 <- c(growth_full$beta,cov_to_logchol(growth_full$G),log(growth_full$sigma2))
J <- matrix(c(0,1,0,0,0,0),1)

The unrestricted vector u1 gives the covariance for the Wald statistic by inversion of the numerical Hessian. At the restricted vector u0, reverse the sign of the numerical gradient to obtain the likelihood score and use the numerical Hessian of the negative log likelihood as observed information. Coordinate two is the tested slope. Negating the minimized value in each fit recovers its maximized log likelihood for the LR calculation.

1
2
3
4
5
6
7
full_vcov <- vcov_information(num_hess(joint_fn,u1)$hessian)$covariance
# The two Wald rows use different expressions for the same null.
test_rows <- rbind(Wald=wald_test(u1[2],J,full_vcov),
  Wald_exponential=wald_test(expm1(u1[2]),exp(u1[2])*J,full_vcov),
  LR=lr_test(-growth_full$value,-growth_null$value,1L),
  score=score_test(-num_grad(joint_fn,u0)$gradient,num_hess(joint_fn,u0)$hessian,2L))
print(test_rows); print(-num_grad(joint_fn,u0)$gradient)
1
2
3
4
5
                 statistic df            p
Wald              85.55041  1 2.258696e-20
Wald_exponential  58.03465  1 2.575414e-14
LR                71.22028  1 3.194873e-17
score            149.50165  1 2.227859e-34
1
2
[1]   0.000000000 149.246097884  -0.001941395  -0.001967039  -0.001151863
[6]   0.001647333

For the population slope, the likelihood ratio statistic is 71.22028, the score statistic is 149.50165, and the Wald statistic is 85.55041. Each tests one restriction. Together with the positive fitted slope, their small chi-square tail probabilities give evidence that the population mean increases with time. Freeing the population slope increased the maximized log likelihood by $71.22028/2=35.61014$.

The Wald calculation uses the uncertainty at the unrestricted slope of 0.40148. Its standard error is approximately $0.40148/\sqrt{85.55041}=0.04341$ response units per unit of time. The score calculation measures a local increase from the null, where even the covariance parameters can have different fitted values. There is no requirement that a single quadratic describe the likelihood across that distance in a finite sample.

The two Wald rows show why the form of a restriction matters. The null $\beta_1=0$ is equivalent to $\exp(\beta_1)=1$. On the exponential scale, the fitted distance is $\exp(\hat\beta_1)-1$, computed by expm1(), and its delta-method standard error is $\exp(\hat\beta_1)\operatorname{SE}(\hat\beta_1)$. For the fitted slope, the transformed distance is about 0.49403 and its standard error is about 0.06485. Squaring their ratio before rounding gives 58.03465. For a positive slope, scaling this distance back by the derivative at the estimate gives $1-\exp(-\hat\beta_1)$, which is smaller than $\hat\beta_1$. That accounts for the smaller statistic. A one-to-one transformation describes exactly the same restricted and unrestricted models, so it leaves their maximized likelihoods and the LR of 71.22028 unchanged. This exponential transformation illustrates how a Wald test depends on the chosen restriction. The Gaussian response model does not make the transformed slope an odds ratio.

At the restricted fit, the partial derivative of the log likelihood with respect to the population slope is 149.2461. In coordinate order, the five nuisance scores are 0.000000000, $-0.001941395$, $-0.001967039$, $-0.001151863$ and $0.001647333$. All five have magnitudes below 0.0020. The nuisance adjustment uses these numerical values at the restricted fit. These residuals describe numerical accuracy at this restricted fit.

A sandwich covariance can enter a Wald test with a valid sampling justification. Substituting one into a likelihood ratio has no such interpretation because the ratio compares likelihood values directly.

For the mean-slope test, use ML under both fixed-effect designs. Restricted maximum likelihood (REML) evaluates the likelihood of response contrasts that eliminate the fixed effects. Removing time from the fixed design changes which contrasts enter that likelihood.

A fixed mean slope can move to either side of zero. A slope variance, however, can move only upward from zero, and its covariance with the random intercept must also vanish there. This boundary changes the null distribution of the test statistic.

The lme4 package provides ML likelihood ratio comparisons for nested linear mixed models.

15.4 Variance components at the boundary and mixture chi-square reference distributions

Can the variation among group means be explained by the residual errors of individual responses alone? Consider $g=40$ independent groups. Each contributes $m=5$ responses at the same covariate values $x_j$, equally spaced from $-1$ to $1$. Write $Y_{ij}=1+0.5x_j+b_i+e_{ij}$ for response $j$ in group $i$. Across groups, the random intercepts $b_i$ are normally distributed with mean zero and variance $v$. The independent normal errors $e_{ij}$ have mean zero and variance $s>0$ and are independent of the intercepts. The fixed intercept one is the population mean at covariate zero, and the fixed slope gives the mean change per covariate unit. The variance $v$ describes shared shifts among groups; $s$ describes response variation within a group around its conditional mean. Both are in squared response units.

Generate one sample under the null with $v=0$ and residual standard deviation one. From the book directory, set the seed to 1504 and generate a response matrix with one group per row and one covariate value per column. The last argument specifies the residual standard deviation. The random-intercept standard deviation defaults to zero.

1
2
3
4
5
6
.libPaths(c(".R-library", .libPaths()))
source("code/lib/boundary_test.R")
boundary_x <- seq(-1, 1, length.out = 5)
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(1504)
Y_boundary <- balanced_variance_simulate(40L, boundary_x, c(1, .5), 1)

The null fit estimates the fixed intercept, fixed slope and residual variance with $v$ set to zero. The larger model estimates the same quantities and allows any $v\geq0$. Thus both models explain systematic change with $x$, and they differ in whether observations in a group can share an additional random intercept. An optimizer working in $\log v$ can approach a very small variance but cannot return zero at a finite coordinate. If the likelihood is maximized at zero, twice the difference in maximized log likelihoods, the likelihood ratio (LR) test statistic, is exactly zero. Fitting over the closed parameter space lets the two maxima coincide.

Why can the two maxima coincide on a sample with visibly different group means? Each group’s marginal covariance is $sI_m+v\mathbf 1\mathbf 1^\top$, where $I_m$ is the identity matrix and $\mathbf 1$ is the vector of ones. Its eigenvalue in the group-mean direction is $a=s+mv$. Each of the $m-1$ directions perpendicular to it has eigenvalue $s$. The covariate sums to zero in each group, so the fitted intercept is the grand mean $\bar y$ and the slope $\hat\beta_1$ comes from regressing the within-group deviations on $x_j$. With $\bar y_i$ the mean in group $i$, define the two sums of squares

\[B=m\sum_i(\bar y_i-\bar y)^2,\qquad W=\sum_i\sum_j(y_{ij}-\bar y_i-\hat\beta_1x_j)^2.\]

After fitting the fixed effects, twice the negative marginal log likelihood, apart from the common normal constant, is $g\log a+B/a+g(m-1)\log s+W/s$. Setting the two partial derivatives to zero gives the estimates $B/g$ and $W/[g(m-1)]$. The maximum likelihood (ML) divisors count the directions contributing to each sum of squares. The between-group estimate measures the variance of $\sqrt{m}\,\bar y_i$ across groups using the ML divisor $g$, without a degrees-of-freedom correction for the fitted mean. If it exceeds the within-group estimate, their difference estimates $mv$. Dividing by $m$ gives the fitted random-intercept variance. When the between-group estimate is no larger than the within-group estimate, the constraint $a\geq s$ puts the maximum at equality. At $v=0$ there is a single residual variance $\hat s_0=(B+W)/(gm)$, the null estimate. In the function below, between and within are the two unconstrained estimates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
balanced_variance_fit <- function(Y, x) {
  G <- nrow(Y)
  m <- ncol(Y)
  stopifnot(is.matrix(Y), G >= 2L, m >= 2L, length(x) == m, all(is.finite(c(Y, x))))
  centered_x <- x - mean(x)
  xx <- sum(centered_x^2)
  stopifnot(xx > 0)
  slope <- sum(sweep(Y, 2L, centered_x, "*")) / (G * xx)
  intercept <- mean(Y) - slope * mean(x)
  means <- rowMeans(Y)
  ss_between <- m * sum((means - mean(means))^2)
  ss_within <- sum((Y - means - matrix(slope * centered_x, G, m, byrow = TRUE))^2)
  sigma2_null <- (ss_between + ss_within) / (G * m)
  # Each group contributes m-1 within directions and one group-mean direction.
  within <- ss_within / (G * (m - 1L))
  between <- ss_between / G
  if (min(sigma2_null, within) <=
      0) stop("The residual variance has no strictly positive ML estimate")
  at_boundary <- between <= within
  sigma2 <- if (at_boundary) sigma2_null else within
  tau2 <- if (at_boundary) 0 else (between - within) / m
  total <- G * m
  null_ll <- -.5 * total * (log(2 * pi) + 1 + log(sigma2_null))

At equality both log likelihoods use $\hat s_0$ and the same normalizing constant. When the fitted random-intercept variance is positive, write $r=(a-s)/s$ at the fitted eigenvalues. Then $\hat s_0=s(1+r/m)$, so twice the log likelihood gain is $g\lbrace m\log(1+r/m)-\log(1+r)\rbrace $. Continue the function definition below. It evaluates this difference with log1p() and returns both maximized log likelihoods.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  if (at_boundary) {
    lr <- 0
  } else {
    # The two linear terms cancel; log1p retains precision near equal eigenvalues.
    ratio <- (between - within) / within
    lr <- G * (m * log1p(ratio / m) - log1p(ratio))
    if (lr < -32 * .Machine$double.eps *
        total) stop("Negative likelihood ratio test statistic")
    lr <- max(0, lr)
  }
  # Differentiate the full log likelihood at tau2 = 0, plugging in the null ML fit.
  score_at_zero <- .5 * m * (ss_between / sigma2_null^2 - G / sigma2_null)
  list(beta = c(intercept = intercept, slope = slope), sigma2_null = sigma2_null,
    sigma2 = sigma2, tau2 = tau2, boundary = at_boundary, score_at_zero = score_at_zero,
    null_loglik = null_ll, alternative_loglik = null_ll + lr / 2, lr = lr)
}

The fitted equality branch assigns zero directly. For a fit with positive random-intercept variance, roundoff can make the computed statistic slightly negative. The function sets it to zero if it lies between $-32\epsilon gm$ and zero, where $\epsilon$ is machine precision. A more negative value stops the calculation.

A mixture reference at the boundary

To derive a null distribution, let $\ell_p(v)$ be the log likelihood after maximizing over the fixed effects and $s$ at each $v$. Near zero its change is approximately $vU_e-v^2 I_e/2$, where $U_e$ is the score for the variance after adjustment for the nuisance parameters and $I_e$ is its efficient information. Maximizing the joint quadratic over the nuisance displacement gives this curvature as the Schur complement of the nuisance block in the information, as in the score test of Section 15.3. At the fitted null the nuisance score vanishes. Differentiating the group-mean term with $a=s+mv$ therefore gives the profile derivative $m\lbrace B/\hat s_0^2-g/\hat s_0\rbrace /2$, printed as score_at_zero.

Standardize the local displacement as $h=v\sqrt{I_e}$ and the efficient score as $Z=U_e/\sqrt{I_e}$. The quadratic becomes $hZ-h^2/2$. Over the admissible values $h\geq0$ its maximizer is $h=0$ when $Z\leq0$ and $h=Z$ when $Z>0$. Twice the maximized gain is consequently $[\max(0,Z)]^2$.

Under the null, $Z$ tends to a standard normal variable as the number of independent groups increases. This argument requires a single tested variance, positive efficient information, and identifiable nuisance parameters that admit small changes in both directions, including a strictly positive residual variance.

Half of the limiting standardized efficient scores are negative, so the variance constraint gives zero gain. For a positive standardized score, twice the gain equals $Z^2$. By symmetry, the square of a standard normal variable conditional on its being positive has the same distribution as its unconditional square. Thus the limiting distribution of the LR test statistic assigns half its probability to zero. The continuous half follows the chi-square distribution with one degree of freedom.

Use the inclusive upper tail $P(T\geq t)$ for a statistic $T$ with this mixture distribution. At $t=0$ the probability is one. For $t>0$ only the continuous part contributes, so the probability is half the one-degree-of-freedom chi-square upper tail.

1
2
3
4
boundary_mixture_p <- function(statistic) {
  stopifnot(all(is.finite(statistic)), all(statistic >= 0))
  ifelse(statistic == 0, 1, .5 * pchisq(statistic, 1, lower.tail = FALSE))
}
1
2
3
4
5
boundary_example <- balanced_variance_fit(Y_boundary, boundary_x)
print(as.data.frame(boundary_example[c("sigma2_null", "tau2", "sigma2", "score_at_zero",
  "null_loglik", "alternative_loglik", "lr")]))
print(c(mixture_p = boundary_mixture_p(boundary_example$lr),
  p_at_atom = boundary_mixture_p(0)))
1
2
3
4
5
6
  sigma2_null       tau2   sigma2 score_at_zero null_loglik alternative_loglik
1    1.092776 0.02335858 1.069418       7.82427   -292.6599          -292.5721
         lr
1 0.1754593
mixture_p p_at_atom 
0.3376524 1.0000000 

The unstandardized derivative, 7.82427, is positive. Allowing a small positive random-intercept variance therefore improves the fit. The fitted random-intercept variance is 0.02336 and the residual variance is 1.06942. The null and alternative log likelihoods are $-292.6599$ and $-292.5721$. Using their unrounded values gives an LR of 0.17546 and a mixture p-value of 0.33765. At the fitted variances, the estimated variance along the group-mean direction is $1.069418+5(0.02335858)\approx1.18621$. This modest excess over the within-group variance is consistent with sampling under the null. As a numerical check, fit the random-intercept model by profile ML to the identical rows.

1
2
3
4
5
6
7
8
9
10
11
12
source("code/lib/dogleg.R")
source("code/lib/lmm_profile.R")
source("code/lib/lmm.R")
boundary_data <- lmm_design(c(t(Y_boundary)), cbind(1, rep(boundary_x, nrow(Y_boundary))),
  matrix(1, length(Y_boundary), 1L), rep(seq_len(nrow(Y_boundary)),
    each = length(boundary_x)))
boundary_lmm <- lmm_fit(boundary_data)
print(c(closed_form = boundary_example$alternative_loglik,
  chapter_8_fit = -boundary_lmm$value,
  difference = -boundary_lmm$value - boundary_example$alternative_loglik,
  tau2_closed_form = boundary_example$tau2, tau2_fit = boundary_lmm$G[1, 1],
  sigma2_closed_form = boundary_example$sigma2, sigma2_fit = boundary_lmm$sigma2))
1
2
3
4
       closed_form      chapter_8_fit         difference   tau2_closed_form 
     -2.925721e+02      -2.925721e+02      -1.705303e-13       2.335858e-02 
          tau2_fit sigma2_closed_form         sigma2_fit 
      2.335855e-02       1.069418e+00       1.069418e+00 

The two calculations agree on the alternative log likelihood to within $2\times10^{-13}$.

Statistics from repeated null samples

Does the limiting mixture describe samples of this size? A separate set of 200 independent samples uses the same covariates, fixed coefficients, residual variance and zero random-intercept variance. Counting exact zeros estimates the probability that the statistic equals zero. Quantiles among the positive statistics describe its continuous part.

1
2
3
4
5
6
7
8
9
study <- readRDS("data/derived/ch15/null-records.rds")
statistics <- vapply(study, function(r) r$summary$statistic, numeric(1))
positive <- statistics[statistics > 0]
boundary <- c(assigned = length(statistics), at_zero = sum(statistics == 0),
              fraction_at_zero = mean(statistics == 0), positive = length(positive),
              positive_median = median(positive), chi1_median = qchisq(.5, 1L),
              positive_q95 = quantile(positive, .95, names = FALSE),
              chi1_q95 = qchisq(.95, 1L))
print(boundary)
1
2
3
4
        assigned          at_zero fraction_at_zero         positive 
     200.0000000      112.0000000        0.5600000       88.0000000 
 positive_median      chi1_median     positive_q95         chi1_q95 
       0.3820354        0.4549364        3.5488055        3.8414588 

The observed fraction at zero was $112/200=0.56$, compared with the limiting 0.50. Among the 88 positive values the median was 0.3820 and the 95th percentile was 3.5488. The corresponding chi-square quantiles are 0.4549 and 3.8415. All 200 samples inform the estimated probability of a boundary estimate. The last two comparisons ask how large the statistic is once it has left the boundary.

The two equal halves of the limiting distribution arise because one standard normal score is projected onto the nonnegative values $h\geq0$. Adding a random slope correlated with an existing random intercept also introduces a covariance. At zero slope variance that covariance must vanish and the correlation is undefined. With several variance components, the admissible displacements have more than one dimension, and the probabilities of different subsets of variances being estimated as zero can depend on the information matrix. A nuisance parameter on the boundary can even yield a limit outside the family of chi-square mixtures. Increasing the observations within a fixed number of groups also requires a separate argument.

A simulated finite-sample reference

For the worked design, compare the same observed ML statistic with its simulated finite-sample null distribution. Fit a Gaussian model with a random intercept and an ordinary Gaussian regression to the same observations, using the same two fixed effects. The finite-sample calculation takes 10,000 draws with seed 15041.

1
2
3
4
5
6
7
8
9
10
11
12
boundary_frame <- data.frame(y = c(t(Y_boundary)), x = rep(boundary_x, nrow(Y_boundary)),
  group = factor(rep(seq_len(nrow(Y_boundary)), each = length(boundary_x))))
boundary_lmer <- lme4::lmer(y ~ x + (1 | group), data = boundary_frame, REML = FALSE)
boundary_lm <- lm(y ~ x, data = boundary_frame)
varcomp <- varTestnlme::varCompTest(boundary_lmer, boundary_lm, output = FALSE)
set.seed(15041)
exact <- RLRsim::exactLRT(boundary_lmer, boundary_lm, nsim = 10000)
print(c(book_LR = boundary_example$lr,
  lme4_LR = 2 * (as.numeric(logLik(boundary_lmer)) - as.numeric(logLik(boundary_lm))),
  book_mixture_p = boundary_mixture_p(boundary_example$lr),
  varTestnlme_p = unname(varcomp$p.value[["pvalue.weights"]]),
  RLRsim_exact_p = unname(exact$p.value)))
1
2
3
No restrictions on fixed effects. REML-based inference preferable.
       book_LR        lme4_LR book_mixture_p  varTestnlme_p RLRsim_exact_p 
     0.1754593      0.1754593      0.3376524      0.3376524      0.2934000 

Twice the difference between the two fitted log likelihoods is 0.1754593, which agrees with the closed-form statistic. The simulated ML tail probability is 0.2934, compared with 0.33765 under the asymptotic mixture.

The message about restricted maximum likelihood concerns a second possible test. Because the two fixed-effect designs agree, one could eliminate the fixed effects and compare restricted log likelihoods. That test would require the null distribution of the restricted likelihood ratio statistic. Both probabilities in the displayed comparison refer to ordinary ML.

Here “exact” describes the finite-sample null law supplied by RLRsim, not an error-free numerical tail probability: the reported value is estimated using 10,000 simulations and the program’s numerical settings.

When the limiting mixture is inadequate for a finite design, the fitted null model gives another way to calibrate the ML statistic. Fix the covariates and group sizes, set $v=0$, and generate new responses using the fitted fixed effects and null residual variance. Refit both models to every new sample, allowing the larger model to attain zero. Comparing the likelihood ratio statistics from those refits with the observed statistic estimates its upper-tail probability under the fitted null. The varTestnlme and RLRsim packages provide variance-component tests.

15.5 Parametric bootstrap with refitting and random-number streams for reproducible replications

How much improvement in fit would a random intercept appear to give if its variance were zero? The observed likelihood ratio statistic was 0.17546. A parametric bootstrap answers the question by generating responses from the fitted null model. It generates with the estimated null parameters fixed and estimates the parameters again on each new sample.

To construct an interval for the fixed slope, the question changes. The interval requires the variation of the estimated slope across samples in which groups can differ in their intercepts. For this purpose, generate responses from the unrestricted fit, including its estimated random-intercept variance. The choice of generating model determines which sampling distribution the bootstrap approximates.

From a fresh session in the book directory, reconstruct the observed fit. Each row of Y_boundary is one group, with five observations at covariate values $-1,-0.5,0,0.5,1$. The seed 1504 and the original generating coefficients reproduce the observed responses. Subsequent bootstrap draws use the coefficients estimated from those responses.

1
2
3
4
5
6
source("code/lib/boundary_test.R")
boundary_x <- seq(-1, 1, length.out = 5)
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(1504)
Y_boundary <- balanced_variance_simulate(40L, boundary_x, c(1, .5), 1)
boundary_example <- balanced_variance_fit(Y_boundary, boundary_x)

Use the same 40 groups and the same covariate values within each group. To generate a new response in group $i$ at position $j$, add a random intercept $b_i^\ast $ and an individual error $e_{ij}^\ast $ to the fitted mean $\hat\beta_0+\hat\beta_1x_j$. Under the fitted null, every $b_i^\ast $ is zero. Draw 200 independent normal errors with mean zero and variance 1.092776. Under the fitted alternative, draw 40 independent normal intercepts with mean zero and variance 0.02335858, one per group. Add that intercept to all five responses in its row and draw fresh independent errors with variance 1.069418. The generator takes standard deviations, so each call passes the square roots of the variances from its generating model. Fit the reduced and unrestricted models to each new response matrix, allowing the fitted random-intercept variance to equal zero.

Null replicates for the variance test

For the test, set the L’Ecuyer-CMRG generator to seed 101505 and assign one stream to each of 399 null replicates. The function parametric_bootstrap() takes the stream list, a function to draw a response matrix and a function to refit it. For each identifier it restores the assigned state, draws one matrix and passes that same matrix to the paired fits.

1
2
3
4
5
6
7
8
9
10
11
parametric_bootstrap <- function(streams, generate, refit) {
  rows <- lapply(seq_along(streams), function(id) {
    assign(".Random.seed", streams[[id]], envir = .GlobalEnv)
    result <- tryCatch(refit(generate()), error = identity)
    if (inherits(result, "error"))
      return(list(id = id, stream = streams[[id]], valid = FALSE,
        reason = conditionMessage(result)))
    list(id = id, stream = streams[[id]], valid = TRUE, fit = result)
  })
  rows
}
1
2
3
4
5
6
7
8
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(101505)
bootstrap_streams <- replicate_streams(399L, .Random.seed)
null_sample <- function() balanced_variance_simulate(40L, boundary_x,
  boundary_example$beta,
  sqrt(boundary_example$sigma2_null))
bootstrap_fits <- parametric_bootstrap(bootstrap_streams, null_sample,
  function(Y) balanced_variance_fit(Y, boundary_x))

The first list entry links one fitted pair to its null generating model and assigned stream. The two log likelihoods in this row refer to the same simulated responses. Both use maximum likelihood (ML) and include the same normalizing constant. The wrapper’s valid flag means that generation and refitting returned without an error. The balanced normal-model refits here use explicit formulas, so they have no iterative convergence test.

1
2
3
4
5
6
first <- bootstrap_fits[[1L]]
stopifnot(first$id == 1L, first$valid)
first_null <- data.frame(null_log_likelihood = first$fit$null_loglik,
                         alternative_log_likelihood = first$fit$alternative_loglik,
                         likelihood_ratio_statistic = first$fit$lr)
print(first_null, digits = 12, row.names = FALSE)

Table 15.1. ML fits for the first bootstrap sample generated under the null.

Null log likelihoodAlternative log likelihoodLikelihood ratio statistic
$-285.52513992$$-285.52500795$$0.00026394$

The unrestricted model increases the log likelihood slightly. Using the fitted values before rounding to the precision of Table 15.1 gives

\[T_1=2(\ell_{\mathrm{alt},1}-\ell_{\mathrm{null},1}) \approx 2[-285.525007945102-(-285.525139915861)] \approx 0.00026394.\]

The third column comes directly from first$fit$lr and agrees with the calculation from the two log likelihoods. The statistic falls below the observed 0.17546, so this replicate contributes zero to the count of statistics at least as large as the observed one.

Let $B$ be the number of assigned null replicates, $T_b$ the statistic from replicate $b$ and $T_{\mathrm{obs}}$ the statistic from the original responses. When all fits are usable, count each tie in the upper tail. The plus-one calculation includes the observed statistic among the $B+1$ values being compared. Generation at estimated null parameters makes this a bootstrap approximation to the null tail. Writing $e=\sum_{b=1}^{B}\mathbf{1}\lbrace T_b\geq T_{\mathrm{obs}}\rbrace $ for the number of simulated exceedances including ties, the resulting Monte Carlo p-value is $(1+e)/(B+1)$. Even if every simulated statistic falls below the observed one, the smallest reportable probability is $1/(B+1)$. Adding one does not make a fitted-null parametric bootstrap an exact finite-sample test in general; the estimated generating parameters still affect its approximation.

How variable is that estimate across repetitions of this simulation with the observed fit fixed? For independent replicates with exceedance probability $q$, the count has variance $Bq(1-q)$. Adding one leaves the variance of the numerator unchanged. Dividing by $B+1$ scales its standard deviation by the same divisor. For usable results from every assigned draw, substitute $\hat q=e/B$ to estimate this Monte Carlo standard error as $\sqrt{B\hat q(1-\hat q)}/(B+1)$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bootstrap_test_summary <- function(results, observed) {
  valid <- vapply(results, function(r) r$valid && is.finite(r$fit$lr), TRUE)
  lr <- vapply(results[valid], function(r) r$fit$lr, 0.0)
  B <- length(results)
  above <- sum(lr >= observed)
  missing <- B - length(lr)
  limits <- (1 + c(above, above + missing)) / (B + 1)
  # With missing fits the tail is bounded by allocating each unresolved outcome both ways.
  p <- if (!missing) limits[1] else NA_real_
  mcse <- if (!missing && B > 1L) sqrt(B * (above / B) *
    (1 - above / B)) / (B + 1) else NA_real_
  data.frame(attempted = B, usable = sum(valid), failed = missing, exceedances = above,
    p = p, lower = limits[1], upper = limits[2], resolution = 1 / (B + 1), MCSE = mcse)
}

Pass the fits to bootstrap_test_summary() to compare the null refits with the statistic in boundary_example.

1
print(bootstrap_test_summary(bootstrap_fits, boundary_example$lr))
1
2
3
4
  attempted usable failed exceedances      p  lower  upper resolution
1       399    399      0         136 0.3425 0.3425 0.3425     0.0025
        MCSE
1 0.02367014

All 399 null statistics were usable and 136 reached or exceeded the observed value. The bootstrap p-value is $137/400=0.3425$ and one additional exceedance would raise it by $1/400=0.0025$. Substituting $\hat q=136/399$ gives $\sqrt{399\hat q(1-\hat q)}/400\approx0.02367$. The difference of 0.00485 between the bootstrap p-value and the asymptotic mixture p-value of 0.33765 is smaller than one Monte Carlo standard error.

What would a failed refit contribute to the upper tail? One attempt is made for each assigned stream. An error during generation or fitting leaves the identifier and the error message in the list. The test summary also requires a finite likelihood ratio statistic. Suppose $f$ of the $B$ outcomes are unresolved and $e$ of the usable outcomes reach the observed statistic. If all unresolved statistics would have fallen below the threshold, the p-value would be $(1+e)/(B+1)$. If all would have reached it, the value would be $(1+e+f)/(B+1)$. In the summary function, above counts the exceedances and missing counts the unresolved outcomes.

The summary includes all assigned draws in the denominator and reports these bounds. It leaves the p-value and its Monte Carlo standard error missing when $f>0$. These are bounds obtained by assigning the unresolved outcomes to either side of the threshold. They are not confidence limits for the tail probability and do not measure Monte Carlo uncertainty. In the displayed run $f=0$, so the two bounds coincide.

Assigning a random-number stream to each replicate

To repeat a particular draw, replicate_streams() associates its starting state with its identifier. The first entry is the full state immediately after set.seed(). The second entry starts one stream beyond the first.

1
2
3
4
5
6
7
8
replicate_streams <- function(B, initial_stream, substreams = FALSE) {
  stopifnot(B >= 1, B == as.integer(B), length(initial_stream) == 7L)
  advance <- if (substreams) parallel::nextRNGSubStream else parallel::nextRNGStream
  streams <- vector("list", B)
  streams[[1L]] <- initial_stream
  if (B > 1L) for (i in 2:B) streams[[i]] <- advance(streams[[i - 1L]])
  streams
}

Successive calls to the advance function fill the remaining entries without drawing any responses. The generator divides its sequence into disjoint streams of length $2^{127}$, with substreams of length $2^{76}$. Replicate one therefore starts from bootstrap_streams[[1L]] whether it runs first or last. Restoring that state reproduces its response matrix with the same generator, design, fitted parameters and code. A worker could receive those inputs together with the identifier and the assigned stream.

The following sequential calculation visits three identifiers in increasing order, then in decreasing order. The outer rev() puts the second set of draws back into identifier order for printing. This separation presumes that a replicate does not exhaust its allocated stream or substream. The bootstrap wrapper above uses sequential lapply() with these assigned streams.

1
2
3
4
5
6
7
8
# A change in schedule leaves the first uniform assigned to each replicate intact.
first_draw <- function(id) {
  assign(".Random.seed", bootstrap_streams[[id]], envir = .GlobalEnv)
  runif(1L)
}
ids <- 1:3
print(data.frame(id = ids, increasing = vapply(ids, first_draw, 0.0),
  decreasing = rev(vapply(rev(ids), first_draw, 0.0))))
1
2
3
4
  id increasing decreasing
1  1 0.01415211 0.01415211
2  2 0.35052762 0.35052762
3  3 0.94211458 0.94211458

The first uniform for identifier 1 is 0.01415 under both processing orders. Identifiers 2 and 3 also repeat their first uniforms, 0.35053 and 0.94211 respectively. Each comparison uses one uniform from the assigned state. The amount of work already done on other replicates has no effect on that first draw.

A percentile interval for the fixed slope

For a percentile interval, use the fitted alternative to generate a separate set of 399 samples. Start each draw at the next substream of its identifier’s original state. This separates its random numbers from those used for the null sample with the same identifier. Extract the fixed slope from each successful unrestricted refit and sort the finite estimates. The central 95 percent of this distribution gives the percentile interval.

1
2
3
4
5
6
7
8
9
10
11
# Percentiles for the slope use data generated under the fitted alternative.
interval_streams <- lapply(bootstrap_streams, parallel::nextRNGSubStream)
alternative_sample <- function() balanced_variance_simulate(40L, boundary_x,
  boundary_example$beta,
  sqrt(boundary_example$sigma2), sqrt(boundary_example$tau2))
interval_fits <- parametric_bootstrap(interval_streams, alternative_sample,
  function(Y) balanced_variance_fit(Y, boundary_x))
slopes <- vapply(interval_fits,
  function(r) if (r$valid) unname(r$fit$beta["slope"]) else NA_real_, 0.0)
print(c(assigned = length(slopes), usable = sum(is.finite(slopes)),
  quantile(slopes, c(.025, .975), type = 7, na.rm = TRUE)))
1
2
   assigned      usable        2.5%       97.5% 
399.0000000 399.0000000   0.2707713   0.6552070 

All 399 estimated slopes were usable. For a probability $p$, the type-7 quantile interpolates at position $1+(399-1)p$ in the sorted slopes, with positions numbered from one. The lower endpoint lies at position 10.95 and the upper endpoint at 389.05. They give the interval $[0.27077,0.65521]$ for the fixed slope.

Its nominal level describes the choice of percentiles. To assess coverage, one would generate many original datasets at a specified true slope, construct an interval from each and count how often it contains that slope. If refits were lost, taking percentiles only among the successful fits could change the interval’s coverage. Finite slope estimates and fit status must both be checked; omission through na.rm is not a remedy for failed estimation.

A replicate can be identified by its generating model and its identifier together. Identifier 1 in bootstrap_fits denotes the first null draw, while identifier 1 in interval_fits denotes a draw under the fitted alternative. Each list entry retains the identifier, its complete starting state and a validity flag, with the paired fit on success or a reason on failure. The two lists contain 399 successful entries per generating model. Each successful fit records the fixed coefficients, the residual variance under each model, the alternative random-intercept variance, both log likelihoods and their likelihood ratio statistic. These fields support the summaries above.

Reproducing an entry also requires the group count and covariates from the common design and the generating coefficients and variances from the observed fit. The lme4 package provides model-based bootstrap resampling, and parallel supplies the stream functions.

15.6 Conditional and marginal randomized quantile residuals

The tests and intervals above take the fitted model as a description of the responses. What percentile should a count of zero occupy if the model assigns appreciable probability to zero? For observations with the same predictive distribution, assigning every zero to the top of that jump would give them identical residuals. Let $F$ be the cumulative distribution function (CDF) for the response under the model, with the observed covariates fixed. At an observed value $y$, write $L=F(y^-)=\Pr(Y<y)$ and $H=F(y)=\Pr(Y\leq y)$. The difference $H-L$ is the probability assigned to $y$. Draw $V$ uniformly on $(0,1)$ independently of $Y$ and use it to select a percentile within that interval. The randomized percentile $U$ and the randomized quantile residual $R$ are

\[U=L+V(H-L),\qquad R=\Phi^{-1}(U),\]

where $\Phi$ is the standard normal CDF. For a continuous response the two endpoints coincide, giving $U=F(Y)$. Under its known continuous distribution this percentile is uniform, so its normal quantile has the standard normal distribution.

For a discrete response, fix a possible count $k$ with probability $p_k>0$. Conditional on $Y=k$, the interpolation makes $U$ uniform between $F(k^-)$ and $F(k)$, an interval of length $p_k$. Take a point $u$ inside this interval. All lower counts contribute $F(k^-)$ to $\Pr(U\leq u)$. Count $k$ contributes its probability $p_k$ times the fraction of its interval to the left of $u$. Higher counts contribute zero. Thus

\[\Pr(U\leq u)=F(k^-)+p_k\,\frac{u-F(k^-)}{p_k}=u .\]

The intervals cover the unit interval up to endpoints of probability zero. It follows that $\Pr(R\leq z)=\Phi(z)$ at every real $z$ under the specified distribution. The function randomized_quantile_residuals() accepts a pair of CDF values per observation. Supplying the uniform vector lets two calculations use the same within-interval positions. The distributional statement uses the true response distribution; fitting its parameters introduces additional variation.

1
2
3
4
5
6
7
8
randomized_quantile_residuals <- function(lower,upper,uniform=runif(length(upper))) {
  stopifnot(length(lower)==length(upper),length(upper)==length(uniform),
    all(lower>=0),all(upper<=1),
    all(lower<=upper),all(uniform>=0 & uniform<=1))
  probability <- lower+uniform*(upper-lower)
  data.frame(lower=lower,upper=upper,uniform=uniform,probability=probability,
    residual=qnorm(probability))
}

The argument to qnorm() is the interpolated probability. If the calculation yields exactly zero or one, the returned normal quantile is respectively $-\infty$ or $+\infty$. A zero-width interval for a supposedly possible discrete response also requires investigation: it can reflect an impossible observation under the model or loss of a very small probability through rounding.

Conditional and marginal CDFs for grouped counts

Which CDF supplies the endpoints for a count in a group? Write $x_{ij}$ for the fixed-effect covariate vector of observation $j$ in group $i$, $\beta$ for its coefficients and $b_i$ for the group’s random intercept. Given $b_i=b$, a Poisson response has mean $\mu_{ij}(b)=\exp(x_{ij}^{\mathsf T}\beta+b)$. With an intercept and one covariate, $\beta_0$ is the log mean count at covariate zero and $b=0$. With $b$ fixed, a unit increase in the covariate changes the log mean by $\beta_1$ and multiplies the expected count by $\exp(\beta_1)$. The random-intercept variance measures between-group variation in the shared shift of the log mean. Counts are independent conditional on their group intercept.

With $P_k(\mu)$ denoting the Poisson probability of at most $k$ events at mean $\mu$, a conditional residual uses $F_{ij}(k\mid b)=P_k(\mu_{ij}(b))$. A residual for an observation in a new group averages that probability over the intercept distribution. For $b_i$ normal with mean zero and variance $\tau^2$, its marginal CDF is

\[F_{ij}(k)=\int P_k\!\left(\exp(x_{ij}^{\mathsf T}\beta+\tau z)\right)\phi(z)\,dz,\]

where $\phi$ is the standard normal density. Both calculations evaluate their respective CDFs at $y-1$ and $y$. The conditional calculation asks where the observation falls for a group at a particular intercept. The marginal calculation asks where it falls before anything is learned about its group’s intercept.

The simulated Poisson data make both questions observable. From the book directory, load the 640 counts in their original order, eight in each of 80 groups. The separate generating record supplies the fixed coefficients, random-intercept variance and realized intercept for each group. The integer vector group_index matches observations to the intercepts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.libPaths(c(".R-library", .libPaths()))
source("code/lib/integration.R")
source("code/lib/inference.R")
gl <- readRDS("data/derived/ch09/fits.rds")
rule <- normal_rule(61L)
count_data <- gl$count
truth <- readRDS("data/source/ch09/GLMM80-count-truth.rds")
count_mu <- exp(drop(count_data$X%*%truth$beta)+
  as.numeric(truth$b)[count_data$group_index])
counts <- count_data$y
marginal_cdf <- function(y,X,beta,sd,rule) {
  mu <- exp(outer(drop(X%*%beta),sd*rule$nodes,"+"))
  drop(matrix(ppois(y,mu),nrow(X))%*%rule$weights)
}

In marginal_cdf() each row corresponds to one observation and each column to a fixed Gauss-Hermite node. The weighted sum of the 61 Poisson probabilities approximates the integral in each row.

Set the random-number generator and seed immediately before drawing the 640 uniforms. Use the entire vector in both calculations. The time-series example continues from the state left by this draw.

1
2
3
4
5
6
7
8
9
10
11
12
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(1506)
v <- runif(length(counts))
marginal_residual <- function(data,beta,sd,v) randomized_quantile_residuals(
  marginal_cdf(data$y-1,data$X,beta,sd,rule),marginal_cdf(data$y,data$X,beta,sd,rule),v)
conditional <- randomized_quantile_residuals(ppois(counts-1,count_mu),
  ppois(counts,count_mu),v)
marginal <- marginal_residual(count_data,truth$beta,sqrt(truth$G[1]),v)
print(head(data.frame(id=count_data$id,count=counts,uniform=v,
  given_effect_lower=conditional$lower,given_effect_upper=conditional$upper,
  new_group_lower=marginal$lower,new_group_upper=marginal$upper,
  given_effect_residual=conditional$residual,new_group_residual=marginal$residual)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  id count    uniform given_effect_lower given_effect_upper new_group_lower
1  1     0 0.79273425          0.0000000          0.6119510       0.0000000
2  1     1 0.72543269          0.5674973          0.8889955       0.4208599
3  1     2 0.96651278          0.8601810          0.9712684       0.6778659
4  1     0 0.56807526          0.0000000          0.4705401       0.0000000
5  1     2 0.96126645          0.7835696          0.9420482       0.5773809
6  1     0 0.08621159          0.0000000          0.3667080       0.0000000
  new_group_upper given_effect_residual new_group_residual
1       0.4639523           -0.03732101         -0.3377100
2       0.7231003            0.84420505          0.3587661
3       0.8426983            1.84592479          0.9829279
4       0.3353214           -0.62099279         -0.8761002
5       0.7625747            1.52131658          0.6915867
6       0.2545561           -1.85757807         -2.0151268

For the first zero, the lower endpoint is zero under either model calculation because a Poisson count cannot be negative. At the first covariate value, $-1$, the generating coefficients are 0.2 and 0.5 and the realized intercept is $-0.41110$. The conditional mean is therefore $\exp(0.2-0.5-0.41110)$. The upper endpoint is the probability of zero, $\exp[-\mu_{11}(b_1)]\approx0.61195$ given the realized intercept, and 0.46395 averaged over a new intercept. Multiplying each upper endpoint by the same uniform, 0.79273, and taking normal quantiles gives $-0.03732$ and $-0.33771$. The larger probability of zero in this particular group places the count closer to the middle of its conditional distribution.

In observed data, substituting a group intercept estimated from that group’s responses also uses the count being diagnosed. The uniformity argument for a known intercept no longer establishes the reference distribution of that fitted residual.

Marginal standard normality is a statement about one residual at a time. Two counts from the same group share an intercept. A large intercept tends to raise both counts, and both can consequently occupy high positions in their respective new-group distributions. Drawing independent uniforms for their positions within the jumps leaves this source of association in place. A test calibrated for independent standard normal observations treats all 640 residuals as independent draws. To judge a diagnostic for these grouped data, its reference distribution must account for the shared intercepts and, when parameters are estimated, for fitting the model.

Predictive residuals for a count series

For a series, the information available before a response arrives determines its predictive CDF. Let $S_t$ be the hidden state at time $t$ and let $\alpha_{t-1,j}$ be the probability of state $j$ given the observations through $t-1$. With transition probability $a_{jk}$ from $j$ to $k$, the probability of state $k$ before observing $Y_t$ is $\pi_{t,k}=\sum_j\alpha_{t-1,j}a_{jk}$. At time one the state probabilities come directly from the fitted initial state distribution. If $\lambda_k$ is the Poisson mean in state $k$, the one-step predictive CDF at count $c$ is $\sum_k\pi_{t,k}P_c(\lambda_k)$. Smoothing would use the current response and later observations when assigning probabilities to its possible states. Filtering through the previous time supplies the state probabilities needed for prediction.

The calculation fixes the parameters at EM estimates from the full series. Thus the state probabilities use only past responses, but parameter estimation also uses later responses. Consequently this is a retrospective diagnostic using fitted parameters, not a prediction assessment in which all parameters were estimated before the next response was observed.

1
2
3
4
5
6
7
8
9
10
11
source("code/lib/stability.R")
source("code/lib/hmm.R")
hfit <- readRDS("data/derived/ch13/estimates.rds")$EM$model
series <- readRDS("data/source/ch13/HMM2.rds")
filtered <- hmm_forward(series,hfit)$filtering
predicted <- rbind(hfit$initial,head(filtered,-1)%*%hfit$transition)
poisson_cdf <- function(value) rowSums(predicted*
  vapply(hfit$parameter,function(mu)ppois(value,mu),
    numeric(length(series))))
time_residual <- randomized_quantile_residuals(poisson_cdf(series-1),poisson_cdf(series))
print(head(data.frame(time=seq_along(series),observation=series,time_residual)))
1
2
3
4
5
6
7
  time observation     lower     upper   uniform probability   residual
1    1           5 0.9601519 0.9883657 0.4164315   0.9719010  1.9094970
2    2           2 0.4352323 0.6961350 0.9463219   0.6821303  0.4736641
3    3           3 0.6953155 0.8564255 0.5466605   0.7833880  0.7836866
4    4           1 0.1520689 0.4329047 0.2771557   0.2299042 -0.7391625
5    5           0 0.0000000 0.1528417 0.7177065   0.1096955 -1.2281494
6    6           3 0.6960957 0.8573567 0.4671543   0.7714295  0.7435628

The first count is five. Its predictive CDF rises from 0.9601519 at four to 0.9883657 at five. The next uniform after the 640 count uniforms is 0.4164315. Interpolation gives 0.9719010 and hence a residual of 1.9094970. The positive residual locates five in the upper tail of the fitted initial mixture. At time two the first count has already updated the state probabilities used for prediction.

Envelopes from refitted simulations

Return to the grouped Poisson counts. How much would the ordered residuals vary if the fitted random-intercept Poisson regression model generated a new dataset? Preserve the covariates and group sizes, draw new group intercepts and counts, and refit the model to those counts. The observed fit used 15 adaptive quadrature nodes. Each of the 199 simulated datasets is refitted with 11 adaptive nodes. To see how one dataset contributes to the envelope, take the first assigned stream. Draw the residual uniforms after the refit and evaluate its marginal CDF with the fixed 61-node rule. The final quantile call retains 19 sample quantiles, at probabilities from 0.05 to 0.95 in steps of 0.05. The original fit and the refits thus use different quadrature orders.

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
source("code/lib/result.R")
source("code/lib/stability.R")
source("code/lib/differentiation.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/newton.R")
source("code/lib/logit.R")
source("code/lib/glm.R")
source("code/lib/lmm.R")
source("code/lib/glmm.R")
source("code/lib/boundary_test.R")
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(101506L)
envelope_streams <- replicate_streams(199L,.Random.seed)
quantiles <- seq(.05,.95,by=.05)
envelope_one <- lapply(1L,function(id) {
  assign(".Random.seed",envelope_streams[[id]],envir=.GlobalEnv)
  base <- gl$count_agq
  input <- glmm_generate(beta=base$beta,G=base$G,family="poisson")
  data <- glmm_as_data(input)
  fit <- tryCatch(glmm_fit(data),error=identity)
  if(inherits(fit,"error") || !isTRUE(fit$converged)) return(list(id=id,valid=FALSE,
    reason=if(inherits(fit,"error")) conditionMessage(fit) else fit$optimizer$reason))
  r <- marginal_residual(data,fit$beta,sqrt(fit$G[1]),runif(data$N))
  list(id=id,valid=TRUE,quantile=quantile(r$residual,quantiles),beta=fit$beta,G=fit$G)
})
envelope_one[[1L]]$quantile[10L]

The first refit gives a median of 0.03415. To reconstruct the entire envelope, use the saved vectors for the 199 refits. The matrix quantiles assembled below from the saved vectors has one column per successful refit and one row per probability. At each probability, take the 2.5th and 97.5th percentiles across columns.

These limits describe simulated sample quantiles under the fitted model. They are not confidence intervals for 19 fixed population quantiles, and the 19 separate limits do not form a simultaneous 95 percent band.

Compute the observed residuals from the original 15-node fit, the same fixed 61-node CDF rule and the original uniforms.

1
2
3
4
5
6
7
8
9
10
source("code/lib/integration.R", local = TRUE)
source("code/lib/inference.R", local = TRUE)
fits <- readRDS("data/derived/ch09/fits.rds")
data <- fits$count
fit <- fits$count_agq
u <- readRDS("data/derived/ch15/randomized-residual-uniforms.rds")
rule <- normal_rule(61L)
mu <- exp(outer(drop(data$X %*% fit$beta), sqrt(fit$G[1L]) * rule$nodes, "+"))
cdf <- function(y) drop(matrix(ppois(y, mu), nrow(data$X)) %*% rule$weights)
observed <- randomized_quantile_residuals(cdf(data$y - 1), cdf(data$y), u)$residual
1
2
3
4
5
6
7
8
9
10
11
12
records <- readRDS("data/derived/ch15/residual-envelope-records.rds")
valid <- vapply(records, function(r) r$valid, logical(1))
probabilities <- seq(.05, .95, by = .05)
# Each column holds the ordered residual quantiles for one successful refit.
quantiles <- vapply(records[valid], function(r) r$quantile,
  numeric(length(probabilities)))
envelope <- data.frame(model = "mixed", p = probabilities,
  observed = quantile(observed, probabilities),
  lower = apply(quantiles, 1L, quantile, .025),
  upper = apply(quantiles, 1L, quantile, .975),
  eligible = sum(valid), assigned = length(records))
print(envelope, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 model    p    observed       lower       upper eligible assigned
 mixed 0.05 -1.69843885 -1.80235478 -1.48475966      199      199
 mixed 0.10 -1.26977036 -1.38689244 -1.14890036      199      199
 mixed 0.15 -0.95925535 -1.12534807 -0.94545291      199      199
 mixed 0.20 -0.79074499 -0.91608929 -0.76239199      199      199
 mixed 0.25 -0.65454833 -0.74464078 -0.60498696      199      199
 mixed 0.30 -0.52319981 -0.60048806 -0.46008399      199      199
 mixed 0.35 -0.38967726 -0.44947678 -0.32613610      199      199
 mixed 0.40 -0.28215869 -0.31000901 -0.18750881      199      199
 mixed 0.45 -0.17637379 -0.18434945 -0.06220477      199      199
 mixed 0.50 -0.04221189 -0.05716629  0.06521870      199      199
 mixed 0.55  0.11741391  0.05069453  0.18669251      199      199
 mixed 0.60  0.24661524  0.18164431  0.32203316      199      199
 mixed 0.65  0.43373027  0.31921661  0.45756729      199      199
 mixed 0.70  0.53110710  0.45973382  0.58871200      199      199
 mixed 0.75  0.67791431  0.59130472  0.74206607      199      199
 mixed 0.80  0.86642771  0.76110491  0.91713735      199      199
 mixed 0.85  0.97696735  0.95154256  1.11880708      199      199
 mixed 0.90  1.19857447  1.18616953  1.37102598      199      199
 mixed 0.95  1.76000850  1.48447372  1.80372287      199      199

For example, the observed median is $-0.04221$ and the pointwise limits are $-0.05717$ and 0.06522. All 199 refits contributed and all 19 observed quantiles lie inside their corresponding intervals. The envelope includes refitting and residual randomization under the stated 15-node original fit and 11-node refit procedures.

Comparison with ordinary Poisson regression

Compare an ordinary Poisson regression with a common intercept and covariate slope against the random-intercept model on the same observed counts. The ordinary regression assumes independent Poisson responses with log mean $\beta_0+\beta_1x$. Its intercept is the log mean at covariate zero, and its slope changes the log mean per covariate unit. It uses just the two columns of d$X. Its CDF is $P_k(\hat\mu_{ij})$ at the fitted regression mean. The mixed-model CDF averages over the fitted intercept distribution. Reuse the observed mixed-model fit in fit and the saved uniform vector in u. The first row below puts the two pairs of CDF values beside the residuals they produce.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
d <- fits$count
v <- u
stopifnot(length(v) == length(d$y))
ng<-length(unique(d$id))
assoc<-function(r)cor(matrix(r,ng,byrow=TRUE)[,1],matrix(r,ng,byrow=TRUE)[,2])
prob<-seq(.05,.95,.05);quad<-normal_rule(61L)
plain<-glm.fit(d$X,d$y,family=poisson());stopifnot(plain$converged)
cdf<-function(y,mixed){
 if(!mixed)return(ppois(y,plain$fitted.values))
 mu<-exp(outer(drop(d$X%*%fit$beta),sqrt(fit$G[1])*quad$nodes,"+"))
 drop(matrix(ppois(y,mu),nrow(d$X))%*%quad$weights)
}
endpoints<-lapply(c(FALSE,TRUE),function(mix)list(lo=cdf(d$y-1,mix),hi=cdf(d$y,mix)))
r<-lapply(endpoints,function(e)randomized_quantile_residuals(e$lo,e$hi,v))
cbind(id=d$id,y=d$y,uniform=v,fixed_lower=r[[1]]$lower,fixed_upper=r[[1]]$upper,
 mixed_lower=r[[2]]$lower,mixed_upper=r[[2]]$upper,
   fixed_residual=r[[1]]$residual,mixed_residual=r[[2]]$residual)[1L, ]

For the first zero the fitted CDF intervals are $[0,0.32214]$ and $[0,0.45101]$, giving residuals $-0.65767$ and $-0.36507$ for ordinary and mixed regression, respectively. Correlate the residual at position one with that at position two across the 80 groups. The correlations are 0.559 and 0.500. With both fits and their endpoints fixed, draw one new uniform vector for both models.

1
2
3
4
5
6
7
8
set.seed(150625)
r2<-runif(length(v))
do.call(rbind,lapply(1:2,function(j){
 e<-endpoints[[j]];repeat_r<-randomized_quantile_residuals(e$lo,e$hi,r2)$residual
 data.frame(model=c("fixed","mixed")[j],lag_first_pair=assoc(r[[j]]$residual),
   different_uniforms=assoc(repeat_r),
 original_first=r[[j]]$residual[1],rerandomized_first=repeat_r[1])
}))

The first residuals become $-1.17233$ and $-0.95912$ and the correlations become 0.434 and 0.325. Only the randomization has changed.

For the ordinary regression, generate 199 Poisson samples at its fitted means and refit the same regression to each. Transposing the mixed-model quantile matrix puts replicates in rows, matching the ordinary regression matrix. The columns now identify probabilities in both models.

1
2
3
4
5
6
7
8
9
10
11
12
13
mq<-t(quantiles)
set.seed(150626)
fq<-do.call(rbind,lapply(1:199,function(i){
 y<-rpois(nrow(d$X),plain$fitted.values);f<-glm.fit(d$X,y,
   family=poisson());stopifnot(f$converged)
 quantile(randomized_quantile_residuals(ppois(y-1,f$fitted.values),
   ppois(y,f$fitted.values))$residual,prob)
}))
qq<-do.call(rbind,lapply(1:2,function(j){q<-list(fq,mq)[[j]]
 data.frame(model=c("fixed","mixed")[j],p=prob,observed=quantile(r[[j]]$residual,prob),
 lower=apply(q,2,quantile,.025),upper=apply(q,2,quantile,.975),
   eligible=nrow(q),assigned=199)
}))

The supplied CSV stores the results of the same envelope calculation, including both sets of limits and observed quantiles. Selecting its 95th-percentile rows connects the upper end of each plotted curve to its numerical limits.

1
2
envelopes <- read.csv("data/derived/ch15/residual-envelopes.csv")
envelopes[envelopes$p == max(envelopes$p), c("model", "p", "observed", "lower", "upper")]

Observed residual quantiles extend below and above the gray band for ordinary Poisson regression. All 19 points lie inside the band for the random-intercept model.

Figure 15.1. Each dot is a sample quantile of the observed randomized quantile residuals, plotted against the standard normal quantile at the same probability. The gray band connects pointwise 95 percent limits from 199 refits of the model in that panel. The dashed line marks equality of the two quantiles.

In Figure 15.1, the ordinary regression has 17 of 19 observed quantiles outside its envelope. Its observed 95th percentile is 2.983, above the upper limit of 1.767. The low end of the observed curve also extends beyond the band. All 19 points in the random-intercept panel fall inside the envelope.

Each point describes one marginal quantile. Pairing the residuals at positions one and two within each of the 80 groups still gives a positive correlation. Each shaded interval applies at its own probability, so the number of points outside has no simultaneous 95 percent calibration. The statmod package provides randomized quantile residuals for ordinary Poisson regression.

15.7 Local independence checks and item fit

Local independence requires that, given ability, an examinee’s answers be independent. This section compares observed and fitted probabilities for pairs of items after integrating over ability, calculates how a shared stimulus changes the pair probabilities in the population and in one sample, and then checks the fit of single items within total-score groups.

Pair discrepancies after integrating over ability

Suppose that examinees who answer one reading item correctly also tend to answer a second item correctly. How much of that association would a single general ability explain? Let $Z$ denote an examinee’s standard normal ability, and let $p_j(z)$ be the fitted probability of a correct response to item $j$ at ability $z$. Write $p_{j1}(z)=p_j(z)$ and $p_{j0}(z)=1-p_j(z)$. Under local independence, the responses to items $i$ and $j$ are independent conditional on the same $Z=z$. Their joint probability at that ability is the product of the two response probabilities. Averaging over examinees gives the four population cell probabilities

\[\pi_{uv}=\int p_{iu}(z)\,p_{jv}(z)\,\phi(z)\,dz, \qquad u,v\in\{0,1\},\]

where $\phi$ is the standard normal density. In particular, two correct responses have probability $\int p_i(z)p_j(z)\phi(z)\,dz$. For items whose probabilities both increase with ability, high-ability examinees contribute disproportionately to this cell. Multiplying the two marginal success probabilities would average over a separate ability for each item and would lose that source of association.

With responses to both items available for $N$ examinees, the model predicts $E_{uv}=N\pi_{uv}$ examinees in cell $(u,v)$. Denote its observed count by $O_{uv}$. The Chen and Thissen local dependence statistic sums the four Pearson contributions, $X^2=\sum_{u,v}(O_{uv}-E_{uv})^2/E_{uv}$. For two dichotomous items, the reported p-value uses a one-degree-of-freedom chi-square approximation. Its accuracy depends on the fitted expected counts and item calibration. The one-degree-of-freedom reference is the proposed approximation for this fitted item-pair diagnostic, not a general chi-square theorem for any four fitted cell counts.

A signed version of Cramér’s $V$ gives the direction of the discrepancy. For a two-by-two table with entries $n_{uv}$, put $C=n_{00}n_{11}$ and $D=n_{01}n_{10}$. The Goodman-Kruskal gamma coefficient is $(C-D)/(C+D)$ when the denominator is positive. Compare gamma for the observed table with gamma for the expected table. The sign of their difference multiplies $\sqrt{X^2/N}$, with a positive sign by convention for a tie. Here signed $V$ scales a discrepancy from model-implied counts; it is not the ordinary Cramér association coefficient computed from independence-table counts and need not have its usual bound of one. From the book directory, load the fitting and integration functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
source("code/lib/irt.R")

The following function compares observed and model-implied counts for every pair of items in a fitted one-factor binary-response model. It returns the Pearson discrepancy, its signed, scaled magnitude and the approximate p-value.

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
multidim_residuals_ld <- function(fit) {
  design <- fit$design
  stopifnot(design$q == 1L)
  data <- design$Y
  J <- ncol(data)
  grid <- multidim_unidimensional_grid(61L)
  probs <- lapply(seq_len(J), function(i) {
    P <- multidim_item_probability(multidim_item_par(fit$par_vec, design, i), grid$Theta)
    cbind(1 - P, P)
  })
  pair_row <- function(i, j) {
    observed <- table(factor(data[, i], levels = 0:1), factor(data[, j], levels = 0:1), useNA = "no")
    n_total <- sum(observed)
    cell <- function(k, m) n_total * sum(probs[[i]][, k] * probs[[j]][, m] * grid$prior)
    fitted <- matrix(c(cell(1, 1), cell(2, 1), cell(1, 2), cell(2, 2)), 2, 2)
    observed_gamma <- multidim_gamma_correlation(observed)
    fitted_gamma <- multidim_gamma_correlation(fitted)
    s <- observed_gamma - fitted_gamma
    sign_defined <- is.finite(s)
    if (!sign_defined) s <- 0
    X2 <- sum((observed - fitted)^2 / fitted)
    data.frame(item1 = i, item2 = j, X2 = X2,
      signed_V = sign(if (s == 0) 1 else s) * sqrt(abs(X2) / n_total),
      p = pchisq(abs(X2), df = 1, lower.tail = FALSE), sign_defined = sign_defined,
      sign_reason = if (sign_defined) "gamma_difference" else "undefined_gamma_nonnegative_magnitude",
      observed_gamma = observed_gamma, fitted_gamma = fitted_gamma)
  }
  rows <- list()
  for (i in seq_len(J)) for (j in seq_len(J)) if (i < j)
    rows[[length(rows) + 1L]] <- pair_row(i, j)
  do.call(rbind, rows)
}

The pair calculation obtains 61 equally spaced ability values from $-6$ to $6$ through multidim_unidimensional_grid(). For each item, multidim_item_par() extracts its parameter block and multidim_item_probability() evaluates its success probabilities at those values. Normalizing the standard normal densities at those points gives the grid weights. Columns one and two of probs[[i]] and probs[[j]] correspond to incorrect and correct responses. Multiplication within a row fixes ability before the sum in cell() averages over it. The helper multidim_gamma_correlation() evaluates the gamma coefficient for each table. If their difference is nonfinite, pair_row() retains the nonnegative discrepancy magnitude and sets sign_defined=FALSE. That magnitude then carries no interpreted direction of association.

Another way to examine the pair is to ask whether an examinee who exceeds the predicted response on one item also tends to exceed it on the other. For examinee $h$, obtain an ability estimate $\hat z_h$, for example the posterior mean given the response pattern. Subtract the predicted probability at that estimate from the observed response to each item, giving $e_{hj}=y_{hj}-p_j(\hat z_h)$. Yen’s $Q_3$ for items $i$ and $j$ is the correlation of these two columns of residuals across examinees. Both responses helped determine $\hat z_h$. A correct answer can raise the estimated ability and thereby raise the predicted probability on the other item as well. Reusing the responses can shift the residual correlation below zero even under local independence. The pairwise statistic computed here uses the integrated cell probabilities.

A shared stimulus in the population and one sample

To give the pair diagnostic a concrete target, first calculate how a shared stimulus changes the population probabilities, then examine one simulated sample. A testlet consists of items that share a stimulus, such as two questions about the same passage. Suppose that, in addition to general ability $Z$, success on the first two items depends on an independent standard normal variable $T$ for the testlet. For item $j$ in this pair the log odds are $a_j(Z-b_j)+0.7T$, with discrimination $a_j$ and difficulty $b_j$. With $T$ fixed, $a_j$ changes the log odds per standard deviation of general ability. At $T=0$, ability $Z=b_j$ gives success probability one half. The testlet loading changes the log odds per standard deviation of $T$ with $Z$ fixed. Responses are independent given both latent variables.

Compare this construction with one in which each item has its own independent standard normal effect, still with loading 0.7. In both cases a given examinee has the same general ability on the two items. Each item also has the same distribution of its own additional effect, so its marginal success probability is unchanged. What changes is the average of the product. With one shared effect, a high value raises both probabilities together at any fixed ability. With separate effects, average each item’s probability over its own effect first, multiply those two averages at the same ability, and then integrate over ability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
rule31 <- normal_rule(31L)
latent <- product_rule(31L,2L)
slopes <- c(.7,.9,1,1.1,1.2,.8,1.3,1)
diffs <- seq(-1.5,1.5,length.out=8)
item_truth <- lapply(seq_along(slopes),
  function(j)dichotomous_item(a=slopes[j],d=-slopes[j]*diffs[j]))
p1 <- plogis(slopes[1]*(latent$nodes[,1]-diffs[1])+.7*latent$nodes[,2])
p2 <- plogis(slopes[2]*(latent$nodes[,1]-diffs[2])+.7*latent$nodes[,2])
probability_at_general <- function(j) drop(plogis(outer(slopes[j]*(rule31$nodes-diffs[j]),
  .7*rule31$nodes,"+"))%*%rule31$weights)
print(rbind(shared=c(margin=sum(exp(latent$log_weights)*p1),
  pair=sum(exp(latent$log_weights)*p1*p2)),
  separate=c(margin=sum(rule31$weights*probability_at_general(1)),
    pair=sum(rule31$weights*probability_at_general(1)*probability_at_general(2)))))
1
2
3
            margin      pair
shared   0.7061108 0.5186271
separate 0.7061108 0.5022179

The two-dimensional Gauss-Hermite rule in latent uses 31 points per dimension for the shared effect calculation. The separate calculation uses successive 31-point sums. The first item’s success probability is 0.70611 in both rows. Sharing the effect raises the probability of two correct responses from 0.50222 to 0.51863, an increase of about 1.64 percentage points.

To see what the pair diagnostic detects in a sample, generate responses from the shared-effect model for 800 new examinees. With seed 1507, draw the 800 general abilities, then the 800 testlet effects, then the uniforms that determine the eight item responses for each examinee. Only the first two items receive the additional effect. Fit a locally independent one-factor two-parameter logistic model to the resulting response matrix. Its EM calibration uses a grid of 61 equally spaced points with normal-density weights, the grid used to evaluate the fitted pair counts.

1
2
3
4
5
6
7
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1507); general <- rnorm(800); testlet <- rnorm(800)
eta <- sweep(outer(general,slopes),2,slopes*diffs)
eta[,1:2] <- eta[,1:2]+.7*testlet
testlet_Y <- matrix(as.integer(runif(length(eta))<plogis(eta)),800)
testlet_fit <- multidim_em(testlet_Y,1L)
stopifnot(testlet_fit$converged)

The fit passed the EM stopping check when every absolute parameter change was below $10^{-4}$. Passing this parameter-change rule is not itself a check of the final likelihood score or of the item-parameter information matrix. Compare the observed pair tables with the fitted expectations.

1
2
3
# Compare each observed pair table with fitted counts using a chi-square approximation.
pairs <- multidim_residuals_ld(testlet_fit)
print(pairs[order(-pairs$X2),][1:5,])
1
2
3
4
5
6
7
8
9
10
11
12
13
   item1 item2        X2    signed_V          p sign_defined      sign_reason
8      2     3 3.2762115 -0.06399425 0.07029101         TRUE gamma_difference
18     3     8 2.2911312  0.05351555 0.13011506         TRUE gamma_difference
6      1     7 1.1807873  0.03841854 0.27719577         TRUE gamma_difference
1      1     2 0.9212078  0.03393390 0.33715805         TRUE gamma_difference
7      1     8 0.8997512 -0.03353638 0.34284843         TRUE gamma_difference
   observed_gamma fitted_gamma
8       0.2358226    0.3620801
18      0.5246671    0.4053645
6       0.4457680    0.3469080
1       0.3251848    0.2530729
7       0.1958417    0.2839964

Of the 28 pairs, items 2 and 3 have the largest statistic, 3.276, with $p=0.070$. Their negative signed $V$ indicates weaker observed association than the fitted model predicts on the gamma scale. Items 1 and 2, the pair specified by the stimulus, rank fourth with $X^2=0.921$, $p=0.337$, and signed $V=0.034$. Their observed association exceeds the fitted association, but the discrepancy does not reach the 0.05 threshold. The population comparison fixed the general-ability item parameters. Here the cell counts vary across samples and the one-factor parameters are estimated from the same 800 response patterns. A higher population probability of two correct responses therefore need not produce a large sample statistic. Estimating detection power would require repeated samples from the specified generating model.

Item fit within total-score groups

A pair statistic combines responses over all levels of performance. To examine one item at a given performance level, group examinees by their total score $S$ on all eight items, including the item being checked. The Orlando and Thissen $S\text{-}X^2$ statistic compares observed and expected counts of incorrect and correct responses within these groups. Let $S_{-j}$ be the sum on the other seven items and let $n_s$ be the observed number with total $s$. For item response $y$, the event $Y_j=y,\ S=s$ requires the remaining items to sum to $s-y$. Local independence at a fixed ability gives the numerator of the conditional probability. Multiplying by the score-group frequency gives the expected count

\[E_{sy}=n_s\, \frac{\int p_{jy}(z)\Pr(S_{-j}=s-y\mid Z=z)\phi(z)\,dz} {\Pr(S=s)} .\]

The fitted model supplies the denominator by integrating the probability of the total over ability. At each node, the probability of a new total $s$ is the sum, over the added item’s categories $k$, of its category probability times the preceding items’ probability of total $s-k$. The first part of the function builds these score distributions and uses them to form the expected counts.

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
multidim_item_fit_sx2 <- function(fit, min_cell = 1) {
  design <- fit$design
  stopifnot(design$q == 1L)
  dat <- design$Y
  J <- ncol(dat)
  if (J < 2L) stop("S-X2 requires at least two items")
  K <- rep(2L, J)
  item_start <- c(1L, cumsum(K) + 1L)
  grid <- multidim_unidimensional_grid(61L)
  prior <- grid$prior
  item_probs <- t(multidim_category_probabilities(fit$par_vec, design, grid$Theta))
  # Group by observed total score, including the item being assessed.
  O <- multidim_observed_score_tables(dat, K)
  Nk <- rowSums(O[[1L]])
  l1_total <- multidim_sum_score_probabilities(item_probs, K, item_start)$likelihood %*% prior
  # Expected counts of item i: its response probability times the summed-score likelihood
  # of the other items, over the likelihood of the total score, times the group size.
  expected_for <- function(i) {
    own <- seq(item_start[i], item_start[i + 1L] - 1L)
    # First rows of the other items once item i is removed.
    starts <- c(1L, cumsum(K[-i]) + 1L)
    # At each node, find the score probabilities for the other items.
    rest <- multidim_sum_score_probabilities(item_probs[-own, , drop = FALSE], K[-i],
      starts)$likelihood
    shares <- matrix(NA, nrow(l1_total), length(own))
    for (j in seq_along(own)) {
      at <- seq_len(nrow(rest)) + j - 1L
      shares[at, j] <- rest %*% (item_probs[own[j], ] * prior) / l1_total[at, ]
    }
    shares[-c(1L, nrow(shares)), , drop = FALSE] * Nk
  }
  E <- lapply(seq_len(J), expected_for)

multidim_sum_score_probabilities() builds the score distribution one item at a time. Its returned likelihood matrix has totals starting at zero in rows and ability nodes in columns. Its inputs K and item_start specify category counts and the starting row of each item’s probabilities. multidim_observed_score_tables() returns one observed table per item, with nonextreme total scores in rows and that item’s responses in columns. Thus Nk counts examinees in each retained total-score group. The rows own of item_probs contain the two response probabilities at the grid points, and rest gives the corresponding distributions of the remaining score. The code indexes items by i and the two response columns by j. Shifting each remaining-score row by j - 1L adds zero or one to form the total. At totals zero and eight the total determines every response, so the calculation drops these two rows.

Before summing the Pearson contributions, pool sparse score groups so that a single tiny expected count does not dominate the statistic. Apply every merge to the observed and expected tables together. The chi-square reference is an approximation after pooling and item parameter estimation. The degrees of freedom equal the number of nonmissing expected cells minus the number of retained groups and the two estimated item parameters. When both response categories contribute in every retained group, this reduces to the number of groups minus two. These degrees of freedom assume two estimated parameters per item; they cannot be reused unchanged for fixed coefficients or a different item model.

The column RMSEA is the root mean square error of approximation derived here from each item’s $S\text{-}X^2$, its degrees of freedom and the number of respondents. For positive degrees of freedom $d$ and $N$ respondents, it is $\sqrt{\max\lbrace (S\text{-}X^2-d)/[d(N-1)],0\rbrace }$: it measures the positive excess over the degrees of freedom on a scale adjusted for $d$ and $N$. The function reports zero when the statistic does not exceed $d$ and an unavailable value when $d=0$. It is an item-level summary; overall structural equation model cutoffs do not follow from this calculation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  tables <- list(O = O, E = E)
  # Sparse cells are pooled before the statistic is computed.
  coll <- multidim_pool_sparse_groups(O, E, min_cell = min_cell)
  # S-X2 over the pooled cells; degrees of freedom: cells - rows - 2, at least 0.
  S_X2 <- vapply(seq_len(J), function(i)
    sum((coll$O[[i]] - coll$E[[i]])^2 / coll$E[[i]], na.rm = TRUE), 0)
  df <- vapply(seq_len(J), function(i) sum(!is.na(coll$E[[i]])) - nrow(coll$E[[i]]) - 2, 0)
  df <- pmax(df, 0)
  S_X2[df == 0] <- NaN
  # RMSEA from S-X2 and its degrees of freedom; NaN without degrees of freedom.
  excess <- S_X2 / df - 1
  RMSEA <- ifelse(df <= 0, NaN,
    suppressWarnings(ifelse(excess > 0 & df > 0, sqrt(excess / (nrow(dat) - 1)), 0)))
  p_value <- suppressWarnings(pchisq(S_X2, df, lower.tail = FALSE))
  list(table = data.frame(item = seq_len(J), S_X2 = S_X2, df = df, RMSEA = RMSEA,
    p = p_value), raw = tables, collapsed = coll,
    status = data.frame(item = seq_len(J), valid = is.finite(S_X2) & df > 0,
      reason = ifelse(df <= 0, "no_positive_degrees_of_freedom",
        ifelse(is.finite(S_X2), "evaluated", "nonfinite_statistic"))))
}

The helper multidim_pool_sparse_groups() removes empty groups and pools a singleton with an adjacent group. When a positive expected count is below one, it combines that group with the neighbor having fewer observations, or with the only available neighbor at an edge. This pooling rule is an implementation choice. It does not guarantee a good chi-square approximation, especially after estimation from the same respondents. The completed function returns the item statistics along with the original and pooled tables. Apply it to the same fitted one-factor model used for the pair checks.

1
2
item_fit <- multidim_item_fit_sx2(testlet_fit)
print(item_fit$table)
1
2
3
4
5
6
7
8
9
  item      S_X2 df       RMSEA          p
1    1  8.427933  5 0.029292592 0.13417519
2    2  5.164036  5 0.006407833 0.39619098
3    3 12.319462  5 0.042803688 0.03066315
4    4  3.469798  5 0.000000000 0.62796245
5    5 10.958721  5 0.038620522 0.05220459
6    6  1.948825  5 0.000000000 0.85617982
7    7  7.339937  4 0.032327026 0.11897806
8    8  5.080896  5 0.004499911 0.40608764

Item 3 has $S\text{-}X^2=12.319$ on five degrees of freedom with $p=0.031$. For item 5 the statistic is 10.959 with $p=0.052$. All remaining item p-values exceed 0.11. Pooling leaves item 7 with four degrees of freedom. The collapsed tables show which counts contributed to an item statistic. Print the one for item 1.

1
2
print(cbind(observed=item_fit$collapsed$O[[1]],
  expected=round(item_fit$collapsed$E[[1]],2)))
1
2
3
4
5
6
7
8
   0   1             
1 47  24 42.93  28.07
2 39  79 48.43  69.57
3 44  88 38.60  93.40
4 29 124 31.96 121.04
5 22  92 16.40  97.60
6  7  89  8.73  87.27
7  2  64  2.95  63.05

For item 1, the first two columns give the observed counts for responses zero and one, and the last two give the fitted expectations. At total one, 47 and 24 compare with 42.93 and 28.07. At total seven, 2 and 64 compare with 2.95 and 63.05. The largest absolute gap is 9.43 at total two. Of 118 examinees in that group, 79 answered correctly against 69.57 expected, while 39 answered incorrectly against 48.43 expected. Using the rounded expectations, the two cells contribute $9.43^2(1/48.43+1/69.57)\approx3.11$ to the item 1 statistic of 8.43.

Item 3’s statistic concerns response counts within total-score groups. The pair statistic for items 2 and 3 concerns association beyond the fitted general ability. A common stimulus is one possible explanation for an unexplained association. Identifying that mechanism requires evidence about how the items were constructed. The 28 pair checks share examinees and often an item. The eight item checks use the same totals and fitted calibration. Their reported p-values have no adjustment for multiple testing. Interpret an unusual result alongside its cell discrepancies and the content of the items before proposing an additional effect. The supplied item-fit and local-dependence functions are translated from the mirt package (code/NOTICE.md), which provides the corresponding diagnostics.

15.8 Identification, Hessian eigenvalues, and variation across starting values

A model can fail to determine its parameters, and a numerical calculation can make a well-determined parameter appear poorly determined. This section uses Hessian eigenvalues in the FA6 factor model to separate these cases and shows how a change of coordinate units alters the eigenvalues. It then compares two-component mixture fits from different starting values and separates integration error from incomplete optimization in a three-parameter logistic calibration.

Distinguishing nonidentification from numerical error

If the Hessian at a factor model fit has a nearly zero eigenvalue, can the data distinguish the loading vectors along that direction? In the simulated FA6 sample, each of 600 people contributes six responses. The negative log likelihood $f$ of those vectors has gradient $g$ and Hessian $H$ in the coordinates used for estimation. At a candidate minimum allowing small changes in every free coordinate, the gradient measures first-order change. The Hessian gives the curvature along any proposed displacement of the loadings and variances. If $U$ is the upper triangular Cholesky factor of $H$, solve $Us=g$ and compute

\[m=\max_j\min\{|g_j|,|s_j|\}.\]

The code reports this quantity as max_min_abs_gradient and flags $m>0.002$. A failed solve leaves the scaled gradient unavailable. For the curvature check, write $\tau=10^{-6}$. An eigenvalue below $-\tau$ flags negative curvature. Otherwise an eigenvalue with absolute value below $\tau$, or failure of the Cholesky factorization, flags numerical singularity. If those checks pass, a largest eigenvalue above $1/\tau$ or a smallest-to-largest ratio below $\tau$ also produces a warning. These are numerical diagnostics. For the factor model, the covariance formula determines whether a small eigenvalue reflects an exact invariance. The reported maximum takes the smaller of the raw and transformed magnitudes separately for each coordinate. It is a software convergence diagnostic, not a likelihood score statistic with a sampling reference distribution.

The response vector follows $Y=\mu+LF+\varepsilon$, with two centered normal factors having covariance $I_2$. The normal errors are independent of the factors and one another, with mean zero and unique variances $\psi_1,\ldots,\psi_6$. The mean $\mu_j$ is the expected response when both factors are zero. In the six-by-two loading matrix $L$, entry $L_{jk}$ changes that conditional mean in response units per standard deviation of factor $k$, with the other factor fixed. The unique variance $\psi_j$ is the remaining response variance given both factors, in squared response units. For any orthogonal two-by-two matrix $R$, write $M=LR$. The common-factor part of the covariance satisfies

\[MM^\top=(LR)(LR)^\top=L(RR^\top)L^\top=LL^\top.\]

The unique variances add the fixed diagonal matrix $\operatorname{diag}(\psi)$ to the covariance, so the full model implies the same covariance $\Sigma$ at every rotation angle. With the response means set to their sample values, the Gaussian negative log likelihood depends on the loadings only through $\Sigma$. For the sample covariance $S$ with divisor $n=600$, the part that varies with the loadings is $n\lbrace \log\vert \Sigma\vert +\operatorname{tr}(S\Sigma^{-1})\rbrace /2$. Read the jointly fitted loadings and unique variances, form $S$ from the observed responses, and compare each rotated covariance with the one at the fitted orientation.

1
2
3
4
5
6
7
8
9
10
11
source("code/lib/factor.R")
source("code/lib/differentiation.R")
source("code/lib/inference.R")
fa <- readRDS("data/derived/ch06/fits.rds")$joint
L <- fa$loadings; psi <- fa$uniquenesses
fa_d <- fa_data(readRDS("data/source/ch06/FA6.rds")$observed)
fa_Sigma <- fa_implied(L,psi)
fa_par <- fa_pack(L,psi)
rotation <- function(a) matrix(c(cos(a),sin(a),-sin(a),cos(a)),2L)
print(data.frame(angle=c(0,.3,.7),max_cov_change=vapply(c(0,.3,.7),function(a)
  max(abs(fa_implied(L%*%rotation(a),psi)-fa_Sigma)),0.0)))
1
2
3
4
  angle max_cov_change
1   0.0   0.000000e+00
2   0.3   2.220446e-16
3   0.7   1.110223e-16

The covariance differences are at rounding precision. Follow the first loading pair through three rotations. In the loop, S denotes the rotated model covariance and fa_d$S contains the sample covariance.

1
2
3
4
5
6
7
angles <- c(-pi/4,0,pi/4)
print(do.call(rbind,lapply(angles,function(angle) {
  loading <- L%*%rotation(angle)
  S <- fa_implied(loading,psi)
  data.frame(angle=angle,first_loading=loading[1,1],second_loading=loading[1,2],
    nll=fa_criterion(S,fa_d)$nll,max_covariance_change=max(abs(S-fa_Sigma)))
})))
1
2
3
4
       angle first_loading second_loading      nll max_covariance_change
1 -0.7853982     0.5690055      0.5690055 4505.966          2.220446e-16
2  0.0000000     0.8046952      0.0000000 4505.966          0.000000e+00
3  0.7853982     0.5690055     -0.5690055 4505.966          2.220446e-16

At zero the first pair is $(0.80470,0)$. Turning the axes by $-\pi/4$ gives $(0.56901,0.56901)$, and turning them by $\pi/4$ gives $(0.56901,-0.56901)$. All three orientations give the same negative log likelihood, 4505.966. The algebra guarantees equality at every angle for any sample size.

Setting $L_{12}=0$ and requiring positive diagonal loadings fixes the orientation. Eleven free loadings and six unique variances then give 17 coordinates. In the packed coordinates of Section 6.1, the two positive diagonal loadings and the six unique variances are on the log scale. Use the analytic gradient to compute curvature at the stored solution in these coordinates.

1
2
3
4
objective <- make_fa_objective(fa_d,2L)
curvature <- num_hess(objective$fn,fa_par,gr=objective$gr)$hessian
nll_gradient_fa <- objective$gr(fa_par)
spectrum <- eigen(curvature,symmetric=TRUE,only.values=TRUE)$values

Use this 17-coordinate Hessian and gradient as the reference for the comparisons below. Append an eighteenth coordinate $a$ and evaluate the criterion at $M=LR(a)$.

1
2
3
4
5
angle_fn <- function(v) {
  nat <- fa_unpack(v[-length(v)],fa_d$p,2L)
  fa_criterion(fa_implied(nat$loadings%*%rotation(v[length(v)]),
    nat$uniquenesses),fa_d)$nll
}

To differentiate it, set $A=\Sigma^{-1}-\Sigma^{-1}S\Sigma^{-1}$. The gradient with respect to $M$ is $G=nAM$. Since $dM=(dL)R(a)+LR^{\prime}(a)\,da$, the gradient with respect to $L$ is $GR(a)^\top$, and a change in the angle gives $\partial f/\partial a=\sum_{ij}G_{ij}[LR^{\prime}(a)]_{ij}$. The log transformation multiplies the derivative with respect to each positive diagonal loading by that loading and the derivative with respect to each unique variance by that variance. Compare this chain rule with numerical derivatives where the derivatives with respect to the loadings are appreciable. The check adds 0.01 to each identified coordinate and sets the angle to 0.3 radians.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
angle_gr <- function(v) {
  nat <- fa_unpack(head(v,-1L),fa_d$p,2L)
  a <- tail(v,1L)
  M <- nat$loadings %*% rotation(a)
  A <- fa_criterion(fa_implied(M,nat$uniquenesses),fa_d)$A
  G <- fa_d$n*A %*% M
  free <- objective$layout$free
  anchor <- objective$layout$anchor
  # Map the derivatives with respect to the loadings back to the unrotated axes.
  dL <- (G %*% t(rotation(a)))[free]
  dL[anchor] <- dL[anchor]*nat$loadings[free][anchor]
  dR <- matrix(c(-sin(a),cos(a),-cos(a),-sin(a)),2L)
  c(dL,fa_d$n/2*diag(A)*nat$uniquenesses,sum(G*(nat$loadings %*% dR)))
}
check_point <- c(fa_par+0.01,.3)
print(check_grad(angle_fn,angle_gr,check_point))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
   coordinate      analytic     numerical absolute_error scaled_error
1           1  3.326374e+00  3.326374e+00   7.376041e-08 2.217442e-08
2           2  1.791568e+00  1.791568e+00   3.887752e-07 2.170028e-07
3           3  4.083028e+00  4.083028e+00   1.844143e-08 4.516606e-09
4           4  2.617171e+00  2.617171e+00   1.702485e-07 6.505060e-08
5           5  3.728877e+00  3.728877e+00   4.865528e-08 1.304824e-08
6           6  2.602016e+00  2.602016e+00   2.572309e-07 9.885831e-08
7           7  1.429822e+00  1.429822e+00   1.459269e-07 1.020595e-07
8           8  6.489891e+00  6.489891e+00   1.995392e-07 3.074616e-08
9           9  4.504152e+00  4.504152e+00   1.206605e-08 2.678872e-09
10         10  5.583177e+00  5.583177e+00   1.075673e-07 1.926632e-08
11         11  4.801959e+00  4.801959e+00   4.603532e-08 9.586778e-09
12         12  2.033096e+00  2.033096e+00   2.130939e-09 1.048125e-09
13         13  1.654569e+00  1.654569e+00   3.378028e-08 2.041637e-08
14         14  2.461130e+00  2.461130e+00   9.323118e-08 3.788145e-08
15         15  2.479014e+00  2.479013e+00   1.256285e-07 5.067679e-08
16         16  2.929551e+00  2.929551e+00   5.277022e-08 1.801308e-08
17         17  2.729240e+00  2.729240e+00   6.064433e-10 2.222023e-10
18         18 -3.907985e-14 -5.346824e-12   5.307744e-12 5.307744e-12

Across all 18 coordinates the largest absolute difference is $3.89\times10^{-7}$. For the angle alone the two derivatives differ by $5.31\times10^{-12}$. At the fitted coordinates and angle zero, take central differences of the analytic gradient with step 0.001 and average each pair of transposed Hessian entries.

1
2
3
angle_curvature <- num_hess(angle_fn,c(fa_par,0),gr=angle_gr)$hessian
print(c(angle_row=max(abs(tail(angle_curvature,1L))),
  angle_column=max(abs(angle_curvature[,ncol(angle_curvature)]))))
1
2
   angle_row angle_column 
5.571573e-11 5.571573e-11 

The largest absolute entry in either the angle row or the angle column is $5.57\times10^{-11}$. Compare the corresponding gradient and eigenvalue diagnostics. The diagnostics come from hessian_checks() in code/lib/inference.R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
hessian_checks <- function(H, gradient, tol_grad = 2e-3, tol_hess = 1e-6) {
  found <- character(0)
  note <- function(text) found <<- c(found, text)
  factor <- tryCatch(chol(H), error = function(e) NULL)
  scaled_grad <- if (is.null(factor)) NULL else tryCatch(solve(factor, gradient), error = function(e) NULL)
  ok <- !is.null(scaled_grad) && !anyNA(scaled_grad)
  max_min_grad <- if (ok) max(pmin(abs(scaled_grad), abs(gradient))) else NA_real_
  if (!ok) note("unable to evaluate scaled gradient") else if (max_min_grad > tol_grad)
    note(sprintf("failed to converge with max|grad| = %g (tol = %g)", max_min_grad, tol_grad))
  eig_vals <- eigen(H, symmetric = TRUE, only.values = TRUE)$values
  negative <- sum(eig_vals < -tol_hess)
  # A singular Hessian: an eigenvalue within tol_hess of zero, or no Cholesky factor.
  singular <- sum(abs(eig_vals) < tol_hess) > 0 || is.null(factor)
  if (negative > 0) {
    note(sprintf("degenerate Hessian with %d negative eigenvalues", negative))
  } else if (singular) {
    note("Hessian is numerically singular at the evaluated point")
  } else {
    if (max(eig_vals) * tol_hess > 1) note("large Hessian eigenvalue at the evaluated scale")
    if (min(eig_vals) / max(eig_vals) < tol_hess) note("small Hessian eigenvalue ratio at the evaluated scale")
  }
  list(max_min_abs_gradient = max_min_grad, smallest = min(eig_vals), largest = max(eig_vals),
    ratio = min(eig_vals) / max(eig_vals), messages = if (length(found)) paste(found, collapse = "; ") else "none")
}

With $R$ the Cholesky factor of the Hessian, scaled_grad solves $Rx=g$, and max_min_abs_gradient is the largest of the smaller of $\vert x_i\vert $ and $\vert g_i\vert $ over coordinates; a value above $2\times10^{-3}$ is reported as a failure to converge. Eigenvalues below $-10^{-6}$ are counted as negative, an eigenvalue within $10^{-6}$ of zero or a failed Cholesky factorization marks the Hessian as singular, and otherwise very large eigenvalues or a ratio of smallest to largest below $10^{-6}$ are noted.

1
2
angle_spectrum <- sort(eigen(angle_curvature,symmetric=TRUE,only.values=TRUE)$values)
print(as.data.frame(hessian_checks(angle_curvature,angle_gr(c(fa_par,0)))))
1
2
3
4
  max_min_abs_gradient     smallest  largest        ratio
1         1.398258e-06 3.709617e-12 1131.075 3.279727e-15
                                                                 messages
1 Hessian is numerically singular at the evaluated point

The gradient passes its numerical check while the Hessian triggers the singularity warning. The covariance identity establishes nonidentification here. A warning alone would also require checking numerical error and parameter scaling. The two smallest eigenvalues distinguish the added angle from the original directions. The message “Hessian is numerically singular at the evaluated point” describes the numerical finding without asserting its cause.

1
2
3
4
5
print(data.frame(coordinates=c("identified","identified plus free angle"),
  dimension=c(length(spectrum),length(spectrum)+1L),
  smallest_eigenvalue=c(min(spectrum),angle_spectrum[1]),
  second_smallest_eigenvalue=c(sort(spectrum)[2],angle_spectrum[2]),
  largest_eigenvalue=max(spectrum),max_abs_identified_score=max(abs(objective$gr(fa_par)))))
1
2
3
4
5
6
                 coordinates dimension smallest_eigenvalue
1                 identified        17        2.780925e+01
2 identified plus free angle        18        3.709617e-12
  second_smallest_eigenvalue largest_eigenvalue max_abs_identified_score
1                   77.06444           1131.075             3.287212e-05
2                   27.80925           1131.075             3.287212e-05

The smallest eigenvalue is now $3.71\times10^{-12}$, and the old minimum, 27.80925, appears in second place. Hessian rank describes a local quadratic approximation. Here the covariance identity proves that the orientation is undetermined over the entire range of angles.

Changing coordinate units without losing identification

A small eigenvalue can also arise when a unit step in one coordinate represents a small change in a loading. Return to the 17 identified coordinates $\theta$ and measure them in new units $u$ with $\theta=Du$. Use a diagonal $D$ with first entry 0.01 and all remaining entries one. A unit step in $u_1$ changes the first log loading by only 0.01. The new gradient is $D^\top g$ and the new Hessian is $D^\top H D$. With the other coordinates fixed, the second derivative along the first coordinate is multiplied by $0.01^2$. The eigenvalues depend on the whole matrix, including its off-diagonal entries.

1
2
3
change <- diag(c(.01,rep(1,nrow(curvature)-1)))
print(rbind(original=range(eigen(curvature,symmetric=TRUE)$values),
  rescaled=range(eigen(crossprod(change,curvature%*%change),symmetric=TRUE)$values)))
1
2
3
                [,1]     [,2]
original 27.80924657 1131.075
rescaled  0.02916883 1121.247

The smallest eigenvalue drops to 0.02916883. Apply the same checks in the new units, using the transformed gradient along with the transformed Hessian.

1
2
3
print(rbind(original=as.data.frame(hessian_checks(curvature,nll_gradient_fa)),
  rescaled=as.data.frame(hessian_checks(crossprod(change,curvature%*%change),
    drop(crossprod(change,nll_gradient_fa))))))
1
2
3
         max_min_abs_gradient    smallest  largest        ratio messages
original         1.398258e-06 27.80924657 1131.075 2.458657e-02     none
rescaled         1.398258e-06  0.02916883 1121.247 2.601462e-05     none

In the original units, the identified Hessian has smallest and largest eigenvalues 27.80925 and 1131.075. Their ratio is 0.02459, and the gradient diagnostic is $1.398258\times10^{-6}$. Both checks pass. In the rescaled coordinates, the ratio falls to $2.601462\times10^{-5}$, still above the warning threshold. The condition number, the reciprocal of that ratio for a positive definite Hessian, has increased even though every $u$ still maps to a distinct $\theta$. Converting back to the original units restores the original spectrum. Recovering a unique set of loadings in the rotation example required an orientation constraint.

Comparing mixture fits across starting values

Rotating the factor axes preserved every fitted density. Interchanging component labels has the same property in a mixture. In the two-component normal mixture fitted to the 300 MIX1 responses, a component indicator selects the first normal distribution with probability $\pi$ and the second with probability $1-\pi$. Within component $k$, $\mu_k$ is the response mean and $\sigma_k^2$ is the response variance, in response units and squared response units, respectively. Swapping the means, variances and mixing proportions together leaves each observation’s mixture density unchanged. Compare four EM starts on this common log likelihood, putting the component with the lower mean first. The saved columns lower_mean and upper_mean already use this ordering.

1
2
mix_starts <- read.csv("data/derived/ch04/starts.csv")
print(mix_starts[,c("start","lower_mean","upper_mean","loglik","reason")])
1
2
3
4
5
       start lower_mean upper_mean    loglik    reason
1  quantiles   55.38180   80.80318 -1152.870 converged
2     narrow   55.26819   80.72616 -1152.872 converged
3   reversed   55.31405   80.75723 -1152.865 converged
4 coincident   70.09452   70.09452 -1215.878 converged

The reversed start ends at $-1152.865$, the quantile start at $-1152.870$, and the narrow start at $-1152.872$. Their sorted means cluster near 55.3 and 80.8. All three runs stopped when the absolute change in log likelihood divided by one plus the absolute current log likelihood fell below $10^{-5}$. That rule permits small differences between the returned coefficients. In the coincident start, both components receive half of each observation in the E step. They therefore receive identical means and variances in the M step, and the same allocation repeats. The means coincide at 70.09 and the log likelihood is $-1215.878$, about 63 units below the best value shown. The stopping rule accepted this symmetric stationary point. Swapping two identical components cannot account for that likelihood gap. The four stopping flags alone would conceal the difference between the separated components and this fit with a single common mean. This comparison concerns the four returned fits. In an unconstrained normal mixture, a component variance can approach zero around a data point and make the likelihood unbounded; selecting the largest of these four values is not proof of an unrestricted global maximum.

Refining integration at fixed item parameters

The next example separates numerical integration error from incomplete optimization. For the weak three-parameter logistic calibration, a response is correct with probability $p_j(z)=c_j+(1-c_j)\operatorname{logit}^{-1}(a_jz+d_j)$ at standard normal ability $z$, with responses independent given ability and $0\leq c_j<1$. The positive $a_j$ changes the log odds of the logistic component per ability standard deviation, and $d_j$ is that component’s log odds at zero ability. They are not the slope and intercept of the full response log odds when $c_j>0$. The lower asymptote $c_j$ is the limiting success probability at low ability; difficulty $-d_j/a_j$ locates the midpoint $(1+c_j)/2$ between that lower limit and one. The marginal likelihood itself requires numerical integration. Read the first sample and inspect both EM records before using their returned item parameters. ML labels maximization of the unpenalized likelihood and MAP labels maximum a posteriori estimation with a normal prior on each item’s logit lower asymptote.

1
2
3
4
case <- readRDS("data/derived/ch10/study-weak3PL.rds")$results[[1L]]
lapply(list(ML = case$fit, MAP = case$modal), function(fit)
  list(converged = fit$converged, reason = fit$reason,
    iterations = fit$optimizer$iterations))

Both records have converged = FALSE and reason = "iteration_limit" after 500 cycles. To isolate the effect of integration, fix each set of coefficients and reevaluate the unpenalized marginal likelihood with three Gauss-Hermite rules. Both the ML and maximum a posteriori (MAP) endpoints are evaluated on this same criterion.

1
2
3
4
5
6
7
8
9
10
11
source("code/lib/stability.R")
source("code/lib/integration.R")
source("code/lib/irt.R")
start <- replicate(8, irt_item("3PL", a = .8, d = 0, c = .1), simplify = FALSE)
case_data <- irt_data(case$Y, start)
nodes <- c(nodes_121 = 121L, nodes_241 = 241L, nodes_361 = 361L)
nll <- function(items) vapply(nodes, function(n)
  irt_estep(case_data, items, normal_rule(n))$value, 0)
steepest <- function(items) max(vapply(items, `[[`, 0, "a"))
print(cbind(rbind(ML = nll(case$fit$items), MAP = nll(case$modal$items)), steepest_a =
  c(steepest(case$fit$items), steepest(case$modal$items))), digits = 10)
1
2
3
      nodes_121   nodes_241   nodes_361  steepest_a
ML  3950.165345 3950.165416 3950.165416 6.108101079
MAP 3950.634700 3950.634785 3950.634784 6.298401907

The eight template items specify the binary response categories when irt_data() groups the 800 examinees’ response vectors by pattern. At each node, irt_estep() (Section 10.3) gives the probability of the observed pattern given ability. It integrates that probability with the normal weights, takes its logarithm, and weights each pattern by its observed count. nll() returns the negative sum for each rule.

The unpenalized negative marginal log likelihood increases by about 0.000071 from 121 to 361 nodes at the ML endpoint and by about 0.000084 at the MAP endpoint. The largest returned slopes are 6.108 and 6.298, respectively. With slopes this steep, finer spacing helps resolve rapid changes in response probability over short ability intervals. The small differences measure the sensitivity of the total negative log likelihood to this refinement at each fixed vector. A curvature check would also need information at neighboring parameter values. Both fits still report the iteration-limit flag. Neither the likelihood label ML nor the prior label MAP certifies that the corresponding maximum was found. Refining integration at a fixed vector also does not replace refitting with the refined rule.

When an angle is undetermined, report which combinations the data identify, such as the implied covariance, and give any orientation constraints used to report individual loadings. At a variance boundary, state which variance reached its limit and which directions of change the model permits. If the curvature remains unstable, specify the parameter units, the eigenvalues and the calculation that produced them. Withhold Wald standard errors for the affected parameters. Replacing small eigenvalues by positive constants before inversion would make those standard errors depend on the chosen replacements. The supplied hessian_checks() is adapted from checkConv() of the lme4 package, with the defaults of lmerControl() (code/NOTICE.md).

15.9 AIC, BIC, and the choice of sample size

How much improvement in fit justifies adding a population parameter? Let $\ell(\hat\theta)$ be the maximized log likelihood of the observed responses, with the latent variables integrated out. Let $k$ count the free population parameters after the model constraints are imposed, and let $n$ denote the sample size under the stated sampling regime. The marginal Akaike information criterion (AIC) and Bayesian information criterion (BIC) are

\[\mathrm{AIC}=-2\ell(\hat\theta)+2k,\qquad \mathrm{BIC}=-2\ell(\hat\theta)+k\log n.\]

Smaller values are preferred when the models describe the same observations with the same likelihood constants. Under the usual regular, correctly specified model, AIC uses $2k$ as a first-order correction for the improvement in apparent fit caused by estimating the parameters from the same responses. For BIC, the marginal density or probability of the data under model $M$ integrates over its population parameters with prior density $\pi_M(\theta)$. Near an isolated maximum with positive definite information and sufficiently small changes allowed in every free parameter direction, the Laplace approximation uses a quadratic expansion of $\ell$ to give

\[p(y\mid M)=\int e^{\ell(\theta)}\pi_M(\theta)\,d\theta \ \approx\ e^{\ell(\hat\theta)}\pi_M(\hat\theta) (2\pi)^{k/2}|J(\hat\theta)|^{-1/2},\]

where $J$ is the observed information for the full sample. Suppose $k$ is fixed, the prior is positive and smooth near the maximum, and $J/n$ approaches a positive definite matrix. Then $\log\vert J\vert =k\log n+O_p(1)$. Thus the information determinant contributes the BIC penalty on the minus twice log scale. For two models with equal prior probabilities, $-(\mathrm{BIC}_1-\mathrm{BIC}_2)/2$ approximates the log posterior odds of model 1 against model 2 up to terms of order one. For unequal prior probabilities, add $\log\lbrace P(M_1)/P(M_2)\rbrace $ to that approximation. The integration in $p(y\mid M)$ is over population parameters with a prior; it is a second integration, distinct from integrating out each person’s latent variables to obtain $\ell$. The remainder that remains bounded in probability in the BIC argument need not be negligible in a particular finite dataset.

In a growth model, the integration over a person’s random intercept and slope takes place before maximizing the likelihood over population parameters. Once the population means, variances and covariance are specified, that averaging determines a density for all four responses. Predicting the person’s intercept and slope after observing the responses introduces no new parameter into this marginal density. The variances and covariance of the effects count toward $k$ because they determine how trajectories vary across people. A criterion conditional on the fitted personal effects asks about further observations from people whose effects have already been estimated. Its penalty must account for the estimation of those effects. The marginal criterion instead evaluates the joint response density for a new person drawn from the population.

Parameter counts and sample sizes in four examples

The following examples identify the free parameters, likelihood calculation and sampling regime for several datasets. Only the two growth models use the same responses and support a direct comparison of criteria; the other examples illustrate how the inputs are chosen.

For the eight dichotomous items in IRT8-2, the 2PL model estimates a slope and an intercept for each item. Fixing the standard normal ability distribution leaves $k=16$. An examinee supplies eight responses at one shared ability. Multiplying the eight conditional probabilities and integrating the product gives one response-pattern probability. Its logarithm enters the sum once for that examinee. Read the response matrix and the Ramsay-accelerated EM fit, then negate its stored negative log likelihood. The fit used quadrature with 61 equally spaced ability values. information_criteria() takes the log likelihood, free-parameter count, sample size and two descriptive labels, and returns one row containing these inputs and the two criteria. The labels record the independent unit and likelihood type. Its input checks do not establish that the supplied fit maximizes that likelihood or that a chosen sample size is statistically justified.

1
2
3
4
5
6
information_criteria <- function(loglik,k,n,unit,kind) {
  stopifnot(length(loglik)==1,is.finite(loglik),k>=0,k==as.integer(k),n>0,nzchar(unit))
  if(!kind %in% c("integrated ML","ordinary ML","HMM forward likelihood"))
    stop("A full comparable data likelihood and its sampling regime are required")
  data.frame(kind=kind,unit=unit,n=n,k=k,logLik=loglik,AIC=-2*loglik+2*k,BIC=-2*loglik+k*log(n))
}

The columns AIC and BIC are the two criteria displayed above, with loglik as $\ell(\hat\theta)$; the function refuses likelihood types other than the three listed.

1
2
3
4
5
6
source("code/lib/inference.R")
irt_y <- readRDS("data/source/ch10/IRT8-2.rds")
irt_fit <- readRDS("data/derived/ch10/fits.rds")$dichotomous$Ramsay_EM
irt_ic <- information_criteria(-irt_fit$value, 2L * ncol(irt_y), nrow(irt_y),
  "examinee with eight items", "integrated ML")
print(irt_ic)

Using the log likelihood rounded to $-3821.381$ gives $7642.762+32=7674.762$ for AIC and $7642.762+16\log(800)\approx7749.716$ for BIC. The code uses the unrounded stored negative log likelihood, giving AIC 7674.763 to three decimal places. The BIC penalty is 106.95. Substituting the number of response cells gives $16\log(6400)\approx140.22$. With test length fixed, both counts grow at the same rate, yet counting cells adds $16\log 8$ to the reported penalty without changing a single pattern probability. The sampling unit for this calibration is the examinee.

In GROWTH4, compare a population mean that changes linearly with time to a constant population mean. Both fits integrate out a correlated random intercept and slope. The unrestricted model estimates two fixed coefficients, three distinct entries of the random-effects covariance matrix and one residual variance. Fixing the population slope at zero removes one parameter and leaves the random slope in the model. Each of 200 people contributes a four-dimensional normal density to the likelihood. Use the two ML fits, growth_full and growth_null, and take the person count from the growth design.

1
2
print(information_criteria(-growth_full$value,6L,growth_full$data$groups,
  "person with four occasions","integrated ML"))
1
2
           kind                       unit   n k    logLik      AIC      BIC
1 integrated ML person with four occasions 200 6 -1229.074 2470.149 2489.939
1
2
print(information_criteria(-growth_null$value,5L,growth_full$data$groups,
  "person with four occasions","integrated ML"))
1
2
           kind                       unit   n k    logLik      AIC      BIC
1 integrated ML person with four occasions 200 5 -1264.684 2539.369 2555.861

The unrestricted log likelihood is $-1229.074$. Its six free parameters incur a BIC penalty of $6\log(200)$, giving 2489.939 from the unrounded fit. The constant-mean model uses the same people and pays $5\log(200)$. Allowing the fixed slope to vary improves twice the log likelihood by 71.220. One additional parameter costs 2 by AIC and $\log(200)\approx5.298$ by BIC. The unrestricted model therefore has the lower AIC by 69.220 and the lower BIC by 65.922.

Using the person count for BIC describes a design in which the number of people increases and the four measurement times remain fixed. When both the number of groups and the number of observations per group increase, information for parameters at different levels may grow at different rates. The determinant argument then requires those rates to be specified.

For HMM2, there is one series of 250 counts. The forward recursion sums over the hidden state paths to give the joint probability of the counts in their observed order. For two states, the search retained the largest log likelihood across ten starts. Each state has a Poisson mean and one free probability in its transition row. A free initial probability brings the nominal count to five.

1
2
series_length <- length(readRDS("data/source/ch13/HMM2.rds"))
print(readRDS("data/derived/ch13/estimates.rds")$series[[2]]$IC)
1
2
free_parameters          loglik             AIC             BIC 
         5.0000       -502.3687       1014.7373       1032.3446 

The log likelihood of $-502.3687$ gives AIC 1014.737 and, using $5\log(250)$, BIC 1032.345. Both calculations count the five free parameters of the fitted model. This is the same long-series BIC convention used in Chapter 13. The initial-state probability enters once, whereas transition and response information accumulates over occasions, so the common length penalty is a convention for this comparison rather than a separate information-growth result for every parameter.

For the three-class model of LCA6, the six binary answers from a respondent form one pattern. The class proportion $\pi_k$ is the probability of belonging to class $k$ before observing those answers. Within that class, item probability $p_{jk}$ is the probability of response one to item $j$. The six responses are independent given the same class. Multiply each class-specific pattern probability by its class proportion and sum the three terms. The model estimates six item probabilities per class and two free class proportions. The third proportion follows from the requirement that the three sum to one.

1
2
3
4
class_row <- readRDS("data/derived/ch12/fits.rds")$search[[3]]$row
print(information_criteria(class_row$loglik,class_row$k,
  nrow(readRDS("data/source/ch12/LCA6.rds")),
  "respondent with six indicators","integrated ML"))
1
2
3
4
           kind                           unit   n  k    logLik      AIC
1 integrated ML respondent with six indicators 600 20 -1919.502 3879.005
       BIC
1 3966.943

The class sum is exact. With 600 independent respondents and $k=20$, the retained fit has log likelihood $-1919.502$, AIC 3879.005 and BIC 3966.943. Interchanging two class labels leaves the pattern probabilities unchanged. If a proportion becomes zero, the item probabilities for that class disappear from the sum. If two profiles coincide, their total proportion can remain fixed while their individual proportions vary. A label convention can select among permutations. It cannot restore curvature in a direction that leaves the fitted distribution unchanged at a zero proportion or a pair of coincident profiles. BIC is commonly reported for class enumeration, but a consistency result for independent mixtures requires conditions on the component family and the allowed parameter space.

Before computing a difference in either criterion, check what each fitting routine optimized. A variational approximation can maximize a lower bound on the observed-data log likelihood, with a gap that varies across models. Penalized quasi-likelihood (PQL) uses a working approximation. Restricted maximum likelihood (REML) uses residual contrasts that change with the fixed-effect design. Dropping different normalizing constants also changes a difference in criteria. For fits obtained by approximation, identify that approximation and reevaluate both fits with the same marginal likelihood and integration accuracy where possible. If their coefficients do not maximize that common likelihood to adequate accuracy, fit them again under it before interpreting an ordinary ML comparison.

Table 15.2 uses the unrounded fits for the criteria and displays the log likelihoods to three decimal places.

Table 15.2. Marginal information criteria and the sampling regime used for BIC.

Response data and modelLikelihood calculationBIC sampling regime$k$Log likelihoodAICBIC
IRT8-2, 2PL61-point quadrature800 examinees, eight items each16−3821.3817674.7637749.716
GROWTH4, fixed slope freeAnalytic Gaussian integral200 people, four occasions each6−1229.0742470.1492489.939
GROWTH4, fixed slope zeroAnalytic Gaussian integral200 people, four occasions each5−1264.6842539.3692555.861
HMM2, two statesExact forward recursionOne series, length 2505−502.3691014.7371032.345
LCA6, three classesExact sum over classes600 respondents, six items each20−1919.5023879.0053966.943

Only the two growth rows compare models on the same responses. The remaining rows give a criterion for each model on its own dataset. The stats package provides AIC() and BIC().

15.10 Checking standard errors, tests, residuals, and interval coverage

How often would a nominal 95 percent interval cover the population slope if a new set of people supplied the responses? To answer that question, specify a population and generate an entire dataset for each replication. For the growth model, the slope is 0.4. Each dataset supplies an estimate, a standard error and an indicator of coverage for each of two estimation methods. For the variance test, generate data with zero random-intercept variance. Each dataset then supplies one rejection decision for each reference distribution. A third design retains a mean slope of 0.5 while allowing the residual variance to depend on the covariate. The two intervals for that slope use the same estimate. In the Poisson design the parameters are known, so each dataset supplies summaries of its residuals directly. In all four designs, a fresh dataset is the unit over which to assess sampling variation.

Growth-slope intervals under the specified normal model

For one growth replication, take 200 people observed at times 0, 1, 2 and 3. Their population intercept is 2 and their population slope is 0.4. Draw the personal intercept and slope deviations jointly from a centered normal distribution with variances 1 and 0.25 and covariance 0.15. Add independent normal errors with standard deviation 0.7. The first saved random-number stream reproduces one such response matrix.

1
2
3
4
5
6
7
8
9
10
source("code/lib/lmm.R")
streams <- readRDS("data/source/ch08/study-streams.rds")
replication <- 1L
assign(".Random.seed", streams[[replication]], envir = .GlobalEnv)
Z <- cbind(1, 0:3)
G <- matrix(c(1, .15, .15, .25), 2)
b <- matrix(rnorm(400), 200, 2) %*% chol(G)
Y <- sweep(b %*% t(Z) + .7 * matrix(rnorm(800), 200, 4), 2, drop(Z %*% c(2, .4)), "+")
X <- Z[rep(1:4, 200), ]
data <- lmm_design(as.vector(t(Y)), X, X, rep(1:200, each = 4))

The block above reconstructs the first response matrix. In the saved growth study, lmm_fit() took the same data twice with method = "scoring". Setting REML to FALSE and then to TRUE gave the ML and REML fits. Each fit supplied its slope and a standard error from the information for the fixed effects. For a fitted four-occasion covariance $V$ and common design $Z$, that information is $200Z^\top V^{-1}Z$. The slope standard error is the square root of the second diagonal entry of the inverse information. An interval covers when the absolute distance from 0.4 to the estimated slope is at most 1.96 standard errors, using the unrounded normal quantile in the calculation.

In the first saved ML fit, the slope was 0.41179 with a standard error of 0.04595. Its distance from 0.4 is about 0.01179, inside the margin of about 0.0901. This replication counts as one covered interval. The next calculation reads the records from all 200 replications, splits them by criterion and retains converged fits with finite slope estimates and positive finite standard errors.

The estimated bias is the mean fitted slope minus its generating value. Its Monte Carlo standard error is the empirical standard deviation of the slopes divided by the square root of the number of usable independent datasets.

1
2
3
4
5
6
7
8
9
10
11
12
growth <- read.csv("data/derived/ch08/recovery-replications.csv")
growth_coverage <- do.call(rbind, lapply(split(growth, growth$criterion), function(d) {
  usable <- !is.na(d$converged) & d$converged & is.finite(d$slope) & is.finite(d$slope_SE) & d$slope_SE > 0
  slope <- d$slope[usable]
  se <- d$slope_SE[usable]
  p <- mean(abs(slope - .4) <= qnorm(.975) * se)
  data.frame(method = d$criterion[1L], assigned = nrow(d), usable = length(slope),
    empirical_SD = sd(slope), mean_SE = mean(se), bias = mean(slope) - .4,
    MCSE_bias = sd(slope) / sqrt(length(slope)), coverage = p,
    MCSE_coverage = sqrt(p * (1 - p) / length(slope)))
}))
print(growth_coverage, row.names = FALSE)
1
2
3
4
5
6
 method assigned usable empirical_SD    mean_SE       bias   MCSE_bias coverage
     ML      200    200   0.04092823 0.04146987 0.00195846 0.002894063     0.96
   REML      200    200   0.04092823 0.04157393 0.00195846 0.002894063     0.96
 MCSE_coverage
    0.01385641
    0.01385641

Across all 200 growth samples, paired ML and REML slopes differ by at most about $5\times10^{-15}$. Their empirical standard deviation is 0.04092823, compared with mean standard errors of 0.04146987 for ML and 0.04157393 for REML. The mean slope exceeds its generating value by 0.00195846 for either method. The Monte Carlo standard error for this bias estimate is $0.04092823/\sqrt{200}=0.002894$ to the displayed precision. Checking the intervals separately with each fit’s own standard error yields 192 covered out of 200 for each method. The estimated coverage is 0.96 with Monte Carlo standard error 0.01386.

Rejection rates at a variance boundary

To check a test at the variance boundary, generate 40 groups with five observations each. The mean is $1+0.5x$, the residual standard deviation is one, and the random-intercept variance is zero. Fit the null model and the model allowing a nonnegative variance to each dataset. Evaluate the likelihood ratio statistic against three references. The regular reference assigns the statistic a one-degree-of-freedom chi-square distribution. The mixture assigns half its probability to zero and half to that chi-square distribution. For the bootstrap, use the null fit from the outer dataset to generate 199 datasets and fit both models to each. The following block reproduces the first outer dataset and its bootstrap calculation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
source("code/lib/boundary_test.R")
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(101510)
null_streams <- replicate_streams(200L, .Random.seed)
x_null <- seq(-1, 1, length.out = 5)
id <- 1L
assign(".Random.seed", null_streams[[id]], envir = .GlobalEnv)
data <- balanced_variance_simulate(40L, x_null, c(1, .5), 1)
fitted <- balanced_variance_fit(data, x_null)
# The first substream is reserved for the outer sample. Inner draws use the next 199.
inner_streams <- replicate_streams(199L,
    parallel::nextRNGSubStream(null_streams[[id]]), TRUE)
inner <- parametric_bootstrap(inner_streams,
  function() balanced_variance_simulate(40L, x_null, fitted$beta,
      sqrt(fitted$sigma2_null)),
  function(Y) balanced_variance_fit(Y, x_null))
summary <- bootstrap_test_summary(inner, fitted$lr)

For the first dataset, the bootstrap p-value was 0.17. Of 199 null refits, 33 likelihood ratio statistics reached or exceeded the observed one. Adding one to the numerator and denominator gives $34/200$. The denominator in that particular p-value counts the observed statistic and bootstrap draws. This is the plus-one Monte Carlo comparison, not an additional independent dataset in the outer study. To estimate the test’s rejection probability, read the saved results from all 200 outer datasets. Count outer datasets with a finite p-value at most 0.05 and divide by the number with a finite p-value for that method.

1
2
3
4
5
6
7
8
9
10
11
records_null <- readRDS("data/derived/ch15/null-records.rds")
null_results <- do.call(rbind, lapply(records_null, function(r) r$summary))
print(do.call(rbind, lapply(c("regular", "mixture", "bootstrap"), function(method) {
  p <- null_results[[method]]
  usable <- sum(is.finite(p))
  rejects <- sum(p <= .05, na.rm = TRUE)
  rate <- if (usable) rejects / usable else NA_real_
  data.frame(reference = method, assigned = length(p),
    usable = usable, rejected = rejects,
    rejection_rate = rate, Monte_Carlo_SE = sqrt(rate * (1 - rate) / usable))
})))
1
2
3
4
  reference assigned usable rejected rejection_rate Monte_Carlo_SE
1   regular      200    200        4          0.020    0.009899495
2   mixture      200    200       11          0.055    0.016120639
3 bootstrap      200    200       10          0.050    0.015411035

All three references have 200 usable p-values. The regular reference rejected 4 times, the mixture 11 times and the bootstrap 10 times. For a rate $\hat p$ based on $B$ independent usable datasets, its estimated Monte Carlo standard error is $\sqrt{\hat p(1-\hat p)/B}$. The rates 0.020, 0.055 and 0.050 have standard errors 0.0099, 0.0161 and 0.0154, respectively. In this null design the regular reference rejected less often than the nominal level. The other two rates are close to 0.05 at the precision of 200 datasets. All three decisions are paired within the same outer dataset. Their individual Monte Carlo standard errors do not provide the standard error of a difference between methods; that comparison uses the paired decisions.

Slope intervals with unequal residual variances

What happens to slope intervals when the mean is correctly specified but the residual variances differ? Use the same 40 groups, five covariate values and mean $1+0.5x$. Give each group a normal random intercept with standard deviation 0.5 and each observation a conditional error with standard deviation $\exp(0.3x)$. Fit a single residual variance. Calculate two standard errors for the same slope estimate. The model-based standard error uses the fitted covariance, and the sandwich standard error uses one score vector per group with the $40/39$ correction. Reproduce the first sample and both standard errors before summarizing the saved repetitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/inference.R")
set.seed(101511L)
unequal_streams <- replicate_streams(200L,.Random.seed)
x <- seq(-1,1,length.out=5)
assign(".Random.seed",unequal_streams[[id]],envir=.GlobalEnv)
Y <- balanced_variance_simulate(40L,x,c(1,.5),exp(.3*x),tau=.5)
f <- balanced_variance_fit(Y,x)
X <- cbind(1,x)
V <- f$tau2*matrix(1,5,5)+diag(f$sigma2,5)
sensitivity <- nrow(Y)*crossprod(X,solve(V,X))
score <- sweep(Y,2,drop(X%*%f$beta))%*%solve(V,X)
model_se <- sqrt(chol2inv(chol(sensitivity))[2,2])
sandwich_se <- vcov_sandwich(sensitivity,score,TRUE)$se[2]
data.frame(id=id,slope=unname(f$beta[2]),model_SE=model_se,cluster_SE=sandwich_se)

In the first sample, the fitted slope is 0.54254. The model-based and group sandwich standard errors are 0.10736 and 0.10097. The next calculation reads all 200 saved samples and applies each method to its own column of standard errors.

1
2
3
4
5
6
7
8
9
10
unequal <- do.call(rbind, readRDS("data/derived/ch15/unequal-variance-records.rds"))
for(type in c("model_SE","cluster_SE")) {
  eligible <- is.finite(unequal$slope) & is.finite(unequal[[type]]) & unequal[[type]] > 0
  n <- sum(eligible)
  cover <- if (n) mean(abs(unequal$slope[eligible]-.5)<=qnorm(.975)*unequal[[type]][eligible]) else NA_real_
  print(data.frame(method=type,assigned=nrow(unequal),usable=n,
    mean_SE=if(n) mean(unequal[[type]][eligible]) else NA_real_,
    empirical_SD=if(n>1L) sd(unequal$slope[eligible]) else NA_real_,
    coverage=cover,coverage_MCSE=if(n) sqrt(cover*(1-cover)/n) else NA_real_))
}
1
2
3
4
5
    method assigned usable  mean_SE empirical_SD coverage coverage_MCSE
1 model_SE      200    200 0.104228    0.1123641     0.92    0.01918333
      method assigned usable   mean_SE empirical_SD coverage coverage_MCSE
1 cluster_SE      200    200 0.1061627    0.1123641     0.93    0.01804162

Both methods retain all 200 datasets under the finite-estimate and positive finite-standard-error checks. The slope estimates have standard deviation 0.1123641. The model-based standard error averages 0.104228 and its interval covers in 184 datasets. The group sandwich standard error averages 0.1061627 and its interval covers in 186. The observed coverages are 0.92 and 0.93 with Monte Carlo standard errors 0.0192 and 0.0180. Treating individual rows as independent gave a third mean standard error, 0.10230. The row-sandwich intervals also covered 184 times. That is a separate calculation: the 184 covered intervals represented in the first displayed row use the model-based standard error from the inverse fitted information.

Conditional and marginal Poisson residuals

The final study fixes the population parameters at their known values and examines residual distributions without fitting a model. For the Poisson responses, generate 80 groups of eight counts with log mean $0.2+0.5x+b_i$, where the group intercept $b_i$ has standard deviation 0.7 and mean zero under a normal distribution. Compute one randomized quantile residual using the realized intercept and another using the CDF integrated over its distribution. Use the same uniform draw for both residuals at each observation. All coefficients and the intercept variance retain their generating values. Each residual vector gives a mean and variance across the 640 observations. To measure dependence, pair the first two residuals from each group and calculate their correlation across the 80 pairs. The following block reproduces the first dataset and its residual summaries.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
source("code/lib/glmm.R")
source("code/lib/integration.R")
rule <- normal_rule(61L)
marginal_cdf <- function(y,X,beta,sd,rule) {
  mu <- exp(outer(drop(X%*%beta),sd*rule$nodes,"+"))
  drop(matrix(ppois(y,mu),nrow(X))%*%rule$weights)
}
marginal_residual <- function(data,beta,sd,v) randomized_quantile_residuals(
  marginal_cdf(data$y-1,data$X,beta,sd,rule),marginal_cdf(data$y,data$X,beta,sd,rule),v)
set.seed(101512L)
poisson_streams <- replicate_streams(200L,.Random.seed)
assign(".Random.seed",poisson_streams[[id]],envir=.GlobalEnv)
sample <- glmm_generate(beta=c(.2,.5),family="poisson")
observed <- glmm_as_data(sample)
u <- runif(observed$N)
r <- marginal_residual(observed,sample$truth$beta,.7,u)$residual
mu <- exp(drop(observed$X%*%sample$truth$beta)+sample$truth$b[observed$group_index,1])
conditional <- randomized_quantile_residuals(ppois(observed$y-1,mu),ppois(observed$y,mu),
  u)$residual
summarize <- function(v) {
  grouped <- matrix(v,nrow=observed$groups,byrow=TRUE)
  c(mean=mean(v),variance=var(v),within_group_correlation=cor(grouped[,1],grouped[,2]))
}
list(id=id,conditional=summarize(conditional),marginal=summarize(r))

In the first generated dataset, the two correlations are 0.00868 and 0.27321. Each supplies one entry in the corresponding column to be averaged over samples. The next calculation reads the saved summaries for all 200 datasets. For each column, the Monte Carlo standard error of its average is the standard deviation of its 200 entries divided by $\sqrt{200}$.

1
2
3
4
5
6
7
residual_study <- readRDS("data/derived/ch15/poisson-residual-records.rds")
for(type in c("conditional","marginal")) {
  estimates <- do.call(rbind,lapply(residual_study,function(record)record[[type]]))
  print(data.frame(conditioning=type,statistic=colnames(estimates),
    datasets=nrow(estimates),
    average=colMeans(estimates),MCSE=apply(estimates,2,sd)/sqrt(nrow(estimates))))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
                         conditioning                statistic datasets
mean                      conditional                     mean      200
variance                  conditional                 variance      200
within_group_correlation  conditional within_group_correlation      200
                             average        MCSE
mean                     0.004140979 0.002823551
variance                 1.002477994 0.003787896
within_group_correlation 0.004208743 0.008061547
                         conditioning                statistic datasets
mean                         marginal                     mean      200
variance                     marginal                 variance      200
within_group_correlation     marginal within_group_correlation      200
                             average        MCSE
mean                     0.007192377 0.004966027
variance                 1.003338658 0.006204670
within_group_correlation 0.276315301 0.007539138

Conditional and marginal mean residuals average 0.00414 and 0.00719, with Monte Carlo standard errors 0.00282 and 0.00497. Their variances average 1.00248 and 1.00334. The first two residuals have average correlation 0.00421 after conditioning on the group intercept and 0.27632 after integrating it out, with Monte Carlo standard errors 0.00806 and 0.00754. The marginal residuals retain the association induced by the shared intercept even though their variance is close to one.

Interpreting the simulation summaries

Each design assigned 200 datasets. Both growth methods and all three null tests used all 200 under their stated eligibility rules. A failed growth fit or a nonfinite slope standard error would remove that fit from its method’s coverage denominator. A missing bootstrap p-value would remove that dataset from the bootstrap rejection rate. Such a rate describes performance among usable results, so report how many were lost. All 200 unequal-variance records and all 200 Poisson records supplied finite summaries. For a method reporting a parameter interval, eligibility also requires a finite estimate, an appropriate positive standard error and a usable fit. A finite logical coverage indicator alone would not exclude an infinite standard error.

The standard error of a fitted parameter and the Monte Carlo standard error of estimated coverage describe different kinds of uncertainty. For example, the slope standard error 0.04147 is in response units per unit of time. The Monte Carlo standard error of 0.01386 describes the precision of coverage on the probability scale.

The growth intervals covered close to their nominal level in the specified normal model. With unequal residual variances, both observed coverages fell below 0.95 and the group sandwich came closer. The small coverage difference between the two interval methods in the unequal-variance study is descriptive; these 200 datasets do not establish a general advantage.

Estimation uses the responses in hand to learn about unknown population parameters. Repeated-sampling evaluation fixes those parameters at specified values and draws new responses and latent effects. Coverage asks how frequently the resulting intervals include that fixed value. The rsimsum package provides summaries of bias, coverage and Monte Carlo error.

This post is licensed under CC BY-NC 4.0 by the author.