# Pradel seniority: growth rate from reverse time
# https://tidyecology.com/posts/pradel-reverse-time-seniority/
#
# 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-15

## ---- setup ----
library(ggplot2)

te_ink <- "#16241d"; te_forest <- "#275139"; te_gold <- "#c9b458"
te_rust <- "#b5534e"; te_sage <- "#93a87f"; te_line <- "#dad9ca"; te_muted <- "#5d6b61"

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(
          plot.background  = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA),
          text = element_text(colour = te_ink),
          plot.title = element_text(face = "bold", colour = te_ink),
          plot.subtitle = element_text(colour = te_muted, size = rel(0.9)),
          axis.text = element_text(colour = te_muted),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          legend.position = "top", legend.title = element_blank())
}

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

## ---- world ----
k <- 7; N1 <- 150; phi <- 0.75; lam <- 1.10; p <- 0.32
gam_true <- phi / lam
Bt   <- N1 * lam^(0:(k - 2)) * (lam - phi)
beta <- c(N1, Bt) / (N1 + sum(Bt))
Nsup <- round(N1 + sum(Bt))
c(sum_beta = sum(beta), superpop = Nsup)

## ---- sim ----
sim_js <- function(N, beta, phi, p, seed, pf = p) {
  set.seed(seed); k <- length(beta)
  e <- sample.int(k, N, replace = TRUE, prob = beta)
  Alive <- matrix(FALSE, N, k)
  Alive[cbind(seq_len(N), e)] <- TRUE
  for (t in 2:k) Alive[, t] <- Alive[, t] | (Alive[, t - 1] & runif(N) < phi)
  H <- matrix(0L, N, k); seen <- rep(FALSE, N)
  for (t in seq_len(k)) {
    H[, t] <- as.integer(Alive[, t] & runif(N) < ifelse(seen, p, pf))
    seen <- seen | H[, t] == 1L
  }
  list(H = H, Alive = Alive)
}
d <- sim_js(Nsup, beta, phi, p, seed = 4277)
H <- d$H[rowSums(d$H) > 0, , drop = FALSE]
Nt_real <- colSums(d$Alive)

## ---- cjs ----
hsum <- function(H) {
  k <- ncol(H); idx <- col(H) * H; idx[idx == 0] <- NA
  list(f = suppressWarnings(apply(idx, 1, min, na.rm = TRUE)),
       l = suppressWarnings(apply(idx, 1, max, na.rm = TRUE)),
       s = rowSums(H), k = k)
}
chi_vec <- function(phi, p, k) {
  chi <- numeric(k); chi[k] <- 1
  for (j in (k - 1):1) chi[j] <- (1 - phi) + phi * (1 - p) * chi[j + 1]
  chi
}
cjs_nll <- function(par, S) {
  phi <- plogis(par[1]); p <- plogis(par[2]); chi <- chi_vec(phi, p, S$k)
  v <- -sum(log(phi^(S$l - S$f) * p^(S$s - 1) * (1 - p)^(S$l - S$f - S$s + 1) * chi[S$l]))
  if (!is.finite(v)) 1e10 else v
}
fit_cjs <- function(H) {
  S <- hsum(H[rowSums(H) > 0, , drop = FALSE])
  fit <- optim(c(qlogis(0.7), qlogis(0.3)), cjs_nll, S = S, method = "BFGS", hessian = TRUE)
  V <- tryCatch(solve(fit$hessian), error = function(e) matrix(NA, 2, 2))
  se <- sqrt(diag(V)); ph <- plogis(fit$par[1]); pd <- plogis(fit$par[2])
  list(phi = ph, p = pd, se_phi = se[1] * ph * (1 - ph), se_p = se[2] * pd * (1 - pd))
}

## ---- both ----
fwd <- fit_cjs(H)
rev <- fit_cjs(H[, k:1])
lam_hat <- fwd$phi / rev$phi

## ---- lambda ----
c(lambda_hat = lam_hat, truth = lam)

## ---- exact ----
all_hist <- function(k) as.matrix(expand.grid(rep(list(0:1), k))[, k:1])
popan_ph2 <- function(S, phi, pf, p, beta) {
  k <- S$k
  chi <- chi_vec(phi, p, k)
  nu <- numeric(k); nu[k] <- 1 - pf
  for (e in (k - 1):1) nu[e] <- (1 - pf) * ((1 - phi) + phi * nu[e + 1])
  x <- phi * (1 - pf); g <- numeric(k); g[1] <- beta[1]
  for (f in 2:k) g[f] <- x * g[f - 1] + beta[f]
  out <- numeric(length(S$s)); out[S$s == 0] <- sum(beta * nu)
  ok <- S$s > 0; f <- S$f[ok]; l <- S$l[ok]; s <- S$s[ok]
  out[ok] <- g[f] * pf * phi^(l - f) * p^(s - 1) * (1 - p)^(l - f - s + 1) * chi[l]
  out
}
cjs_nll_f <- function(par, S, fr) {
  phi <- plogis(par[1]); p <- plogis(par[2]); chi <- chi_vec(phi, p, S$k)
  v <- -sum(fr * log(phi^(S$l - S$f) * p^(S$s - 1) * (1 - p)^(S$l - S$f - S$s + 1) * chi[S$l]))
  if (!is.finite(v)) 1e10 else v
}
fit_cjs_f <- function(A, fr) {
  ok <- rowSums(A) > 0; S <- hsum(A[ok, , drop = FALSE])
  f <- optim(c(qlogis(.7), qlogis(.3)), cjs_nll_f, S = S, fr = fr[ok], method = "BFGS",
             control = list(reltol = 1e-14, maxit = 5000))
  list(phi = plogis(f$par[1]), p = plogis(f$par[2]))
}

