# Vuong test for zero inflation, and what to use instead
# https://tidyecology.com/posts/vuong-test-for-zero-inflation/
#
# 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-09-06

## ---- setup ----
library(ggplot2)
library(patchwork)

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          strip.text       = element_text(colour = te_ink, face = "bold"))
}

## ---- sci-tex-helper ----
sci_tex <- function(x, digits = 2) {
  s <- formatC(x, format = "e", digits = digits)
  paste0("$", sub("e.*", "", s), " \\times 10^{", as.integer(sub(".*e", "", s)), "}$")
}

## ---- design ----
lam_true  <- 1.5                   # beetles per trap in a working trap
pi_set    <- c(0, 0.10, 0.20)      # share of traps that cannot catch
n_set     <- c(50, 100, 200)       # traps per survey
n_rep     <- 2000                  # surveys per cell, fixed before any rate was seen
alpha_lev <- 0.05
z_crit    <- qnorm(1 - alpha_lev)  # one-sided 5 per cent, as pscl prints it
bound_tol <- 1e-3                  # a fitted pi below this counts as on the bound

draw_survey <- function(n, p, lam = lam_true) {
  ifelse(runif(n) < p, 0L, rpois(n, lam))
}

# intercept-only ZIP: the likelihood needs only n0, n, sum(y) and sum(lgamma(y + 1))
zip_nll <- function(par, n0, n, sy, slg) {
  lam <- exp(par[1]); p <- plogis(par[2])
  -(n0 * log(p + (1 - p) * exp(-lam)) + (n - n0) * log1p(-p) +
      sy * log(lam) - (n - n0) * lam - slg)
}
fit_zip <- function(y) {
  n0 <- sum(y == 0); n <- length(y)
  start_par <- c(log(mean(y)), qlogis(min(max(n0 / n, 0.01), 0.99)))
  o <- optim(start_par, zip_nll, n0 = n0, n = n, sy = sum(y), slg = sum(lgamma(y + 1)),
             method = "BFGS",
             control = list(maxit = 10000, reltol = .Machine$double.eps^(1 / 1.6)))
  c(lam = exp(o$par[1]), pi = plogis(o$par[2]))
}
ll_zip_obs <- function(y, lam, p) {
  ifelse(y == 0, log(p + (1 - p) * exp(-lam)), log1p(-p) + dpois(y, lam, log = TRUE))
}

# the three statistics exactly as pscl::vuong computes them, ZIP as model 1
vuong_z <- function(m, k_diff = 1) {
  n <- length(m); s <- sd(m)
  c(raw = sum(m) / (s * sqrt(n)),
    aic = (sum(m) - k_diff) / (s * sqrt(n)),
    bic = (sum(m) - k_diff * log(n) / 2) / (s * sqrt(n)))
}

survey_tests <- function(y) {
  n <- length(y); ybar <- mean(y); n0 <- sum(y == 0)
  f <- fit_zip(y)
  m <- ll_zip_obs(y, f[["lam"]], f[["pi"]]) - dpois(y, ybar, log = TRUE)
  vz <- vuong_z(m)
  p0 <- exp(-ybar)
  u  <- n0 / p0 - n                                # score for pi at pi = 0
  info <- n * (1 - p0) / p0 - n * ybar             # its variance, lambda estimated
  c(n = n, n0 = n0, ybar = ybar, pi_hat = f[["pi"]],
    v_raw = vz[["raw"]], v_aic = vz[["aic"]], v_bic = vz[["bic"]],
    lr = max(0, 2 * sum(m)), z_score = u / sqrt(info),
    bound_num = f[["pi"]] < bound_tol, bound_cf = n0 / n <= p0)
}

## ---- worked ----
set.seed(611)
n_ex <- 50; p_ex <- 0.10
ex_bound <- NULL; ex_inner <- NULL; n_drawn <- 0
while (is.null(ex_bound) || is.null(ex_inner)) {
  y <- draw_survey(n_ex, p_ex); n_drawn <- n_drawn + 1
  tt <- survey_tests(y)
  if (tt[["bound_cf"]] && is.null(ex_bound)) { ex_bound <- tt; n_at_bound <- n_drawn }
  if (!tt[["bound_cf"]] && is.null(ex_inner)) { ex_inner <- tt; n_at_inner <- n_drawn }
}
ex_tab <- data.frame(survey = c("on the bound", "inside"),
  zeros = c(ex_bound[["n0"]], ex_inner[["n0"]]),
  poisson_zeros = n_ex * exp(-c(ex_bound[["ybar"]], ex_inner[["ybar"]])),
  pi_hat = c(ex_bound[["pi_hat"]], ex_inner[["pi_hat"]]),
  raw = c(ex_bound[["v_raw"]], ex_inner[["v_raw"]]),
  aic = c(ex_bound[["v_aic"]], ex_inner[["v_aic"]]),
  bic = c(ex_bound[["v_bic"]], ex_inner[["v_bic"]]),
  score_z = c(ex_bound[["z_score"]], ex_inner[["z_score"]]))
