# Checking an occupancy variant
# https://tidyecology.com/posts/checking-an-occupancy-variant/
#
# 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 ----
library(ggplot2)
library(grid)

te_ink <- "#16241d"; te_forest <- "#275139"; te_gold <- "#c9b458"
te_rust <- "#b5534e"; te_sage <- "#93a87f"

theme_te <- function() {
  theme_minimal(base_size = 11) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = "grey90", linewidth = 0.3),
          plot.title = element_text(colour = te_ink, face = "bold", size = 11),
          plot.subtitle = element_text(colour = "grey35", size = 9),
          axis.title = element_text(colour = te_ink, size = 9),
          axis.text = element_text(colour = "grey30", size = 8),
          legend.position = "bottom",
          legend.title = element_blank(),
          legend.text = element_text(size = 8))
}
two_panel <- function(p1, p2) {
  grid.newpage()
  pushViewport(viewport(layout = grid.layout(1, 2)))
  print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(p2, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}

## ---- 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)), "}$")
}

## ---- cells ----
Nmax <- 80L; Nv <- 0:Nmax
p_occ <- function(th, K) { psi <- plogis(th[1]); p <- plogis(th[2])
  psi * dbinom(0:K, K, p) + c(1 - psi, rep(0, K)) }
p_rn <- function(th, K) { lam <- exp(th[1]); r <- plogis(th[2])
  colSums(dpois(Nv, lam) *
    t(sapply(Nv, function(n) dbinom(0:K, K, 1 - (1 - r)^n)))) }
p_mix <- function(th, K) { psi <- plogis(th[1]); p1 <- plogis(th[2])
  p2 <- plogis(th[3]); w <- plogis(th[4])
  psi * (w * dbinom(0:K, K, p1) + (1 - w) * dbinom(0:K, K, p2)) +
    c(1 - psi, rep(0, K)) }
p_fp <- function(th, K) { psi <- plogis(th[1]); p11 <- plogis(th[2])
  p10 <- plogis(th[3])
  psi * dbinom(0:K, K, p11) + (1 - psi) * dbinom(0:K, K, p10) }

pv <- list(occ = p_occ, rn = p_rn, mix = p_mix, fp = p_fp)
st <- list(occ = c(0, 0), rn = c(0, 0),
           mix = c(0, qlogis(0.4), qlogis(0.1), 0),
           fp = c(0, qlogis(0.4), qlogis(0.05)))
nl <- lapply(names(pv), function(k) {
  function(par, nvec, K) -sum(nvec * log(pmax(pv[[k]](par, K), 1e-300)))
})
names(nl) <- names(pv)
ct <- list(maxit = 8000, reltol = 1e-12)
fitn <- function(k, nvec, K) {
  o <- optim(st[[k]], nl[[k]], nvec = nvec, K = K, method = "Nelder-Mead",
             control = ct)
  o <- optim(o$par, nl[[k]], nvec = nvec, K = K, method = "Nelder-Mead",
             control = ct)
  list(par = o$par, nll = o$value, aic = 2 * o$value + 2 * length(st[[k]]))
}
tab <- function(d, K) as.numeric(table(factor(d, levels = 0:K)))

R <- 300L; K <- 6L
set.seed(4275); N <- rpois(R, 2.0); d_rn <- rbinom(R, K, 1 - (1 - 0.12)^N)
site_nll <- function(par, d, K) -sum(log(pmax(p_occ(par, K)[d + 1], 1e-300)))
chk <- abs(site_nll(c(0.3, -0.8), d_rn, K) - nl$occ(c(0.3, -0.8), tab(d_rn, K), K))

## ---- fp-guard-1 ----
stopifnot(chk / abs(site_nll(c(0.3, -0.8), d_rn, K)) < 1e-10)

