# The parametric bootstrap and a boundary problem
# https://tidyecology.com/posts/the-parametric-bootstrap/
#
# The R code of this Tidy Ecology tutorial, chunk by chunk, in the order of the post.
# Run it top to bottom in a fresh R session. Code the post shows but does not run
# is commented out. The prose, and the numbers it quotes, are in the post itself.
# Post last modified: 2026-11-15

## ---- setup ----
suppressMessages({library(MASS); library(ggplot2)})
te_ink <- "#275139"; te_green <- "#4e7a5a"; te_gold <- "#c98a1b"
te_rose <- "#a5524a"; te_slate <- "#3f5c7a"; te_grey <- "#8a8a80"
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(text = element_text(colour = "#2f3e35"),
          plot.title = element_text(face = "bold", colour = "#233a2c", size = rel(1.02)),
          plot.subtitle = element_text(colour = "#54655b", size = rel(0.86)),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "#e7e3d8", linewidth = 0.3),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          axis.text = element_text(colour = "#54655b"),
          legend.position = "bottom", plot.margin = margin(8, 12, 8, 12))
}

## ---- data ----
set.seed(243)
n <- 90
x <- as.numeric(scale(runif(n, 0, 10)))     # standardised environmental gradient
mu <- exp(1.15 + 0.5 * x)
y <- rnbinom(n, size = 6, mu = mu)           # counts with mild overdispersion
disp_obs <- var(y) / mean(y)                 # crude variance-to-mean ratio

## ---- fit-lrt ----
lrt_stat <- function(y, x) {
  m_pois <- glm(y ~ x, family = poisson)
  m_nb <- suppressWarnings(tryCatch(glm.nb(y ~ x), error = function(e) NULL))
  if (is.null(m_nb)) return(0)
  max(0, 2 * (as.numeric(logLik(m_nb)) - as.numeric(logLik(m_pois))))
}
LRT_obs <- lrt_stat(y, x)
p_naive <- 1 - pchisq(LRT_obs, df = 1)         # naive chi-squared(1)
p_mix   <- 0.5 * (1 - pchisq(LRT_obs, df = 1)) # asymptotic 50:50 mixture

## ---- pboot ----
m_pois <- glm(y ~ x, family = poisson)
mu_hat <- fitted(m_pois)
set.seed(909)
Bpb <- 1500
LRT_star <- replicate(Bpb, lrt_stat(rpois(n, mu_hat), x))
p_boot <- (1 + sum(LRT_star >= LRT_obs)) / (Bpb + 1)
frac0  <- mean(LRT_star < 1e-6)                # share of the null exactly at zero

## ---- fig-null ----
pos <- LRT_star[LRT_star > 1e-6]
dd <- data.frame(v = pos)
crit_naive <- qchisq(0.95, 1); crit_mix <- qchisq(0.90, 1)
ggplot(dd, aes(v)) +
  geom_histogram(aes(y = after_stat(density) * (1 - frac0)), bins = 45,
                 fill = "#dfe8e0", colour = "#c4d3c6", linewidth = 0.2) +
  stat_function(fun = function(z) 0.5 * dchisq(z, 1), colour = te_green, linewidth = 0.9) +
  stat_function(fun = function(z) dchisq(z, 1), colour = te_rose, linewidth = 0.7,
                linetype = "dashed") +
  geom_vline(xintercept = LRT_obs, colour = te_ink, linewidth = 0.8) +
  geom_vline(xintercept = crit_mix, colour = te_green, linewidth = 0.5, linetype = "dotted") +
  geom_vline(xintercept = crit_naive, colour = te_rose, linewidth = 0.5, linetype = "dotted") +
  annotate("text", x = 6.2, y = 0.34, label = sprintf("spike at zero: %.0f%%", 100 * frac0),
           hjust = 0, size = 3.1, colour = "#233a2c") +
  annotate("text", x = 6.2, y = 0.30, label = "solid: half chi-squared (correct)",
           hjust = 0, size = 3, colour = te_green) +
  annotate("text", x = 6.2, y = 0.265, label = "dashed: full chi-squared (naive)",
           hjust = 0, size = 3, colour = te_rose) +
  annotate("text", x = LRT_obs + 0.15, y = 0.11, label = "observed", hjust = 0,
           size = 3, colour = te_ink) +
  coord_cartesian(xlim = c(0, 12), ylim = c(0, 0.42)) +
  labs(title = "The null is a mixture, not a chi-squared",
       subtitle = "Positive part of 1500 simulated null statistics, with the two asymptotic curves",
       x = "likelihood-ratio statistic", y = "density (scaled to positive mass)") +
  theme_te() + theme(legend.position = "none")

## ---- calib ----
naive_size <- mean(LRT_star > qchisq(0.95, 1))   # actual size of the naive 5% test
alpha_grid <- seq(0.01, 0.20, by = 0.01)
size_naive <- sapply(alpha_grid, function(a) mean(LRT_star > qchisq(1 - a, 1)))

## ---- fig-calib ----
dp <- data.frame(method = factor(c("naive\nchi-squared", "0.5:0.5\nmixture", "parametric\nbootstrap"),
                                 levels = c("naive\nchi-squared", "0.5:0.5\nmixture", "parametric\nbootstrap")),
                 p = c(p_naive, p_mix, p_boot),
                 col = c(te_rose, te_gold, te_ink))
pA <- ggplot(dp, aes(method, p, fill = col)) +
  geom_col(width = 0.66) +
  geom_hline(yintercept = 0.05, linetype = "dashed", colour = "#233a2c", linewidth = 0.6) +
  geom_text(aes(label = sprintf("%.3f", p)), vjust = -0.5, size = 3, colour = "#233a2c") +
  scale_fill_identity() +
  coord_cartesian(ylim = c(0, 0.095)) +
  labs(title = "One statistic, three verdicts", x = NULL, y = "p-value") +
  theme_te() + theme(axis.text.x = element_text(size = 7.5))
dcal <- data.frame(nominal = alpha_grid, actual = size_naive)
pB <- ggplot(dcal, aes(nominal, actual)) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = "#8a8a80", linewidth = 0.5) +
  geom_line(colour = te_rose, linewidth = 0.9) +
  geom_point(colour = te_rose, size = 1.3) +
  labs(title = "Naive test is conservative", subtitle = "Actual vs nominal rejection rate",
       x = "nominal level", y = "actual size under null") +
  theme_te() + theme(legend.position = "none")
grid::grid.newpage()
grid::pushViewport(grid::viewport(layout = grid::grid.layout(1, 2)))
print(pA, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 1))
print(pB, vp = grid::viewport(layout.pos.row = 1, layout.pos.col = 2))
