# Bayesian closed capture-recapture
# https://tidyecology.com/posts/bayesian-closed-capture-recapture/
#
# 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

## ---- sim ----
set.seed(1873)
N.true <- 300L; K <- 6L; p.true <- 0.30
Y.full <- matrix(rbinom(N.true * K, 1, p.true), N.true, K)   # every animal
detected <- rowSums(Y.full) > 0
Yobs <- Y.full[detected, , drop = FALSE]                     # only the seen ones
nobs <- nrow(Yobs); never.true <- N.true - nobs

## ---- naive ----
naive.N <- nobs

## ---- augment ----
M <- 600L                                        # augmentation ceiling
Yaug <- rbind(Yobs, matrix(0L, M - nobs, K))
ysum <- rowSums(Yaug)                             # capture frequency per pseudo-animal
zero <- ysum == 0

## ---- gibbs ----
n.iter <- 12000L; burn <- 2000L
N.s <- numeric(n.iter); p.s <- numeric(n.iter)
z <- as.integer(ysum > 0); omega <- 0.5; pp <- 0.5
for (it in 1:n.iter) {
  sz <- sum(z)
  # inclusion probability: conjugate Beta
  omega <- rbeta(1, 1 + sz, 1 + M - sz)
  # detection over included animals: conjugate Beta
  succ <- sum(ysum[z == 1]); opp <- sz * K
  pp <- rbeta(1, 1 + succ, 1 + opp - succ)
  # inclusion indicators for zero-history pseudo-animals
  psi <- omega * (1 - pp)^K / (omega * (1 - pp)^K + (1 - omega))
  z[zero] <- rbinom(sum(zero), 1, psi)
  z[!zero] <- 1L
  N.s[it] <- sum(z); p.s[it] <- pp
}
keep <- (burn + 1):n.iter
N.post <- N.s[keep]; p.post <- p.s[keep]; unseen.post <- N.post - nobs

## ---- summary ----
N.med <- median(N.post); N.ci <- quantile(N.post, c(.025, .975))
p.med <- median(p.post); p.ci <- quantile(p.post, c(.025, .975))
un.med <- median(unseen.post); un.ci <- quantile(unseen.post, c(.025, .975))

## ---- fig-N ----
library(ggplot2)
ink <- "#16241d"; forest <- "#275139"; sage <- "#93a87f"; paper <- "#f5f4ee"
rust <- "#b5534e"; gold <- "#cda23f"; line <- "#dad9ca"
theme_te <- theme_minimal(base_size = 12) +
  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 = line, linewidth = 0.3),
        plot.title = element_text(colour = ink, face = "bold", size = 13),
        plot.subtitle = element_text(colour = "#5d6b61", size = 10),
        axis.title = element_text(colour = ink), axis.text = element_text(colour = "#46604a"),
        legend.position = "none")
ggplot(data.frame(N = N.post), aes(N)) +
  geom_histogram(aes(y = after_stat(density)), bins = 40, fill = sage, colour = paper, linewidth = 0.15) +
  geom_vline(xintercept = N.true, colour = rust, linewidth = 0.8) +
  geom_vline(xintercept = naive.N, colour = gold, linewidth = 0.8, linetype = "dashed") +
  labs(title = "Posterior population size from augmented capture histories",
       subtitle = "Red: true N. Gold dashed: naive count of distinct animals seen.",
       x = "Population size N", y = "Posterior density") + theme_te

## ---- fig-freq ----
obs.freq <- tabulate(rowSums(Yobs), K)
un.mean <- mean(unseen.post); un.lo <- quantile(unseen.post, .025); un.hi <- quantile(unseen.post, .975)
df2 <- data.frame(times = 0:K, count = c(un.mean, obs.freq),
                  lo = c(un.lo, obs.freq), hi = c(un.hi, obs.freq),
                  kind = c("estimated", rep("observed", K)))
ggplot(df2, aes(times, count, fill = kind)) +
  geom_col(width = 0.7) +
  geom_errorbar(data = subset(df2, kind == "estimated"),
                aes(ymin = lo, ymax = hi), width = 0.25, colour = ink, linewidth = 0.5) +
  geom_point(aes(x = 0, y = never.true), colour = rust, size = 2.5) +
  scale_fill_manual(values = c(estimated = gold, observed = forest)) +
  scale_x_continuous(breaks = 0:K) +
  labs(title = "Capture frequency, with the estimated never-seen class",
       subtitle = "Green: animals seen 1 to K times. Gold: posterior for the zero class. Red: truth.",
       x = "Times captured", y = "Number of animals") + theme_te