print(format(ex_tab, digits = 3), row.names = FALSE)

## ---- mainsim ----
cells <- expand.grid(p = pi_set, n = n_set)
set.seed(3290)
sims <- do.call(rbind, lapply(seq_len(nrow(cells)), function(k) {
  r <- t(replicate(n_rep, survey_tests(draw_survey(cells$n[k], cells$p[k]))))
  data.frame(p = cells$p[k], r)
}))
sims$bound_num <- sims$bound_num == 1; sims$bound_cf <- sims$bound_cf == 1

agree_bound <- mean(sims$bound_num == sims$bound_cf)
n_disagree  <- sum(sims$bound_num != sims$bound_cf)
dis <- sims[sims$bound_num != sims$bound_cf, ]
dis_pi_max  <- if (nrow(dis)) max(dis$pi_hat) else NA_real_
dis_gap_max <- if (nrow(dis)) max(abs(dis$n0 / dis$n - exp(-dis$ybar))) else NA_real_
on_b <- sims$bound_cf
forced_aic <- mean(sims$v_aic[on_b] < -z_crit)
forced_bic <- mean(sims$v_bic[on_b] < -z_crit)
n_on_b     <- sum(on_b)
max_raw_b  <- max(sims$v_raw[on_b])
max_aic_b  <- max(sims$v_aic[on_b]); min_aic_b <- min(sims$v_aic[on_b])
forced_num <- mean(sims$v_aic[sims$bound_num] < -z_crit)

## ---- fig-bound ----
bd <- sims[sims$n == 50 & sims$p == 0.10, ]
min_inside <- min(bd$v_aic[!bd$bound_cf])
n_cell_b <- sum(bd$bound_cf); aic_rng_cell <- range(bd$v_aic[bd$bound_cf])
bound_slope <- unname(coef(lm(log(-v_aic) ~ log(pi_hat), data = bd[bd$bound_cf, ]))[2])
bd$state <- ifelse(bd$bound_cf, "on the bound", "inside")
squash <- function(v) asinh(v / 2)            # linear near zero, log far out
y_brk <- c(-1e4, -1e3, -100, -10, 0, 10)
bound_lab <- sprintf("%d surveys on the bound:\nstatistic from %.0f to %.0f", n_cell_b,
                     aic_rng_cell[1], aic_rng_cell[2])
ggplot(bd, aes(pi_hat, squash(v_aic), colour = state)) +
  geom_hline(yintercept = squash(c(-z_crit, z_crit)), colour = te_body,
             linetype = "dashed", linewidth = 0.5) +
  geom_point(size = 1, alpha = 0.45) +
  annotate("text", x = 2e-6, y = squash(-40), label = bound_lab, hjust = 0,
           colour = te_rust, size = 3.6) +
  annotate("text", x = 2e-6, y = squash(-z_crit) - 0.35, hjust = 0, size = 3.6,
           colour = te_body, label = "below: Poisson significantly better") +
  annotate("text", x = 2e-6, y = squash(z_crit) + 0.5, hjust = 0, size = 3.6,
           colour = te_body, label = "above: ZIP significantly better") +
  scale_x_log10(labels = scales::label_log()) +
  scale_y_continuous(breaks = squash(y_brk), labels = format(y_brk, big.mark = ",", trim = TRUE)) +
  scale_colour_manual(values = c(inside = te_forest, "on the bound" = te_rust),
                      name = NULL) +
  labs(x = "fitted zero-inflation probability (log scale)",
       y = "AIC-corrected Vuong statistic",
       title = "The corrected Vuong statistic at the boundary",
       subtitle = "50 traps, a tenth of them dead; dashed lines at the one-sided 5 per cent points") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- rates ----