A  <- all_hist(k);   S  <- hsum(A)
Ar <- A[, k:1];      Sr <- hsum(Ar)
M  <- 1e6
ph <- popan_ph2(S, phi, p, p, beta); fr <- M * ph
ex_f <- fit_cjs_f(A[S$s > 0, , drop = FALSE], fr[S$s > 0])
ex_r <- fit_cjs_f(Ar[Sr$s > 0, , drop = FALSE], fr[Sr$s > 0])
gap  <- ex_r$phi - gam_true

## ---- gradient ----
nu_vec <- function(phi, p, k) {
  nu <- numeric(k); nu[k] <- 1 - p
  for (e in (k - 1):1) nu[e] <- (1 - p) * ((1 - phi) + phi * nu[e + 1])
  nu
}
ent_vec <- function(phi, p, beta, k) {
  x <- phi * (1 - p); g <- numeric(k); g[1] <- beta[1]
  for (f in 2:k) g[f] <- x * g[f - 1] + beta[f]
  g
}
popan_ph <- function(S, phi, p, beta) {
  k <- S$k; chi <- chi_vec(phi, p, k); g <- ent_vec(phi, p, beta, k)
  ok <- S$s > 0; out <- numeric(length(S$s))
  out[!ok] <- sum(beta * nu_vec(phi, p, k))
  f <- S$f[ok]; l <- S$l[ok]; s <- S$s[ok]
  out[ok] <- g[f] * p * phi^(l - f) * p^(s - 1) * (1 - p)^(l - f - s + 1) * chi[l]
  out
}
popan_nll <- function(par, freq, S, n) {
  k <- S$k
  N <- n + exp(par[1]); phi <- plogis(par[2]); p <- plogis(par[3])
  bl <- c(0, par[4:(k + 2)]); beta <- exp(bl) / sum(exp(bl))
  ph <- popan_ph(S, phi, p, beta)
  P0 <- ph[S$s == 0]
  if (!is.finite(P0) || P0 <= 0 || P0 >= 1) return(1e10)
  pv <- ph[S$s > 0]; if (any(!is.finite(pv)) || any(pv <= 0)) return(1e10)
  v <- -(lgamma(N + 1) - lgamma(N - n + 1) + (N - n) * log(P0) + sum(freq * log(pv)))
  if (!is.finite(v)) 1e10 else v
}
fit_popan_f <- function(A, fr, n) {
  S <- hsum(A); k <- S$k
  f <- optim(c(log(0.5 * n), qlogis(.7), qlogis(.3), rep(0, k - 1)), popan_nll,
             freq = fr[S$s > 0], S = S, n = n, method = "BFGS",
             control = list(reltol = 1e-14, maxit = 8000))
  n + exp(f$par[1])
}

pht  <- popan_ph2(S, phi, 0.18, 0.45, beta); frt <- M * pht
tr_f <- fit_cjs_f(A[S$s > 0, , drop = FALSE], frt[S$s > 0])
tr_r <- fit_cjs_f(Ar[Sr$s > 0, , drop = FALSE], frt[Sr$s > 0])
tr_N <- fit_popan_f(A, frt, M * (1 - pht[S$s == 0]))
err  <- c(phi    = 100 * (tr_f$phi / phi - 1),
          gamma  = 100 * (tr_r$phi / gam_true - 1),
          lambda = 100 * ((tr_f$phi / tr_r$phi) / lam - 1),
          N      = 100 * (tr_N / M - 1))
round(err, 2)
fmt_pct <- function(x) ifelse(abs(x) < 0.005, "0.00%", sprintf("%+.2f%%", x))

## ---- fig-gradient ----
lab <- c(phi = "survival", gamma = "seniority", lambda = "growth rate",
         N = "superpopulation")
df_g <- data.frame(what = factor(lab[names(err)], levels = lab),
                   err = as.numeric(err),
                   band = c("conditions on first capture", "conditions on first capture",
                            "conditions on first capture", "models first capture"))
