# N-mixture reliability and the detection trade-off
# https://tidyecology.com/posts/n-mixture-identifiability-and-reliability/
#
# 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-08

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

nll_pois <- function(par, y, K) {           # Poisson-abundance marginal NLL
  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",
        control = list(reltol = 1e-12, maxit = 1000))

## ---- 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))
}

## ---- demo1 ----
set.seed(4254)
R <- 120L; Tv <- 2L                              # few visits, low detection
lam_true <- 3.0
Kgrid <- c(30, 120, 400, 800)
draw_lo <- function() {                          # one survey from the same design
  N <- rpois(R, lam_true)
  matrix(rbinom(R * Tv, rep(N, Tv), 0.12), R, Tv)
}
sets_lo <- replicate(40, draw_lo(), simplify = FALSE)
lam_lo  <- t(sapply(sets_lo, function(y)
  sapply(Kgrid, function(K) exp(fit_pois(y, K, c(log(3), qlogis(0.2)))$par[1]))))

set.seed(4255)                                   # contrast: adequate detection
N_ok   <- rpois(R, lam_true)
y_ok   <- matrix(rbinom(R * Tv, rep(N_ok, Tv), 0.45), R, Tv)
lam_ok <- sapply(Kgrid, function(K) exp(fit_pois(y_ok, K, c(log(3), 0))$par[1]))

base   <- lam_lo[, 1]                               # estimate at the lowest ceiling
tracks <- lam_lo[, ncol(lam_lo)] / lam_lo[, ncol(lam_lo) - 1] > 1.05  # still rising between the two largest ceilings

## ---- fig-runaway ----
lab_run <- "low detection: follows K"
lab_set <- "low detection: settles"
lab_ok  <- "adequate detection"
kdf <- rbind(
  data.frame(K = rep(Kgrid, each = nrow(lam_lo)), lambda = as.vector(lam_lo),
             id = rep(seq_len(nrow(lam_lo)), times = length(Kgrid)),
             case = ifelse(rep(tracks, times = length(Kgrid)), lab_run, lab_set)),
  data.frame(K = Kgrid, lambda = lam_ok, id = 0L, case = lab_ok)
)
pal <- c(te_bark, te_slate, te_forest); names(pal) <- c(lab_run, lab_set, lab_ok)
wid <- c(0.6, 0.6, 1.3); names(wid) <- names(pal)
p_a <- ggplot(kdf, aes(K, lambda, group = id, colour = case, linewidth = case)) +
  geom_line(alpha = 0.85) +
  scale_y_log10() +
  scale_colour_manual(values = pal) +
  scale_linewidth_manual(values = wid, guide = "none") +
  guides(colour = guide_legend(nrow = 2)) +
  labs(title = "Estimate versus numerical ceiling", x = "Ceiling K",
       y = "Fitted mean abundance (log)") +
  theme_te()

lamgrid <- seq(1.5, 38, length.out = 26)
profdev <- function(y, K) {
  v <- sapply(lamgrid, function(L) optimize(function(q) nll_pois(c(log(L), q), y, K),
                                            c(-8, 6))$objective)
  2 * (v - min(v))
}
i_run <- which.max(lam_lo[, ncol(lam_lo)] / base)
i_set <- which.min(abs(base - median(base)))
pdf_df <- rbind(
  data.frame(lambda = lamgrid, dev = profdev(sets_lo[[i_run]], 150), case = lab_run),
  data.frame(lambda = lamgrid, dev = profdev(sets_lo[[i_set]], 150), case = lab_set),
  data.frame(lambda = lamgrid, dev = profdev(y_ok, 150), case = lab_ok)
)
p_b <- ggplot(pdf_df, aes(lambda, dev, colour = case)) +
  geom_hline(yintercept = 3.84, linetype = "dashed", colour = "#8a8578") +
  geom_line(linewidth = 0.9) +
  coord_cartesian(ylim = c(0, 14)) +
  scale_colour_manual(values = pal, guide = "none") +
  labs(title = "Profile deviance for abundance", x = "Mean abundance",
       y = "Profile deviance") +
  theme_te()
two_panel(p_a, p_b)

## ---- thumb ----
ggsave("thumbnail.png", p_a, width = 7.5, height = 5.4, dpi = 100)

## ---- demo2 ----
nll_nb <- function(par, y, K) {              # add a log-dispersion parameter
  lam <- exp(par[1]); p <- plogis(par[2]); sz <- exp(par[3])
  Nv <- 0:K; lp <- dnbinom(Nv, mu = lam, size = sz, 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
}

set.seed(4256)
R <- 150L; Tv <- 3L; K <- 80L
N2 <- rpois(R, 2.8)
y2 <- matrix(rbinom(R * Tv, rep(N2, Tv), 0.35), R, Tv)   # genuinely Poisson
fp <- fit_pois(y2, K, c(log(2), 0))
fn <- optim(c(log(2), 0, log(5)), nll_nb, y = y2, K = K, method = "BFGS")
aic_p  <- 2 * fp$value + 2 * 2
aic_nb <- 2 * fn$value + 2 * 3
nb_size <- exp(fn$par[3])
# how flat is the dispersion? profile the negative log-likelihood at two sizes
prof_sz <- function(s) optim(c(log(2), 0),
  function(q) nll_nb(c(q[1], q[2], log(s)), y2, K), method = "Nelder-Mead")$value
nll_s100 <- prof_sz(100); nll_s1000 <- prof_sz(1000)

## ---- demo3 ----
# beta-binomial counts: detection probability itself varies, with intra-visit
# correlation rho; rho = 0 is the ordinary binomial, larger rho is more heterogeneity
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))
}
set.seed(4257)
R <- 150L; Tv <- 4L; K <- 55L; reps <- 8L; lam_true <- 3.0; p_true <- 0.40
rhos <- c(0.0001, 0.10, 0.20, 0.35, 0.55)
sweep <- do.call(rbind, lapply(rhos, function(rh) {
  m <- t(replicate(reps, {
    N <- rpois(R, lam_true); y <- sapply(1:Tv, function(t) rbb(N, p_true, rh))
    f <- fit_pois(y, K, c(log(3), qlogis(0.4))); c(exp(f$par[1]), plogis(f$par[2]))
  }))
  data.frame(rho = rh, lam = mean(m[, 1]), lam_sd = sd(m[, 1]), p = mean(m[, 2]))
}))

## ---- fig-inflation ----
p_l <- ggplot(sweep, aes(rho, lam)) +
  geom_ribbon(aes(ymin = lam - lam_sd, ymax = lam + lam_sd), fill = te_moss, alpha = 0.35) +
  geom_line(colour = te_forest, linewidth = 0.9) + geom_point(colour = te_forest, size = 2) +
  geom_hline(yintercept = lam_true, linetype = "dashed", colour = te_bark) +
  labs(title = "Abundance versus heterogeneity",
       x = "Detection heterogeneity (rho)",
       y = "Estimated mean abundance") +
  theme_te()
p_r <- ggplot(sweep, aes(rho, p)) +
  geom_line(colour = te_slate, linewidth = 0.9) + geom_point(colour = te_slate, size = 2) +
  geom_hline(yintercept = p_true, linetype = "dashed", colour = te_bark) +
  labs(title = "Detection versus heterogeneity",
       x = "Detection heterogeneity (rho)",
       y = "Estimated detection") +
  theme_te()
two_panel(p_l, p_r)
