Integrating over latent variables
The probability of a cluster’s observed binary response pattern is needed to compare values of the regression coefficients and random-intercept variance by likelihood. A random-intercept logistic regression model gives the pattern’s conditional probability at any specified value of the shared intercept. That intercept is unobserved, so choosing one value leaves out other possibilities consistent with the model. Even when the regression coefficients and the intercept distribution are specified, the probability of the recorded pattern still requires a calculation over those possibilities. The chapter follows one constructed cluster, the six binary responses of RI1, from fixed Gaussian quadrature to rules that adapt to the observed responses, and then to several latent variables and to random and quasi-random points.
5.1 A random-intercept logistic regression model and its marginal likelihood
Each independently sampled cluster contributes one response pattern. In the constructed example RI1, row $j$ pairs covariate $x_j$ with response $y_j$. The six responses share a normal random intercept $b$ with mean zero and standard deviation $\sigma=0.7$. With fixed intercept $\beta_0=-0.4$ and slope $\beta_1=0.8$, the log odds are $\eta_j(b)=\beta_0+\beta_1x_j+b$. The cluster-specific intercept is $\beta_0+b$. The responses are conditionally independent given $b$ and their covariates.
Here $\beta_0$ is the log odds of a response of one at $x=0$ for a cluster with $b=0$. With $b$ fixed, a one-unit increase in $x$ adds $\beta_1=0.8$ to the log odds and multiplies the odds by $\exp(0.8)$. A positive $b$ raises all six conditional response probabilities. The standard deviation $\sigma=0.7$ describes variation in intercepts across clusters, in log-odds units; it measures heterogeneity in the population. In this example the two regression coefficients and $\sigma$ are specified, and the integration averages over the unobserved $b$.
Starting in the book directory, load the functions. The column eta_at_zero gives the linear predictors at $b=0$.
1
2
3
4
5
6
7
8
for (file in c("stability", "result", "newton", "differentiation", "simulation",
"line_search", "quasi_newton")) {
source(paste0("code/lib/", file, ".R"))
}
RI1 <- list(x = c(-1, -0.5, 0, 0.5, 1, 1.5), y = c(0, 0, 1, 0, 1, 1),
beta = c(-0.4, 0.8), latent_sd = 0.7)
print(data.frame(x = RI1$x, y = RI1$y, eta_at_zero = RI1$beta[1] + RI1$beta[2] * RI1$x))
1
2
3
4
5
6
7
x y eta_at_zero
1 -1.0 0 -1.2
2 -0.5 0 -0.8
3 0.0 1 -0.4
4 0.5 0 0.0
5 1.0 1 0.4
6 1.5 1 0.8
At a given $b$, write $p_j(b)=1/\lbrace 1+\exp[-\eta_j(b)]\rbrace $ for the probability of a one. The first row has $x_1=-1$ and $y_1=0$, so its factor in the probability of the observed pattern is $1-p_1(b)$, with $\eta_1(b)=-1.2+b$. Conditional independence makes the pattern probability the product of the six factors evaluated at that same $b$. Taking its logarithm gives the conditional log likelihood $\ell_c(b)$ at the specified regression coefficients. Adding one log density for the shared random intercept gives the log integrand $h(b)$, the joint log density of the recorded pattern and $b$. The distribution of $b$ before conditioning on the responses is often called its prior distribution; here it is the normal random-effects distribution in the model, with its parameters fixed. With $\phi_\sigma$ denoting the $N(0,\sigma^2)$ density, these functions are
\[\begin{aligned} \ell_c(b) &=\sum_{j=1}^6\{y_j\log p_j(b)+(1-y_j)\log[1-p_j(b)]\}\\ &=\sum_{j=1}^6\{y_j\eta_j(b)-\log[1+\exp(\eta_j(b))]\},\\ h(b)&=\ell_c(b)+\log\phi_\sigma(b) =\ell_c(b)-\frac{b^2}{2\sigma^2}-\log(\sqrt{2\pi}\,\sigma). \end{aligned}\]The contribution of this cluster to the marginal likelihood is its pattern probability $I=\int_{-\infty}^{\infty}\exp[h(b)]\,db$. The remaining sections of this chapter approximate this integral by different methods and compare their results at the same model parameters.
The derivatives will locate the peak and measure its curvature for adaptive quadrature and the Laplace approximation (Sections 5.4 and 5.5). Since $d\eta_j/db=1$, differentiating $\log[1+\exp(\eta_j)]$ gives $p_j(b)$. Row $j$ therefore contributes $y_j-p_j(b)$ to the first derivative and $-p_j(b)[1-p_j(b)]$ to the second. Including the derivatives of the normal log density gives
\[h'(b)=\sum_{j=1}^6[y_j-p_j(b)]-\frac{b}{\sigma^2}, \qquad h''(b)=-\sum_{j=1}^6p_j(b)[1-p_j(b)]-\frac{1}{\sigma^2}.\]The function make_ri_integrand() collects the conditional log probability, the full log integrand and its derivatives for the given observations and model parameters. The returned object ri will supply these functions to the integration methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
make_ri_integrand <- function(x, y, beta, latent_sd) {
stopifnot(length(x) == length(y), length(y) > 0L, length(beta) == 2L,
all(is.finite(c(x, y, beta, latent_sd))), all(y %in% 0:1),
length(latent_sd) == 1L, latent_sd > 0)
offset <- beta[1] + beta[2] * x
response <- function(b) vapply(b, function(value) {
eta <- offset + value
sum(-y * log1pexp(-eta) - (1 - y) * log1pexp(eta))
}, numeric(1))
h <- function(b) response(b) + dnorm(b, 0, latent_sd, log = TRUE)
gr <- function(b) sum(y - plogis(offset + b)) - b / latent_sd^2
he <- function(b) {
eta <- offset + b
matrix(-sum(plogis(eta) * plogis(-eta)) - 1 / latent_sd^2, 1, 1)
}
# Minimize the negative log posterior density, up to a constant, to center the quadrature rule.
X <- cbind(1, x)
Z <- matrix(1, length(y), 1)
Zty <- crossprod(Z, y)
invD <- solve(matrix(latent_sd^2))
linkinv <- binomial()$linkinv
attr(h, "posterior") <- list(
fn = function(b) c(0.5 * crossprod(b, invD) %*% b) -
sum(dbinom(y, 1L, linkinv(as.vector(X %*% beta + Z %*% b)), TRUE), na.rm = TRUE),
gr = function(b) drop(-Zty + crossprod(Z, linkinv(as.vector(X %*% beta + Z %*% b))) +
invD %*% b))
list(response = response, h = h, gr = gr, he = he, latent_sd = latent_sd,
x = x, y = y, beta = beta)
}
ri <- make_ri_integrand(RI1$x, RI1$y, RI1$beta, RI1$latent_sd)
make_ri_integrand() fixes the observations and parameters: the returned ri$x and ri$y contain $x_j$ and $y_j$, ri$beta contains $(\beta_0,\beta_1)$, and ri$latent_sd is $\sigma$. The random intercept $b$ is an input to the returned functions, not an estimated field in the object. For each supplied $b$, ri$response() sums the six log probabilities using log1pexp() (Section 1.1). The first row contributes -log1pexp(eta[1]). The function ri$h() adds the normal log density once. Both accept a vector of $b$ values, while ri$gr() and ri$he() evaluate the derivatives at one $b$. The stored posterior attribute will be used to find adaptive-quadrature centers in Section 5.4.
Before using the derivatives to locate a peak and set a local scale, compare them with finite differences of the log integrand. With explicit step sizes, num_grad() and num_hess() take central differences of ri$h(). Each row reports the absolute errors at one point and step.
1
2
3
4
5
6
7
8
ri_derivative_check <- do.call(rbind, lapply(c(-1, 0, 0.5), function(b) {
do.call(rbind, lapply(c(1e-3, 1e-4, 1e-5), function(step) {
data.frame(b = b, step = step,
gradient_error = abs(num_grad(ri$h, b, step = step)$gradient - ri$gr(b)),
Hessian_error = abs(num_hess(ri$h, b, step = step)$hessian[1, 1] - ri$he(b)[1, 1]))
}))
}))
print(ri_derivative_check, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
b step gradient_error Hessian_error
-1.0 1e-03 7.285998e-08 1.573629e-08
-1.0 1e-04 7.252332e-10 5.037525e-08
-1.0 1e-05 2.357270e-11 1.649096e-06
0.0 1e-03 1.592302e-08 3.868280e-08
0.0 1e-04 1.611864e-10 3.557417e-08
0.0 1e-05 2.089018e-11 6.981035e-06
0.5 1e-03 2.365860e-08 3.711310e-08
0.5 1e-04 2.344507e-10 7.879419e-08
0.5 1e-05 7.965406e-12 4.450916e-06
At each of the three points, first-derivative errors fell from roughly $10^{-8}$ to $10^{-10}$ to $10^{-11}$ as the step went from $10^{-3}$ to $10^{-4}$ to $10^{-5}$. The second-derivative errors were of order $10^{-8}$ at the two wider steps. At the narrowest step, they rose to $1.65$, $6.98$ and $4.45$ times $10^{-6}$ at $b=-1$, $0$ and $0.5$, respectively. The second difference subtracts nearly equal values and divides by the squared step, magnifying rounding error.
For a numerical reference, scalar_reference() sets shift to $h(0)$. Subtracting this constant before exponentiation makes the scaled integrand one at zero. integrate() uses its default tolerances over the whole real line. Since $\exp[h(b)]=\exp[h(0)]\exp[h(b)-h(0)]$, adding shift to log(result$value) restores the log marginal probability.
1
2
3
4
5
6
7
8
9
10
11
scalar_reference <- function(h, anchor = 0) {
shift <- h(anchor)
result <- stats::integrate(function(b) exp(h(b) - shift), -Inf, Inf)
list(log_integral = shift + log(result$value),
estimated_relative_error = result$abs.error / result$value,
subdivisions = result$subdivisions, message = result$message)
}
ri_reference <- scalar_reference(ri$h)
print(c(conditional_at_zero = ri$response(0), log_integral = ri_reference$log_integral,
conditional_probability_at_zero = exp(ri$response(0)),
marginal_probability = exp(ri_reference$log_integral)))
1
2
3
4
conditional_at_zero log_integral conditional_probability_at_zero
-3.12466148 -3.36164251 0.04395181
marginal_probability
0.03467825
conditional_at_zero is the conditional log probability, $-3.12466148$. Its exponential, conditional_probability_at_zero, gives 0.04395181 for a cluster whose random intercept is known to be zero. Averaging over all $b$ gave 0.03467825, with log probability $-3.36164251$.
Which values of $b$ contribute most to the integral? The following calculation evaluates the two factors of the integrand and their product on a common grid from $-3$ to $3$.
1
2
3
4
b_grid <- seq(-3, 3, length.out = 1201)
integrand_curves <- data.frame(b = b_grid, conditional = exp(ri$response(b_grid)),
latent = dnorm(b_grid, sd = ri$latent_sd), joint = exp(ri$h(b_grid)))
stopifnot(all(is.finite(as.matrix(integrand_curves))))
Figure 5.1. The six-response pattern probability given $b$, the density of $b$, and their product. The dotted lines mark zero on the common horizontal axis. Each panel has its own vertical scale.
In Figure 5.1, the responses give the highest conditional probability near $b=0.2$. Multiplication by the normal density moves the peak to about $0.08$ and concentrates the product more narrowly than the normal density alone. The product has area $I$ over the whole real line. Dividing by this area gives the conditional density of $b$ given the six responses.
What changes if each response has its own independent random intercept with the same normal distribution? Let $f_j(y_j\mid b)$ denote the Bernoulli probability of the observed outcome in row $j$. With a shared $b$, a change in $b$ shifts all six log odds together. With independent intercepts $b_1,\ldots,b_6$, the average enters separately for each response, giving
\[I_{\mathrm{shared}}=\int_{\mathbb R} \left\{\prod_{j=1}^6 f_j(y_j\mid b)\right\}\phi_\sigma(b)\,db, \qquad I_{\mathrm{independent}}=\prod_{j=1}^6 \int_{\mathbb R} f_j(y_j\mid b_j)\phi_\sigma(b_j)\,db_j.\]The file data/source/ch05/RI1.rds supplies the same six observations and parameter values. The function joint_probability() multiplies the six probabilities at a common $b$. For a recorded one, sign is positive and plogis() gives the success probability. For a zero, reversing the sign of the linear predictor gives the failure probability. The single integral in shared averages that product. Each entry of individual integrates one response probability.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
d <- readRDS("data/source/ch05/RI1.rds")
eta <- d$beta[1] + d$beta[2] * d$x
sign <- ifelse(d$y == 1, 1, -1)
# Conditional independence gives a product at a fixed shared intercept.
joint_probability <- function(b) vapply(b, function(value) {
prod(plogis(sign * (eta + value)))
}, numeric(1))
scale <- joint_probability(0) * dnorm(0, sd = d$latent_sd)
shared <- scale * integrate(function(b) joint_probability(b) *
dnorm(b, sd = d$latent_sd) / scale,
-Inf, Inf)$value
# With an independent intercept for each response, integrate before taking the product.
individual <- vapply(seq_along(eta), function(j) {
integrate(function(b) plogis(sign[j] * (eta[j] + b)) * dnorm(b, sd = d$latent_sd),
-Inf, Inf)$value
}, numeric(1))
pattern_probability <- data.frame(model = c("one shared intercept",
"six independent intercepts",
"zero variance"),
probability = c(shared, prod(individual), joint_probability(0)))
print(pattern_probability)
1
2
3
4
model probability
1 one shared intercept 0.03467825
2 six independent intercepts 0.04102050
3 zero variance 0.04395181
With independent intercepts, prod(individual) gave 0.04102050. With a shared intercept, shared gave 0.03467825. When the variance is zero, joint_probability(0) gives 0.04395181. For the shared intercept, Figure 5.1 suggests using the observed pattern to place more integration points near the peak of the product; Section 5.4 develops this idea.
A normal response provides an analytic check on the integral. Suppose $Y=0.5+b+\epsilon$, where $b\sim N(0,0.7^2)$ and the residual $\epsilon\sim N(0,0.6^2)$ is independent of $b$. Given $b$, the response has a normal distribution with mean $0.5+b$ and variance $0.6^2$. The constant 0.5 is the population mean response, and $b$ shifts the conditional mean on the response scale. The standard deviation 0.7 describes variation in these shifts; 0.6 describes response variation around a given conditional mean. Both standard deviations have the same units as $Y$. Adding the independent normal terms gives a normal marginal distribution for $Y$ with mean $0.5$ and variance $0.7^2+0.6^2=0.85$. At the observed $y=1.2$, normal_normal_integrand() returns the log integrand in h and the analytic log marginal density in exact.
1
2
3
4
5
6
7
8
9
10
11
12
13
normal_normal_integrand <- function(y, mean, latent_sd, residual_sd) {
stopifnot(all(is.finite(c(y, mean, latent_sd, residual_sd))),
latent_sd > 0, residual_sd > 0)
response <- function(b) dnorm(y, mean + b, residual_sd, log = TRUE)
h <- function(b) response(b) + dnorm(b, 0, latent_sd, log = TRUE)
gr <- function(b) (y - mean - b) / residual_sd^2 - b / latent_sd^2
he <- function(b) matrix(-1 / residual_sd^2 - 1 / latent_sd^2, 1, 1)
list(response = response, h = h, gr = gr, he = he, latent_sd = latent_sd,
exact = dnorm(y, mean, sqrt(latent_sd^2 + residual_sd^2), log = TRUE))
}
gaussian <- normal_normal_integrand(1.2, 0.5, 0.7, 0.6)
print(c(variance = 0.7^2 + 0.6^2, log_density = gaussian$exact,
density = exp(gaussian$exact)))
1
2
variance log_density density
0.8500000 -1.1259144 0.3243558
The analytic density at 1.2 is 0.3243558. Integrating the product of the conditional response density and the random-intercept density should reproduce this value, or $-1.1259144$ on the log scale. The stats package provides numerical integration in one dimension.
5.2 Orthogonal polynomials, Gaussian quadrature, and construction of nodes and weights
Suppose the conditional probability of a response pattern can be evaluated at just four values of the random intercept. Which four values should enter the average over the intercept, and how much weight should each receive? First take the averaging distribution to be standard normal. Let $Z$ have this distribution, let $\phi$ denote its density, and write $f(z)$ for the function to be averaged. A quadrature rule with $n$ nodes (evaluation points) $z_i$ and weights $w_i$ approximates this expectation by a weighted sum
\[E[f(Z)]=\int_{-\infty}^{\infty}f(z)\phi(z)\,dz \;\approx\; Q_n(f)=\sum_{i=1}^{n}w_i f(z_i).\]The nodes and weights depend on the distribution, so the same rule can average several functions of $Z$. For the constant function $f(z)=1$, the integral is one, so an exact rule for constants must have $\sum_i w_i=1$. Exactness for $f(z)=z^2$ also requires the weighted sum of squared nodes to equal the standard normal second moment, one.
The nodes can satisfy several moment conditions at once if they are chosen using orthogonal polynomials. Write $P_k$ for the polynomial of degree $k$ in such a family. Orthogonality means that the expected product of two members of different degrees is zero. Under the standard normal distribution, the Hermite polynomials in the convention with leading coefficient one have this property. Writing these as $\mathrm{He}_k$, take $P_k=\mathrm{He}_k/\sqrt{k!}$ so that each polynomial has expected square one. This specifies the orthonormal family used below and distinguishes its scaling from the Hermite convention in Section 5.3:
\[E[P_m(Z)P_k(Z)] =\int_{-\infty}^{\infty}P_m(z)P_k(z)\phi(z)\,dz =\begin{cases}1,&m=k,\\0,&m\ne k.\end{cases}\]The first two are $P_0(z)=1$ and $P_1(z)=z$. Every polynomial of degree below $n$ is a linear combination of $P_0,\ldots,P_{n-1}$, since these have successive degrees and nonzero leading coefficients. Thus $P_n$ is orthogonal to every such polynomial. This property forces $P_n$ to have $n$ distinct real roots. To see why, form the product of $z-a$ over the real roots $a$ at which $P_n$ changes sign. If there were fewer than $n$ such roots, the product would have degree below $n$. Yet multiplying it by $P_n$ gives a polynomial of constant sign with nonzero integral against the positive normal density, contradicting orthogonality. Using these $n$ roots as nodes makes it possible to integrate every polynomial through degree $2n-1$ exactly.
To find the weights for these nodes, divide a polynomial $g$ of degree at most $2n-1$ by $P_n$ to obtain $g=qP_n+r$. The quotient $q$ has degree at most $n-1$ and the remainder $r$ has degree below $n$. Orthogonality gives $E[q(Z)P_n(Z)]=0$. At every node $z_i$, the same product vanishes because $P_n(z_i)=0$. Both the integral and the quadrature sum therefore depend only on $r$. Its values at the $n$ nodes determine it everywhere. The Lagrange basis polynomial $L_i$ is one at $z_i$ and zero at the other nodes, so interpolation gives
\[L_i(z)=\prod_{j\ne i}\frac{z-z_j}{z_i-z_j}, \qquad r(z)=\sum_{i=1}^n r(z_i)L_i(z).\]Taking expectations gives $E[r(Z)]=\sum_i r(z_i)E[L_i(Z)]$. Thus $w_i=E[L_i(Z)]$. Substitution of $g(z_i)=r(z_i)$ into the quadrature sum gives $Q_n(g)=E[r(Z)]=E[g(Z)]$.
For the standard normal measure, the Hermite recurrence determines both the nodes and the weights. Set $P_{-1}(z)=0$. Multiplication by $z$ relates three successive orthonormal polynomials through
\[zP_k(z)=\sqrt{k}\,P_{k-1}(z)+\sqrt{k+1}\,P_{k+1}(z), \qquad k\ge 0.\]At a root $z_i$ of $P_n$, let $v_i=(P_0(z_i),\ldots,P_{n-1}(z_i))^\top$. With four nodes, the second recurrence reads $z_iP_1(z_i)=P_0(z_i)+\sqrt{2}\,P_2(z_i)$. The last reads $z_iP_3(z_i)=\sqrt{3}\,P_2(z_i)$ because $P_4(z_i)=0$. In general, the $n$ rows give $Jv_i=z_i v_i$. The Jacobi matrix $J$ is the symmetric tridiagonal matrix of this polynomial recurrence. Its entries are recurrence coefficients; it is not the Jacobian matrix of partial derivatives. Its diagonal is zero and its adjacent entries are $J_{k,k+1}=J_{k+1,k}=\sqrt{k}$ for $k=1,\ldots,n-1$. Since $J$ has dimension $n$ and each of the $n$ distinct roots is an eigenvalue, its eigenvalues give all the nodes. To recover $L_i$ from the same polynomial values, consider
\[L_i(z)=\frac{\sum_{k=0}^{n-1}P_k(z_i)P_k(z)}{v_i^\top v_i}.\]At $z_i$, the numerator is $v_i^\top v_i$. At every other node $z_j$, it is $v_i^\top v_j=0$ because eigenvectors of a real symmetric matrix for distinct eigenvalues are orthogonal. A polynomial of degree below $n$ is determined by these $n$ values, which identifies it as $L_i$. On taking its normal expectation, only the $k=0$ term survives, since $P_0=1$ and the other polynomials are orthogonal to the constant. It follows that $w_i=1/(v_i^\top v_i)$. The first component of $v_i$ is $P_0(z_i)=1$. Dividing $v_i$ by its length therefore makes the square of its first component equal to the weight.
The function normal_rule() takes a positive integer n and returns the nodes and their weights in matching order. The first calculation constructs a four-node rule.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
normal_rule <- function(n) {
stopifnot(length(n) == 1L, is.finite(n), n >= 1, n == floor(n))
if (n == 1) {
nodes <- 0
} else {
jacobi <- matrix(0, n, n)
# The two adjacent diagonals contain the same Hermite recurrence coefficients.
jacobi[cbind(1:(n - 1), 2:n)] <- jacobi[cbind(2:n, 1:(n - 1))] <-
sqrt(seq_len(n - 1))
nodes <- rev(eigen(jacobi, symmetric = TRUE, only.values = TRUE)$values)
}
# Evaluate polynomials of degrees 0 through n - 1 at each node.
weights <- vapply(nodes, function(x) {
p <- c(1, x)[seq_len(min(n, 2))]
if (n > 2) for (k in 2:(n - 1)) p[k + 1] <-
(x * p[k] - sqrt(k - 1) * p[k - 1]) / sqrt(k)
1 / sum(p^2)
}, numeric(1))
stopifnot(all(is.finite(nodes)), all(is.finite(weights)), all(weights > 0),
abs(sum(weights) - 1) < 1e-12)
list(nodes = nodes, weights = weights, measure = "standard_normal")
}
rule4 <- normal_rule(4)
print(data.frame(node = rule4$nodes, weight = rule4$weights))
1
2
3
4
5
node weight
1 -2.3344142 0.04587585
2 -0.7419638 0.45412415
3 0.7419638 0.45412415
4 2.3344142 0.04587585
The two nodes nearest zero, $\pm0.7419638$, each receive weight 0.45412415. Each outer node at $\pm2.3344142$ receives 0.04587585.
For one node, the root of $P_1$ is zero. The vector p then contains only $P_0(0)=1$, so the weight is one. For more nodes, jacobi stores the recurrence coefficients on either side of the diagonal. The call to eigen() requests just the eigenvalues, and rev() arranges them in increasing order. At each node x, the first two entries of p are one and x. Its entry p[k] represents $P_{k-1}(x)$ because R indices start at one. For n = 4, the first pass through the recurrence sets p[3] to $(x^2-1)/\sqrt{2}$. The next adds $P_3(x)$, completing the four entries whose squares give the denominator in 1 / sum(p^2). The function checks that the weights are positive and sum to one within $10^{-12}$ before it returns the rule.
Reading the rows in reverse order pairs each negative node with its positive counterpart. Pairwise sums of nodes and differences of weights should both be zero.
1
2
3
print(c(total_weight = sum(rule4$weights),
node_symmetry = max(abs(rule4$nodes + rev(rule4$nodes))),
weight_symmetry = max(abs(rule4$weights - rev(rule4$weights)))))
1
2
total_weight node_symmetry weight_symmetry
1.000000e+00 3.330669e-16 1.110223e-16
The weights summed to one at the printed precision. The largest absolute sum of paired nodes was $3.33\times10^{-16}$ and the largest absolute difference between their weights was $1.11\times10^{-16}$.
For four nodes, the proof guarantees exactness through degree seven. Evaluating $f(z)=z^k$ gives one check for each power $k$. The column normal contains the standard normal moments. The odd moments vanish by symmetry. For even $k\ge 2$, integration by parts with $\phi^{\prime}(z)=-z\phi(z)$ gives $E[Z^k]=(k-1)E[Z^{k-2}]$, starting from $E[1]=1$. For each power, quadrature sums the node powers times their weights using the full precision in rule4. The column error subtracts the normal moment from that sum.
1
2
3
4
5
normal_moments <- c(1, 0, 1, 0, 3, 0, 15, 0, 105)
quadrature_moments <- vapply(0:8, function(power) sum(rule4$weights * rule4$nodes^power),
numeric(1))
print(data.frame(power = 0:8, quadrature = quadrature_moments,
normal = normal_moments, error = quadrature_moments - normal_moments))
1
2
3
4
5
6
7
8
9
10
power quadrature normal error
1 0 1.000000e+00 1 4.440892e-16
2 1 -8.326673e-17 0 -8.326673e-17
3 2 1.000000e+00 1 2.220446e-16
4 3 -2.220446e-16 0 -2.220446e-16
5 4 3.000000e+00 3 8.881784e-16
6 5 0.000000e+00 0 0.000000e+00
7 6 1.500000e+01 15 0.000000e+00
8 7 0.000000e+00 0 0.000000e+00
9 8 8.100000e+01 105 -2.400000e+01
Through degree seven, the odd sums were below $10^{-13}$ in absolute value, and the sixth moment was 15 at the displayed precision. The degree-eight row can be explained directly from the four node locations. The Hermite recurrence gives $\sqrt{24}\,P_4(z)=z^4-6z^2+3$, so at each of the four nodes $z_i^8=(6z_i^2-3)^2$. The weighted sum for the eighth power therefore equals $36(3)-36(1)+9=81$, using exactness for powers four, two and zero. The normal eighth moment is $7(15)=105$, giving the signed difference of $-24$. The statmod package provides Gaussian quadrature for standard normal expectations.
5.3 Gauss-Hermite quadrature and normal change of variables
The random intercept in RI1 has standard deviation 0.7. How can nodes calculated for a standard normal variable give the probability of this cluster’s six responses? Write $y$ for the observed pattern and $p(y\mid b)$ for its probability at a shared random intercept $b$, with the covariates and regression coefficients fixed. For a normal random intercept with mean $\mu$ and standard deviation $\sigma>0$, the density at $b$ is $\phi((b-\mu)/\sigma)/\sigma$, where $\phi$ denotes the standard normal density. Setting $b=\mu+\sigma z$ gives $db=\sigma\,dz$. Both variables range over the real line, so the cluster’s marginal probability is
The Jacobian $\sigma$ cancels the density factor $1/\sigma$. The intercept’s mean and standard deviation now enter the conditional probability through its argument.
For an $n$-point standard normal rule, let $z_k$ and $w_k$ denote the node and quadrature weight in row $k$. These positive weights sum to one and act as probabilities in a finite approximation to the normal distribution. They are not the probabilities that a continuous normal variable equals the individual nodes. To approximate the expectation, evaluate the conditional probability at $b_k=\mu+\sigma z_k$, multiply by $w_k$, and sum over $k$. Taking the logarithm gives the cluster’s approximate contribution to the log marginal likelihood
\[\log I \;\approx\; \log\!\left\{\sum_{k=1}^{n} w_k\,p(y\mid\mu+\sigma z_k)\right\}.\]The same transformed intercept enters all six Bernoulli factors in a row. It is their product that receives weight $w_k$. Since the weights already average over the normal distribution, the function evaluated at the nodes is just the conditional pattern probability. For a conditional log probability $\ell_c(b_k)$, the weighted term on the probability scale is $\exp\lbrace \log w_k+\ell_c(b_k)\rbrace $. The logarithm in the formula applies to the sum of those terms.
Gauss-Hermite nodes can also be tabulated for the physicists’ Hermite polynomials. That convention integrates against $e^{-x^2}\,dx$, whose integral over the real line is $\sqrt{\pi}$. To see how to use such a table for a standard normal expectation, write $z=\sqrt{2}\,x$. The exponent $-z^2/2$ becomes $-x^2$, and $dz=\sqrt{2}\,dx$ changes the normalizing constant from $1/\sqrt{2\pi}$ to $1/\sqrt{\pi}$. For a function $f$ with finite normal expectation, the result is
\[E[f(Z)]=\frac{1}{\sqrt{\pi}}\int_{-\infty}^{\infty} f(\sqrt{2}\,x)e^{-x^2}\,dx.\]If the table lists nodes $x_k$ and weights $a_k$, the corresponding probability rule uses $z_k=\sqrt{2}\,x_k$ and $w_k=a_k/\sqrt{\pi}$. The function normal_rule() computes the standard normal nodes directly and its weights already sum to one. For this probability rule, only the change from the standard normal scale to the random-intercept scale remains.
The function gauss_hermite_rule() transforms the standard normal rule to the intercept scale. The function log_quadrature() combines one log weight and one supplied log-function value per node. Its argument log_integrand must match the measure represented by the rule: the normal-expectation rule requires the conditional log probability, while weights for ordinary integration require the full log integrand, including the random-intercept density.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
gauss_hermite_rule <- function(n, mean = 0, sd = 1) {
stopifnot(length(mean) == 1L, is.finite(mean), length(sd) == 1L, is.finite(sd), sd > 0)
base <- normal_rule(n)
# Transform the nodes to the random-intercept scale and keep the probability weights.
list(nodes = matrix(mean + sd * base$nodes, ncol = 1), log_weights = log(base$weights),
standard_nodes = matrix(base$nodes, ncol = 1), count = n, dimension = 1L,
measure = "normal_expectation", mean = mean, sd = sd, valid = TRUE)
}
log_quadrature <- function(log_integrand, rule) {
if (!isTRUE(rule$valid)) return(list(log_integral = NA_real_, valid = FALSE,
reason = rule$reason, evaluations = 0L, rule = rule))
values <- vapply(seq_len(nrow(rule$nodes)), function(j) log_integrand(rule$nodes[j, ]),
numeric(1))
valid <- !anyNA(values) && !any(values == Inf)
# Add one log weight to the log integrand value in the same row.
total <- if (valid) logsumexp(rule$log_weights + values) else NA_real_
list(log_integral = total, valid = valid,
reason = if (valid) "evaluated" else "invalid_integrand",
evaluations = nrow(rule$nodes), log_values = values, rule = rule)
}
The function gauss_hermite_rule() calls normal_rule() and returns a rule labeled "normal_expectation". Row $k$ of its one-column matrix nodes contains $b_k$, and the matching entry of log_weights contains $\log w_k$. For RI1, the log term in row $k$ is rule$log_weights[k] + ri$response(rule$nodes[k, ]). In the four-node rule, the positive inner node becomes $b_k=0.7(0.7419638)\approx0.519375$. Its log term adds $\log(0.45412415)$ to the conditional log probability evaluated there. The code uses the unrounded nodes and weights. The call to logsumexp() (Section 1.3) returns the logarithm of the sum of these terms.
The evaluations field counts calls to the supplied log integrand, one per row when the rule is valid. The returned valid flag excludes missing values and positive infinity in the evaluated function values; it does not certify integration accuracy or test the resulting sum for finiteness.
How does the approximation change with the node count for the binary pattern and for a normal response? Both calculations use a random intercept with mean zero and standard deviation 0.7. For the normal example, gaussian$response() evaluates the log density at 1.2 under a normal distribution with conditional mean $0.5+b$ and residual standard deviation 0.6. The reference for that example is its analytic marginal log density, gaussian$exact. For the binary pattern, ri_reference$log_integral comes from numerical integration on the real line. Each error column subtracts its own reference from the approximate log integral.
1
2
3
4
5
6
7
8
9
node_counts <- c(3, 7, 15, 31)
fixed_comparison <- do.call(rbind, lapply(node_counts, function(n) {
a <- log_quadrature(ri$response, gauss_hermite_rule(n, sd = ri$latent_sd))
b <- log_quadrature(gaussian$response, gauss_hermite_rule(n, sd = gaussian$latent_sd))
data.frame(nodes = n, RI1_log_integral = a$log_integral,
RI1_error = a$log_integral - ri_reference$log_integral,
normal_log_integral = b$log_integral, normal_error = b$log_integral - gaussian$exact)
}))
print(fixed_comparison, row.names = FALSE)
1
2
3
4
5
nodes RI1_log_integral RI1_error normal_log_integral normal_error
3 -3.344707 1.693502e-02 -1.197051 -7.113627e-02
7 -3.361548 9.487425e-05 -1.128488 -2.574120e-03
15 -3.361643 5.403091e-09 -1.125914 5.363241e-07
31 -3.361643 -1.776357e-15 -1.125914 6.852297e-13
At three nodes, the binary log probability exceeded its numerical reference by 0.016935, while the normal log density was below its analytic value by 0.071136. For RI1, the signed differences at seven, fifteen and thirty-one nodes were $9.49\times10^{-5}$, $5.40\times10^{-9}$ and $-1.78\times10^{-15}$. For the normal response, they were $-0.002574$, $5.36\times10^{-7}$ and $6.85\times10^{-13}$. The 15-node and 31-node log probabilities for RI1 both print as $-3.361643$. The error columns use the unrounded values. At every count in this comparison, the absolute difference was larger for the normal response. This ordering describes these two conditional response functions at the specified parameters.
The numerical reference has its own error estimate. The function scalar_reference() of Section 5.1 computes it. Applying it to gaussian$h permits a check against a known log density.
1
2
3
4
gaussian_reference <- scalar_reference(gaussian$h)
print(c(RI1_reference = ri_reference$log_integral,
RI1_estimated_relative_error = ri_reference$estimated_relative_error,
normal_reference_error = gaussian_reference$log_integral - gaussian$exact))
1
2
RI1_reference RI1_estimated_relative_error normal_reference_error
-3.361643e+00 1.167381e-07 -5.551115e-15
For RI1, RI1_estimated_relative_error was $1.167381\times10^{-7}$. The ratio result$abs.error / result$value divides the estimated absolute error by the integral returned for the same scaled function. It is the integrator’s error estimate, not a bound on the true error. The much smaller 31-node difference in RI1_error measures agreement with this numerical reference rather than establishing accuracy to that many digits. The signed difference between the numerical and analytic normal log densities was $-5.551115\times10^{-15}$.
What happens at the same 31 nodes if the function supplied to log_quadrature() is ri$h()? At each node, it adds the normal log density to the conditional log probability in ri$response().
1
2
3
doubled_density <- log_quadrature(ri$h, gauss_hermite_rule(31, sd = ri$latent_sd))
print(c(correct_log_integral = tail(fixed_comparison$RI1_log_integral, 1),
extra_prior_density = doubled_density$log_integral))
1
2
correct_log_integral extra_prior_density
-3.361643 -4.166854
Including the density again changed the result from $-3.361643$ to $-4.166854$. For the $N(0,0.7^2)$ random-intercept density $\phi_{0.7}$, the second call approximates the logarithm of $\int p(y\mid b)\phi_{0.7}(b)^2\,db$. Here the density reaches its maximum at zero, where $1/(0.7\sqrt{2\pi})<1$. Multiplying by it again reduces every term in the sum. Using ri$response() with these weights gives the required average over the shared random intercept. The statmod package provides Gauss-Hermite quadrature under both weight conventions.
5.4 Adaptive quadrature using the conditional mode and negative Hessian
The fixed Gauss-Hermite rule for RI1 centers its nodes at zero and spaces them using the random-intercept standard deviation of 0.7. How should their locations reflect the six observed responses in this cluster? At fixed regression coefficients and random-intercept variance, the conditional density of $b$ given the responses is $\exp[h(b)]/I$, where $I$ is the marginal pattern probability. Its denominator is constant in $b$. The conditional mode $\hat b$ therefore maximizes $h$, and the negative second derivative $H=-h^{\prime\prime}(\hat b)$ measures how sharply the log integrand falls near that maximum. Adaptive Gauss-Hermite quadrature (AGQ in the code) uses this conditional mode and its negative Hessian to place nodes. These derivatives are with respect to the random effect, with the model parameters fixed. The quantity $H^{-1/2}$ is the standard deviation of the normal approximation at the mode. It approximates the conditional spread of $b$, rather than uncertainty in an estimated regression coefficient.
To see how the center sets the node locations, first take the exact mode and write $s=H^{-1/2}$ for the standard deviation of the local normal approximation. Near the mode, the vanishing first derivative leaves a quadratic change of about $-H(b-\hat b)^2/2$ in $h(b)$. A displacement of $s$ therefore corresponds to one standard deviation of the normal distribution with this curvature. Now set $b=\hat b+sz$. Since $s>0$, the differential is $db=s\,dz$, and the exact integral becomes
\[I=\int_{-\infty}^{\infty}e^{h(b)}\,db =\int_{-\infty}^{\infty}e^{h(\hat b+sz)}s\,dz.\]In the new coordinate, zero is the conditional mode and the local quadratic change is $-z^2/2$. The substitution uses the local curvature to place points. At each point the integral still uses the full log integrand $h$.
For a standard normal variable $Z$, the quadrature weights already account for its density. To apply them to the integral with respect to $dz$, multiply and divide its integrand by $\phi(z)$, the standard normal density. Since $\phi(z)>0$ at every finite $z$, the quotient is well defined. Writing the nodes as $z_k$ and their probability weights as $w_k$ gives
\[I=E\!\left[\frac{s\,e^{h(\hat b+sZ)}}{\phi(Z)}\right] \;\approx\;\sum_{k=1}^{n} \frac{w_k s}{\phi(z_k)}\,e^{h(\hat b+sz_k)}.\]The factor $s$ accounts for the length scale of $b$. Dividing by $\phi(z_k)$ compensates for using the standard normal probability weights to integrate over that scale. Both operations belong in the weight. The resulting weights $w_k s/\phi(z_k)$ are integration coefficients and need not sum to one; normalizing them would change the integral being approximated. The normal random-intercept density in $h$ remains part of the model and is evaluated at $\hat b+sz_k$.
Finding the conditional mode
To find the mode starting from $b=0$, conditional_mode() passes the objective function $f=-h$ and the negatives of both supplied derivatives to inner_newton(). At the current $b$, let $g=f^{\prime}(b)$ and $H_b=f^{\prime\prime}(b)$. In this scalar problem, the shifted Newton equation and the trial point are
The shift $t=1/u-1$ starts at zero with $u=1$. From the book directory, the following call loads the solver. The function conditional_mode() then recomputes the unshifted curvature at the returned point and checks that the Cholesky factorization succeeds and $f$ is finite at that point.
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/integration.R")
conditional_mode <- function(h, gr, he, start, control = list()) {
fit <- tryCatch(inner_newton(function(b) -h(b), function(b) -gr(b), function(b) -he(b),
start, control), error = identity)
if (inherits(fit, "error")) {
return(list(mode = rep(NA_real_, length(start)), valid = FALSE,
reason = "inner_failed",
message = conditionMessage(fit)))
}
# Check the unshifted curvature at the point returned by Newton.
H <- -he(fit$par)
R <- tryCatch(chol(H), error = function(e) NULL)
list(mode = fit$par, curvature = H, factor = R, log_integrand_gradient = gr(fit$par),
fit = fit,
valid = !is.null(R) && is.finite(fit$value),
reason = if (is.null(R)) "invalid_curvature" else fit$reason)
}
ri_mode <- conditional_mode(ri$h, ri$gr, ri$he, 0)
print(c(mode = ri_mode$mode,
log_integrand_derivative = ri_mode$log_integrand_gradient,
curvature = ri_mode$curvature[1, 1],
prior_sd = ri$latent_sd, local_sd = 1 / sqrt(ri_mode$curvature[1, 1]),
iterations = ri_mode$fit$iterations, valid = ri_mode$valid))
1
2
3
4
mode log_integrand_derivative curvature prior_sd
7.943699e-02 -1.740439e-10 3.383148e+00 7.000000e-01
local_sd iterations valid
5.436751e-01 3.000000e+00 1.000000e+00
The Newton loop reported three iterations. Its return field ri_mode$reason is "small_step". The derivative of $h$ at the returned point $b=0.07943699$ is $-1.74\times10^{-10}$. For this random-intercept logistic regression model, with conditional success probability $p_j(b)$ for response $j$, $-h^{\prime\prime}(b)=\sum_j p_j(b)[1-p_j(b)]+1/\sigma^2\ge 1/\sigma^2$ everywhere. The strict concavity makes the stationary point the unique mode. Since $h^{\prime}(\hat b)=0$, the mean value theorem gives $\vert h^{\prime}(b)\vert =\vert h^{\prime\prime}(\xi)\vert \,\vert b-\hat b\vert $ at some $\xi$ between the two points. Thus a derivative magnitude at most $10^{-8}$ bounds the distance to the mode by $\sigma^2\,10^{-8}=4.9\times10^{-9}$. The unshifted curvature rounds to 3.383148. Using its unrounded value in $1/\sqrt{H}$ gives local_sd as 0.5436751, compared with 0.7 for the model distribution of $b$. The approximation is narrower after incorporating these responses; its standard deviation need not equal that of the exact conditional distribution.
When the gradient test requires a move, the solver first moves $u$ toward one using $u_0+(1-u_0)\sqrt u$, with $u_0=10^{-4}$. A trial requires a positive definite shifted Hessian, tested by Cholesky factorization, and a finite $f(b_+)\le f(b)+\sqrt{\epsilon}$, where $\epsilon$ is .Machine$double.eps, the gap between one and the next larger representable double-precision number. If a trial fails, reducing $u$ increases the shift. The solver stops with an error if any gradient component is nonfinite or exceeds $10^{60}$ in absolute value. Once the largest absolute component falls below $10^{-8}$, the solver retains the current point, giving a step of length zero.
Starting at iteration 11, the solver first tests the decrease in $f$ from values[i-9] to values[i]. A difference smaller than $10^{-3}$ permits an early stop if the unshifted Hessian of $f$ passes its check. This comparison also includes a negative difference, which would mean that $f$ increased over the window; it is not a separate gradient test. A failed curvature check increments refused. On any iteration that continues, a displacement shorter than $10^{-8}$ gives the stopping reason small_step. If the loop passes that test without stopping, refused > 5L triggers an error. The default iteration limit is 1,000.
A second way to choose the center uses the gradient during optimization and computes the curvature afterward. For RI1, agq_mode() obtains the objective function and gradient from the posterior attribute of ri$h. In exact arithmetic, this objective differs from the negative log conditional density only by an additive constant independent of $b$, so its minimizer maximizes $h$. If the attribute is absent, the function forms $-h$ and its gradient directly from h and gr. The BFGS fit starts at zero.
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
agq_mode <- function(h, gr, start, control = list()) {
posterior <- attr(h, "posterior")
if (is.null(posterior)) posterior <- list(fn = function(b) -h(b),
gr = function(b) -gr(b))
fit <- bfgs(posterior$fn, posterior$gr, start, control)
x <- fit$par
negative_log_gradient <- posterior$gr
n <- length(x)
# Difference the gradient in each coordinate to obtain one Hessian column.
step <- 0.001 * pmax(abs(x), 1)
res <- vapply(seq_len(n), function(i) {
up <- x; up[i] <- x[i] + step[i]
down <- x; down[i] <- x[i] - step[i]
c(negative_log_gradient(up) - negative_log_gradient(down)) / (up[i] - down[i])
}, numeric(n))
H <- 0.5 * (res + t(res))
R <- tryCatch(chol(H), error = function(e) NULL)
list(mode = x, curvature = H, factor = R, log_integrand_gradient = gr(x), fit = fit,
valid = !is.null(R) && is.finite(fit$value),
reason = if (is.null(R)) "invalid_curvature" else fit$reason)
}
agq_center <- agq_mode(ri$h, ri$gr, 0)
print(c(mode = agq_center$mode,
log_integrand_derivative = agq_center$log_integrand_gradient,
curvature = agq_center$curvature[1, 1],
Newton_mode = ri_mode$mode, Newton_curvature = ri_mode$curvature[1, 1],
BFGS_iterations = agq_center$fit$iterations))
1
2
3
4
mode log_integrand_derivative curvature Newton_mode
7.943698e-02 1.800333e-08 3.383148e+00 7.943699e-02
Newton_curvature BFGS_iterations
3.383148e+00 3.000000e+00
BFGS returned a center of 0.07943698, with $h^{\prime}$ there equal to $1.80\times10^{-8}$. Its curvature estimate and the analytic curvature at the Newton center both round to 3.383148. The BFGS counter starts at one and reached three after two BFGS updates. The field valid records whether the negative log posterior density, up to its omitted constant, is finite at the center and the curvature admits a Cholesky factorization. A fit at its iteration limit can pass both checks, so the stopping reason accompanies the center.
The posterior attribute was stored with ri$h by make_ri_integrand() in Section 5.1. Its implementation first computes response probabilities and then calls dbinom(), whereas ri$h() computes log probabilities directly; extreme linear predictors can therefore lead to different numerical behavior.
At the returned vector x, the code estimates column $i$ of the Hessian by evaluating the gradient of the objective function on either side of coordinate $i$, at distance $0.001\max(\vert x_i\vert ,1)$. Dividing their difference by the coordinate separation gives res[, i]. Averaging this matrix with its transpose gives a symmetric estimate of the negative Hessian of $h$ to factor. This finite-difference matrix is computed after optimization; it is not the inverse-Hessian approximation updated inside BFGS.
The function agh_rule() constructs this scalar adaptive Gauss-Hermite rule. It calls agq_mode() for the center and curvature.
The same block constructs a second cluster that repeats the six covariate and response pairs twenty times. Its coefficients remain $(-0.4,0.8)$ and its model standard deviation for the shared random intercept is set to 2. These assignments define a different integrand for comparing node placement. Each variance is specified, not estimated from its single cluster.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
agh_rule <- function(n, h, gr, start = 0, control = list()) {
stopifnot(length(start) == 1L)
inner <- agq_mode(h, gr, start, control)
if (!inner$valid) return(list(valid = FALSE, reason = inner$reason,
inner = inner, count = 0L))
base <- normal_rule(n)
# Convert the standard normal nodes and weights to the scale of the random intercept.
scale <- 1 / inner$factor[1, 1]
list(nodes = matrix(inner$mode + scale * base$nodes, ncol = 1),
log_weights = log(base$weights) + log(scale) - dnorm(base$nodes, log = TRUE),
standard_nodes = matrix(base$nodes, ncol = 1), count = n, dimension = 1L,
measure = "ordinary_integral", inner = inner, valid = TRUE, reason = "constructed")
}
RI1_concentrated <- list(x = rep(RI1$x, 20), y = rep(RI1$y, 20),
beta = RI1$beta, latent_sd = 2)
concentrated <- do.call(make_ri_integrand, RI1_concentrated)
If inner$valid is false, agh_rule() returns the reason and a node count of zero. At a center passing those checks, the scalar Cholesky factor in inner$factor[1, 1] is the positive square root of the estimated curvature. Its reciprocal is scale, the standard deviation of the normal approximation at that center. This rule obtains the curvature by differencing the supplied gradient in agq_mode(). Row $k$ of nodes is the computed center plus scale times $z_k$. The corresponding log_weights entry is $\log w_k+\log s-\log\phi(z_k)$. Adding that entry to $h$ evaluated at the same node gives one log term for log_quadrature().
Adaptive and fixed rules compared
In RI1_concentrated, the 120 responses share one random intercept. Their conditional log probability is twenty times the six-response log probability, while the new normal log density enters only once. For each cluster, scalar_reference() integrates its own full joint integrand. Each signed difference below subtracts that numerical reference log integral from the fixed or adaptive approximation. The code calls this reference truth; it remains a numerical approximation with its own integration error. The fixed rule receives model$response and the adaptive rule receives model$h. At a given node count both sums use one function evaluation per node. The adaptive calculation also evaluates the objective function and its gradient to locate the center, then differences the gradient to estimate curvature.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
concentrated_reference <- scalar_reference(concentrated$h)
adaptive_comparison <- do.call(rbind, lapply(list(RI1 = ri, concentrated = concentrated),
function(model) {
truth <- scalar_reference(model$h)$log_integral
do.call(rbind, lapply(node_counts, function(n) {
fixed <- log_quadrature(model$response, gauss_hermite_rule(n, sd = model$latent_sd))
adaptive <- log_quadrature(model$h, agh_rule(n, model$h, model$gr))
data.frame(responses = length(model$y), nodes = n,
fixed_error = fixed$log_integral - truth,
adaptive_error = adaptive$log_integral - truth, mode = adaptive$rule$inner$mode,
local_sd = 1 / sqrt(adaptive$rule$inner$curvature[1, 1]),
inner_valid = adaptive$rule$inner$valid)
}))
}))
print(adaptive_comparison, row.names = FALSE)
1
2
3
4
5
6
7
8
9
responses nodes fixed_error adaptive_error mode local_sd inner_valid
6 3 1.693502e-02 -7.467865e-07 0.07943698 0.5436751 TRUE
6 7 9.487425e-05 2.081869e-08 0.07943698 0.5436751 TRUE
6 15 5.403091e-09 2.975398e-14 0.07943698 0.5436751 TRUE
6 31 -1.776357e-15 2.220446e-15 0.07943698 0.5436751 TRUE
120 3 1.404306e+00 -6.931671e-06 0.19815951 0.1918595 TRUE
120 7 1.027011e+00 -4.486793e-10 0.19815951 0.1918595 TRUE
120 15 6.648826e-01 1.904255e-11 0.19815951 0.1918595 TRUE
120 31 3.105273e-01 1.907097e-11 0.19815951 0.1918595 TRUE
With six responses, three fixed nodes gave a log integral 0.016935 above the reference. Three adaptive nodes gave a difference of $-7.47\times10^{-7}$. At 15 nodes the adaptive difference was $2.98\times10^{-14}$. At 31 nodes both differences had magnitude below $3\times10^{-15}$.
For the 120 responses, the center moved to 0.19815951 and the local standard deviation fell from 0.5436751 to 0.1918595. The three-node differences from its reference were 1.404306 for the fixed rule and $-6.93\times10^{-6}$ for the adaptive rule. Even at 31 nodes, the fixed difference was 0.3105273. The adaptive differences were $-4.49\times10^{-10}$ at seven nodes and about $1.9\times10^{-11}$ at both 15 and 31 nodes.
In this comparison the prior became wider while the conditional distribution became more concentrated. The fixed nodes spread out with the wider prior. The adaptive nodes move closer together around the new mode, where most of the integral accumulates.
What happens to the 15-node approximation if the center search stops early? For the original six responses, start BFGS at $b=3$ and set maxit = 1L. The stopping reason and $h^{\prime}$ refer to the point BFGS returned. The last two fields come from evaluating the adaptive sum at 15 nodes around that point.
1
2
3
4
5
6
failed_rule <- agh_rule(15, ri$h, ri$gr, start = 3, control = list(maxit = 1L))
failed_integral <- log_quadrature(ri$h, failed_rule)
print(list(reason = failed_rule$inner$reason,
log_integrand_derivative_at_returned_point = failed_rule$inner$log_integrand_gradient,
log_integral = failed_integral$log_integral,
integrand_evaluations = failed_integral$evaluations))
1
2
3
4
5
6
7
8
9
10
11
$reason
[1] "iteration_limit"
$log_integrand_derivative_at_returned_point
[1] -3.901963
$log_integral
[1] -3.361643
$integrand_evaluations
[1] 15
BFGS reported iteration_limit, and $h^{\prime}=-3.901963$ at the returned center shows that it is away from stationarity. The 15-node log integral was $-3.361643$, agreeing with the numerical reference $-3.36164251$ to six decimal places. This comparison checks the integral at the only node count tried around this center. The negative derivative has a different implication for the center itself. Moving a small distance toward smaller $b$ raises the log integrand. The curvature in the supplied agq_mode() is computed as in GLMMadaptive, and the negative log posterior of make_ri_integrand() and its gradient follow its log_post_b() and score_log_post_b() (code/NOTICE.md); GLMMadaptive provides adaptive Gauss-Hermite quadrature for generalized linear mixed models.
5.5 Laplace approximation and one-point adaptive quadrature
How can the log integrand and its curvature at the conditional mode be used to approximate a cluster’s contribution to the marginal likelihood? Let $y$ be the cluster’s observed responses and $z\in\mathbb R^d$ its vector of random effects. With the model parameters fixed, the log integrand is $h(z)=\log p(y\mid z)+\log p(z)$, where $p(y\mid z)$ is the conditional response probability or density and $p(z)$ is the random-effects density. The marginal likelihood contribution is $I=\int_{\mathbb R^d}\exp[h(z)]\,dz$. Suppose a finite mode $\hat z$ exists, every sufficiently small displacement from it is allowed in $\mathbb R^d$, and $h$ is twice continuously differentiable throughout a neighborhood of that point. Assume also that its negative Hessian $H=-\nabla^2 h(\hat z)$ is positive definite. For a displacement $v=z-\hat z$, the linear term in the Taylor expansion vanishes because $\nabla h(\hat z)=0$. The quadratic expansion and the resulting approximation to the integrand are
\[h(\hat z+v)=h(\hat z)-\tfrac12 v^\top H v+o(\lVert v\rVert^2), \qquad e^{h(\hat z+v)}\approx e^{h(\hat z)}e^{-v^\top H v/2}.\]As $v$ approaches zero, the remainder divided by $\lVert v\rVert^2$ tends to zero. The approximation has the same height as the integrand at $\hat z$. After normalization, the approximating normal density has covariance matrix $H^{-1}$. This is the covariance of the approximation; the actual conditional distribution of the random effects can have different moments. The integral depends on the width of this peak as well as its height. The integral of the absolute difference between the two integrands bounds the approximation error, so the comparison must include the tails. A local Taylor expansion alone does not guarantee that one peak represents the whole integral, especially if other peaks contribute substantially.
To integrate the quadratic approximation, take the upper triangular Cholesky factor $R$ such that $H=R^\top R$. In the variable $u=Rv$, the quadratic form is $u^\top u$ and the volume element is $dz=\vert H\vert ^{-1/2}\,du$, where $\vert H\vert $ denotes the determinant. The exponential now factors across coordinates. Integrating $\exp(-u_j^2/2)$ along coordinate $j$ gives $\sqrt{2\pi}$, the same factor for each of the $d$ coordinates. Multiplying by the height and taking the logarithm gives the Laplace approximation
\[I\approx e^{h(\hat z)}(2\pi)^{d/2}|H|^{-1/2}, \qquad \log I\approx h(\hat z)+\frac{d}{2}\log(2\pi)-\frac12\log|H|.\]Here $d$ counts random effects integrated for one cluster. A cluster with 120 responses and a single shared random intercept still has $d=1$. With the height and all other curvatures fixed, a larger eigenvalue of $H$ narrows the normal approximation along its corresponding eigenvector and reduces its integral.
A zero eigenvalue of the negative Hessian would give a direction with no second-order decrease in the quadratic approximation. The exponential of the quadratic would then have infinite integral along that direction, even though higher-order terms in the actual log integrand could still make the original integral finite.
For a scalar random intercept $b$, the curvature is the positive number $H=-h^{\prime\prime}(\hat b)$, and the local standard deviation is $s=1/\sqrt H$. Consider the adaptive rule that uses a single standard normal node. Its node is zero and its probability weight is one. The transformed node is $\hat b+s\cdot0=\hat b$. With $\phi$ denoting the standard normal density, the corrected weight for ordinary integration is $s/\phi(0)$. The resulting one-point sum is
\[\frac{s}{\phi(0)}e^{h(\hat b)} =e^{h(\hat b)}\sqrt{\frac{2\pi}{H}}.\]Its logarithm is precisely the scalar Laplace expression. This identity compares formulas evaluated with the same center and curvature. Whether their common value approximates the original integral well depends on how much the log integrand departs from its quadratic expansion.
The function laplace_approx() uses conditional_mode() to obtain the Newton center and the Cholesky factor of the unshifted negative Hessian there. The optional argument inner accepts a mode calculation already made for that integrand.
1
2
3
4
5
6
7
8
9
10
11
12
laplace_approx <- function(h, gr, he, start, control = list(), inner = NULL) {
# The caller may already have fitted the conditional mode for this same integrand.
if (is.null(inner)) inner <- conditional_mode(h, gr, he, start, control)
if (!inner$valid) return(list(log_integral = NA_real_, valid = FALSE,
reason = inner$reason, inner = inner))
d <- length(start)
# The log determinant is twice the sum of the log Cholesky diagonal entries.
log_determinant <- 2 * sum(log(diag(inner$factor)))
list(log_integral = h(inner$mode) + d * log(2 * pi) / 2 - log_determinant / 2,
valid = TRUE, reason = "evaluated", dimension = d, inner = inner,
log_determinant = log_determinant)
}
Since $\vert H\vert $ is the square of the product of the diagonal entries of $R$, 2 * sum(log(diag(inner$factor))) computes $\log\vert H\vert $. The length of start supplies $d$. If the curvature fails its Cholesky check, inner$valid is false and the function returns the recorded reason with a missing log integral. When these validity checks pass, h(inner$mode) supplies the log height. The stopping reason and gradient still describe whether the center search reached a stationary point.
Each row of the comparison integrates over one random intercept, with both mode searches starting at zero. In the row labeled normal in the integrand column, the quantity of interest is the marginal density at $y=1.2$. Both the conditional normal log density and the normal random-intercept log density are quadratic in $b$, so their sum equals its quadratic expansion everywhere. The reference gaussian$exact is the log density under the marginal normal distribution with mean 0.5 and variance 0.85. In the RI1 and concentrated rows, each integral averages the joint conditional probability of the observed binary responses over the shared intercept’s normal density. Each uses its own numerical reference. The column difference subtracts the Laplace log integral from the one-point adaptive log integral. The columns Laplace_error and AGQ15_error subtract the row’s reference log integral from the Laplace and 15-node adaptive estimates, respectively.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
laplace_results <- lapply(list(RI1 = ri, normal = gaussian, concentrated = concentrated),
function(model) {
laplace_approx(model$h, model$gr, model$he, 0)
})
laplace_comparison <- do.call(rbind, lapply(c("RI1", "normal", "concentrated"),
function(name) {
model <- list(RI1 = ri, normal = gaussian, concentrated = concentrated)[[name]]
reference_log_integral <- c(RI1 = ri_reference$log_integral, normal = gaussian$exact,
concentrated = concentrated_reference$log_integral)[name]
one <- log_quadrature(model$h, agh_rule(1, model$h, model$gr))
high <- log_quadrature(model$h, agh_rule(15, model$h, model$gr))
lap <- laplace_results[[name]]
data.frame(integrand = name, Laplace = lap$log_integral, one_AGQ = one$log_integral,
difference = one$log_integral - lap$log_integral,
Laplace_error = lap$log_integral - reference_log_integral,
AGQ15_error = high$log_integral - reference_log_integral,
max_abs_log_integrand_derivative = max(abs(lap$inner$log_integrand_gradient)),
row.names = NULL)
}))
print(laplace_comparison, row.names = FALSE)
1
2
3
4
5
6
7
8
integrand Laplace one_AGQ difference Laplace_error AGQ15_error
RI1 -3.366721 -3.366721 1.180415e-08 -5.078807e-03 2.975398e-14
normal -1.125914 -1.125914 -8.881784e-16 -2.220446e-16 -2.220446e-16
concentrated -64.304634 -64.304634 2.952594e-08 -1.633242e-03 1.904255e-11
max_abs_log_integrand_derivative
1.740439e-10
1.110223e-16
5.115688e-09
For the normal response, both methods gave the analytic value $-1.125914$ to six decimal places. For the six responses in RI1, the log height is the negative of the minimized value in ri_mode$fit$value. Combining that height, about $-3.676256$, with the curvature 3.383148 gives the Laplace log integral $-3.366721$ after rounding. The one-point value rounds to the same number, about 0.005079 below the numerical reference. The last column of the model comparison gives an absolute first derivative of $1.74\times10^{-10}$ for RI1, evidence that the computed center is close to stationary.
The one-point calculation used a BFGS center and differenced the gradient for its curvature. The Laplace calculation used a Newton center and the analytic curvature there. The difference of $1.18\times10^{-8}$ includes both changes, so the row cannot assign a separate effect to either one.
For the 120 responses sharing one intercept, the two log integrals rounded to $-64.304634$ and differed by $2.95\times10^{-8}$. The Laplace estimate was 0.001633 below its reference, a smaller error than for the six responses. This comparison changes the specified random-intercept standard deviation from 0.7 to 2 as well as the number of responses. With 15 adaptive nodes, the differences from the two binary references were $2.98\times10^{-14}$ and $1.90\times10^{-11}$.
Where does the quadratic miss the shape of the six-response log integrand? At a signed distance of $t$ local standard deviations from the computed Newton mode, the point is $b=\hat b+t/\sqrt H$. The quadratic predicts $h(\hat b)-t^2/2$ there. Subtracting that prediction from $h(b)$ gives the approximation difference stored as residual in the next calculation. It is a difference between two log-function values, not an observed response minus a fitted response. A positive residual means that the log integrand lies above its quadratic approximation at that point.
1
2
3
4
5
standard_distance <- c(-2, -1, 0, 1, 2)
local_points <- ri_mode$mode + standard_distance / sqrt(ri_mode$curvature[1, 1])
quadratic_residual <- data.frame(standard_distance = standard_distance,
residual = ri$h(local_points) - ri$h(ri_mode$mode) + standard_distance^2 / 2)
print(quadratic_residual, row.names = FALSE)
1
2
3
4
5
6
standard_distance residual
-2 0.0382037019
-1 0.0032427198
0 0.0000000000
1 0.0001942706
2 0.0149988806
At distances $-2,-1,0,1,2$, the residuals were 0.03820, 0.00324, 0, 0.00019 and 0.01500. At the center the two heights coincide by construction. Two local standard deviations below the mode, the departure exceeded twice the departure at the same distance above it. The paired residuals show how unevenly the log integrand departs from the quadratic nearby. The evaluations stop two local standard deviations from the mode on each side. They leave the far tails undetermined, and a skewness coefficient would require moments of the whole conditional distribution. The TMB package implements the Laplace approximation for integrals over random effects.
5.6 Product quadrature rules and the growth of multidimensional grids
When a person’s responses depend on two latent variables, the marginal probability of the response pattern is a double integral. To construct the nodes, start with independent standard normal variables $Z_1$ and $Z_2$. At $(u,v)$ their joint density is $\phi(u)\phi(v)$, where $\phi$ is the standard normal density. Write $z_i$ and $w_i$ for node $i$ and its probability weight in a one-dimensional rule with $n$ nodes. For each fixed value of $Z_1$, approximate the inner expectation over $Z_2$. Applying the same rule to the outer expectation gives, for an integrable function $f$,
\[E[f(Z_1,Z_2)] \approx \sum_{i=1}^n w_i\sum_{j=1}^n w_j f(z_i,z_j) =\sum_{i=1}^n\sum_{j=1}^n w_iw_j f(z_i,z_j).\]Each pair $(i,j)$ specifies one point on the grid. Independence gives it the product weight $w_iw_j$ even when $f$ depends jointly on the two variables.
How should these points be placed when the model has correlated latent variables? Let $z$ be a column vector of $d$ independent standard normal variables. The R matrix z stores each grid point as a row in that same order. For a normal model distribution of the latent variables with mean $\mu$ and positive definite covariance $G$, take the upper triangular Cholesky factor $R$ with $R^\top R=G$. Each row of z %*% R represents the displacement $R^\top z$ in column form. The standard normal vector has identity covariance $I_d$, so its transformed covariance is $R^\top I_d R=G$. Adding $\mu$ places the fixed grid on the prior scale.
For an adaptive grid, let $H$ be the positive definite negative Hessian of the log integrand at its mode. Now $R^\top R=H$, and backsolve(R, diag(dimension)) computes $A=R^{-1}$. Each row of z %*% t(A) represents $Az$. The transformed normal vector has covariance $H^{-1}$, the covariance of the normal approximation at the mode, because
Adding the mode $\hat b$ centers the adaptive grid at the peak of the joint integrand. The log Jacobian for integration is $\log\vert \det A\vert =-\sum_j\log R_{jj}$, since the determinant of triangular $R$ is the product of its positive diagonal entries.
For a fixed rule, transforming the point leaves its probability weight unchanged. For an adaptive row with standard coordinates $(u_1,\ldots,u_d)$, the weight must also account for ordinary integration at the new scale. On the log scale, the correction is $-\sum_j\log R_{jj}-\sum_j\log\phi(u_j)$. The first term changes volume and the second removes the standard normal density implicit in the probability weights. The function product_rule() constructs either kind of grid, according to whether a covariance or a curvature matrix is supplied.
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
product_rule <- function(n, dimension, center = rep(0, dimension),
covariance = NULL, curvature = NULL, max_nodes = 100000L) {
stopifnot(length(n) == 1L, is.finite(n), n >= 1, n == floor(n),
length(dimension) == 1L, is.finite(dimension),
dimension >= 1, dimension == floor(dimension),
length(center) == dimension, all(is.finite(center)),
is.finite(max_nodes), max_nodes >= 1)
if (dimension * log(n) > log(max_nodes) + 1e-12) stop("Product grid exceeds max_nodes")
if (!is.null(covariance) && !is.null(curvature)) stop("Choose covariance or curvature")
base <- normal_rule(n)
index <- as.matrix(expand.grid(rep(list(seq_len(n)), dimension)))
z <- matrix(base$nodes[index], ncol = dimension)
log_weights <- rowSums(matrix(log(base$weights[index]), ncol = dimension))
if (is.null(curvature)) {
if (is.null(covariance)) covariance <- diag(dimension)
stopifnot(identical(dim(covariance), c(as.integer(dimension), as.integer(dimension))))
stopifnot(all(is.finite(covariance)), isSymmetric(covariance))
R <- chol(covariance)
# With standard nodes in rows, the covariance after transformation is t(R) %*% R.
points <- sweep(z %*% R, 2, center, "+")
measure <- "normal_expectation"
} else {
stopifnot(identical(dim(curvature), c(as.integer(dimension), as.integer(dimension))))
stopifnot(all(is.finite(curvature)), isSymmetric(curvature))
R <- chol(curvature)
A <- backsolve(R, diag(dimension))
# The covariance of the local normal approximation is A %*% t(A).
points <- sweep(z %*% t(A), 2, center, "+")
log_weights <- log_weights - sum(log(diag(R))) -
rowSums(matrix(dnorm(z, log = TRUE), ncol = dimension))
measure <- "ordinary_integral"
}
list(nodes = points, log_weights = log_weights, standard_nodes = z,
count = nrow(points), dimension = dimension, measure = measure, valid = TRUE)
}
The function product_rule() enumerates the index combinations with expand.grid(). With four nodes on each of two axes, the first index varies fastest. Row two contains indices $(2,1)$, giving standard nodes $(-0.7419638,-2.3344142)$. Its probability weight is approximately $0.45412415\times0.04587585$. The corresponding entry of log_weights adds the two log weights.
For the fixed rule, set the mean to $(0.3,-0.4)^\top$ and choose $G$ with variances 1 and 2 and covariance 0.6. Weighting each row and summing down the columns gives the mean of the finite distribution defined by the nodes and their probability weights.
1
2
3
4
5
6
G <- matrix(c(1, 0.6, 0.6, 2), 2)
correlated_rule <- product_rule(4, 2, center = c(0.3, -0.4), covariance = G)
weights <- exp(correlated_rule$log_weights)
weighted_mean <- colSums(weights * correlated_rule$nodes)
centered <- sweep(correlated_rule$nodes, 2, weighted_mean)
print(weighted_mean)
1
[1] 0.3 -0.4
Centering the rows at that mean gives the weighted covariance as a cross product.
1
print(crossprod(centered, weights * centered))
1
2
3
[,1] [,2]
[1,] 1.0 0.6
[2,] 0.6 2.0
1
print(c(sum_weights = sum(weights), points = correlated_rule$count))
1
2
sum_weights points
1 16
The 16 points reproduce the specified mean and covariance because their entries involve only linear and quadratic terms in the standard nodes. The four-node rule integrates these exactly on each axis. The weight sum checks normalization.
Grid size and dimension
With $n$ choices on each of $d$ axes, the grid contains $n^d$ points. Adding one latent variable multiplies the number of function evaluations by $n$ when the integrand is evaluated once per point. The following calculation raises each node count to the power $d$, the dimension of integration, without allocating the grids.
1
2
3
4
grid_counts <- outer(1:8, c(7, 15, 31), function(d, n) n^d)
colnames(grid_counts) <- c("7", "15", "31")
rownames(grid_counts) <- 1:8
print(grid_counts)
1
2
3
4
5
6
7
8
9
7 15 31
1 7 15 31
2 49 225 961
3 343 3375 29791
4 2401 50625 923521
5 16807 759375 28629151
6 117649 11390625 887503681
7 823543 170859375 27512614111
8 5764801 2562890625 852891037441
In two dimensions, the rules require 49, 225 and 961 points. At eight dimensions, 31 nodes per axis require 852,891,037,441 points. Before allocating the grid, product_rule() compares $d\log n$ with the logarithm of its 100,000-point default limit, allowing for rounding. Figure 5.2 plots these counts on a logarithmic scale.
Figure 5.2. Number of product-rule points by dimension of integration. Circles mark $7^d$, triangles $15^d$ and squares $31^d$. On the logarithmic vertical axis, the constant multiplier for each additional variable gives each series its straight line.
Fixed and adaptive grids in two dimensions
How much does the additional work improve a two-dimensional integral? In both constructed examples the latent vector $b$ has distribution $N(0,G)$, using the covariance matrix just checked. For the normal model let $Y=b+\epsilon$, where $\epsilon$ is independent of $b$ and has distribution $N(0,S)$ with $S=\operatorname{diag}(1,0.8)$. Here $b$ is the person’s conditional mean vector. Its covariance $G$ describes how those means vary across people, with variances 1 and 2 and covariance 0.6. The errors $\epsilon$ are deviations of the responses from those conditional means. Their conditional variances are 1 and 0.8, with zero covariance. Adding the two independent normal vectors gives $Y\sim N(0,G+S)$: the marginal response covariance includes both sources of variation. For the observed response $y=(0.7,-0.3)^\top$, gaussian2_exact evaluates that marginal log density. The helper log_normal() takes one response vector, a mean vector and a covariance matrix and returns one multivariate normal log density. It uses the Cholesky factor for the quadratic form and log determinant.
1
2
3
4
5
6
7
8
9
10
11
12
log_normal <- function(x, mean, covariance) {
R <- chol(covariance)
z <- forwardsolve(t(R), x - mean)
-length(x) * log(2 * pi) / 2 - sum(log(diag(R))) - sum(z^2) / 2
}
y2 <- c(0.7, -0.3)
S <- diag(c(1, 0.8))
gaussian2_response <- function(b) log_normal(y2, b, S)
gaussian2_h <- function(b) gaussian2_response(b) + log_normal(b, c(0, 0), G)
gaussian2_gr <- function(b) as.vector(solve(S, y2 - b) - solve(G, b))
gaussian2_he <- function(b) -solve(S) - solve(G)
gaussian2_exact <- log_normal(y2, c(0, 0), G + S)
In the binary example, one person gives the pattern $(1,0,1,1)$. Conditional on $b$, the four responses are independent Bernoulli variables with log odds $\eta=a+Bb$. The intercepts are $(-0.8,0.3,-0.2,0.5)^\top$. Each $a_j$ is response $j$’s log odds of a one when both latent variables are zero. The rows of the factor-loading matrix $B$ are $(1,0.2)$, $(0.4,1)$, $(0.8,-0.5)$ and $(-0.3,0.9)$, respectively. With the other latent variable fixed, a one-unit increase in $b_r$ adds $B_{jr}$ to response $j$’s log odds and multiplies its odds by $\exp(B_{jr})$. A positive loading raises that response probability and a negative loading lowers it. In this binary model, $G$ specifies population variances 1 and 2 and covariance 0.6 for the latent variables. Their scales and the loadings are fixed for this integration example. The first success contributes the log of the success probability at $\eta_1=-0.8+b_1+0.2b_2$. For this response, a one-unit increase in $b_2$ at fixed $b_1$ adds 0.2 to the log odds.
1
2
3
4
5
6
7
BINARY2 <- list(y = c(1, 0, 1, 1), intercept = c(-0.8, 0.3, -0.2, 0.5),
loadings = rbind(c(1, 0.2), c(0.4, 1), c(0.8, -0.5), c(-0.3, 0.9)), covariance = G)
binary2_response <- function(b) {
eta <- as.vector(BINARY2$intercept + BINARY2$loadings %*% b)
sum(-BINARY2$y * log1pexp(-eta) - (1 - BINARY2$y) * log1pexp(eta))
}
binary2_h <- function(b) binary2_response(b) + log_normal(b, c(0, 0), G)
Write $h(b)$ for the binary log integrand and $p_j$ for the success probability at $\eta_j$. Differentiating $y_j\eta_j-\log(1+e^{\eta_j})$ with respect to $\eta_j$ gives $y_j-p_j$. Its derivative is $-p_j(1-p_j)$. The chain rule maps these derivatives to $b$ through the loading matrix. The prior contributes $-G^{-1}b$ to the gradient and $G^{-1}$ to the negative Hessian. Combining the response and prior terms gives
\[\nabla h(b)=B^\top(y-p)-G^{-1}b,\qquad H(b)=-\nabla^2 h(b)=B^\top W B+G^{-1}, \quad W=\operatorname{diag}\{p_j(1-p_j)\}.\]The functions below implement the analytic derivatives. Starting at $(0,0)^\top$, conditional_mode() uses them to locate the binary center and obtain its curvature.
1
2
3
4
5
6
7
8
9
10
11
binary2_gr <- function(b) {
p <- plogis(BINARY2$intercept + BINARY2$loadings %*% b)
as.vector(crossprod(BINARY2$loadings, BINARY2$y - p) - solve(G, b))
}
binary2_he <- function(b) {
eta <- as.vector(BINARY2$intercept + BINARY2$loadings %*% b)
w <- plogis(eta) * plogis(-eta)
-crossprod(BINARY2$loadings, w * BINARY2$loadings) - solve(G)
}
binary2_mode <- conditional_mode(binary2_h, binary2_gr, binary2_he, c(0, 0))
stopifnot(binary2_mode$valid)
In w * BINARY2$loadings, the first variance $p_1(1-p_1)$ multiplies both entries of the first row, $(1,0.2)$. The other rows are scaled in the same way before multiplication by $B^\top$. The function binary2_he() returns $-H(b)$.
In the fixed sum, gaussian2_response and binary2_response supply the conditional log density and log probability. In the adaptive sum, binary2_h also includes the log prior density. Its grid is centered at the computed binary mode, approximately $(0.4293,-0.1830)^\top$, and uses the full curvature matrix there. Each error below subtracts the corresponding reference on the log scale. The binary reference uses a finer fixed grid with $81^2$ points.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
binary2_reference <- log_quadrature(binary2_response,
product_rule(81, 2, covariance = G))$log_integral
multi_comparison <- do.call(rbind, lapply(c(7, 15, 31, 61), function(n) {
fixed <- product_rule(n, 2, covariance = G)
adaptive <- product_rule(n, 2, center = binary2_mode$mode,
curvature = binary2_mode$curvature)
data.frame(nodes_per_integration_variable = n, nodes = n^2,
normal_error = log_quadrature(gaussian2_response, fixed)$log_integral -
gaussian2_exact,
binary_fixed_error = log_quadrature(binary2_response, fixed)$log_integral -
binary2_reference,
binary_adaptive_error = log_quadrature(binary2_h, adaptive)$log_integral -
binary2_reference)
}))
print(multi_comparison, row.names = FALSE)
1
2
3
4
5
nodes_per_integration_variable nodes normal_error binary_fixed_error binary_adaptive_error
7 49 8.576496e-04 -3.832841e-04 4.496649e-06
15 225 -5.949744e-06 -5.186179e-07 1.114938e-09
31 961 -3.795808e-11 1.028599e-11 -7.904788e-14
61 3721 -4.440892e-16 8.881784e-16 -8.881784e-16
At seven nodes per axis, the fixed approximation to the normal log density exceeded its exact value by $8.58\times10^{-4}$. The binary differences were $-3.83\times10^{-4}$ for the fixed grid and $4.50\times10^{-6}$ for the adaptive grid. At 15 nodes per axis, these fell in magnitude to $5.19\times10^{-7}$ and $1.11\times10^{-9}$, and at 31 to $1.03\times10^{-11}$ and $7.90\times10^{-14}$. The normal fixed differences at 15 and 31 were $-5.95\times10^{-6}$ and $-3.80\times10^{-11}$. The normal model also permits a direct check of the Laplace calculation.
1
2
3
4
5
6
print(c(normal_exact = gaussian2_exact,
normal_Laplace_error = laplace_approx(gaussian2_h, gaussian2_gr,
gaussian2_he, c(0, 0))$log_integral - gaussian2_exact,
binary_reference = binary2_reference,
binary_max_abs_log_integrand_derivative = max(abs(binary2_mode$
log_integrand_gradient))))
1
2
3
4
normal_exact normal_Laplace_error
-2.838175e+00 0.000000e+00
binary_reference binary_max_abs_log_integrand_derivative
-3.583412e+00 9.992007e-16
The Laplace log density matched the exact normal value of $-2.838175$ to the precision shown because the log integrand is quadratic in $b$. The $81\times81$ fixed reference for the binary log probability was $-3.583412$. The largest absolute gradient component, $9.99\times10^{-16}$, measures stationarity at the binary center. The normal errors use an analytic reference. The binary differences measure agreement with a finer numerical grid, whose value can also contain integration error.
For a factor-loading or design matrix with many zero entries, storing only the nonzero entries can reduce the work of computing the linear predictor at each point. The product rule still enumerates every combination of nodes across the latent variables. A reduction in dimension requires a property of the integral itself. For example, if the latent variables split into independent groups and the conditional response probability factors over the same groups, each group can be integrated separately and the results multiplied. Using $n$ nodes for each of two such one-dimensional integrals then requires $2n$ evaluations of the separate factors, rather than $n^2$ evaluations of their joint product. In the four-response pattern, even the first response involves both $b_1$ and $b_2$, and the prior also correlates them. Centering the grid at the mode changes where the $n^2$ evaluations are made. Both latent variables still enter each evaluation. The GLMMadaptive package uses multidimensional adaptive quadrature to integrate over random effects in generalized linear mixed models.
5.7 Monte Carlo integration, importance sampling, and Halton sequences
A quadrature rule evaluates the conditional probability of the observed responses at specified nodes. What if the integration points are drawn from the distribution of the random intercept? For the observed pattern $y=(0,0,1,0,1,1)$ in RI1, let $L(b)=P(Y=y\mid b)$ at the fixed coefficients $(-0.4,0.8)$. The marginal pattern probability is $I=E[L(b)]$ under $b\sim N(0,0.7^2)$. Each draw $b_s$ sets a common intercept for all six conditional response probabilities in $L(b_s)$. With $N$ independent draws, the Monte Carlo (MC) estimator and its estimated Monte Carlo standard error are
Each summand has expectation $I$, and independence makes the variance of the mean $\operatorname{Var}[L(b)]/N$. Substituting the sample variance of the $N$ values $L(b_s)$ and taking the square root gives the displayed standard error. Here $0\le L(b)\le1$, so the variance exists. This Monte Carlo standard error describes variation across new sets of integration points for the same observed responses and fixed model parameters. It does not measure uncertainty from sampling new people or clusters.
Prior draws can give very small values of $L(b_s)$ where the observed response pattern is unlikely. To sample elsewhere, write $h(b)=\log L(b)+\log\phi_{0.7}(b)$, with $\phi_{0.7}$ denoting the prior density. Importance sampling (IS) draws from a chosen proposal distribution and corrects for that choice. Choose a proposal density $q$ that is positive wherever $e^{h(b)}>0$. Here both the Bernoulli pattern probability and the normal density are positive at every finite $b$, so the proposal must cover the whole real line. Multiplying and dividing by $q$ gives
\[I=\int\frac{e^{h(b)}}{q(b)}\,q(b)\,db=E_q[W(b)],\qquad W(b_s)=\frac{e^{h(b_s)}}{q(b_s)},\qquad \widehat I_{\rm IS}=\frac1N\sum_{s=1}^N W(b_s).\]Each draw’s importance weight $W(b_s)$ accounts for how often $q$ samples its location. With independent draws from $q$, their mean is unbiased for $I$. For a finite second moment $E_q[W^2]$, independence gives $\operatorname{Var}(\widehat I_{\rm IS})=(E_q[W^2]-I^2)/N$. Its standard error can then be estimated by the sample standard deviation of the weights divided by $\sqrt N$.
If the quantity of interest were the conditional mean of a function $g(b)$ given $y$, its numerator would be $\int g(b)e^{h(b)}\,db$ and its denominator would be $I$. Estimating both with the same draws gives the self-normalized importance-sampling estimate $\sum_s\tilde w_s g(b_s)$, where $\tilde w_s=W(b_s)/\sum_r W(b_r)$. This ratio estimates a conditional expectation and is generally biased for finite $N$, although it is consistent when the relevant expectations exist. Normalization cancels the scale needed to estimate $I$ itself.
The function is_estimate() computes the importance-sampling estimate on the log scale and reports the original-scale standard error and weight diagnostics. It can also evaluate ordinary Monte Carlo by taking the prior density as the proposal.
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
is_estimate <- function(log_integrand, points, log_proposal) {
points <- as.matrix(points)
n <- nrow(points)
stopifnot(n >= 2L, all(is.finite(points)))
h_values <- vapply(seq_len(n), function(j) log_integrand(points[j, ]), numeric(1))
proposal <- vapply(seq_len(n), function(j) log_proposal(points[j, ]), numeric(1))
if (anyNA(h_values) || any(h_values == Inf) || any(!is.finite(proposal))) {
return(list(log_integral = NA_real_, integral = NA_real_, mcse = NA_real_,
log_mcse_integral = NA_real_, relative_se = NA_real_, ess = NA_real_,
largest_weight = NA_real_, log_weights = h_values - proposal,
valid = FALSE, reason = "invalid_log_density", evaluations = n))
}
log_weights <- h_values - proposal
shift <- max(log_weights)
if (!is.finite(shift)) return(list(log_integral = -Inf, integral = 0, mcse = NA_real_,
log_mcse_integral = NA_real_, relative_se = NA_real_, ess = NA_real_,
largest_weight = NA_real_, log_weights = log_weights,
valid = FALSE, reason = "all_zero_weights", evaluations = n))
scaled <- exp(log_weights - shift)
log_integral <- shift + log(mean(scaled))
relative_se <- sd(scaled) / (sqrt(n) * mean(scaled))
# Restore the weight scale to obtain the log of the original-scale standard error.
log_mcse_integral <- shift + log(sd(scaled) / sqrt(n))
normalized <- scaled / sum(scaled)
list(log_integral = log_integral, integral = exp(log_integral),
mcse = exp(log_mcse_integral),
log_mcse_integral = log_mcse_integral, relative_se = relative_se,
ess = 1 / sum(normalized^2),
largest_weight = max(normalized), log_weights = log_weights, evaluations = n,
valid = TRUE, reason = "evaluated")
}
In is_estimate(), each row of points contains one draw. The vector h_values stores the log integrand $h(b)$ at each draw, and proposal stores $\log q(b)$ there. Their difference h_values - proposal is the log importance weight. Subtracting the largest log weight before exponentiating gives scaled. Adding that maximum back after taking the log of the mean restores the scale of the integral.
The field mcse reports the estimated standard error on the integral’s original scale, and log_mcse_integral stores the logarithm of that standard error. The field relative_se divides the original-scale standard error by the estimated integral. For a positive integral with finite weight variance, this ratio also gives the delta-method approximation to the standard error of the log integral.
Dividing scaled by its sum cancels the shift and gives the normalized weights. Their maximum is the fraction of the estimated integral contributed by the most influential draw. The effective sample size (ESS) computed as $1/\sum_s\tilde w_s^2$ equals $N$ for equal contributions and approaches one when a single draw supplies almost the entire sum. Here ESS summarizes the concentration of the observed importance weights. The function’s valid flag reports that its numerical input checks passed; it does not establish that the weight variance is finite.
The proposal in three_part_draws() assigns probability $1/3$ to each of three components. The first draws $0.7T$ for a Student $t$ variable $T$ with five degrees of freedom. The multiplier 0.7 is this component’s scale, while its standard deviation is $0.7\sqrt{5/3}$. The second draws from a normal centered at the conditional mode $\hat b\approx0.07944$ with standard deviation 0.7. The third has the same center and uses the local standard deviation $1/\sqrt H\approx0.54368$, where $H=-h^{\prime\prime}(\hat b)$. This construction follows the three-component proposal described for the glmm package, whose normal components are centered at random-effect predictions obtained by penalized quasi-likelihood. Here the model parameters are fixed, so their center is the conditional mode for the observed responses.
For any draw, including one generated by the third component, the proposal density in the importance denominator is the arithmetic mean of all three component densities. The scaled $t$ component puts positive density throughout the real line and has heavier tails than the normal prior. Since $L(b)\le 1$, the squared joint density divided by this mixture is integrable in both tails.
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
three_part_draws <- function(n, prior_variance, mode, mode_precision, df = 5) {
part <- runif(n)
m1 <- sum(part < 1 / 3)
m2 <- sum(part < 1 / 3 + 1 / 3) - m1
m3 <- n - m1 - m2
prior_sd <- sqrt(prior_variance)
local_sd <- sqrt(1 / mode_precision)
t_part <- if (m1 > 0) (rnorm(m1) * prior_sd) / sqrt(rchisq(m1, df) / df) + 0 else NULL
normal_at_mode_latent_sd <- if (m2 > 0) vapply(seq_len(m2),
function(k) rnorm(1) * prior_sd + mode, 0) else NULL
normal_at_mode_local_sd <- if (m3 > 0) vapply(seq_len(m3),
function(k) rnorm(1) * local_sd + mode, 0) else NULL
prior_precision <- 1 / prior_variance
tconst <- lgamma((df + 1) / 2) - lgamma(df / 2) - 1 * log(df * pi) / 2 +
.5 * log(prior_precision)
log_density <- function(u) {
d <- u - mode
pieces <- c(tconst - log(1 + u * (prior_precision * u) / df) * (df / 2 + 1 / 2),
.5 * ((-1) * log(2 * pi) + log(prior_precision) - d * (prior_precision * d)),
.5 * ((-1) * log(2 * pi) + log(mode_precision) - d * (mode_precision * d)))
# All three component densities enter the denominator for every point.
top <- max(pieces)
total <- 0
for (i in 1:3) total <- total + (1 / 3) * exp(pieces[i] - top)
log(total) + top
}
list(points = matrix(c(t_part, normal_at_mode_latent_sd, normal_at_mode_local_sd),
ncol = 1), log_density = log_density,
counts = c(t_at_zero = m1, normal_at_mode_latent_sd = m2,
normal_at_mode_local_sd = m3))
}
In the code, prior_sd is $\sqrt{\texttt{prior_variance}}$ and local_sd is $1/\sqrt{\texttt{mode_precision}}$; the latter uses the negative second derivative at the computed mode, the precision of the local normal approximation. The returned log_density() evaluates all three component densities for each point, regardless of which component generated it.
A Halton sequence
A deterministic alternative uses the Halton sequence. It assigns the first prime numbers in order as bases, one for each coordinate, and reverses the digits of successive integer indices into fractional digits. The function halton() returns one row per index.
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
first_primes <- function(dimension) {
stopifnot(length(dimension) == 1L, is.finite(dimension), dimension >= 1,
dimension == floor(dimension))
primes <- numeric(dimension)
candidate <- 2
found <- 0L
while (found < dimension) {
divisors <- primes[seq_len(found)]
divisors <- divisors[divisors <= sqrt(candidate)]
if (!any(candidate %% divisors == 0)) {
found <- found + 1L
primes[found] <- candidate
}
candidate <- candidate + 1
}
primes
}
radical_inverse <- function(index, base) {
stopifnot(all(is.finite(index)), all(index >= 0), all(index == floor(index)),
all(index <= 2^53 - 1), length(base) == 1L, base >= 2, base == floor(base))
value <- numeric(length(index))
place <- 1 / base
while (any(index > 0)) {
digit <- index %% base
value <- value + digit * place
index <- floor(index / base)
place <- place / base
}
value
}
halton <- function(n, dimension, skip = 0L) {
stopifnot(length(n) == 1L, is.finite(n), n >= 1, n == floor(n),
length(skip) == 1L, is.finite(skip), skip >= 0, skip == floor(skip),
skip + n <= 2^53 - 1)
bases <- first_primes(dimension)
index <- skip + seq_len(n)
points <- vapply(bases, function(base) radical_inverse(index, base), numeric(n))
points <- matrix(points, nrow = n, ncol = dimension)
stopifnot(all(points > 0), all(points < 1))
points
}
print(halton(7, 2))
1
2
3
4
5
6
7
8
[,1] [,2]
[1,] 0.500 0.3333333
[2,] 0.250 0.6666667
[3,] 0.750 0.1111111
[4,] 0.125 0.4444444
[5,] 0.625 0.7777778
[6,] 0.375 0.2222222
[7,] 0.875 0.5555556
In first_primes() a candidate qualifies when none of the primes already found up to its square root divides it. For index $i$, radical_inverse() takes the least significant digit first and puts it immediately after the radix point, then fills successive places from the remaining digits. The default skip = 0L starts at index 1, and a positive skip advances the first index by that amount.
Row three illustrates the digit reversal: index 3 is $11$ in base two, giving $1/2+1/4=3/4$, and $10$ in base three, giving $0/3+1/9=1/9$. The first seven entries in base two are $1/2,1/4,3/4,1/8,5/8,3/8,7/8$. In base three they are $1/3,2/3,1/9,4/9,7/9,2/9,5/9$. For these positive indices, the radical inverses lie strictly between zero and one. For the scalar intercept, transforming just the first coordinate $u$ by $b=0.7\Phi^{-1}(u)$ gives finite normal quantiles on the prior scale. Averaging the conditional probabilities at those points gives the Halton approximation.
1
2
halton_points <- matrix(ri$latent_sd * qnorm(halton(2000, 1)), ncol = 1)
halton_value <- logsumexp(ri$response(halton_points[, 1])) - log(2000)
Comparing the estimates from one set of draws
For a single comparison, the Mersenne-Twister generator starts from seed 100507. The prior draws, mixture draws and draws from the narrow normal proposal are generated in that order. With prior draws, the denominator cancels the prior factor in the joint density, giving exactly the conditional probability as the weight.
1
2
3
4
5
6
7
8
9
10
11
12
13
proposal_mean <- ri_mode$mode
proposal_sd <- 1 / sqrt(ri_mode$curvature[1, 1])
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(100507)
mc_points <- matrix(rnorm(2000, sd = ri$latent_sd), ncol = 1)
is_draws <- three_part_draws(2000, ri$latent_sd^2, proposal_mean, ri_mode$curvature[1, 1])
is_points <- is_draws$points
poor_points <- matrix(rnorm(2000, 2, 0.15), ncol = 1)
mc_fit <- is_estimate(ri$h, mc_points,
function(b) dnorm(b, sd = ri$latent_sd, log = TRUE))
is_fit <- is_estimate(ri$h, is_points, is_draws$log_density)
poor_fit <- is_estimate(ri$h, poor_points, function(b) dnorm(b, 2, 0.15, log = TRUE))
print(is_draws$counts)
1
2
t_at_zero normal_at_mode_latent_sd normal_at_mode_local_sd
651 683 666
Of the 2,000 mixture draws, 651 came from the scaled $t$ at zero, 683 from the normal at the mode with prior scale, and 666 from the normal at the mode with local scale. Independent uniform draws give random component counts with multinomial probabilities $(1/3,1/3,1/3)$. Grouping the resulting points by component leaves the importance-weight sum, sample variance, and weight diagnostics unchanged; the rows in the grouped output are no longer in independent mixture-draw order.
With 2,000 evaluations of the supplied log integrand or conditional log probability per method, the numerical reference ri_reference$log_integral supplies a common comparison on the log scale. For each method using random draws, the table gives the sample-based standard-error calculation on the probability scale, together with their effective sample size and largest normalized weight. The narrow-proposal row prints this calculation even though, as shown below, its sampling variance is infinite. The last row uses a fixed sequence. The count excludes proposal-density evaluations, random-number generation, and the mode calculation used to construct the mixture.
1
2
3
4
5
6
7
8
9
10
11
12
sampling_comparison <- do.call(rbind, lapply(list(MC = mc_fit,
importance = is_fit, poor = poor_fit),
function(fit) {
data.frame(evaluations = fit$evaluations, log_integral = fit$log_integral,
log_integral_difference = fit$log_integral - ri_reference$log_integral,
sample_se = fit$mcse, ess = fit$ess, largest_weight = fit$largest_weight)
}))
sampling_comparison <- rbind(sampling_comparison, Halton = data.frame(evaluations = 2000,
log_integral = halton_value,
log_integral_difference = halton_value - ri_reference$log_integral,
sample_se = NA_real_, ess = NA_real_, largest_weight = NA_real_))
print(sampling_comparison)
1
2
3
4
5
evaluations log_integral log_integral_difference sample_se ess largest_weight
MC 2000 -3.352460 0.0091822041 2.343849e-04 1835.440752 0.0006450265
importance 2000 -3.361876 -0.0002336419 1.985239e-04 1876.977134 0.0005960667
poor 2000 -8.527011 -5.1653683554 7.057221e-05 7.848282 0.3483720258
Halton 2000 -3.361444 0.0001989513 NA NA NA
The signed log differences were 0.00918 for independent prior draws, $-0.000234$ for the mixture, $-5.16537$ for the narrow $N(2,0.15^2)$ proposal and 0.000199 for Halton. For prior draws and mixture draws, the effective sample sizes were about 1,835 and 1,877, with largest normalized weights of 0.000645 and 0.000596. With the narrow proposal, one draw contributed 0.348 of the sum and the effective sample size was 7.85.
In the MC row, sample_se is mc_fit$mcse, the estimated standard error of the integral, 0.000234385. Its logarithm, mc_fit$log_mcse_integral, is $-8.35855$. Dividing the original-scale standard error by the estimated probability of 0.03499814 gives 0.00669707, stored as mc_fit$relative_se. This is the approximate standard error of the log integral; the value $-8.35855$ is the logarithm of the original-scale standard error.
The deterministic Halton calculation reports NA for sample_se, ess and largest_weight. Its fixed points do not provide independent random replications from which to estimate a Monte Carlo standard error. Weight summaries could be calculated for these points, but would not validate that standard-error formula. Its difference from the numerical reference measures agreement at this point count.
How can a proposal with support on the whole line give such a small estimate? The single run with the narrow normal proposal illustrates where it samples and how much the largest observed weight contributes.
1
2
3
4
5
6
7
print(c(minimum_draw = min(poor_points), maximum_draw = max(poor_points),
mode = proposal_mean, log_joint_density_at_minimum = ri$h(min(poor_points)),
log_proposal_density_at_minimum = dnorm(min(poor_points), 2, 0.15, log = TRUE),
largest_log_weight = max(poor_fit$log_weights),
finite_variance_threshold = ri$latent_sd^2 / 2,
local_normal_component_variance = proposal_sd^2,
narrow_proposal_variance = 0.15^2))
1
2
3
4
5
6
minimum_draw maximum_draw mode
1.48232516 2.50233309 0.07943699
log_joint_density_at_minimum log_proposal_density_at_minimum largest_log_weight
-6.95768318 -4.97709044 -1.98059274
finite_variance_threshold local_normal_component_variance narrow_proposal_variance
0.24500000 0.29558265 0.02250000
Even the smallest draw, 1.48233, lay well above the mode of 0.07944. At that draw, log_joint_density_at_minimum was $-6.958$ and log_proposal_density_at_minimum was $-4.977$. Subtracting the latter from the former gives the largest observed log weight, about $-1.981$. Exponentiating this difference and dividing by the sum of the 2,000 weights gave its share of 0.348. The effective sample size of 7.85 describes concentration among the observed weights.
To assess the variance across possible samples, consider the second moment $E_q[W^2]=\int e^{2h(b)}/q(b)\,db$. The logarithm of the function being integrated is
\[2\log L(b)+2\log\phi_{0.7}(b)-\log q(b) =\left(-\frac{1}{0.7^2}+\frac{1}{2v_q}\right)b^2+O(|b|+1),\]where $v_q$ is the variance of the normal proposal centered at 2. Expanding $(b-2)^2$ in the log proposal density explains why its nonzero mean contributes a linear term. Each Bernoulli log probability has magnitude at most $\log 2+\vert \eta_j\vert $ for its linear predictor $\eta_j$, so the six responses contribute at most linear growth in either tail. The quadratic coefficient is positive because $v_q=0.0225$ is below $0.7^2/2=0.245$. The second-moment integrand therefore grows in both tails and its integral diverges.
The printed 0.29558265 is the variance of the mixture’s local normal component. The field finite_variance_threshold marks where the quadratic tail coefficient changes sign: a variance strictly above 0.245 gives a negative coefficient and one strictly below gives a positive coefficient. At equality, the linear and remaining terms must be examined; the quadratic term alone does not decide integrability.
The narrow proposal has positive density on the whole real line, so $E_q[W]=I$ and the original-scale sample mean is unbiased. That expectation includes draws to which the narrow proposal assigns very little probability. Each finite sample can yield a numerical standard error even though the sampling variance of its mean is infinite. The unbiasedness calculation applies before taking the logarithm of the estimate.
Variation across repeated integrations
To measure variation across integrations, the responses and model parameters remain fixed while the draws change. The 200 replications use separate streams from L’Ecuyer’s combined multiple recursive generator (L'Ecuyer-CMRG), designed to supply separate pseudorandom sequences for the replications. Seed 100507 initializes the first stream. For the mixture applied to RI1, study_settings takes the center and curvature from the Newton fit ri_mode. For the normal response, it uses the corresponding fit in laplace_results$normal$inner.
1
2
3
4
5
6
7
8
9
10
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(100507)
replication_streams <- vector("list", 200)
replication_streams[[1]] <- .Random.seed
for (r in 2:200) replication_streams[[r]] <-
parallel::nextRNGStream(replication_streams[[r - 1]])
study_settings <- list(n = 2000L, mode = proposal_mean,
precision = ri_mode$curvature[1, 1],
gaussian_mode = laplace_results$normal$inner$mode,
gaussian_precision = laplace_results$normal$inner$curvature[1, 1])
Within each replication, integration_replication() uses 2,000 draws for each of five estimates. The three binary estimates use the prior, the mixture and the narrow proposal. The two normal estimates are marginal densities at $y=1.2$, obtained with prior draws and mixture draws. Each replication begins with its own stream, and the five methods take their draws successively from it.
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
integration_replication <- function(replication, streams, settings) {
assign(".Random.seed", streams[[replication]], envir = .GlobalEnv)
ri <- make_ri_integrand(c(-1, -0.5, 0, 0.5, 1, 1.5), c(0, 0, 1, 0, 1, 1),
c(-0.4, 0.8), 0.7)
gauss <- normal_normal_integrand(1.2, 0.5, 0.7, 0.6)
means <- c(0, settings$mode, 2, 0, settings$gaussian_mode)
scales <- c(0.7, NA, 0.15, 0.7, NA)
precisions <- c(NA, settings$precision, NA, NA, settings$gaussian_precision)
# The first three estimates are for the binary pattern and the last two for the normal.
log_integrands <- list(ri$h, ri$h, ri$h, gauss$h, gauss$h)
do.call(rbind, lapply(seq_along(means), function(k) {
if (is.na(scales[k])) {
draws <- three_part_draws(settings$n, 0.7^2, means[k], precisions[k])
points <- draws$points
log_proposal <- draws$log_density
} else {
points <- matrix(rnorm(settings$n, means[k], scales[k]), ncol = 1)
log_proposal <- function(b) dnorm(b, means[k], scales[k], log = TRUE)
}
fit <- is_estimate(log_integrands[[k]], points, log_proposal)
data.frame(replication = replication, method = c("RI1 MC", "RI1 IS", "RI1 poor",
"normal MC", "normal IS")[k],
integral = fit$integral, sample_se = fit$mcse, valid = fit$valid, reason = fit$reason, ess = fit$ess)
}))
}
1
integration_replication(1L, replication_streams, study_settings)
In data/derived/ch05/replications.csv, the five rows for replication 1 give binary integral estimates of 0.03439126, 0.03484530 and 0.0002856450 in that order. The two normal estimates were 0.32687105 and 0.32116137.
A separate R session can summarize all 1,000 saved rows from the book directory. For the binary pattern, the calculation integrates the shifted joint density. For the normal response, it uses the analytic marginal density.
For each method, mean_error subtracts the reference integral from the mean of the usable estimates on the original scale. The count usable includes estimates whose numerical validity flag is true and whose integral is finite. The field empirical_sd is their sample standard deviation across replications. The field mean_sample_se averages the finite within-replication standard-error calculations, and sample_se_count records how many enter that average.
For the finite-variance methods, mean_error_mcse divides the standard deviation across usable replications by the square root of their count. It measures uncertainty in the reported average error from repeating the integration a finite number of times. Thus mean_sample_se concerns a single integration with 2,000 draws, while mean_error_mcse concerns the average over the repeated integrations. The narrow-proposal method has infinite sampling variance, as the tail calculation showed, so its mean_error_mcse is left missing.
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/stability.R")
source("code/lib/integration_models.R")
d <- readRDS("data/source/ch05/RI1.rds")
ri <- do.call(make_ri_integrand, d)
shift <- ri$h(0)
reference <- integrate(function(b) exp(ri$h(b) - shift), -Inf, Inf)
ri_reference <- list(log_integral = shift + log(reference$value))
gaussian <- normal_normal_integrand(1.2, 0.5, 0.7, 0.6)
study_results <- read.csv("data/derived/ch05/replications.csv")
stopifnot(identical(as.integer(table(factor(study_results$replication, levels = 1:200))), rep(5L, 200L)))
study_summary <- do.call(rbind, lapply(unique(study_results$method), function(method) {
rows <- study_results[study_results$method == method, ]
reference_integral <- exp(if (startsWith(method, "RI1")) ri_reference$log_integral else gaussian$exact)
eligible <- !is.na(rows$valid) & rows$valid & is.finite(rows$integral)
values <- rows$integral[eligible]
sample_se <- rows$sample_se[eligible & is.finite(rows$sample_se)]
n <- length(values)
data.frame(method = method, repetitions = nrow(rows), invalid = sum(!eligible), usable = n,
mean = if (n) mean(values) else NA_real_,
mean_error = if (n) mean(values) - reference_integral else NA_real_,
mean_error_mcse = if (method == "RI1 poor" || n < 2L) NA_real_ else sd(values) / sqrt(n),
empirical_sd = if (n > 1L) sd(values) else NA_real_,
mean_sample_se = if (length(sample_se)) mean(sample_se) else NA_real_,
sample_se_count = length(sample_se), largest = if (n) max(values) else NA_real_)
}))
print(study_summary, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
method repetitions invalid usable mean mean_error
RI1 MC 200 0 200 0.0347031409 2.488834e-05
RI1 IS 200 0 200 0.0346947494 1.649681e-05
RI1 poor 200 0 200 0.0003794065 -3.429885e-02
normal MC 200 0 200 0.3249671174 6.113644e-04
normal IS 200 0 200 0.3244709920 1.152390e-04
mean_error_mcse empirical_sd mean_sample_se sample_se_count largest
1.755787e-05 0.0002483058 0.0002371683 200 0.035277446
1.423078e-05 0.0002012536 0.0001968844 200 0.035140111
NA 0.0006229761 0.0002093456 200 0.006282692
3.554186e-04 0.0050263774 0.0051807028 200 0.338791983
2.274739e-04 0.0032169665 0.0031021701 200 0.335125183
Both usable and sample_se_count are 200 for every method. For RI1 MC, the empirical standard deviation across replications was 0.000248, compared with the mean Monte Carlo standard-error calculation within each replication of 0.000237. For RI1 IS, the pair was 0.000201 and 0.000197. For the normal response, the corresponding pairs were 0.00503 and 0.00518 under prior sampling and 0.00322 and 0.00310 under mixture sampling. The normal log integrand is quadratic, but the three-part mixture differs from the exact conditional normal density, so its weights still vary. For the four finite-variance methods, the standard errors of the reported mean errors range from $1.42\times10^{-5}$ to $3.55\times10^{-4}$.
The mean_error_mcse entry for RI1 poor is missing because its sampling variance is infinite. A finite sample spread cannot estimate a finite standard error for this method. Its mean estimate was 0.000379 against a reference of 0.03468, and its largest estimate was 0.00628. All 200 estimates in this row were finite. Its empirical standard deviation of 0.000623 describes the 200 realized estimates. The mean value 0.000209 is the average of the standard-error formula evaluated on those particular draws; it is not an estimate of a finite sampling standard deviation for this method. The invalid = 0 entry records that the code checks passed and does not alter this infinite-variance result.
The Halton points are identical each time the same indices are used. Back in the session that generated them, extending the sequence gives a comparison with the reference at several point counts.
1
2
3
4
5
6
7
8
9
halton_refinement <- do.call(rbind, lapply(c(500, 1000, 2000, 4000), function(n) {
b <- 0.7 * qnorm(halton(n, 1)[, 1])
data.frame(points = n,
RI1_log_integral_difference = logsumexp(ri$response(b)) - log(n) -
ri_reference$log_integral,
normal_log_integral_difference = logsumexp(gaussian$response(b)) - log(n) -
gaussian$exact)
}))
print(halton_refinement, row.names = FALSE)
1
2
3
4
5
points RI1_log_integral_difference normal_log_integral_difference
500 1.717809e-03 2.255804e-04
1000 5.884448e-04 4.968016e-05
2000 1.989513e-04 1.685338e-05
4000 6.718546e-05 6.254540e-06
For 500, 1,000, 2,000 and 4,000 points, the signed binary log differences were 0.00172, 0.000588, 0.000199 and 0.0000672. Doubling the point count reduced the discrepancy at each of these three refinements. The randtoolbox package provides Halton sequences in R.
5.8 Checking integration error and reusing inner optimization solutions
For the six responses in RI1, the reference log probability is about $-3.361642515$. How closely do the numerical sums reproduce it? Each comparison subtracts the numerical reference from the unrounded approximate log integral. A positive difference means the method assigns the observed pattern a higher probability than the reference does. The count column gives the number of terms in the final sum. Evaluations used to find a center or estimate curvature are additional work.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
integration_comparison <- rbind(
do.call(rbind, lapply(node_counts,
function(n) data.frame(method = "fixed GH", count = n,
inner = "none", log_integral = log_quadrature(ri$response,
gauss_hermite_rule(n, sd = 0.7))$log_integral))),
do.call(rbind, lapply(c(1, node_counts), function(n) {
fit <- log_quadrature(ri$h, agh_rule(n, ri$h, ri$gr))
data.frame(method = "adaptive GH", count = n, inner = fit$rule$inner$reason,
log_integral = fit$log_integral)
})), data.frame(method = "Laplace", count = 1, inner = laplace_results$RI1$inner$reason,
log_integral = laplace_results$RI1$log_integral),
data.frame(method = c("MC", "importance", "Halton"), count = 2000,
inner = c("none", ri_mode$reason, "none"),
log_integral = c(mc_fit$log_integral, is_fit$log_integral, halton_value)))
integration_comparison$log_integral_difference <-
integration_comparison$log_integral - ri_reference$log_integral
print(integration_comparison, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
method count inner log_integral log_integral_difference
fixed GH 3 none -3.344707 1.693502e-02
fixed GH 7 none -3.361548 9.487425e-05
fixed GH 15 none -3.361643 5.403091e-09
fixed GH 31 none -3.361643 -1.776357e-15
adaptive GH 1 converged -3.366721 -5.078795e-03
adaptive GH 3 converged -3.361643 -7.467865e-07
adaptive GH 7 converged -3.361642 2.081869e-08
adaptive GH 15 converged -3.361643 2.975398e-14
adaptive GH 31 converged -3.361643 2.220446e-15
Laplace 1 small_step -3.366721 -5.078807e-03
MC 2000 none -3.352460 9.182204e-03
importance 2000 small_step -3.361876 -2.336419e-04
Halton 2000 none -3.361444 1.989513e-04
With three fixed nodes the difference from the reference is about $0.0169$. At seven nodes it falls to $9.49\times10^{-5}$, at fifteen to $5.40\times10^{-9}$, and at thirty-one it is negative and within $2\times10^{-15}$ of zero. Such near equality measures agreement between numerical evaluations. Each fixed rule integrates against the prior and needs no inner fit.
The adaptive rows use the stopping reason from the BFGS fit. Their one-node error is $-0.005078795$, about $1.2\times10^{-8}$ above the Laplace error. The two calculations use different estimates of both the center and the curvature. Laplace uses the Newton fit, which stopped at small_step. At three adaptive nodes the error is already $-7.47\times10^{-7}$, followed by $2.08\times10^{-8}$, $2.98\times10^{-14}$ and $2.22\times10^{-15}$.
Prior sampling and the Halton sum need no center. The importance sampler uses the previously computed Newton center. Its row prints ri_mode$reason, the stopping reason small_step of that Newton fit. The signed errors for prior sampling, mixture sampling and Halton integration are $0.00918$, $-0.000234$ and $0.000199$, respectively. All three errors at 2,000 evaluations exceed the three-node adaptive error in absolute value for this pattern.
An optimizer evaluates the likelihood at different parameter values and may use differences between evaluations to choose a direction. To check the log likelihood used in that search, vary the fixed intercept $a$ with the slope fixed at $0.8$ and the random-intercept standard deviation at $0.7$. This evaluates the log likelihood as a function of $a$ with the other two parameters fixed. A profile likelihood would require fitting the remaining parameters at each intercept. At each of the four intercepts, both calculations rebuild the same model. Its log integrand supplies the numerical reference and the fifteen-node approximation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
intercept_grid <- c(-1, -0.4, 0.2, 1)
grid_reference <- function(intercept) {
model <- make_ri_integrand(RI1$x, RI1$y, c(intercept, 0.8), 0.7)
scalar_reference(model$h)$log_integral
}
grid_approximation <- function(intercept, n = 15L) {
model <- make_ri_integrand(RI1$x, RI1$y, c(intercept, 0.8), 0.7)
log_quadrature(model$h, agh_rule(n, model$h, model$gr))$log_integral
}
objective_grid <- data.frame(intercept = intercept_grid,
reference = vapply(intercept_grid, grid_reference, numeric(1)),
AGQ15 = vapply(intercept_grid, grid_approximation, numeric(1)))
objective_grid$error <- objective_grid$AGQ15 - objective_grid$reference
print(objective_grid, row.names = FALSE)
1
2
3
4
5
intercept reference AGQ15 error
-1.0 -3.596396 -3.596396 -8.171241e-14
-0.4 -3.361643 -3.361643 2.975398e-14
0.2 -3.408741 -3.408741 4.440892e-16
1.0 -3.906532 -3.906532 -1.185718e-13
The largest absolute discrepancy is $1.19\times10^{-13}$, at $a=1$. To examine the slope at each grid value, evaluate each function on either side of $a$. For a step $s$, num_grad() (Section 3.1) gives the central difference at $a$.
1
2
3
4
5
6
7
8
9
objective_derivatives <- do.call(rbind, lapply(intercept_grid, function(a) {
do.call(rbind, lapply(c(1e-3, 1e-4, 1e-5), function(step) {
ref <- num_grad(grid_reference, a, step = step)$gradient
approx <- num_grad(grid_approximation, a, step = step)$gradient
data.frame(intercept = a, step = step, reference_slope = ref,
AGQ_slope = approx, difference = approx - ref)
}))
}))
print(objective_derivatives, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
intercept step reference_slope AGQ_slope difference
-1.0 1e-03 0.6235518 0.6235518 2.220446e-13
-1.0 1e-04 0.6235518 0.6235518 4.440892e-12
-1.0 1e-05 0.6235518 0.6235518 2.220446e-11
-0.4 1e-03 0.1571169 0.1571169 0.000000e+00
-0.4 1e-04 0.1571169 0.1571169 -2.220446e-12
-0.4 1e-05 0.1571169 0.1571169 0.000000e+00
0.2 1e-03 -0.3137425 -0.3137425 -2.220446e-13
0.2 1e-04 -0.3137426 -0.3137426 -2.220446e-12
0.2 1e-05 -0.3137426 -0.3137426 2.220446e-11
1.0 1e-03 -0.9254827 -0.9254827 2.220446e-13
1.0 1e-04 -0.9254827 -0.9254827 2.220446e-12
1.0 1e-05 -0.9254827 -0.9254827 2.220446e-11
At the smallest step the reference slopes are $0.6235518$, $0.1571169$, $-0.3137426$ and $-0.9254827$. At $-0.4$, a small increase in the fixed intercept raises the log likelihood. At $0.2$, a small increase lowers it. At $0.2$ the coarsest step gives $-0.3137425$ for both functions. Across all twelve comparisons the two numerical slopes differ by at most $2.220446\times10^{-11}$ to the precision shown. Agreement checks the effect of substituting the quadrature calculation in a difference quotient. Both slopes still depend on the finite step.
Inner convergence and integration accuracy
Could a rule give an accurate integral even if its center is far from the conditional mode? Start Newton’s method at $b=3$ and allow one update. Use the returned point and the analytic curvature there to place the nodes by hand. The unchecked_error column gives the difference from the numerical reference at that unfinished center. For solved_error, agh_rule() (Section 5.4) carries out its usual BFGS search and estimates curvature by differencing the gradient at the returned point. The label solved_error identifies that second calculation; neither label by itself certifies convergence or bounds the true integration error.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
unfinished <- conditional_mode(ri$h, ri$gr, ri$he, 3, control = list(maxit = 1L))
inner_accuracy <- do.call(rbind, lapply(c(1, 3, 15, 31), function(n) {
base <- normal_rule(n)
scale <- 1 / sqrt(unfinished$curvature[1, 1])
b <- unfinished$mode + scale * base$nodes
unchecked <- logsumexp(log(base$weights) + log(scale) -
dnorm(base$nodes, log = TRUE) + ri$h(b))
solved <- log_quadrature(ri$h, agh_rule(n, ri$h, ri$gr))
data.frame(nodes = n,
max_abs_derivative_at_unfinished_center = max(abs(unfinished$log_integrand_gradient)),
unchecked_error = unchecked - ri_reference$log_integral,
accepted_unfinished = unfinished$valid,
solved_error = solved$log_integral - ri_reference$log_integral)
}))
print(inner_accuracy, row.names = FALSE)
1
2
3
4
5
nodes max_abs_derivative_at_unfinished_center unchecked_error accepted_unfinished solved_error
1 2.285395 -7.738449e-01 TRUE -5.078795e-03
3 2.285395 -1.570122e-02 TRUE -7.467865e-07
15 2.285395 -2.106315e-12 TRUE 2.975398e-14
31 2.285395 2.220446e-15 TRUE 2.220446e-15
At the returned point, the derivative divided by the negative second derivative gives the proposed Newton displacement. The completed Newton fit supplies a separate center for comparison.
1
2
3
print(c(unfinished_center = unfinished$mode, solved_center = ri_mode$mode,
unfinished_Newton_displacement = as.vector(
solve(unfinished$curvature, unfinished$log_integrand_gradient))))
1
2
unfinished_center solved_center unfinished_Newton_displacement
-0.60736255 0.07943699 0.70555538
The one-step Newton run reached its iteration limit at $-0.60736255$. The log integrand still has derivative $2.285395$ there. Dividing that derivative by the local negative second derivative gives $+0.70555538$, the displacement a further full Newton step would propose. The separately printed center $0.07943699$ comes from the completed Newton run. The flag accepted_unfinished copies unfinished$valid. The flag records a finite negative log integrand and a successful Cholesky factorization of the unshifted curvature. At the unfinished center the one-node log error is $-0.774$ and the three-node error is $-0.0157$. At the BFGS center those errors are $-0.00508$ and $-7.47\times10^{-7}$. Yet fifteen nodes at the unfinished center already reduce the error to about $-2.1\times10^{-12}$. Adding nodes improves the integral while the derivative at that center remains exactly the same.
Reusing conditional modes across likelihood evaluations
Now let several independent clusters have distinct random intercepts $b_i\sim N(0,\sigma^2)$. The fixed coefficients $\beta_0,\beta_1$ and standard deviation $\sigma$ are common to the clusters; each cluster’s intercept deviation has its own value. If $h_i(b;\theta)$ is the joint log density of cluster $i$’s responses and its intercept, integration gives that cluster’s contribution to the marginal likelihood. Independence gives the full log likelihood
\[\ell(\theta)=\sum_i\log\int_{\mathbb R}\exp\{h_i(b;\theta)\}\,db.\]The function below takes a list of clusters and returns a function evaluated at $(\beta_0,\beta_1,\log\sigma)$: the fixed intercept, the slope and the log standard deviation. Exponentiating the third parameter gives the standard deviation used to rebuild each integrand. By default a fifteen-node adaptive rule is used for each cluster. On the first evaluation every search starts from zero. On a later evaluation each can start from its own stored center, even though the integrand has changed with the parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
make_random_intercept_loglik <- function(clusters, n = 15L,
reuse_previous_modes = TRUE, control = list()) {
stopifnot(length(clusters) > 0L)
last_modes <- rep(NA_real_, length(clusters))
function(parameter) {
stopifnot(length(parameter) == 3L, all(is.finite(parameter)),
is.finite(exp(parameter[3])),
exp(parameter[3]) > 0)
contributions <- rep(NA_real_, length(clusters))
results <- vector("list", length(clusters))
started_at_previous_modes <- reuse_previous_modes && !anyNA(last_modes)
starts <- if (started_at_previous_modes) last_modes else rep(0, length(clusters))
for (i in seq_along(clusters)) {
model <- make_ri_integrand(clusters[[i]]$x, clusters[[i]]$y, parameter[1:2],
exp(parameter[3]))
rule <- agh_rule(n, model$h, model$gr, starts[i], control)
results[[i]] <- log_quadrature(model$h, rule)
if (results[[i]]$valid) contributions[i] <- results[[i]]$log_integral
}
valid <- all(vapply(results, function(x) x$valid, logical(1)))
if (reuse_previous_modes && valid) last_modes <<-
vapply(results, function(x) x$rule$inner$mode, numeric(1))
list(loglik = if (valid) sum(contributions) else NA_real_,
contributions = contributions,
valid = valid, integrations = results, starts = starts,
started_at_previous_modes = started_at_previous_modes,
parameter = parameter, method = "adaptive GH", nodes_per_cluster = n)
}
}
The assignment to last_modes occurs only after all cluster integrals pass the code’s valid checks. If an integration returns valid = FALSE, the function returns NA for the total and retains the centers from the last evaluation that passed these checks. The individual contributions and integration results show which cluster needs attention.
Three instances of the marginal log likelihood function evaluate the same cluster and parameter grid. The first starts every fit from zero. The second uses the preceding center as the next starting point as the intercept increases. The third begins with an empty set of stored centers and traverses the grid in decreasing order. The outer rev() puts this third set of results back into increasing intercept order, so each row compares identical parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
clusters <- list(list(x = RI1$x, y = RI1$y))
from_zero <- make_random_intercept_loglik(clusters, reuse_previous_modes = FALSE)
from_previous_mode <- make_random_intercept_loglik(clusters)
reverse <- make_random_intercept_loglik(clusters)
parameters <- lapply(intercept_grid, function(a) c(a, 0.8, log(0.7)))
zero_start_results <- lapply(parameters, from_zero)
previous_mode_results <- lapply(parameters, from_previous_mode)
reverse_results <- rev(lapply(rev(parameters), reverse))
mode_start_comparison <- data.frame(intercept = intercept_grid,
from_zero = vapply(zero_start_results, function(x) x$loglik, numeric(1)),
from_previous_mode = vapply(previous_mode_results, function(x) x$loglik, numeric(1)),
reverse = vapply(reverse_results, function(x) x$loglik, numeric(1)),
iterations_from_zero = vapply(zero_start_results,
function(x) x$integrations[[1]]$rule$inner$fit$iterations, numeric(1)),
iterations_from_previous_mode = vapply(previous_mode_results,
function(x) x$integrations[[1]]$rule$inner$fit$iterations, numeric(1)))
print(mode_start_comparison, row.names = FALSE)
1
2
3
4
5
intercept from_zero from_previous_mode reverse iterations_from_zero iterations_from_previous_mode
-1.0 -3.596396 -3.596396 -3.596396 4 4
-0.4 -3.361643 -3.361643 -3.361643 3 3
0.2 -3.408741 -3.408741 -3.408741 4 4
1.0 -3.906532 -3.906532 -3.906532 4 4
Subtracting the zero-start column from each reuse column at full precision gives two comparisons at matched intercepts. The following check tests their largest absolute difference and whether all three evaluations pass the integration validity checks.
1
2
3
4
5
6
7
max_start_difference <- max(abs(mode_start_comparison$from_previous_mode -
mode_start_comparison$from_zero),
abs(mode_start_comparison$reverse - mode_start_comparison$from_zero))
stopifnot(max_start_difference < 1e-9,
all(vapply(c(previous_mode_results, zero_start_results, reverse_results),
function(x) x$valid, logical(1))))
print(c(maximum_order_difference = max_start_difference, tolerance = 1e-9))
1
2
maximum_order_difference tolerance
8.881784e-16 1.000000e-09
Across the grid, agreement to six printed decimals could conceal a difference larger than the chosen tolerance of $10^{-9}$. The comparison uses the absolute differences of from_previous_mode and reverse from from_zero at each intercept. Forward reuse differs most from starting at zero at intercept $0.2$, by $8.881784\times10^{-16}$ in absolute value. For reverse reuse the corresponding maximum is $4.440892\times10^{-16}$. All twelve grid evaluations passed the validity check and both differences are below tolerance. The grid establishes agreement of these approximate log likelihoods at the four tested parameter values within the chosen tolerance. It does not establish independence from evaluation order at every possible parameter value.
The two forward columns of iteration counts both contain 4, 3, 4 and 4. They copy the BFGS counter fit$iterations, which begins at one. For example, follow zero_start_results[[2]]$integrations[[1]]$rule$inner$fit$history at intercept $-0.4$. It contains an initial record, two BFGS updates and two terminal step records. The reported counter is three. To see when the starting point changes the work, visit $-0.399$ after the forward sequence and then repeat that value.
1
2
3
4
5
6
7
8
9
10
11
nearby_parameter <- c(-0.399, 0.8, log(0.7))
nearby_from_zero <- from_zero(nearby_parameter)
nearby_from_previous_mode <- from_previous_mode(nearby_parameter)
repeat_from_previous_mode <- from_previous_mode(nearby_parameter)
print(data.frame(evaluation = c("nearby parameter from zero",
"nearby parameter from previous mode", "repeated parameter from previous mode"),
iterations = vapply(list(nearby_from_zero, nearby_from_previous_mode,
repeat_from_previous_mode),
function(x) x$integrations[[1]]$rule$inner$fit$iterations, numeric(1)),
loglik = c(nearby_from_zero$loglik, nearby_from_previous_mode$loglik,
repeat_from_previous_mode$loglik)))
1
2
3
4
evaluation iterations loglik
1 nearby parameter from zero 3 -3.361486
2 nearby parameter from previous mode 4 -3.361486
3 repeated parameter from previous mode 1 -3.361486
The fresh zero start gives counter three. The stored center from intercept $1$ gives four, although $-0.399$ is close to an earlier grid value. Only the centers from the most recent evaluation passing the code checks are retained. The function stores these centers as starting values and recomputes the objective, derivatives, and quadrature at the new parameter values; it does not reuse an earlier likelihood value. A second evaluation at $-0.399$ starts at its own previously fitted center and gives one. All three evaluations print $-3.361486$. Reusing a center can therefore reduce or increase the work: the repeated visit starts near its solution, while moving from intercept $1$ requires an extra iteration compared with starting from zero.
Returning to the original parameters gives the following result.
1
2
3
cluster_value <- from_zero(c(-0.4, 0.8, log(0.7)))
print(cluster_value[c("loglik", "contributions", "valid", "parameter", "method",
"nodes_per_cluster")])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$loglik
[1] -3.361643
$contributions
[1] -3.361643
$valid
[1] TRUE
$parameter
[1] -0.4000000 0.8000000 -0.3566749
$method
[1] "adaptive GH"
$nodes_per_cluster
[1] 15
At the original intercept the single contribution is the entire log likelihood, $-3.361643$, for the specified random-intercept variance $0.7^2$. In every case the integral uses the current coefficients and variance.
The TMB package also provides a choice of starting values for inner optimization over random effects through random.start. Its documented default uses the random effects from the best likelihood evaluation so far; the function here instead retains the centers from the most recent evaluation passing its checks.

