# The robust design and temporary emigration
# https://tidyecology.com/posts/robust-design-temporary-emigration/
#
# 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)), "}$")
}

## ---- sim ----
sim_rd <- function(N, Tp, K, phi, g_io, g_oo, p, seed, g_init = NULL) {
  set.seed(seed)
  if (is.null(g_init)) g_init <- g_io
  st <- ifelse(runif(N) < g_init, 2L, 1L)        # 1 = in, 2 = out, 3 = dead
  S <- matrix(0L, N, Tp); D <- matrix(0L, N, Tp)
  for (t in seq_len(Tp)) {
    if (t > 1) {
      surv <- (st != 3L) & (runif(N) < phi)
      nxt <- rep(3L, N); u <- runif(N)
      i1 <- surv & st == 1L; i2 <- surv & st == 2L
      nxt[i1] <- ifelse(u[i1] < g_io, 2L, 1L)    # in  -> out with prob g_io
      nxt[i2] <- ifelse(u[i2] < g_oo, 2L, 1L)    # out -> out with prob g_oo
      st <- nxt
    }
    S[, t] <- st
    for (j in seq_len(K)) D[, t] <- D[, t] + as.integer(st == 1L & runif(N) < p)
  }
  list(D = D, S = S, alive = colSums(S != 3L), avail = colSums(S == 1L))
}

Tp <- 5; K <- 4; N <- 400; phi <- 0.85; gam <- 0.30; p <- 0.32
pin <- 1 - (1 - p)^K          # detection inside one primary period
pstar <- (1 - gam) * pin      # what a single collapsed column actually measures
w  <- sim_rd(N, Tp, K, phi, gam, gam, p, seed = 2278)
D  <- w$D                     # counts: animals x primaries, each 0..K
Hc <- (D > 0) * 1L            # the same data, collapsed to presence/absence
rbind(alive = w$alive, available = w$avail, caught = colSums(Hc))

## ---- 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, fr = 1) {
  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 <- function(H, fr = NULL) {
  ok <- rowSums(H) > 0; S <- hsum(H[ok, , drop = FALSE])
  fr <- if (is.null(fr)) 1 else fr[ok]
  o <- optim(c(qlogis(0.7), qlogis(0.3)), cjs_nll, S = S, fr = fr, method = "BFGS",
             control = list(reltol = 1e-14, maxit = 5000), hessian = TRUE)
  V <- tryCatch(solve(o$hessian), error = function(e) matrix(NA, 2, 2))
  se <- sqrt(abs(diag(V))); ph <- plogis(o$par[1])
  list(phi = ph, p = plogis(o$par[2]), se_phi = se[1] * ph * (1 - ph))
}
cj <- fit_cjs(Hc)

## ---- m0 ----
fit_m0 <- function(d, K) {
  d <- d[d > 0]; n <- length(d); sx <- sum(d)
  nll <- function(par) {
    Nn <- n + exp(par[1]); pp <- plogis(par[2])
    -(lgamma(Nn + 1) - lgamma(Nn - n + 1) + (Nn - n) * K * log(1 - pp) +
        sx * log(pp) + (n * K - sx) * log(1 - pp))
  }
  o <- optim(c(log(0.3 * n + 1), qlogis(0.4)), nll, method = "BFGS",
             control = list(reltol = 1e-12, maxit = 5000))
  c(N = n + exp(o$par[1]), p = plogis(o$par[2]))
}
m0 <- t(sapply(1:Tp, function(t) fit_m0(D[, t], K)))
m0_ratio <- m0[, "N"] / w$alive
round(rbind(N_hat = m0[, "N"], alive = w$alive, ratio = m0_ratio), 3)

