# Lost collar signals and informative censoring
# https://tidyecology.com/posts/lost-signals-and-informative-censoring/
#
# 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

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

te_paper  <- "#f5f4ee"
te_ink    <- "#16241d"
te_body   <- "#2c3a31"
te_forest <- "#275139"
te_rust   <- "#b5534e"
te_gold   <- "#c9b458"
te_line   <- "#dad9ca"

theme_datasheet <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.background  = element_rect(fill = te_paper, colour = NA),
          panel.background = element_rect(fill = te_paper, colour = NA),
          panel.grid.major = element_line(colour = te_line, linewidth = 0.3),
          panel.grid.minor = element_blank(),
          text             = element_text(colour = te_body),
          plot.title       = element_text(colour = te_ink, face = "bold"),
          plot.subtitle    = element_text(colour = te_body),
          axis.text        = element_text(colour = te_body),
          strip.text       = element_text(colour = te_ink, face = "bold"))
}

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

## ---- design ----
t_end   <- 730                      # administrative end of the study, days
hz_win  <- 0.0022                   # daily death hazard, winter
hz_sum  <- 0.0006                   # daily death hazard, summer
bat_shp <- 5                        # Weibull shape of collar battery life
bat_scl <- 520                      # Weibull scale, the nominal life in days
cut_frac <- 0.6                     # field rule: losses before this share of nominal life
n_animal <- 120                     # collared animals per study
n_rep    <- 400                     # simulated studies per cell

is_winter <- function(d) { r <- d %% 365; r < 90 | r >= 300 }
day_mid <- seq_len(t_end) - 0.5
cum_win <- c(0, cumsum(is_winter(day_mid)))
cum_haz <- c(0, cumsum(ifelse(is_winter(day_mid), hz_win, hz_sum)))
win_365 <- cum_win[366]
S1_true <- exp(-cum_haz[366])       # true one-year survival

winter_days <- function(tt) {
  f <- pmin(floor(tt), t_end - 1)
  cum_win[f + 1] + (tt - f) * is_winter(f + 0.5)
}

sim_study <- function(n, q, shp = bat_shp, scl = bat_scl, p_early = 0, early_mean = 60) {
  u  <- rexp(n)
  td <- approx(cum_haz, 0:t_end, xout = u, rule = 2, ties = "ordered")$y
  td[u >= max(cum_haz)] <- Inf
  tb <- rweibull(n, shp, scl)
  if (p_early > 0) {
    early <- runif(n) < p_early
    tb[early] <- pmin(tb[early], rexp(sum(early), 1 / early_mean))
  }
  tt <- pmin(td, tb, t_end)
  fate <- ifelse(tt == t_end, "end",
          ifelse(td < tb, ifelse(runif(n) < q, "lost", "dead"), "lost"))
  list(t = tt, fate = fate, tb = tb, hidden = td < tb & fate == "lost")
}

## ---- estimators ----
km_at <- function(tt, ev, at = 365) {
  o <- order(tt, -ev); tt <- tt[o]; ev <- ev[o]
  at_risk <- length(tt) - seq_along(tt) + 1
  k <- ev & tt <= at
  ut <- unique(tt[k])
  if (!length(ut)) return(c(S = 1, lo = 1, hi = 1))
  d_n <- tabulate(match(tt[k], ut), length(ut)); r_n <- at_risk[match(ut, tt)]
  S <- prod(1 - d_n / r_n); v <- sum(d_n / (r_n * (r_n - d_n)))
  if (S <= 0 || S >= 1) return(c(S = S, lo = S, hi = S))
  se <- sqrt(v) / abs(log(S)); lS <- log(-log(S))
  c(S = S, lo = exp(-exp(lS + 1.96 * se)), hi = exp(-exp(lS - 1.96 * se)))
}

