# Bayesian Cormack-Jolly-Seber survival
# https://tidyecology.com/posts/bayesian-cjs-survival/
#
# 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-05-19

## ---- sim ----
set.seed(4816)
n.occ <- 6
marked <- rep(30, n.occ - 1)          # 30 newly marked at occasions 1..5
phi.true <- 0.72
p.true <- 0.42
N <- sum(marked)                       # total marked

CH <- matrix(0, N, n.occ)              # capture histories
f <- integer(N)                        # first-capture (marking) occasion
row <- 0
for (g in seq_along(marked)) for (k in seq_len(marked[g])) {
  row <- row + 1
  f[row] <- g
  CH[row, g] <- 1                      # marked and released
  alive <- TRUE
  for (t in (g + 1):n.occ) {
    if (alive) alive <- (runif(1) < phi.true)
    if (alive && runif(1) < p.true) CH[row, t] <- 1
  }
}
last <- apply(CH, 1, function(x) max(which(x == 1)))

## ---- naive ----
ever.recap <- sapply(1:N, function(i) any(CH[i, (f[i] + 1):n.occ] == 1))
naive.return <- mean(ever.recap)

## ---- gibbs ----
n.iter <- 15000L
burn <- 3000L
phi.s <- numeric(n.iter); p.s <- numeric(n.iter)
nalive <- matrix(0L, n.iter, n.occ)

phi <- 0.5; p <- 0.5; d <- last
for (it in 1:n.iter) {
  # draw latent last-alive occasion for each animal
  for (i in 1:N) {
    li <- last[i]
    if (li == n.occ) { d[i] <- n.occ; next }
    ts <- li:n.occ
    steps <- ts - li
    logw <- steps * log(phi) + steps * log(1 - p) +
            ifelse(ts < n.occ, log(1 - phi), 0)
    w <- exp(logw - max(logw))
    d[i] <- sample(ts, 1, prob = w)
  }
  # conjugate survival update: successes and one death per animal that dies
  phi <- rbeta(1, 1 + sum(d - f), 1 + sum(d < n.occ))
  # conjugate recapture update over alive, post-release occasions
  opp <- 0L; rec <- 0L
  for (i in 1:N) if (d[i] > f[i]) {
    idx <- (f[i] + 1):d[i]
    opp <- opp + length(idx)
    rec <- rec + sum(CH[i, idx])
  }
  p <- rbeta(1, 1 + rec, 1 + opp - rec)
  phi.s[it] <- phi; p.s[it] <- p
  for (t in 1:n.occ) nalive[it, t] <- sum(f <= t & d >= t)
}
keep <- (burn + 1):n.iter
phi.post <- phi.s[keep]; p.post <- p.s[keep]

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

## ---- fig-post ----
library(ggplot2); library(dplyr)
ink <- "#16241d"; forest <- "#275139"; 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"),
        strip.text = element_text(colour = ink, face = "bold"), legend.position = "none")

d1 <- bind_rows(
  data.frame(param = "Apparent survival (phi)", value = phi.post),
  data.frame(param = "Recapture probability (p)", value = p.post))
truth <- data.frame(param = c("Apparent survival (phi)", "Recapture probability (p)"),
                    x = c(phi.true, p.true))
naive.df <- data.frame(param = "Apparent survival (phi)", x = naive.return)
ggplot(d1, aes(value)) +
  geom_density(fill = forest, colour = forest, alpha = 0.35, linewidth = 0.5) +
  geom_vline(data = truth, aes(xintercept = x), colour = rust, linewidth = 0.7) +
  geom_vline(data = naive.df, aes(xintercept = x), colour = gold, linewidth = 0.7, linetype = "dashed") +
  facet_wrap(~param, scales = "free") +
  labs(title = "Posterior survival and recapture, with the naive return rate",
       subtitle = "Red: simulating truth. Gold dashed: naive apparent return rate (survival panel).",
       x = "probability", y = "Posterior density") +
  theme_te

## ---- fig-alive ----
library(tidyr)
sage <- "#93a87f"
n.det <- colSums(CH)
al.mean <- colMeans(nalive[keep, ])
al.lo <- apply(nalive[keep, ], 2, quantile, 0.025)
al.hi <- apply(nalive[keep, ], 2, quantile, 0.975)
d2 <- data.frame(occ = 1:n.occ, det = n.det, mean = al.mean, lo = al.lo, hi = al.hi)
ggplot(d2, aes(occ)) +
  geom_ribbon(aes(ymin = lo, ymax = hi), fill = sage, alpha = 0.35) +
  geom_line(aes(y = mean), colour = forest, linewidth = 0.8) +
  geom_point(aes(y = mean), colour = forest, size = 2) +
  geom_col(aes(y = det), fill = ink, width = 0.18) +
  scale_x_continuous(breaks = 1:n.occ) +
  labs(title = "Latent alive individuals versus detections per occasion",
       subtitle = "Bars: individuals detected. Line and band: posterior alive count.",
       x = "Occasion", y = "Number of individuals") +
  theme_te