p_grad <- ggplot(df_g, aes(what, err, fill = band)) +
  geom_col(width = 0.62) +
  geom_hline(yintercept = 0, colour = te_ink, linewidth = 0.5) +
  geom_text(aes(label = fmt_pct(err),
                vjust = ifelse(err < 0, 1.5, -0.6)), size = 3.6, colour = te_ink) +
  scale_fill_manual(values = c(`conditions on first capture` = te_forest,
                               `models first capture` = te_rust)) +
  scale_y_continuous(limits = c(-58, 14)) +
  labs(title = "The same assumption, three levels of exposure",
       subtitle = "Exact asymptotic error, naive capture 0.18 against recapture 0.45",
       x = NULL, y = "Error in the probability limit") +
  theme_te()
p_grad

## ---- thumb ----
thumb_title <- paste(strwrap("Error in the probability limit by quantity", 46), collapse = "\n")
ggsave("thumbnail.png",
       p_grad + labs(title = thumb_title) +
         theme(plot.title = element_text(size = 13, face = "bold"),
               plot.subtitle = element_text(size = 9.5),
               plot.margin = margin(8, 14, 8, 8)),
       width = 7.5, height = 5.4, dpi = 100, bg = "#f5f4ee")

## ---- mc ----
LA <- SE <- numeric(200)
for (b in 1:200) {
  dd <- sim_js(Nsup, beta, phi, p, seed = 40000 + b)
  Hb <- dd$H[rowSums(dd$H) > 0, , drop = FALSE]
  f <- fit_cjs(Hb); r <- fit_cjs(Hb[, k:1])
  LA[b] <- f$phi / r$phi
  SE[b] <- LA[b] * sqrt((f$se_phi / f$phi)^2 + (r$se_phi / r$phi)^2)
}
mc_sd <- sd(LA); mean_se <- mean(SE)

## ---- boot ----
fit_cjs_ph <- function(H) {
  S <- hsum(H[rowSums(H) > 0, , drop = FALSE])
  o <- optim(c(qlogis(0.7), qlogis(0.3)), cjs_nll, S = S, method = "BFGS")
  plogis(o$par[1])
}
boot_lambda <- function(H, B, seed) {
  set.seed(seed); n <- nrow(H); kk <- ncol(H); out <- numeric(B)
  for (b in seq_len(B)) {
    Hb <- H[sample.int(n, n, replace = TRUE), , drop = FALSE]
    out[b] <- tryCatch(fit_cjs_ph(Hb) / fit_cjs_ph(Hb[, kk:1]), error = function(e) NA_real_)
  }
  out[is.finite(out)]
}
bl  <- boot_lambda(H, B = 500, seed = 5277)
qb  <- quantile(bl, c(0.025, 0.975))
del <- lam_hat * sqrt((fwd$se_phi / fwd$phi)^2 + (rev$se_phi / rev$phi)^2)
wald <- c(lam_hat - 1.96 * del, lam_hat + 1.96 * del)

## ---- fig-boot ----
df_b  <- data.frame(lam = bl)
df_ci <- data.frame(
  kind = c("percentile (bootstrap)", "Wald (delta method)"),
  lo   = c(qb[1], wald[1]), hi = c(qb[2], wald[2]), y = c(78, 88))
ggplot(df_b, aes(lam)) +
  geom_histogram(bins = 32, fill = te_forest, alpha = 0.8, colour = NA) +
  geom_vline(xintercept = lam, colour = te_ink, linetype = 2, linewidth = 0.8) +
  geom_errorbar(data = df_ci, aes(xmin = lo, xmax = hi, y = y, colour = kind),
                inherit.aes = FALSE, orientation = "y", width = 6, linewidth = 1.1) +
  annotate("text", x = lam + 0.004, y = 60, label = "truth", colour = te_ink,
           hjust = 0, size = 3.6, fontface = "bold") +
  scale_colour_manual(values = c(`percentile (bootstrap)` = te_gold,
                                 `Wald (delta method)` = te_rust)) +
  labs(title = "One dataset, two accounts of the same uncertainty",
       subtitle = sprintf("500 replicates; bootstrap SD %.4f against a Monte Carlo spread of %.4f",
                          sd(bl), mc_sd),
       x = "Population growth rate", y = "Bootstrap replicates") +
  theme_te()

## ---- cover ----
cvB <- cvD <- wB <- wD <- numeric(200)
for (b in 1:200) {
  dd <- sim_js(Nsup, beta, phi, p, seed = 40000 + b)
  Hb <- dd$H[rowSums(dd$H) > 0, , drop = FALSE]
  f <- fit_cjs(Hb); r <- fit_cjs(Hb[, k:1]); L <- f$phi / r$phi
  s <- L * sqrt((f$se_phi / f$phi)^2 + (r$se_phi / r$phi)^2)
  cvD[b] <- abs(L - lam) < 1.96 * s; wD[b] <- 2 * 1.96 * s
  qq <- quantile(boot_lambda(Hb, B = 200, seed = 90000 + b), c(0.025, 0.975))
  cvB[b] <- qq[1] <= lam && lam <= qq[2]; wB[b] <- diff(qq)
}