nll_cr <- function(p, W, U, dd, ll, wi, hb) {
  hw <- exp(p[1]); hs <- exp(p[2]); q <- plogis(p[3])
  h <- ifelse(wi, hw, hs); den <- q * h + hb
  -(-sum(W) * hw - sum(U) * hs + sum(dd) * log(1 - q) + sum(log(h[dd])) + sum(log(den[ll])))
}
grad_cr <- function(p, W, U, dd, ll, wi, hb) {
  hw <- exp(p[1]); hs <- exp(p[2]); q <- plogis(p[3])
  h <- ifelse(wi, hw, hs); den <- q * h + hb
  -c(-sum(W) * hw + sum(dd & wi) + sum((q * h * wi / den)[ll]),
     -sum(U) * hs + sum(dd & !wi) + sum((q * h * (!wi) / den)[ll]),
     -q * sum(dd) + sum((h * q * (1 - q) / den)[ll]))
}
fit_cr <- function(D, shp, scl, ci = FALSE) {
  W <- winter_days(D$t); U <- D$t - W; wi <- is_winter(D$t)
  dd <- D$fate == "dead"; ll <- D$fate == "lost"
  hb <- (shp / scl) * (D$t / scl)^(shp - 1)          # bench battery hazard
  o <- optim(c(log(0.001), log(0.001), 0), nll_cr, grad_cr, W = W, U = U,
             dd = dd, ll = ll, wi = wi, hb = hb, method = "BFGS")
  H1 <- win_365 * exp(o$par[1]) + (365 - win_365) * exp(o$par[2])
  out <- c(S = exp(-H1), q = plogis(o$par[3]), conv = o$convergence, lo = NA, hi = NA)
  if (ci) {
    hess <- optimHess(o$par, nll_cr, grad_cr, W = W, U = U, dd = dd, ll = ll, wi = wi, hb = hb)
    vc <- tryCatch(solve(hess), error = function(e) matrix(NA, 3, 3))
    g <- c(win_365 * exp(o$par[1]), (365 - win_365) * exp(o$par[2]), 0) / H1
    se <- sqrt(drop(t(g) %*% vc %*% g))
    out[c("lo", "hi")] <- exp(-H1 * exp(c(1.96, -1.96) * se))
  }
  out
}
rule_S <- function(D, nominal, frac = cut_frac)
  km_at(D$t, D$fate == "dead" | (D$fate == "lost" & D$t < frac * nominal))

## ---- one-study ----
set.seed(4120)
D1 <- sim_study(n_animal, q = 0.3)
n_dead <- sum(D1$fate == "dead"); n_lost <- sum(D1$fate == "lost")
n_hidden <- sum(D1$hidden); n_batt <- n_lost - n_hidden; n_end <- sum(D1$fate == "end")
ex_km <- km_at(D1$t, D1$fate == "dead")
sv <- summary(survfit(Surv(D1$t, D1$fate == "dead") ~ 1, conf.type = "log-log"), times = 365)
km_gap <- max(abs(ex_km - c(sv$surv, sv$lower, sv$upper)))
ex_bound <- km_at(D1$t, D1$fate != "end")[["S"]]
ex_rule  <- rule_S(D1, bat_scl)[["S"]]
ex_mle   <- fit_cr(D1, bat_shp, bat_scl, ci = TRUE)

## ---- q-grid ----
q_grid <- c(0, 0.1, 0.3, 0.5)
mult_grid <- c(0.7, 0.8, 0.9, 1, 1.1, 1.2, 1.3) # bench scale over true scale
frac_grid <- c(0.4, 0.5, 0.6, 0.7, 0.8)

one_study <- function(n, q, scl = bat_scl, mult = mult_grid, p_early = 0, fracs = frac_grid) {
  D <- sim_study(n, q, scl = scl, p_early = p_early)
  k <- km_at(D$t, D$fate == "dead")
  b <- km_at(D$t, D$fate != "end")
  r <- c(km = k[["S"]], km_cov = k[["lo"]] <= S1_true & S1_true <= k[["hi"]],
         bound = b[["S"]], bracket = b[["lo"]] <= S1_true & S1_true <= k[["hi"]],
         width = k[["hi"]] - b[["lo"]],
         q_real = sum(D$hidden) / max(1, sum(D$hidden | D$fate == "dead")))
  for (f in fracs) r[paste0("frac_", f)] <- rule_S(D, scl, f)[["S"]]
  for (m in mult) {
    z <- fit_cr(D, bat_shp, m * scl, ci = m == 1)
    r[paste0("S_", m)] <- z[["S"]]; r[paste0("q_", m)] <- z[["q"]]
    r[paste0("conv_", m)] <- z[["conv"]]
    r[paste0("rule_", m)] <- rule_S(D, m * scl)[["S"]]
    if (m == 1) r["mle_cov"] <- z[["lo"]] <= S1_true & S1_true <= z[["hi"]]
  }
  r
}
set.seed(20918)
t_grid <- system.time(
  grid_res <- lapply(q_grid, function(q) t(replicate(n_rep, one_study(n_animal, q))))
)[["elapsed"]]
names(grid_res) <- q_grid