## ---- worlds ----
set.seed(4273); z2 <- rbinom(R, 1L, 0.60); d_bet <- rbinom(R, K, z2 * rbeta(R, 1.2, 4.0))
set.seed(4276); z3 <- rbinom(R, 1L, 0.55); d_std <- rbinom(R, K, z3 * 0.30)
set.seed(4274); z4 <- rbinom(R, 1L, 0.10)
d_fp <- rowSums(matrix(rbinom(R * K, 1L,
  ifelse(rep(z4, K) == 1, 0.35, 0.05)), R, K))

worlds <- list(
  list(name = "abundance", d = d_rn, truth = 1 - exp(-2.0)),
  list(name = "heterogeneity", d = d_bet, truth = 0.60),
  list(name = "textbook", d = d_std, truth = 0.55),
  list(name = "false positives", d = d_fp, truth = 0.10))

## ---- fig-worlds ----
df_w <- do.call(rbind, lapply(worlds, function(w) {
  data.frame(d = 0:K, prop = tab(w$d, K) / R, world = w$name)
}))
df_w$world <- factor(df_w$world, levels = sapply(worlds, `[[`, "name"))
pw <- ggplot(df_w, aes(d, prop, colour = world)) +
  geom_line(linewidth = 0.7) +
  geom_point(size = 1.5) +
  scale_colour_manual(values = c(te_forest, te_rust, te_gold, te_sage)) +
  guides(colour = guide_legend(nrow = 2)) +
  scale_x_continuous(breaks = 0:K) +
  labs(title = "Four processes, four ordinary tables", x = "detections out of six",
       y = "proportion of sites",
       subtitle = "nothing here announces which model is right") +
  theme_te()

nv_rn <- tab(d_rn, K)
ks <- c("occ", "rn", "mix", "fp")
knm <- c("occupancy", "Royle-Nichols", "mixture", "false-positive")
df_f <- do.call(rbind, lapply(seq_along(ks), function(i) {
  data.frame(d = 0:K, count = R * pv[[ks[i]]](fitn(ks[i], nv_rn, K)$par, K),
             model = knm[i])
}))
pf <- ggplot() +
  geom_col(data = data.frame(d = 0:K, count = nv_rn), aes(d, count),
           fill = te_sage, alpha = 0.5, width = 0.75) +
  geom_line(data = df_f, aes(d, count, colour = model), linewidth = 0.6) +
  scale_colour_manual(values = c("occupancy" = te_rust,
                                 "Royle-Nichols" = te_forest,
                                 "mixture" = te_gold, "false-positive" = "grey55")) +
  guides(colour = guide_legend(nrow = 2)) +
  scale_x_continuous(breaks = 0:K) +
  labs(title = "Four models, one abundance world", x = "detections out of six",
       y = "sites", subtitle = "bars: observed. the curves nearly coincide") +
  theme_te()
two_panel(pw, pf)

## ---- gof ----
X2f <- function(nvec, th, k, K) {
  e <- sum(nvec) * pv[[k]](th, K)
  sum((nvec - e)^2 / pmax(e, 1e-8))
}
gofn <- function(k, nvec, K, B, seed) {
  f <- fitn(k, nvec, K); obs <- X2f(nvec, f$par, k, K); Rn <- sum(nvec)
  set.seed(seed)
  bs <- replicate(B, {
    nb <- as.numeric(rmultinom(1, Rn, pv[[k]](f$par, K)))
    X2f(nb, fitn(k, nb, K)$par, k, K)
  })
  list(fit = f, p = mean(bs >= obs), chat = obs / mean(bs))
}
cal <- sapply(1:20, function(i) {
  set.seed(60000L + i); zz <- rbinom(R, 1L, 0.55); dd <- rbinom(R, K, zz * 0.30)
  gofn("occ", tab(dd, K), K, 150, 9275)$p
})

## ---- four ----
res <- do.call(rbind, lapply(worlds, function(w) {
  nv <- tab(w$d, K); g <- gofn("occ", nv, K, 200, 9275); th <- g$fit$par
  se <- sqrt(diag(solve(optimHess(th, nl$occ, nvec = nv, K = K))))[1]
  sei <- se * sqrt(max(g$chat, 1))
  data.frame(world = w$name, truth = w$truth, naive = mean(w$d > 0),
             psi = plogis(th[1]), p = plogis(th[2]), gof = g$p, chat = g$chat,
             lo = plogis(th[1] - 1.96 * sei), hi = plogis(th[1] + 1.96 * sei))
}))
res$covers <- res$lo <= res$truth & res$truth <= res$hi
rn_row <- res[res$world == "abundance", ]

