# Checking an N-mixture model
# https://tidyecology.com/posts/checking-an-n-mixture-model/
#
# 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-10-07

## ---- machinery ----
library(ggplot2)

nll_pois <- function(par, y, K) {
  lam <- exp(par[1]); p <- plogis(par[2])
  Nv <- 0:K; lp <- dpois(Nv, lam, log = TRUE); ll <- 0
  for (i in seq_len(nrow(y))) {
    yi <- y[i, ]; idx <- (max(yi) + 1):(K + 1); Ni <- Nv[idx]
    lb <- rowSums(vapply(yi, function(v) dbinom(v, Ni, p, log = TRUE),
                         numeric(length(Ni))))
    ll <- ll + log(sum(exp(lp[idx] + lb)))
  }
  if (!is.finite(ll)) return(1e10)
  -ll
}
fit_pois <- function(y, K, start = c(log(2), 0))
  optim(start, nll_pois, y = y, K = K, method = "BFGS")

## ---- helpers ----
theme_te <- function(base_size = 12) {
  theme_minimal(base_size = base_size) +
    theme(
      panel.grid.minor = element_blank(),
      panel.grid.major = element_line(colour = "#e3e0d5", linewidth = 0.3),
      plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
      panel.background = element_rect(fill = "#f5f4ee", colour = NA),
      axis.text  = element_text(colour = "#40493c"),
      axis.title = element_text(colour = "#275139"),
      plot.title = element_text(colour = "#275139", face = "bold", size = rel(0.98)),
      legend.position = "top", legend.title = element_blank(),
      legend.text = element_text(colour = "#40493c")
    )
}
te_forest <- "#275139"; te_moss <- "#7cc28a"; te_bark <- "#9a7b4f"; te_slate <- "#4a6b8a"
two_panel <- function(pa, pb) {
  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))
}

## ---- gof ----
# beta-binomial detection, used to build an overdispersed data set
rbb <- function(N, p, rho) {
  a <- p * (1 - rho) / rho; b <- (1 - p) * (1 - rho) / rho
  rbinom(length(N), N, rbeta(length(N), a, b))
}
ft <- function(y, lam, p) { E <- lam * p; sum((sqrt(y) - sqrt(E))^2) }

gof_boot <- function(y, K, B = 80, boot_seed = 1) {
  f <- fit_pois(y, K); lam <- exp(f$par[1]); p <- plogis(f$par[2])
  Tobs <- ft(y, lam, p); set.seed(boot_seed); Tb <- numeric(B)
  for (b in 1:B) {
    N  <- rpois(nrow(y), lam)
    ys <- matrix(rbinom(nrow(y) * ncol(y), rep(N, ncol(y)), p), nrow(y), ncol(y))
    fb <- fit_pois(ys, K); Tb[b] <- ft(ys, exp(fb$par[1]), plogis(fb$par[2]))
  }
  list(lam = lam, p = p, Tobs = Tobs, Tb = Tb,
       pval = mean(Tb >= Tobs), chat = Tobs / mean(Tb))
}

Tv <- 3L; K <- 40L; B <- 80L
set.seed(4280)                                   # a well-specified data set
R <- 110L; Ng <- rpois(R, 2.5)
yg <- matrix(rbinom(R * Tv, rep(Ng, Tv), 0.40), R, Tv)
set.seed(4261)                                   # detection heterogeneity added
Nb <- rpois(R, 2.5); yb <- sapply(1:Tv, function(t) rbb(Nb, 0.40, 0.30))

gg <- gof_boot(yg, K, B); gb <- gof_boot(yb, K, B)

## ---- fig-gof ----
gdf <- rbind(data.frame(T = gg$Tb, case = "well-specified"),
             data.frame(T = gb$Tb, case = "overdispersed"))
obs <- data.frame(case = c("well-specified", "overdispersed"),
                  Tobs = c(gg$Tobs, gb$Tobs))
mk_hist <- function(cs, fill, obsv) {
  ggplot(subset(gdf, case == cs), aes(T)) +
    geom_histogram(bins = 22, fill = fill, colour = "#f5f4ee", linewidth = 0.2) +
    geom_vline(xintercept = obsv, linetype = "dashed", colour = te_bark, linewidth = 0.9) +
    labs(title = if (cs == "well-specified") "Well-specified model" else "Overdispersed data",
         x = "Freeman-Tukey statistic", y = "Bootstrap frequency") +
    theme_te()
}
two_panel(mk_hist("well-specified", te_forest, gg$Tobs),
          mk_hist("overdispersed", te_slate, gb$Tobs))

## ---- resid ----
# marginal CDF of the site total S = sum of visits; S given N is Binomial(T*N, p)
Fss <- function(s, lam, p, Tv, K) { Nv <- 0:K; sum(dpois(Nv, lam) * pbinom(s, Tv * Nv, p)) }
rq_site <- function(y, lam, p, K, rseed = 99) {
  Tv <- ncol(y); S <- rowSums(y); set.seed(rseed)
  lo <- vapply(S, function(s) Fss(s - 1, lam, p, Tv, K), numeric(1))
  hi <- vapply(S, function(s) Fss(s,     lam, p, Tv, K), numeric(1))
  qnorm(pmin(pmax(runif(length(S), lo, hi), 1e-6), 1 - 1e-6))
}
rg <- rq_site(yg, gg$lam, gg$p, K); rb <- rq_site(yb, gb$lam, gb$p, K)

## ---- fig-resid ----
qq_df <- function(r) { n <- length(r); data.frame(th = qnorm(ppoints(n)), sr = sort(r)) }
mk_qq <- function(r, ttl, col) {
  ggplot(qq_df(r), aes(th, sr)) +
    geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = te_bark) +
    geom_point(colour = col, size = 1.3, alpha = 0.75) +
    coord_cartesian(ylim = c(-4, 4)) +
    labs(title = ttl, x = "Theoretical quantile", y = "Residual quantile") +
    theme_te()
}
two_panel(mk_qq(rg, "Well-specified model", te_forest),
          mk_qq(rb, "Overdispersed data", te_slate))

## ---- ksens ----
set.seed(4254)                                   # low detection, unreliable
Rl <- 120L; Tl <- 2L; Nl <- rpois(Rl, 3.0)
yl <- matrix(rbinom(Rl * Tl, rep(Nl, Tl), 0.12), Rl, Tl)
Kseq <- c(30, 60, 120, 300)
lam_reliable   <- sapply(Kseq, function(K) exp(fit_pois(yg, K)$par[1]))
lam_unreliable <- sapply(Kseq, function(K) exp(fit_pois(yl, K, c(log(3), qlogis(0.2)))$par[1]))

## ---- mild ----
set.seed(7001)
Nm <- rpois(R, 2.5); ym <- sapply(1:Tv, function(t) rbb(Nm, 0.40, 0.08))
gm <- gof_boot(ym, K, B)