rate_tab <- do.call(rbind, lapply(split(sims, list(sims$p, sims$n)), function(d) {
  nn <- d$n[1]
  data.frame(p = d$p[1], n = nn,
    raw_zip = mean(d$v_raw > z_crit),  raw_poi = mean(d$v_raw < -z_crit),
    aic_zip = mean(d$v_aic > z_crit),  aic_poi = mean(d$v_aic < -z_crit),
    bic_zip = mean(d$v_bic > z_crit),  bic_poi = mean(d$v_bic < -z_crit),
    lrt_chi1 = mean(d$lr > qchisq(1 - alpha_lev, 1)),
    lrt_bar  = mean(d$lr > qchisq(1 - 2 * alpha_lev, 1)),
    score1   = mean(d$z_score > z_crit),
    score2   = mean(d$z_score^2 > qchisq(1 - alpha_lev, 1)),
    ic_aic   = mean(d$lr > 2), ic_bic = mean(d$lr > log(nn)),
    bound    = mean(d$bound_cf), bound_num = mean(d$bound_num))
}))
rate_tab <- rate_tab[order(rate_tab$p, rate_tab$n), ]
rt <- function(col, p, n) rate_tab[[col]][rate_tab$p == p & rate_tab$n == n]
mcse <- function(r) sqrt(r * (1 - r) / n_rep)
print(format(rate_tab[, c("p", "n", "raw_zip", "score1", "lrt_bar", "lrt_chi1",
                          "ic_aic", "aic_poi", "bic_poi", "bound")], digits = 3),
      row.names = FALSE)

## ---- fig-grid ----
proc_lev <- c("raw Vuong", "AIC-corrected Vuong", "BIC-corrected Vuong",
              "score test, one-sided", "boundary LRT", "plain AIC")
long_one <- function(col, proc, direction) {
  data.frame(p = rate_tab$p, n = rate_tab$n, rate = rate_tab[[col]],
             procedure = proc, direction = direction)
}
dir_lev <- c("prefers ZIP", "Poisson significantly better")
grid_df <- rbind(
  long_one("raw_zip", "raw Vuong", dir_lev[1]),
  long_one("score1", "score test, one-sided", dir_lev[1]),
  long_one("lrt_bar", "boundary LRT", dir_lev[1]),
  long_one("ic_aic", "plain AIC", dir_lev[1]),
  long_one("raw_poi", "raw Vuong", dir_lev[2]),
  long_one("aic_poi", "AIC-corrected Vuong", dir_lev[2]),
  long_one("bic_poi", "BIC-corrected Vuong", dir_lev[2]))
grid_df$procedure <- factor(grid_df$procedure, levels = proc_lev)
grid_df$direction <- factor(grid_df$direction, levels = dir_lev)
grid_df$truth <- factor(ifelse(grid_df$p == 0, "Poisson truth",
                               sprintf("ZIP, pi = %.2f", grid_df$p)),
                        levels = c("Poisson truth", sprintf("ZIP, pi = %.2f", pi_set[-1])))
grid_df$se2 <- 2 * mcse(grid_df$rate)
proc_col <- c(te_rust, te_gold, te_ink, te_forest, te_forest, te_body)
proc_lty <- c("solid", "solid", "solid", "solid", "dashed", "dotted")
proc_shp <- c(16, 17, 15, 16, 1, 4)
names(proc_col) <- names(proc_lty) <- names(proc_shp) <- proc_lev
ggplot(grid_df, aes(n, rate, colour = procedure, linetype = procedure, shape = procedure)) +
  geom_hline(yintercept = alpha_lev, colour = te_body, alpha = 0.5, linewidth = 0.5) +
  geom_errorbar(aes(ymin = rate - se2, ymax = rate + se2), width = 6,
                linewidth = 0.4, linetype = "solid") +
  geom_line(linewidth = 0.8) + geom_point(size = 2) +
  facet_grid(direction ~ truth) +
  scale_colour_manual(values = proc_col, name = NULL) +
  scale_linetype_manual(values = proc_lty, name = NULL) +
  scale_shape_manual(values = proc_shp, name = NULL) +
  scale_x_continuous(breaks = n_set) +
  scale_y_continuous(limits = c(0, 1)) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "traps per survey", y = "share of surveys",
       title = "Who finds the zeros, and who certifies the Poisson",
       subtitle = "grey line: 5 per cent") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- arithmetic ----
cf_bound <- 0.5
cf_chi1  <- 0.5 * alpha_lev
cf_aic   <- 0.5 * pchisq(2, 1, lower.tail = FALSE)
cf_bic   <- 0.5 * pchisq(log(n_set), 1, lower.tail = FALSE)
arith <- data.frame(n = n_set,
  bound_sim = rate_tab$bound[rate_tab$p == 0],
  chi1_sim  = rate_tab$lrt_chi1[rate_tab$p == 0],
  aic_sim   = rate_tab$ic_aic[rate_tab$p == 0],
  bic_sim   = rate_tab$ic_bic[rate_tab$p == 0], bic_cf = cf_bic)
print(format(arith, digits = 3), row.names = FALSE)

