Midpoint, Laplace and Laplace-Adapted Midpoint Rules for the Marginal Likelihood of Normal Data
#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 900
library(shiny)
### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
env = parent.frame(), quoted = FALSE) {
func <- shiny::exprToFunction(expr, env, quoted)
shiny::renderImage({
info <- shiny::getCurrentOutputInfo()
w <- if (is.numeric(width)) width else info$width()
h <- if (is.numeric(height)) height else info$height()
shiny::req(w > 0, h > 0)
pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
if (is.null(pr)) pr <- 1
f <- tempfile(fileext = ".png")
dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
on.exit(grDevices::dev.off(dev), add = TRUE)
grDevices::dev.control(displaylist = "enable")
v <- withVisible(func())
if (v$visible) print(v$value)
list(src = f, contentType = "image/png", width = w, height = h,
coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
}, deleteFile = TRUE)
}
log_sum_exp <- function(lx) { m <- max(lx); m + log(sum(exp(lx - m))) }
mu_0 <- 0; w_0 <- 0 # prior means for mu and w = log(sigma)
sigma_true <- 2 # true sd of the simulated data
ui <- fluidPage(
wellPanel(
fluidRow(
column(3, sliderInput("mu_true", "data location (true mu)", min = -10, max = 10,
value = -5, step = 0.5)),
column(3, sliderInput("n_obs", "number of observations", min = 10, max = 200,
value = 100, step = 10)),
column(3, sliderInput("sig_mu", "prior sd of mu", min = 1, max = 20,
value = 10, step = 1)),
column(3, sliderInput("sig_w", "prior sd of w", min = 1, max = 20,
value = 10, step = 1))),
fluidRow(
column(3, sliderInput("n_grid", "midpoint grid points per axis", min = 5, max = 100,
value = 20, step = 5)),
column(3, sliderInput("n_lap", "Laplace-adapted grid points per axis", min = 2, max = 40,
value = 10, step = 1)),
column(3, actionButton("new", "New sample")),
column(3, checkboxInput("zoom", "zoom to the posterior", FALSE)))
),
tags$style("#tab table { font-size: 85%; }"),
fluidRow(
column(8,
fluidRow(
column(6, plotOutput("nat", height = "340px")),
column(6, plotOutput("unit", height = "340px"))),
fluidRow(
column(6, plotOutput("nat_lap", height = "340px")),
column(6, plotOutput("unit_lap", height = "340px")))),
column(4,
h5("log P(y) by each method"),
tableOutput("tab"))
)
)
server <- function(input, output, session) {
### simulated normal data: y_i ~ N(mu_true, sigma_true^2); only the sufficient statistics are needed
dat <- reactive({
set.seed(input$new + 1)
x <- input$mu_true + sigma_true * rnorm(input$n_obs)
list(n = length(x), S1 = sum(x), S2 = sum(x^2), xbar = mean(x), sd = sd(x))
})
### log L(mu, w) + log pi(mu, w) at the points (mu[i], w[i]), and on the outer product of mu and w
log_post_pt <- function(mu, w, d, sig_mu, sig_w) {
SS <- d$S2 - 2 * mu * d$S1 + d$n * mu^2
-0.5 * d$n * log(2 * pi) - d$n * w - 0.5 * exp(-2 * w) * SS +
dnorm(mu, mu_0, sig_mu, log = TRUE) + dnorm(w, w_0, sig_w, log = TRUE)
}
log_post <- function(mu, w, d, sig_mu, sig_w) {
SS <- d$S2 - 2 * mu * d$S1 + d$n * mu^2
outer(SS, w, function(ss, w) -0.5 * d$n * log(2 * pi) - d$n * w - 0.5 * exp(-2 * w) * ss) +
outer(dnorm(mu, mu_0, sig_mu, log = TRUE), dnorm(w, w_0, sig_w, log = TRUE), "+")
}
st <- reactive({
d <- dat(); sig_mu <- input$sig_mu; sig_w <- input$sig_w
### Laplace approximation: posterior mode and curvature
fit <- nlm(function(th) -log_post_pt(th[1], th[2], d, sig_mu, sig_w),
c(d$xbar, log(d$sd)), hessian = TRUE)
mode <- fit$estimate
H <- fit$hessian
Lc <- t(chol(solve(H))) # covariance = Lc Lc'
se <- sqrt(diag(solve(H)))
log_lap <- -fit$minimum + log(2 * pi) - 0.5 * as.numeric(determinant(H)$modulus)
### reference value: a fine grid centred on the posterior mode
mu_f <- mode[1] + seq(-8, 8, length.out = 400) * se[1]
w_f <- mode[2] + seq(-8, 8, length.out = 400) * se[2]
log_true <- log_sum_exp(as.vector(log_post(mu_f, w_f, d, sig_mu, sig_w))) +
log(diff(mu_f[1:2])) + log(diff(w_f[1:2]))
### product midpoint rule on the unit square, u = logistic(mu), v = logistic(w)
n <- input$n_grid; h <- 1 / n; grid <- (seq_len(n) - 0.5) * h
log_jac <- function(u) -log(u) - log(1 - u) # log |d mu / d u|
G <- log_post(qlogis(grid), qlogis(grid), d, sig_mu, sig_w) + outer(log_jac(grid), log_jac(grid), "+")
log_mid <- log_sum_exp(as.vector(G)) + 2 * log(h)
wn <- exp(G - max(G)); wn <- wn / sum(wn)
### product midpoint rule on a Laplace-adapted grid: theta = mode + Lc z, z = (qnorm(u), qnorm(v)),
### so the integrand on the unit square is g~(u, v) = |det Lc| L pi(theta) / {phi(z1) phi(z2)}
k <- input$n_lap; hk <- 1 / k; ugrid <- (seq_len(k) - 0.5) * hk
U <- as.matrix(expand.grid(u = ugrid, v = ugrid))
Z <- qnorm(U)
Th <- t(mode + Lc %*% t(Z)) # grid points in the (mu, w) scale
lf <- log_post_pt(Th[, 1], Th[, 2], d, sig_mu, sig_w) + 0.5 * rowSums(Z^2) + log(2 * pi) +
sum(log(diag(Lc))) + 2 * log(hk)
log_lmid <- log_sum_exp(lf)
wl <- exp(lf - max(lf)); wl <- wl / sum(wl)
list(d = d, sig_mu = sig_mu, sig_w = sig_w, mode = mode, se = se, Lc = Lc,
log_true = log_true, log_lap = log_lap,
n = n, h = h, grid = grid, log_jac = log_jac, log_mid = log_mid, ess = 1 / sum(wn^2),
k = k, hk = hk, U = U, Th = Th, log_lmid = log_lmid, ess_lap = 1 / sum(wl^2))
})
heat_cols <- hcl.colors(40, "YlOrRd", rev = TRUE)
### a heatmap of L(mu, w) pi(mu, w) on its natural scale, with a set of points drawn on top
draw_nat <- function(s, pts, ptlab) {
if (input$zoom) {
xr <- s$mode[1] + c(-6, 6) * s$se[1]; yr <- s$mode[2] + c(-6, 6) * s$se[2]
} else {
xr <- c(-10, 10); yr <- c(-5, 5)
}
mu_g <- seq(xr[1], xr[2], length.out = 300); w_g <- seq(yr[1], yr[2], length.out = 300)
lp <- log_post(mu_g, w_g, s$d, s$sig_mu, s$sig_w)
f <- exp(lp - max(lp))
par(mar = c(4, 4, 3, 1))
image(mu_g, w_g, f, col = heat_cols, xlab = expression(mu), ylab = expression(w == log~sigma),
main = expression(L(mu, w)~pi(mu, w)~"(natural scale)"))
if (max(f) > 0) contour(mu_g, w_g, f, nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray30")
points(pts, pch = 19, cex = 0.4, col = adjustcolor("black", 0.55))
points(s$mode[1], s$mode[2], pch = 3, lwd = 2, col = "steelblue", cex = 1.3)
legend("topright", bty = "n", pch = c(19, 3), col = c("gray30", "steelblue"),
legend = c(ptlab, "posterior mode"), cex = 0.85)
}
### row 1, left: the midpoint grid mapped back to (mu, w)
output$nat <- renderPlot({
s <- st()
draw_nat(s, expand.grid(mu = qlogis(s$grid), w = qlogis(s$grid)), "midpoint grid, mapped back")
})
### row 1, right: the transformed integrand g(u, v) on the unit square, with the midpoint grid
output$unit <- renderPlot({
s <- st()
m <- 200; ug <- (seq_len(m) - 0.5) / m
G <- log_post(qlogis(ug), qlogis(ug), s$d, s$sig_mu, s$sig_w) +
outer(s$log_jac(ug), s$log_jac(ug), "+")
par(mar = c(4, 4, 3, 1))
image(ug, ug, exp(G - max(G)), col = heat_cols, xlab = "u", ylab = "v",
main = expression(g(u, v) == L~pi~"/"~"{"*u(1-u)*v(1-v)*"}"~"(unit square)"))
contour(ug, ug, exp(G - max(G)), nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray30")
if (s$n <= 40) abline(v = seq(0, 1, by = s$h), h = seq(0, 1, by = s$h), col = adjustcolor("gray30", 0.35))
points(expand.grid(s$grid, s$grid), pch = 19, cex = 0.35, col = adjustcolor("black", 0.5))
})
### row 2, left: the Laplace-adapted midpoint grid mapped back to (mu, w)
output$nat_lap <- renderPlot({
s <- st()
draw_nat(s, data.frame(mu = s$Th[, 1], w = s$Th[, 2]), "Laplace-adapted grid, mapped back")
})
### row 2, right: the Laplace-adapted integrand g~(u, v) on the unit square, with its midpoint grid;
### it is nearly flat when the posterior is close to its Laplace normal approximation
output$unit_lap <- renderPlot({
s <- st()
m <- 200; ug <- (seq_len(m) - 0.5) / m
Zg <- qnorm(as.matrix(expand.grid(ug, ug)))
Tg <- t(s$mode + s$Lc %*% t(Zg))
G <- matrix(log_post_pt(Tg[, 1], Tg[, 2], s$d, s$sig_mu, s$sig_w) + 0.5 * rowSums(Zg^2), m, m)
f <- exp(G - max(G))
par(mar = c(4, 4, 3, 1))
image(ug, ug, f, col = heat_cols, zlim = c(0, 1), xlab = "u", ylab = "v",
main = expression(tilde(g)(u, v) == L~pi~"/"~"{"*phi(z[1])*phi(z[2])*"}"~"(unit square)"))
contour(ug, ug, f, nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray30")
if (s$k <= 40) abline(v = seq(0, 1, by = s$hk), h = seq(0, 1, by = s$hk), col = adjustcolor("gray30", 0.35))
points(s$U, pch = 19, cex = 0.5, col = adjustcolor("black", 0.6))
})
output$tab <- renderTable({
s <- st()
est <- c(s$log_true, s$log_lap, s$log_mid, s$log_lmid)
data.frame(
Method = c("Reference", "Laplace", sprintf("Logistic midpoint %dx%d", s$n, s$n),
sprintf("Laplace-adapted midpoint %dx%d", s$k, s$k)),
Evals = c(400^2, 1, s$n^2, s$k^2),
`log P(y)` = sprintf("%.3f", est),
Error = c("", sprintf("%.3f", est[-1] - est[1])),
`Eff. pts` = c("", "", sprintf("%.1f", s$ess), sprintf("%.1f", s$ess_lap)),
check.names = FALSE)
}, striped = TRUE, align = "lrrrr")
}
shinyApp(ui, server)
About the app
Shows how the product midpoint rule of the Numerical Quadrature unit computes the marginal likelihood of normal data when both the mean \(\mu\) and the standard deviation are unknown, how it fails when the posterior is far from where the grid looks, and how a midpoint rule on a grid centred and scaled by the Laplace approximation avoids the failure.
The problem. Data \(y_1,\ldots,y_n\mid\mu,\sigma\overset{iid}{\sim}N(\mu,\sigma^2)\) are simulated with the “data location” as the true mean and \(\sigma=2\). With \(w=\log\sigma\), the priors are independent, \(\mu\sim N(0,\sigma_\mu^2)\) and \(w\sim N(0,\sigma_w^2)\), and the marginal likelihood is the two-dimensional integral \[P(y)=\iint L(\mu,w)\,\pi(\mu,w)\,d\mu\,dw .\]
Rule 1: product midpoint rule on a logistic grid. Mapping each parameter to \((0,1)\) by \(u=1/(1+e^{-\mu})\), \(v=1/(1+e^{-w})\) gives \(P(y)=\int_0^1\!\int_0^1 g(u,v)\,du\,dv\) with \(g(u,v)=L\pi\big/\{u(1-u)v(1-v)\}\), and the midpoint rule is \(P(y)\approx h^2\sum_{j,k}g(u_j,v_k)\) with \(u_j=(j-\tfrac12)h\), \(v_k=(k-\tfrac12)h\), \(h=1/n\). The grid is fixed in advance and does not look at where the posterior is.
Rule 2: Laplace approximation. Let \(\hat\theta=(\hat\mu,\hat w)\) be the posterior mode and \(H\) the Hessian of \(-\log(L\pi)\) there. Approximating the log of the integrand by a quadratic gives \[\log P(y)\approx\log\{L\pi\}(\hat\theta)+\log 2\pi-\tfrac12\log\det H,\] one function evaluation after the optimization.
Rule 3: product midpoint rule on a Laplace-adapted grid. Write the covariance of the Laplace approximation as \(\Sigma=H^{-1}=CC^\top\) and change variables to \(\theta=\hat\theta+Cz\), so that \(z\sim N(0,I)\) under the approximation. Then map each coordinate of \(z\) to \((0,1)\) by the standard normal CDF, \(u=\Phi(z_1)\), \(v=\Phi(z_2)\), in place of the logistic map of Rule 1. With \(\phi\) the standard normal density, \[P(y)=\int_0^1\!\!\int_0^1 \tilde g(u,v)\,du\,dv,\qquad \tilde g(u,v)=|\det C|\,\frac{(L\pi)(\hat\theta+Cz)}{\phi(z_1)\,\phi(z_2)},\qquad z=\big(\Phi^{-1}(u),\Phi^{-1}(v)\big),\] and the midpoint rule with \(k\) points per axis is \(P(y)\approx h_k^2\sum_{j,l}\tilde g(u_j,v_l)\) with \(u_j=(j-\tfrac12)h_k\), \(v_l=(l-\tfrac12)h_k\), \(h_k=1/k\). Each term is the posterior kernel divided by its Laplace normal density, a ratio that is nearly constant when the posterior is close to normal, so a handful of points per axis is enough. The Cholesky factor \(C\) also takes care of the correlation between \(\mu\) and \(w\).
The four plots. Each is a contour heatmap of the same posterior kernel in a different coordinate system, with the points of a rule drawn on top.
- Row 1, left: \(L\pi\) on its natural scale with the logistic midpoint grid mapped back to \((\mu,w)\). The grid points crowd around \((0,0)\) and thin out quickly away from it. The cross is the posterior mode. Tick “zoom to the posterior” (it applies to both left plots) to see the shape of the posterior itself.
- Row 1, right: the transformed integrand \(g(u,v)\) on the unit square with the \(n\times n\) midpoint grid (the lines are drawn for up to 40 points per axis).
- Row 2, left: the same natural-scale surface with the Laplace-adapted grid \(\hat\theta+C\big(\Phi^{-1}(u_j),\Phi^{-1}(v_l)\big)\) mapped back, which sits on and around the posterior wherever it is.
- Row 2, right: the Laplace-adapted integrand \(\tilde g(u,v)\) on the unit square with the \(k\times k\) midpoint grid, on the same colour scale as its maximum. The flatter \(\tilde g\) is, the closer the posterior is to its Laplace normal approximation and the better the rule works; compare it with the thin spike of \(g\) in row 1.
The table (to the right of the plots) lists the value of \(\log P(y)\) from each method (Reference: a fine product grid centred on the posterior mode; Laplace; Logistic midpoint \(n\times n\); Laplace-adapted midpoint \(k\times k\)), the number of function evaluations (Evals), the error against the reference, and, for the two midpoint rules, the effective number of grid points (Eff. pts) \(1/\sum_i\bar g_i^2\) (\(\bar g_i\) the values of the integrand at the grid points, normalized to sum to 1), a measure of how many points carry the mass; it is at most the number of points, and close to it when the integrand is flat.
What to try. With the data location near 0 and a vague prior, all the rules are close to the reference. Move the data location to \(-5\) and then \(-10\): the posterior moves out into the tail of the logistic grid, \(g\) becomes a thin spike near the boundary of the square, the effective number of grid points collapses, and the midpoint error becomes large however many points per axis you add (a larger sample makes the posterior narrower and the failure worse). The Laplace-adapted midpoint rule is unaffected by the location of the data: nearly all of its points carry mass (Eff. pts is close to \(k^2\)), and its error is about that of the Laplace approximation, which is already small for normal data with a moderate \(n\). Its error shrinks only slowly as \(k\) grows, however: where the posterior has heavier tails than its Laplace normal approximation, \(\tilde g\) rises towards the edges of the square, and the outermost cells, which stand for the whole tails, sample that rise poorly. Reduce the number of observations to see the posterior depart from normality and the Laplace error grow.
library(shiny)
### renderPlot replacement: Safari 27 (WebKit) cannot hold the call stack of
### shiny::renderPlot in webR ("Maximum call stack size exceeded"), so draw with
### renderImage instead, which nests about 45 fewer R calls
renderPlot <- function(expr, width = "auto", height = "auto", res = 72, ...,
env = parent.frame(), quoted = FALSE) {
func <- shiny::exprToFunction(expr, env, quoted)
shiny::renderImage({
info <- shiny::getCurrentOutputInfo()
w <- if (is.numeric(width)) width else info$width()
h <- if (is.numeric(height)) height else info$height()
shiny::req(w > 0, h > 0)
pr <- shiny::getDefaultReactiveDomain()$clientData$pixelratio
if (is.null(pr)) pr <- 1
f <- tempfile(fileext = ".png")
dev <- shiny:::startPNG(f, w * pr, h * pr, res = res * pr)
on.exit(grDevices::dev.off(dev), add = TRUE)
grDevices::dev.control(displaylist = "enable")
v <- withVisible(func())
if (v$visible) print(v$value)
list(src = f, contentType = "image/png", width = w, height = h,
coordmap = shiny:::getCoordmap(v$value, w * pr, h * pr, res * pr))
}, deleteFile = TRUE)
}
log_sum_exp <- function(lx) { m <- max(lx); m + log(sum(exp(lx - m))) }
mu_0 <- 0; w_0 <- 0 # prior means for mu and w = log(sigma)
sigma_true <- 2 # true sd of the simulated data
ui <- fluidPage(
wellPanel(
fluidRow(
column(3, sliderInput("mu_true", "data location (true mu)", min = -10, max = 10,
value = -5, step = 0.5)),
column(3, sliderInput("n_obs", "number of observations", min = 10, max = 200,
value = 100, step = 10)),
column(3, sliderInput("sig_mu", "prior sd of mu", min = 1, max = 20,
value = 10, step = 1)),
column(3, sliderInput("sig_w", "prior sd of w", min = 1, max = 20,
value = 10, step = 1))),
fluidRow(
column(3, sliderInput("n_grid", "midpoint grid points per axis", min = 5, max = 100,
value = 20, step = 5)),
column(3, sliderInput("n_lap", "Laplace-adapted grid points per axis", min = 2, max = 40,
value = 10, step = 1)),
column(3, actionButton("new", "New sample")),
column(3, checkboxInput("zoom", "zoom to the posterior", FALSE)))
),
tags$style("#tab table { font-size: 85%; }"),
fluidRow(
column(8,
fluidRow(
column(6, plotOutput("nat", height = "340px")),
column(6, plotOutput("unit", height = "340px"))),
fluidRow(
column(6, plotOutput("nat_lap", height = "340px")),
column(6, plotOutput("unit_lap", height = "340px")))),
column(4,
h5("log P(y) by each method"),
tableOutput("tab"))
)
)
server <- function(input, output, session) {
### simulated normal data: y_i ~ N(mu_true, sigma_true^2); only the sufficient statistics are needed
dat <- reactive({
set.seed(input$new + 1)
x <- input$mu_true + sigma_true * rnorm(input$n_obs)
list(n = length(x), S1 = sum(x), S2 = sum(x^2), xbar = mean(x), sd = sd(x))
})
### log L(mu, w) + log pi(mu, w) at the points (mu[i], w[i]), and on the outer product of mu and w
log_post_pt <- function(mu, w, d, sig_mu, sig_w) {
SS <- d$S2 - 2 * mu * d$S1 + d$n * mu^2
-0.5 * d$n * log(2 * pi) - d$n * w - 0.5 * exp(-2 * w) * SS +
dnorm(mu, mu_0, sig_mu, log = TRUE) + dnorm(w, w_0, sig_w, log = TRUE)
}
log_post <- function(mu, w, d, sig_mu, sig_w) {
SS <- d$S2 - 2 * mu * d$S1 + d$n * mu^2
outer(SS, w, function(ss, w) -0.5 * d$n * log(2 * pi) - d$n * w - 0.5 * exp(-2 * w) * ss) +
outer(dnorm(mu, mu_0, sig_mu, log = TRUE), dnorm(w, w_0, sig_w, log = TRUE), "+")
}
st <- reactive({
d <- dat(); sig_mu <- input$sig_mu; sig_w <- input$sig_w
### Laplace approximation: posterior mode and curvature
fit <- nlm(function(th) -log_post_pt(th[1], th[2], d, sig_mu, sig_w),
c(d$xbar, log(d$sd)), hessian = TRUE)
mode <- fit$estimate
H <- fit$hessian
Lc <- t(chol(solve(H))) # covariance = Lc Lc'
se <- sqrt(diag(solve(H)))
log_lap <- -fit$minimum + log(2 * pi) - 0.5 * as.numeric(determinant(H)$modulus)
### reference value: a fine grid centred on the posterior mode
mu_f <- mode[1] + seq(-8, 8, length.out = 400) * se[1]
w_f <- mode[2] + seq(-8, 8, length.out = 400) * se[2]
log_true <- log_sum_exp(as.vector(log_post(mu_f, w_f, d, sig_mu, sig_w))) +
log(diff(mu_f[1:2])) + log(diff(w_f[1:2]))
### product midpoint rule on the unit square, u = logistic(mu), v = logistic(w)
n <- input$n_grid; h <- 1 / n; grid <- (seq_len(n) - 0.5) * h
log_jac <- function(u) -log(u) - log(1 - u) # log |d mu / d u|
G <- log_post(qlogis(grid), qlogis(grid), d, sig_mu, sig_w) + outer(log_jac(grid), log_jac(grid), "+")
log_mid <- log_sum_exp(as.vector(G)) + 2 * log(h)
wn <- exp(G - max(G)); wn <- wn / sum(wn)
### product midpoint rule on a Laplace-adapted grid: theta = mode + Lc z, z = (qnorm(u), qnorm(v)),
### so the integrand on the unit square is g~(u, v) = |det Lc| L pi(theta) / {phi(z1) phi(z2)}
k <- input$n_lap; hk <- 1 / k; ugrid <- (seq_len(k) - 0.5) * hk
U <- as.matrix(expand.grid(u = ugrid, v = ugrid))
Z <- qnorm(U)
Th <- t(mode + Lc %*% t(Z)) # grid points in the (mu, w) scale
lf <- log_post_pt(Th[, 1], Th[, 2], d, sig_mu, sig_w) + 0.5 * rowSums(Z^2) + log(2 * pi) +
sum(log(diag(Lc))) + 2 * log(hk)
log_lmid <- log_sum_exp(lf)
wl <- exp(lf - max(lf)); wl <- wl / sum(wl)
list(d = d, sig_mu = sig_mu, sig_w = sig_w, mode = mode, se = se, Lc = Lc,
log_true = log_true, log_lap = log_lap,
n = n, h = h, grid = grid, log_jac = log_jac, log_mid = log_mid, ess = 1 / sum(wn^2),
k = k, hk = hk, U = U, Th = Th, log_lmid = log_lmid, ess_lap = 1 / sum(wl^2))
})
heat_cols <- hcl.colors(40, "YlOrRd", rev = TRUE)
### a heatmap of L(mu, w) pi(mu, w) on its natural scale, with a set of points drawn on top
draw_nat <- function(s, pts, ptlab) {
if (input$zoom) {
xr <- s$mode[1] + c(-6, 6) * s$se[1]; yr <- s$mode[2] + c(-6, 6) * s$se[2]
} else {
xr <- c(-10, 10); yr <- c(-5, 5)
}
mu_g <- seq(xr[1], xr[2], length.out = 300); w_g <- seq(yr[1], yr[2], length.out = 300)
lp <- log_post(mu_g, w_g, s$d, s$sig_mu, s$sig_w)
f <- exp(lp - max(lp))
par(mar = c(4, 4, 3, 1))
image(mu_g, w_g, f, col = heat_cols, xlab = expression(mu), ylab = expression(w == log~sigma),
main = expression(L(mu, w)~pi(mu, w)~"(natural scale)"))
if (max(f) > 0) contour(mu_g, w_g, f, nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray30")
points(pts, pch = 19, cex = 0.4, col = adjustcolor("black", 0.55))
points(s$mode[1], s$mode[2], pch = 3, lwd = 2, col = "steelblue", cex = 1.3)
legend("topright", bty = "n", pch = c(19, 3), col = c("gray30", "steelblue"),
legend = c(ptlab, "posterior mode"), cex = 0.85)
}
### row 1, left: the midpoint grid mapped back to (mu, w)
output$nat <- renderPlot({
s <- st()
draw_nat(s, expand.grid(mu = qlogis(s$grid), w = qlogis(s$grid)), "midpoint grid, mapped back")
})
### row 1, right: the transformed integrand g(u, v) on the unit square, with the midpoint grid
output$unit <- renderPlot({
s <- st()
m <- 200; ug <- (seq_len(m) - 0.5) / m
G <- log_post(qlogis(ug), qlogis(ug), s$d, s$sig_mu, s$sig_w) +
outer(s$log_jac(ug), s$log_jac(ug), "+")
par(mar = c(4, 4, 3, 1))
image(ug, ug, exp(G - max(G)), col = heat_cols, xlab = "u", ylab = "v",
main = expression(g(u, v) == L~pi~"/"~"{"*u(1-u)*v(1-v)*"}"~"(unit square)"))
contour(ug, ug, exp(G - max(G)), nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray30")
if (s$n <= 40) abline(v = seq(0, 1, by = s$h), h = seq(0, 1, by = s$h), col = adjustcolor("gray30", 0.35))
points(expand.grid(s$grid, s$grid), pch = 19, cex = 0.35, col = adjustcolor("black", 0.5))
})
### row 2, left: the Laplace-adapted midpoint grid mapped back to (mu, w)
output$nat_lap <- renderPlot({
s <- st()
draw_nat(s, data.frame(mu = s$Th[, 1], w = s$Th[, 2]), "Laplace-adapted grid, mapped back")
})
### row 2, right: the Laplace-adapted integrand g~(u, v) on the unit square, with its midpoint grid;
### it is nearly flat when the posterior is close to its Laplace normal approximation
output$unit_lap <- renderPlot({
s <- st()
m <- 200; ug <- (seq_len(m) - 0.5) / m
Zg <- qnorm(as.matrix(expand.grid(ug, ug)))
Tg <- t(s$mode + s$Lc %*% t(Zg))
G <- matrix(log_post_pt(Tg[, 1], Tg[, 2], s$d, s$sig_mu, s$sig_w) + 0.5 * rowSums(Zg^2), m, m)
f <- exp(G - max(G))
par(mar = c(4, 4, 3, 1))
image(ug, ug, f, col = heat_cols, zlim = c(0, 1), xlab = "u", ylab = "v",
main = expression(tilde(g)(u, v) == L~pi~"/"~"{"*phi(z[1])*phi(z[2])*"}"~"(unit square)"))
contour(ug, ug, f, nlevels = 6, drawlabels = FALSE, add = TRUE, col = "gray30")
if (s$k <= 40) abline(v = seq(0, 1, by = s$hk), h = seq(0, 1, by = s$hk), col = adjustcolor("gray30", 0.35))
points(s$U, pch = 19, cex = 0.5, col = adjustcolor("black", 0.6))
})
output$tab <- renderTable({
s <- st()
est <- c(s$log_true, s$log_lap, s$log_mid, s$log_lmid)
data.frame(
Method = c("Reference", "Laplace", sprintf("Logistic midpoint %dx%d", s$n, s$n),
sprintf("Laplace-adapted midpoint %dx%d", s$k, s$k)),
Evals = c(400^2, 1, s$n^2, s$k^2),
`log P(y)` = sprintf("%.3f", est),
Error = c("", sprintf("%.3f", est[-1] - est[1])),
`Eff. pts` = c("", "", sprintf("%.1f", s$ess), sprintf("%.1f", s$ess_lap)),
check.names = FALSE)
}, striped = TRUE, align = "lrrrr")
}
shinyApp(ui, server)This app accompanies Numerical Quadrature in the book.