rmse <- function(x) sqrt(mean((x - S1_true)^2))
mcse_rmse <- function(x) sd((x - S1_true)^2) / (2 * rmse(x) * sqrt(length(x)))
col_stat <- function(q, col, fun = mean) fun(grid_res[[as.character(q)]][, col])

km_tab <- data.frame(q = q_grid,
  km = sapply(q_grid, col_stat, col = "km"),
  closed = S1_true^(1 - q_grid),
  bound = sapply(q_grid, col_stat, col = "bound"),
  rule = sapply(q_grid, col_stat, col = "rule_1"),
  mle = sapply(q_grid, col_stat, col = "S_1"),
  km_cov = sapply(q_grid, col_stat, col = "km_cov"),
  mle_cov = sapply(q_grid, col_stat, col = "mle_cov"),
  q_hat = sapply(q_grid, col_stat, col = "q_1"),
  q_real = sapply(q_grid, col_stat, col = "q_real"))
km_formula_gap <- max(abs(km_tab$km - km_tab$closed))
max_mcse_mean <- max(sapply(q_grid, function(q) sapply(c("km", "S_1", "rule_1"),
  function(cc) sd(grid_res[[as.character(q)]][, cc]) / sqrt(n_rep))))
n_nonconv <- sum(sapply(grid_res, function(M) sum(M[, grep("^conv_", colnames(M))] != 0)))
round(km_tab, 3)

## ---- fig-km-bias ----
km_long <- rbind(
  data.frame(q = q_grid, est = km_tab$km, method = "Kaplan-Meier, losses censored"),
  data.frame(q = q_grid, est = km_tab$bound, method = "all losses as deaths"),
  data.frame(q = q_grid, est = km_tab$rule, method = "60 per cent rule"),
  data.frame(q = q_grid, est = km_tab$mle, method = "likelihood, true battery curve"))
km_long$method <- factor(km_long$method, levels = unique(km_long$method))
q_fine <- seq(0, 0.5, by = 0.01)
ggplot(km_long, aes(q, est, colour = method)) +
  geom_hline(yintercept = S1_true, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_line(data = data.frame(q = q_fine, est = S1_true^(1 - q_fine)),
            aes(q, est), inherit.aes = FALSE, colour = te_ink, linetype = "dotted", linewidth = 0.7) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.4) +
  scale_colour_manual(values = c(te_rust, te_ink, te_gold, te_forest), name = NULL) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "share of deaths that silence the collar (q)", y = "mean estimated one-year survival",
       title = "Hidden deaths lift Kaplan-Meier along a closed form",
       subtitle = "dashed: true survival; dotted: S^(1 - q)") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- bench ----
bench_long <- do.call(rbind, lapply(q_grid, function(q) {
  M <- grid_res[[as.character(q)]]
  rbind(data.frame(q = q, mult = mult_grid, method = "likelihood",
                   rmse = sapply(mult_grid, function(m) rmse(M[, paste0("S_", m)])),
                   mean = sapply(mult_grid, function(m) mean(M[, paste0("S_", m)]))),
        data.frame(q = q, mult = mult_grid, method = "60 per cent rule",
                   rmse = sapply(mult_grid, function(m) rmse(M[, paste0("rule_", m)])),
                   mean = sapply(mult_grid, function(m) mean(M[, paste0("rule_", m)]))))
}))
km_rmse <- sapply(q_grid, function(q) rmse(grid_res[[as.character(q)]][, "km"]))
names(km_rmse) <- q_grid
bget <- function(q, m, meth, what = "rmse")
  bench_long[[what]][bench_long$q == q & bench_long$mult == m & bench_long$method == meth]
# first optimistic bench multiplier at which the likelihood loses to plain Kaplan-Meier
break_even <- sapply(q_grid, function(q) {
  up <- mult_grid[mult_grid > 1]
  worse <- up[sapply(up, function(m) bget(q, m, "likelihood") > km_rmse[[as.character(q)]])]
  if (length(worse)) min(worse) else NA
})
names(break_even) <- q_grid
max_mcse_rmse <- max(sapply(q_grid, function(q) sapply(mult_grid, function(m)
  mcse_rmse(grid_res[[as.character(q)]][, paste0("S_", m)]))))