## ---- aicmat ----
aic_tab <- do.call(rbind, lapply(worlds, function(w) {
  nv <- tab(w$d, K)
  f <- lapply(c("occ", "rn", "mix", "fp"), fitn, nvec = nv, K = K)
  a <- sapply(f, `[[`, "aic")
  psis <- c(plogis(f[[1]]$par[1]), 1 - exp(-exp(f[[2]]$par[1])),
            plogis(f[[3]]$par[1]), plogis(f[[4]]$par[1]))
  data.frame(world = w$name, truth = w$truth,
             pick = c("occupancy", "Royle-Nichols", "mixture",
                      "false-positive")[which.min(a)],
             psi_pick = psis[which.min(a)],
             best = min(a), gap = sort(a)[2] - min(a))
}))

## ---- nesting ----
nv_std <- tab(d_std, K)
f_o <- fitn("occ", nv_std, K); f_f <- fitn("fp", nv_std, K)
p10_fitted <- plogis(f_f$par[3])
nll_diff <- abs(f_o$nll - f_f$nll)

## ---- mc ----
M <- 150L
psi_true <- 1 - exp(-2.0)
mc <- t(sapply(1:M, function(m) {
  set.seed(80000L + m); NN <- rpois(R, 2.0); dd <- rbinom(R, K, 1 - (1 - 0.12)^NN)
  nv <- tab(dd, K)
  g <- gofn("occ", nv, K, 100, 9275); th <- g$fit$par
  se <- sqrt(diag(solve(optimHess(th, nl$occ, nvec = nv, K = K))))[1]
  fits <- sapply(c("occ", "rn", "mix", "fp"), function(k) fitn(k, nv, K)$aic)
  c(psi = plogis(th[1]), gofp = g$p, chat = g$chat,
    cov_plain = as.numeric(abs(th[1] - qlogis(psi_true)) < 1.96 * se),
    cov_infl = as.numeric(abs(th[1] - qlogis(psi_true)) <
                          1.96 * se * sqrt(max(g$chat, 1))),
    pick = as.numeric(which.min(fits)))
}))
pass <- mean(mc[, "gofp"] > 0.05)
trap <- mean(mc[, "gofp"] > 0.05 & mc[, "cov_plain"] == 0)

## ---- fig-gof ----
res$lab <- factor(res$world, levels = res$world)
p1 <- ggplot(res, aes(lab, chat, fill = chat > 1)) +
  geom_col(width = 0.62) +
  geom_hline(yintercept = 1, linetype = "dashed", colour = te_ink, linewidth = 0.4) +
  scale_fill_manual(values = c("FALSE" = te_sage, "TRUE" = te_rust),
                    labels = c("passes", "fires")) +
  labs(title = "The test misses the case that matters", x = NULL,
       y = "overdispersion factor",
       subtitle = "the standard model is wrong in three of these four") +
  theme_te() + theme(axis.text.x = element_text(angle = 20, hjust = 1))

df_mc <- data.frame(psi = mc[, "psi"],
                    gof = ifelse(mc[, "gofp"] > 0.05, "fit accepted",
                                 "fit rejected"))
p2 <- ggplot(df_mc, aes(psi, fill = gof)) +
  geom_histogram(bins = 24, alpha = 0.75, position = "stack") +
  geom_vline(xintercept = psi_true, linetype = "dashed", colour = te_ink,
             linewidth = 0.4) +
  scale_fill_manual(values = c("fit accepted" = te_gold,
                               "fit rejected" = te_forest)) +
  labs(title = "Half of these passed the check", x = "estimated occupancy",
       y = "replicates", subtitle = "dashed: the truth") +
  theme_te()
two_panel(p1, p2)