## ---- split ----
split_tab <- do.call(rbind, lapply(split(sims[sims$p > 0, ], list(sims$p[sims$p > 0], sims$n[sims$p > 0])), function(d) {
  b <- d$bound_cf
  data.frame(p = d$p[1], n = d$n[1], n_bound = sum(b), n_inside = sum(!b),
    share_bound = mean(b),
    wrong_bound = if (any(b)) mean(d$v_aic[b] < -z_crit) else NA_real_,
    wrong_inside = mean(d$v_aic[!b] < -z_crit),
    wrong_all = mean(d$v_aic < -z_crit),
    forced_share = if (any(d$v_aic < -z_crit)) sum(b & d$v_aic < -z_crit) / sum(d$v_aic < -z_crit) else NA_real_)
}))
split_tab <- split_tab[order(split_tab$p, split_tab$n), ]
st <- function(col, p, n) split_tab[[col]][split_tab$p == p & split_tab$n == n]
print(format(split_tab, digits = 3), row.names = FALSE)

## ---- fig-split ----
sp_long <- rbind(
  data.frame(split_tab[, c("p", "n")], part = "forced on the bound",
             rate = split_tab$share_bound * ifelse(is.na(split_tab$wrong_bound), 0, split_tab$wrong_bound)),
  data.frame(split_tab[, c("p", "n")], part = "inside the bound",
             rate = (1 - split_tab$share_bound) * split_tab$wrong_inside))
sp_long$part <- factor(sp_long$part, levels = c("forced on the bound", "inside the bound"))
sp_long$truth <- sprintf("ZIP, pi = %.2f", sp_long$p)
ggplot(sp_long, aes(factor(n), rate, fill = part)) +
  geom_col(width = 0.6, colour = te_paper, linewidth = 0.3) +
  facet_wrap(~ truth) +
  scale_fill_manual(values = c(te_rust, te_gold), name = NULL) +
  labs(x = "traps per survey", y = "share of surveys: Poisson significantly better",
       title = "Where the wrong verdicts come from",
       subtitle = "AIC-corrected Vuong, one-sided 5 per cent") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- covsim ----