## ---- rd ----
rd_nll <- function(par, D, K, markov, wt = NULL, fcap = NULL) {
  phi <- plogis(par[1]); g_io <- plogis(par[2])
  g_oo <- if (markov) plogis(par[3]) else g_io
  p <- plogis(par[length(par)])
  Tp <- ncol(D); pk <- 1 - (1 - p)^K
  Tm <- matrix(c(phi * (1 - g_io), phi * g_io, 1 - phi,
                 phi * (1 - g_oo), phi * g_oo, 1 - phi,
                 0, 0, 1), 3, 3, byrow = TRUE)
  E1 <- dbinom(0:K, K, p); n <- nrow(D)
  if (is.null(wt)) wt <- rep(1, n)
  f <- if (is.null(fcap)) max.col(D > 0, ties.method = "first") else fcap
  ll <- log(E1[D[cbind(seq_len(n), f)] + 1] / pk)     # conditional on first capture
  for (ff in unique(f)) {
    if (ff == Tp) next
    idx <- which(f == ff)
    al <- matrix(0, length(idx), 3); al[, 1] <- 1
    for (t in (ff + 1):Tp) {
      d <- D[idx, t]; z <- as.numeric(d == 0)
      al <- (al %*% Tm) * cbind(E1[d + 1], z, z)
    }
    ll[idx] <- ll[idx] + log(rowSums(al))
  }
  v <- -sum(wt * ll); if (!is.finite(v)) 1e10 else v
}
fit_rd <- function(D, K, markov = FALSE, wt = NULL, hess = FALSE) {
  if (is.null(wt)) D <- D[rowSums(D) > 0, , drop = FALSE]
  fc <- max.col(D > 0, ties.method = "first")
  st <- if (markov) rep(c(qlogis(.7), qlogis(.3)), c(1, 3)) else c(qlogis(.7), qlogis(.3), qlogis(.3))
  o <- optim(st, rd_nll, D = D, K = K, markov = markov, wt = wt, fcap = fc,
             method = "BFGS", control = list(maxit = 8000, reltol = 1e-13), hessian = hess)
  np <- length(o$par)
  r <- list(phi = plogis(o$par[1]), g_io = plogis(o$par[2]),
            g_oo = if (markov) plogis(o$par[3]) else plogis(o$par[2]),
            p = plogis(o$par[np]), nll = o$value, aic = 2 * o$value + 2 * np)
  if (hess) {
    V <- tryCatch(solve(o$hessian), error = function(e) matrix(NA, np, np))
    s <- sqrt(abs(diag(V))); d <- plogis(o$par) * (1 - plogis(o$par))
    r$se_phi <- s[1] * d[1]; r$se_g <- s[2] * d[2]; r$se_p <- s[np] * d[np]
  }
  r
}
Df <- D[rowSums(D) > 0, , drop = FALSE]
r1 <- fit_rd(Df, K, markov = FALSE, hess = TRUE)

## ---- ht ----
pk  <- 1 - (1 - r1$p)^K
nt  <- colSums(D > 0)
Nht <- nt / ((1 - r1$g_io) * pk)
ht_ratio <- mean(Nht / w$alive)
round(Nht, 1)

## ---- fig-nt ----
df_nt <- data.frame(
  primary = rep(1:Tp, 4),
  value = c(w$alive, Nht, m0[, "N"], nt),
  kind = rep(c("alive (truth)", "robust design", "closed model per primary",
               "raw count"), each = Tp))
ggplot(df_nt, aes(primary, value, colour = kind, shape = kind)) +
  geom_line(data = subset(df_nt, kind == "alive (truth)"), linewidth = 0.9) +
  geom_point(size = 3) +
  scale_colour_manual(values = c(`alive (truth)` = te_ink, `robust design` = te_forest,
                                 `closed model per primary` = te_gold,
                                 `raw count` = te_rust)) +
  scale_y_continuous(limits = c(0, 430)) +
  labs(title = "Three estimates, three different populations",
       subtitle = sprintf("Five primaries of four nights; survival %.2f, temporary emigration %.2f",
                          phi, gam),
       x = "Primary period", y = "Number of animals") +
  theme_te()

## ---- exact ----
all_rows <- function(Tp, K) as.matrix(expand.grid(rep(list(0:K), Tp))[, Tp:1])
rd_pd <- function(U, phi, g_io, g_oo, p, K, g_init) {
  Tm <- matrix(c(phi * (1 - g_io), phi * g_io, 1 - phi,
                 phi * (1 - g_oo), phi * g_oo, 1 - phi, 0, 0, 1), 3, 3, byrow = TRUE)
  E1 <- dbinom(0:K, K, p); d0 <- c(1 - g_init, g_init, 0)
  z <- (U == 0) * 1; out <- numeric(nrow(U))
  for (i in seq_len(nrow(U))) {
    al <- d0 * c(E1[U[i, 1] + 1], z[i, 1], z[i, 1])
    for (t in 2:ncol(U)) al <- as.vector(al %*% Tm) * c(E1[U[i, t] + 1], z[i, t], z[i, t])
    out[i] <- sum(al)
  }
  out
}
U   <- all_rows(Tp, K)
pdA <- rd_pd(U, phi, gam, gam, p, K, g_init = gam)
mass <- sum(pdA) - 1
kp  <- rowSums(U) > 0 & pdA > 1e-13
fr  <- 1e6 * pdA[kp] / sum(pdA[kp])
ex  <- fit_rd(U[kp, , drop = FALSE], K, markov = FALSE, wt = fr)
c(phi = ex$phi - phi, gamma = ex$g_io - gam, p = ex$p - p)

## ---- fp-guard-1 ----
stopifnot(abs(mass) < 1e-10)