q3 <- grid_res[["0.3"]]
q_hat_lo <- mean(q3[, "q_0.7"]); q_hat_hi <- mean(q3[, "q_1.3"])
rule_bound_mult <- 365 / (cut_frac * bat_scl)
bracket_q <- sapply(q_grid, col_stat, col = "bracket")
width_q <- sapply(q_grid, col_stat, col = "width")

## ---- fig-bench ----
km_ref <- data.frame(q = q_grid, rmse = km_rmse)
lab_q <- function(x) paste("q =", x)
ggplot(bench_long, aes(mult, rmse, colour = method)) +
  geom_hline(data = km_ref, aes(yintercept = rmse), colour = te_rust,
             linetype = "dashed", linewidth = 0.6) +
  geom_vline(xintercept = 1, colour = te_line, linewidth = 0.6) +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  facet_wrap(~ q, nrow = 1, labeller = as_labeller(lab_q)) +
  scale_colour_manual(values = c(likelihood = te_forest, "60 per cent rule" = te_gold), name = NULL) +
  scale_x_continuous(breaks = c(0.7, 1, 1.3)) +
  labs(x = "bench battery life relative to the true life", y = "RMSE of one-year survival",
       title = "An optimistic bench curve costs more than a pessimistic one",
       subtitle = "dashed red: Kaplan-Meier with losses censored") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- fig-rule-frac ----
frac_long <- do.call(rbind, lapply(q_grid, function(q) {
  M <- grid_res[[as.character(q)]]
  data.frame(q = factor(q), frac = frac_grid,
             mean = sapply(frac_grid, function(f) mean(M[, paste0("frac_", f)])))
}))
fget <- function(q, f) frac_long$mean[frac_long$q == q & frac_long$frac == f]
best_frac <- sapply(q_grid, function(q) {
  M <- grid_res[[as.character(q)]]
  frac_grid[which.min(sapply(frac_grid, function(f) rmse(M[, paste0("frac_", f)])))]
})
ggplot(frac_long, aes(frac, mean, colour = q)) +
  geom_hline(yintercept = S1_true, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_vline(xintercept = 365 / bat_scl, colour = te_body, linetype = "dotted", linewidth = 0.6) +
  geom_line(linewidth = 0.9) + geom_point(size = 2.2) +
  scale_colour_manual(values = c(te_ink, te_forest, te_gold, te_rust), name = "q") +
  labs(x = "cut-off as a share of nominal battery life", y = "mean estimated one-year survival",
       title = "The right cut-off depends on the unknown q",
       subtitle = "dashed: true survival; dotted: cut-off reaches day 365") +
  theme_datasheet() + theme(legend.position = "right")

## ---- stress ----
scen <- list(list(lab = "baseline", q = 0.3, scl = bat_scl, pe = 0),
             list(lab = "wear-out at 300 d", q = 0.3, scl = 300, pe = 0),
             list(lab = "early failures, q = 0", q = 0, scl = bat_scl, pe = 0.1),
             list(lab = "early failures, q = 0.3", q = 0.3, scl = bat_scl, pe = 0.1))
set.seed(31702)
stress <- do.call(rbind, lapply(scen, function(s) {
  M <- t(replicate(n_rep, one_study(n_animal, s$q, scl = s$scl, mult = 1,
                                    p_early = s$pe, fracs = cut_frac)))
  cols <- c(km = "Kaplan-Meier", bound = "all losses as deaths",
            rule_1 = "60 per cent rule", S_1 = "likelihood, bench curve")
  data.frame(scenario = s$lab, method = unname(cols),
             mean = sapply(names(cols), function(cc) mean(M[, cc])),
             lo = sapply(names(cols), function(cc) quantile(M[, cc], 0.1)),
             hi = sapply(names(cols), function(cc) quantile(M[, cc], 0.9)),
             rmse = sapply(names(cols), function(cc) rmse(M[, cc])),
             mle_cov = mean(M[, "mle_cov"]), bracket = mean(M[, "bracket"]),
             width = mean(M[, "width"]))
}))
rownames(stress) <- NULL
sget <- function(sc, meth, what = "mean") stress[[what]][stress$scenario == sc & stress$method == meth]
p_early_batt <- 0.1 * (1 - exp(-365 / 60))
print(stress[, c("scenario", "method", "mean", "rmse")], digits = 3)

## ---- fig-stress ----
stress$scenario <- factor(stress$scenario, levels = rev(sapply(scen, `[[`, "lab")))
stress$method <- factor(stress$method, levels = c("Kaplan-Meier", "all losses as deaths",
                                                  "60 per cent rule", "likelihood, bench curve"))
ggplot(stress, aes(mean, scenario, colour = method)) +
  geom_vline(xintercept = S1_true, colour = te_body, linetype = "dashed", linewidth = 0.5) +
  geom_errorbar(aes(xmin = lo, xmax = hi), orientation = "y", width = 0.25,
                position = position_dodge(width = 0.7), linewidth = 0.5) +
  geom_point(size = 2.4, position = position_dodge(width = 0.7)) +
  scale_colour_manual(values = c(te_rust, te_ink, te_gold, te_forest), name = NULL) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "estimated one-year survival (mean, 10th to 90th percentile)", y = NULL,
       title = "Early collar failures look like deaths to both repairs",
       subtitle = "dashed: true survival") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- retrieved ----