b_slope <- 0.5
b_int   <- log(lam_true) - b_slope^2 / 2       # E[exp(b_slope * x)] = exp(b_slope^2 / 2)
n_rep_cov <- 500                              # fixed before any rate was seen
zipx_nll <- function(par, y, X, is0) {
  lam <- exp(drop(X %*% par[1:2])); p <- plogis(par[3])
  -sum(ifelse(is0, log(p + (1 - p) * exp(-lam)), log1p(-p) + dpois(y, lam, log = TRUE)))
}
survey_tests_x <- function(y, x) {
  n <- length(y); X <- cbind(1, x); is0 <- y == 0
  gp <- glm.fit(X, y, family = poisson()); mu <- gp$fitted.values
  start_par <- c(gp$coefficients, qlogis(min(max(mean(is0), 0.01), 0.99)))
  o <- optim(start_par, zipx_nll, y = y, X = X, is0 = is0, method = "BFGS",
             control = list(maxit = 10000, reltol = .Machine$double.eps^(1 / 1.6)))
  lam_z <- exp(drop(X %*% o$par[1:2])); p_z <- plogis(o$par[3])
  m  <- ll_zip_obs(y, lam_z, p_z) - dpois(y, mu, log = TRUE)
  vz <- vuong_z(m)
  p0 <- exp(-mu); u <- sum(is0 / p0) - n
  xm <- crossprod(X, mu)
  info <- sum((1 - p0) / p0) - drop(crossprod(xm, solve(crossprod(X, X * mu), xm)))
  c(n = n, pi_hat = p_z, v_raw = vz[["raw"]], v_aic = vz[["aic"]], v_bic = vz[["bic"]],
    lr = max(0, 2 * sum(m)), z_score = u / sqrt(info),
    bound_num = p_z < bound_tol, bound_cf = u <= 0)
}
cov_cells <- data.frame(p = c(0, 0.10, 0.10), n = c(200, 50, 200))
set.seed(3291)
cov_sims <- do.call(rbind, lapply(seq_len(nrow(cov_cells)), function(k) {
  r <- t(replicate(n_rep_cov, {
    x <- rnorm(cov_cells$n[k])
    y <- ifelse(runif(cov_cells$n[k]) < cov_cells$p[k], 0L,
                rpois(cov_cells$n[k], exp(b_int + b_slope * x)))
    survey_tests_x(y, x)
  }))
  data.frame(p = cov_cells$p[k], r)
}))
cov_sims$bound_num <- cov_sims$bound_num == 1; cov_sims$bound_cf <- cov_sims$bound_cf == 1
cov_tab <- do.call(rbind, lapply(split(cov_sims, list(cov_sims$p, cov_sims$n), drop = TRUE), function(d) {
  b <- d$bound_cf
  data.frame(p = d$p[1], n = d$n[1], bound = mean(b), agree = mean(b == d$bound_num),
    forced = if (any(b)) mean(d$v_aic[b] < -z_crit) else NA_real_,
    raw_zip = mean(d$v_raw > z_crit), aic_poi = mean(d$v_aic < -z_crit),
    bic_poi = mean(d$v_bic < -z_crit), score1 = mean(d$z_score > z_crit),
    lrt_bar = mean(d$lr > qchisq(1 - 2 * alpha_lev, 1)), max_raw_b = if (any(b)) max(d$v_raw[b]) else NA_real_)
}))
cov_tab <- cov_tab[order(cov_tab$p, cov_tab$n), ]
ct <- function(col, p, n) cov_tab[[col]][cov_tab$p == p & cov_tab$n == n]
print(format(cov_tab, digits = 3), row.names = FALSE)
cov_agree <- mean(cov_sims$bound_cf == cov_sims$bound_num)
cov_forced <- mean(cov_sims$v_aic[cov_sims$bound_cf] < -z_crit)
shift_z <- vapply(seq_len(nrow(cov_cells)), function(k) {
  a <- ct("bound", cov_cells$p[k], cov_cells$n[k]); r <- rt("bound", cov_cells$p[k], cov_cells$n[k])
  (a - r) / sqrt(a * (1 - a) / n_rep_cov + r * (1 - r) / n_rep)
}, 0)
skewness_of <- function(z) mean(((z - mean(z)) / sd(z))^3)
z0_cov <- cov_sims$z_score[cov_sims$p == 0 & cov_sims$n == 200]
z0_int <- sims$z_score[sims$p == 0 & sims$n == 200]
lrt_crit <- qchisq(1 - 2 * alpha_lev, 1)
d_null <- cov_sims[cov_sims$p == 0 & cov_sims$n == 200, ]
d_zip  <- cov_sims[cov_sims$p == 0.1 & cov_sims$n == 200, ]
cov_either0    <- mean(d_null$z_score > z_crit | d_null$lr > lrt_crit)
cov_lrt_only   <- sum(d_zip$lr > lrt_crit & d_zip$z_score <= z_crit)
cov_score_only <- sum(d_zip$z_score > z_crit & d_zip$lr <= lrt_crit)

## ---- fig-cov ----
cmp <- do.call(rbind, lapply(seq_len(nrow(cov_cells)), function(k) {
  p <- cov_cells$p[k]; n <- cov_cells$n[k]
  lab <- sprintf("%s, %d traps", ifelse(p == 0, "Poisson", sprintf("pi = %.2f", p)), n)
  data.frame(design = lab, model = rep(c("intercept only", "covariate on the mean"), 2),
    quantity = rep(c("on the bound", "AIC-Vuong: Poisson significantly better"), each = 2),
    rate = c(rt("bound", p, n), ct("bound", p, n), rt("aic_poi", p, n), ct("aic_poi", p, n)),
    se2 = 2 * sqrt(c(rt("bound", p, n) * (1 - rt("bound", p, n)) / n_rep,
                     ct("bound", p, n) * (1 - ct("bound", p, n)) / n_rep_cov,
                     rt("aic_poi", p, n) * (1 - rt("aic_poi", p, n)) / n_rep,
                     ct("aic_poi", p, n) * (1 - ct("aic_poi", p, n)) / n_rep_cov)))
}))
cmp$design <- factor(cmp$design, levels = unique(cmp$design))
cmp$quantity <- factor(cmp$quantity, levels = c("on the bound", "AIC-Vuong: Poisson significantly better"))
ggplot(cmp, aes(rate, design, colour = model)) +
  geom_errorbar(aes(xmin = rate - se2, xmax = rate + se2), orientation = "y", width = 0.2,
                position = position_dodge(width = 0.5), linewidth = 0.5) +
  geom_point(size = 2.6, position = position_dodge(width = 0.5)) +
  facet_wrap(~ quantity) +
  scale_colour_manual(values = c("intercept only" = te_forest, "covariate on the mean" = te_rust),
                      name = NULL) +
  scale_x_continuous(limits = c(0, 1)) +
  labs(x = "share of surveys", y = NULL, title = "A covariate does not rescue the corrected test",
       subtitle = "bars: two Monte Carlo standard errors") +
  theme_datasheet() + theme(legend.position = "bottom")