## ---- markov ----
all_hist <- function(k) as.matrix(expand.grid(rep(list(0:1), k))[, k:1])
rd_ph <- function(A, phi, g_io, g_oo, ps, g_init) {
  Tm <- matrix(c(phi * (1 - g_io), phi * g_io, 1 - phi,
                 phi * (1 - g_oo), phi * g_oo, 1 - phi, 0, 0, 1), 3, 3, byrow = TRUE)
  d0 <- c(1 - g_init, g_init, 0); out <- numeric(nrow(A))
  for (i in seq_len(nrow(A))) {
    em <- function(t, s) if (s == 1) (if (A[i, t] == 1) ps else 1 - ps) else as.numeric(A[i, t] == 0)
    al <- d0 * c(em(1, 1), em(1, 2), em(1, 3))
    for (t in 2:ncol(A)) al <- as.vector(al %*% Tm) * c(em(t, 1), em(t, 2), em(t, 3))
    out[i] <- sum(al)
  }
  out
}
A    <- all_hist(Tp)
g_oo <- 0.72                      # away animals stay away
g_st <- gam / (1 - g_oo + gam)    # stationary fraction away
cjs_rand <- fit_cjs(A, 1e6 * rd_ph(A, phi, gam, gam,  pin, g_init = gam))
cjs_mark <- fit_cjs(A, 1e6 * rd_ph(A, phi, gam, g_oo, pin, g_init = g_st))
c(random = cjs_rand$phi, markovian = cjs_mark$phi, truth = phi)

## ---- markov-rd ----
pdM <- rd_pd(U, phi, gam, g_oo, p, K, g_init = g_st)
kpM <- rowSums(U) > 0 & pdM > 1e-13
frM <- 1e6 * pdM[kpM] / sum(pdM[kpM]); UM <- U[kpM, , drop = FALSE]
rd_wrong <- fit_rd(UM, K, markov = FALSE, wt = frM)
rd_right <- fit_rd(UM, K, markov = TRUE,  wt = frM)
c(rd_random = rd_wrong$phi, rd_markov = rd_right$phi, naive_cjs = cjs_mark$phi)

## ---- het ----
rd_pd_mix <- function(U, phi, g_io, g_oo, pv, wv, K, g_init) {
  o <- numeric(nrow(U))
  for (m in seq_along(pv)) o <- o + wv[m] * rd_pd(U, phi, g_io, g_oo, pv[m], K, g_init)
  o
}
pv <- c(0.15, 0.49); wv <- c(0.5, 0.5)
pdB <- rd_pd_mix(U, phi, gam, gam, pv, wv, K, g_init = gam)
kpB <- rowSums(U) > 0 & pdB > 1e-13
frB <- 1e6 * pdB[kpB] / sum(pdB[kpB])
het <- fit_rd(U[kpB, , drop = FALSE], K, markov = FALSE, wt = frB)

p_true_in <- sum(wv * (1 - (1 - pv)^K))   # true chance of catching a present animal
p_fit_in  <- 1 - (1 - het$p)^K            # what the fitted model believes
n_ratio   <- ((1 - gam) * p_true_in) / ((1 - het$g_io) * p_fit_in)
round(c(phi = het$phi, gamma = het$g_io, p = het$p), 4)

## ---- sweep ----
Nseq <- c(400, 800, 1600, 3200, 6400)
sw <- t(sapply(Nseq, function(NN) {
  PH <- NM <- numeric(100)
  for (b in 1:100) {
    ww <- sim_rd(NN, Tp, K, phi, gam, g_oo, p, seed = 70000 + b, g_init = g_st)
    DD <- ww$D[rowSums(ww$D) > 0, , drop = FALSE]
    f <- fit_rd(DD, K, markov = TRUE)
    PH[b] <- f$phi; NM[b] <- nrow(DD)
  }
  c(N = NN, marked = mean(NM), rmse = sqrt(mean((PH - phi)^2)), boundary = mean(PH > 0.99))
}))
round(sw, 4)

## ---- fig-sweep ----
df_sw <- data.frame(marked = sw[, "marked"], rmse = sw[, "rmse"],
                    lab = sprintf("%.0f%% at the boundary", 100 * sw[, "boundary"]))
ggplot(df_sw, aes(marked, rmse)) +
  geom_line(colour = te_forest, linewidth = 0.9) +
  geom_point(colour = te_forest, size = 3) +
  geom_text(aes(label = lab), vjust = c(-1.1, -1.1, -1.1, -1.1, 2),
            hjust = c(0, 0, 0, 0, 1),
            size = 3.4, colour = te_muted) +
  scale_x_log10(breaks = round(sw[, "marked"])) +
  scale_y_continuous(limits = c(0, 0.115)) +
  labs(title = "Consistent, and still not usable",
       subtitle = "Markovian robust design; 100 studies per size, true survival 0.85",
       x = "Marked animals (log scale)", y = "Survival RMSE") +
  theme_te()