wb_fit <- function(tb, t_ret, truncated) {
  nll <- function(p) {
    k <- exp(p[1]); s <- exp(p[2])
    -sum(dweibull(tb, k, s, log = TRUE) + truncated * (t_ret / s)^k)
  }
  exp(optim(c(log(3), log(mean(tb))), nll)$par)
}
one_retrieved <- function(n, q = 0.3) {
  D <- sim_study(n, q)
  back <- D$fate %in% c("dead", "end")           # collars recovered still working
  wn <- wb_fit(D$tb[back], D$t[back], FALSE)
  wt <- wb_fit(D$tb[back], D$t[back], TRUE)
  zb <- fit_cr(D, bat_shp, bat_scl, ci = TRUE)
  zt <- fit_cr(D, wt[1], wt[2], ci = TRUE)
  zn <- fit_cr(D, wn[1], wn[2])
  c(n_back = sum(back), naive_scl = wn[2], trunc_scl = wt[2], naive_shp = wn[1], trunc_shp = wt[1],
    bench = zb[["S"]], bench_cov = zb[["lo"]] <= S1_true & S1_true <= zb[["hi"]],
    trunc = zt[["S"]], trunc_cov = zt[["lo"]] <= S1_true & S1_true <= zt[["hi"]],
    naive = zn[["S"]], rule_trunc = rule_S(D, wt[2])[["S"]], km = km_at(D$t, D$fate == "dead")[["S"]],
    q_bench = zb[["q"]])
}
n_grid <- c(60, 120, 240)
set.seed(52210)
ret <- lapply(n_grid, function(n) t(replicate(n_rep, one_retrieved(n))))
names(ret) <- n_grid
ret_tab <- do.call(rbind, lapply(n_grid, function(n) {
  M <- ret[[as.character(n)]]
  data.frame(n = n, collars_back = mean(M[, "n_back"]),
             naive_scale = median(M[, "naive_scl"]), trunc_scale = median(M[, "trunc_scl"]),
             bias_bench = mean(M[, "bench"]) - S1_true, rmse_bench = rmse(M[, "bench"]),
             cov_bench = mean(M[, "bench_cov"]),
             bias_trunc = mean(M[, "trunc"]) - S1_true, rmse_trunc = rmse(M[, "trunc"]),
             cov_trunc = mean(M[, "trunc_cov"]),
             bias_naive = mean(M[, "naive"]) - S1_true, rmse_naive = rmse(M[, "naive"]),
             rmse_rule = rmse(M[, "rule_trunc"]), rmse_km = rmse(M[, "km"]),
             sd_q = sd(M[, "q_bench"]))
}))
rget <- function(n, col) ret_tab[[col]][ret_tab$n == n]
mcse_cov <- sqrt(0.95 * 0.05 / n_rep)
cov_step_z <- (rget(240, "cov_trunc") - rget(120, "cov_trunc")) /
  sqrt((rget(240, "cov_trunc") * (1 - rget(240, "cov_trunc")) + rget(120, "cov_trunc") * (1 - rget(120, "cov_trunc"))) / n_rep)
show_tab <- ret_tab[, c("n", "collars_back", "naive_scale", "trunc_scale", "bias_naive", "bias_trunc", "cov_trunc", "cov_bench")]
show_tab[, c("cov_trunc", "cov_bench")] <- 100 * show_tab[, c("cov_trunc", "cov_bench")]
names(show_tab) <- c("animals", "collars back", "plain scale", "truncated scale", "bias plain", "bias truncated", "coverage truncated, per cent", "coverage true curve, per cent")
knitr::kable(show_tab, digits = c(0, 1, 1, 1, 3, 3, 1, 1))
