# A state change seen only at visits
# https://tidyecology.com/posts/state-seen-only-at-visits/
#
# 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-09-24

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

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))
}

n_animal    <- 300    # collared animals, all uninfected at marking
rate_change <- 0.4    # infections per animal-year
haz_base    <- 0.3    # deaths per animal-year before infection
tau_follow  <- 4      # years of follow-up

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

## ---- simulate ----
sim_panel <- function(n, hr, dv, shape = 1) {
  t_change <- rexp(n, rate_change)
  u_draw   <- rexp(n)
  h_at     <- haz_base * t_change^shape          # cumulative hazard at the change
  t_death  <- ifelse(u_draw <= h_at, (u_draw / haz_base)^(1 / shape),
                     ((u_draw - h_at) / (haz_base * hr) + t_change^shape)^(1 / shape))
  t_obs <- pmin(t_death, tau_follow)
  dead  <- as.integer(t_death <= tau_follow)
  k_max <- round(tau_follow / dv)
  n_vis <- ifelse(dead == 1, pmin(floor(t_obs / dv), k_max), k_max)  # live visits after marking
  j_pos <- ceiling(t_change / dv)                                      # first visit after the change
  seen  <- j_pos <= n_vis
  t_detect <- ifelse(seen, j_pos * dv, Inf)
  data.frame(id = seq_len(n), t_change, t_obs, dead, n_vis, seen, t_detect,
             t_mid = ifelse(seen, t_detect - dv / 2, Inf))
}

hr_demo <- 3; dv_demo <- 1
set.seed(20261010)
cohort <- sim_panel(n_animal, hr_demo, dv_demo)

n_dead    <- sum(cohort$dead)
n_changed <- sum(cohort$t_change < cohort$t_obs)
n_seen    <- sum(cohort$seen)
n_unseen  <- sum(cohort$t_change < cohort$t_obs & !cohort$seen)
n_unseen_dead <- sum(cohort$t_change < cohort$t_obs & !cohort$seen & cohort$dead == 1)
n_seen_last   <- sum(cohort$seen & cohort$t_detect == cohort$t_obs)

## ---- fig-timelines ----
pick <- c(head(cohort$id[cohort$seen & cohort$dead == 1 & cohort$t_detect < cohort$t_obs], 4),
          head(cohort$id[!cohort$seen & cohort$t_change < cohort$t_obs & cohort$dead == 1], 4),
          head(cohort$id[cohort$t_change >= cohort$t_obs & cohort$dead == 1], 2),
          head(cohort$id[cohort$t_change >= cohort$t_obs & cohort$dead == 0], 2))
tl <- cohort[match(pick, cohort$id), ]
tl$row <- rev(seq_along(pick))
grp_at <- c(10.5, 6.5, 2.5)
grp_lab <- c("seen infected", "infected,\ndied unseen", "never infected")
seg <- rbind(
  data.frame(row = tl$row, x0 = 0, x1 = pmin(tl$t_change, tl$t_obs), part = "uninfected"),
  data.frame(row = tl$row, x0 = pmin(tl$t_change, tl$t_obs), x1 = tl$t_obs, part = "infected"))
seg$part <- factor(seg$part, levels = c("uninfected", "infected"))
vis <- do.call(rbind, lapply(seq_len(nrow(tl)), function(i)
  if (tl$n_vis[i] > 0) data.frame(row = tl$row[i], x = seq_len(tl$n_vis[i]) * dv_demo,
                                  pos = seq_len(tl$n_vis[i]) * dv_demo >= tl$t_change[i])))
imm <- tl[tl$seen, ]

ggplot() +
  geom_segment(data = seg, aes(x = x0, xend = x1, y = row, yend = row, colour = part),
               linewidth = 1.6, lineend = "butt") +
  geom_segment(data = imm, aes(x = t_mid, xend = t_detect, y = row + 0.32, yend = row + 0.32),
               colour = te_gold, linewidth = 2.4) +
  geom_point(data = vis, aes(x, row, fill = pos), shape = 21, size = 2.4, colour = te_ink, stroke = 0.7) +
  geom_point(data = tl[tl$dead == 1, ], aes(t_obs, row), colour = te_rust, size = 2.6) +
  scale_colour_manual(values = c(uninfected = te_line, infected = te_forest), name = NULL) +
  scale_fill_manual(values = c(`FALSE` = te_paper, `TRUE` = te_ink), guide = "none") +
  scale_x_continuous(limits = c(0, tau_follow + 0.05), breaks = 0:4) +
  scale_y_continuous(breaks = grp_at, labels = grp_lab) +
  labs(x = "years since marking", y = NULL,
       title = "What the visits see",
       subtitle = "circles: visits (filled = positive); red: death; gold: midpoint's infected time") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- codings ----
cox_coded <- function(d, t_ch) {
  ch   <- t_ch < d$t_obs
  pre  <- data.frame(t0 = 0, t1 = ifelse(ch, t_ch, d$t_obs), ev = ifelse(ch, 0L, d$dead), x = 0L)
  post <- data.frame(t0 = t_ch[ch], t1 = d$t_obs[ch], ev = d$dead[ch], x = 1L)
  f <- coxph(Surv(t0, t1, ev) ~ x, data = rbind(pre, post))
  pt1 <- sum(post$t1 - post$t0); pt0 <- sum(pre$t1 - pre$t0)
  c(b = unname(coef(f)), s = sqrt(vcov(f)[1, 1]),
    rr = (sum(post$ev) / pt1) / (sum(pre$ev) / pt0), pt1 = pt1, pt0 = pt0)
}
ci_hr <- function(fit) exp(fit[["b"]] + c(0, -1.96, 1.96) * fit[["s"]])

fit_true <- cox_coded(cohort, cohort$t_change)
fit_det  <- cox_coded(cohort, cohort$t_detect)
fit_mid  <- cox_coded(cohort, cohort$t_mid)
hr_true_fit <- ci_hr(fit_true); hr_det <- ci_hr(fit_det); hr_mid <- ci_hr(fit_mid)

## ---- idm ----
idm_negll <- function(p, cnt, r_dead, s_dead, dv) {
  if (any(!is.finite(p)) || any(abs(p) > 30)) return(1e10)
  a <- exp(p[1]); h0 <- exp(p[2]); h1 <- exp(p[3]); dl <- a + h0 - h1
  P00 <- function(t) exp(-(a + h0) * t)
  P11 <- function(t) exp(-h1 * t)
  P01 <- function(t) a * exp(-h1 * t) * (if (abs(dl) < 1e-9) t else -expm1(-dl * t) / dl)
  ll <- cnt[1] * log(P00(dv)) + cnt[2] * log(P01(dv)) + cnt[3] * log(P11(dv)) +
    sum(log(ifelse(s_dead == 1, P11(r_dead) * h1, P00(r_dead) * h0 + P01(r_dead) * h1)))
  if (is.finite(ll)) -ll else 1e10
}

idm_starts <- list(log(c(0.4, 0.3, 0.3)), log(c(0.1, 1, 1)), log(c(1, 0.1, 3)))

fit_idm <- function(d, dv) {
  j <- ceiling(d$t_change / dv)   # used only through the visits: j <= n_vis exactly when seen
  cnt <- c(sum(ifelse(d$seen, j - 1, d$n_vis)),        # gaps 0 -> 0
           sum(d$seen),                                # gaps 0 -> 1
           sum(ifelse(d$seen, d$n_vis - j, 0)))        # gaps 1 -> 1
  dd <- d$dead == 1
  r_dead <- d$t_obs[dd] - d$n_vis[dd] * dv
  s_dead <- as.integer(d$seen[dd])
  fits <- lapply(idm_starts, function(st) optim(st, idm_negll, cnt = cnt, r_dead = r_dead,
                                                s_dead = s_dead, dv = dv, method = "BFGS"))
  vals <- sapply(fits, `[[`, "value")
  best <- fits[[which.min(vals)]]
  v <- solve(optimHess(best$par, idm_negll, cnt = cnt, r_dead = r_dead, s_dead = s_dead, dv = dv))
  c(b = best$par[3] - best$par[2], s = sqrt(v[3, 3] + v[2, 2] - 2 * v[2, 3]),
    spread = max(vals) - min(vals), conv = best$convergence,
    a = exp(best$par[1]), h0 = exp(best$par[2]))
}

fit_ill <- fit_idm(cohort, dv_demo)
hr_ill <- ci_hr(fit_ill)

## ---- replicates ----
n_rep <- 200
hr_grid <- c(0.5, 1, 3); dv_grid <- c(0.5, 1, 2)

one_rep <- function(hr, dv) {
  d <- sim_panel(n_animal, hr, dv)
  ft <- cox_coded(d, d$t_change); fd <- cox_coded(d, d$t_detect); fm <- cox_coded(d, d$t_mid)
  fi <- fit_idm(d, dv)
  moved <- sum(d$t_detect[d$seen] - d$t_mid[d$seen])   # person-time the midpoint moves
  c(b_true = ft[["b"]], s_true = ft[["s"]], b_det = fd[["b"]], s_det = fd[["s"]],
    b_mid = fm[["b"]], s_mid = fm[["s"]], b_idm = fi[["b"]], s_idm = fi[["s"]],
    spread = fi[["spread"]], conv = fi[["conv"]],
    rr_det = fd[["rr"]], rr_mid = fm[["rr"]], pt1 = fd[["pt1"]], pt0 = fd[["pt0"]], moved = moved,
    n_seen = sum(d$seen), unseen = mean(d$t_change < d$t_obs & !d$seen))
}

cells <- expand.grid(dv = dv_grid, hr = hr_grid)
set.seed(60330)
reps <- lapply(seq_len(nrow(cells)), function(i)
  as.data.frame(t(replicate(n_rep, one_rep(cells$hr[i], cells$dv[i])))))

methods <- c(true = "true change time", det = "detection visit", mid = "midpoint", idm = "illness-death")
summ <- do.call(rbind, lapply(seq_len(nrow(cells)), function(i) {
  r <- reps[[i]]; hr <- cells$hr[i]
  do.call(rbind, lapply(names(methods), function(m) {
    b <- r[[paste0("b_", m)]]; s <- r[[paste0("s_", m)]]
    data.frame(hr = hr, dv = cells$dv[i], method = methods[[m]],
               med = exp(median(b)), q10 = exp(quantile(b, 0.1)), q90 = exp(quantile(b, 0.9)),
               cover = mean(abs(b - log(hr)) < 1.96 * s), reject = mean(abs(b / s) > 1.96))
  }))
}))
rownames(summ) <- NULL
cell_of <- function(hr, dv) which(cells$hr == hr & cells$dv == dv)
sv <- function(hr, dv, m, col = "med") summ[[col]][summ$hr == hr & summ$dv == dv & summ$method == methods[[m]]]
mcse <- function(p, n = n_rep) sqrt(p * (1 - p) / n)

idm_cover <- summ$cover[summ$method == methods[["idm"]]]
idm_ratio <- summ$med[summ$method == methods[["idm"]]] / summ$hr[summ$method == methods[["idm"]]]
spread_max <- max(sapply(reps, function(r) max(r$spread)))
n_nonconv  <- sum(sapply(reps, function(r) sum(r$conv != 0)))
unseen_of  <- function(hr, dv) median(reps[[cell_of(hr, dv)]]$unseen)

## ---- fig-grid ----
summ$method <- factor(summ$method, levels = unname(methods))
hr_labs <- sprintf("true HR %s", as.character(hr_grid))
summ$panel  <- factor(sprintf("true HR %s", as.character(summ$hr)), levels = hr_labs)
meth_cols <- setNames(c(te_body, te_gold, te_rust, te_forest), unname(methods))
meth_shapes <- setNames(c(1, 16, 16, 16), unname(methods))
truth_df <- data.frame(panel = factor(hr_labs, levels = hr_labs), hr = hr_grid)
dodge <- position_dodge(width = 0.6)
p_est <- ggplot(summ, aes(factor(dv), med, colour = method, shape = method)) +
  geom_hline(data = truth_df, aes(yintercept = hr), colour = te_ink, linetype = "dashed", linewidth = 0.5) +
  geom_errorbar(aes(ymin = q10, ymax = q90), width = 0, linewidth = 0.8, position = dodge) +
  geom_point(size = 2.4, stroke = 1, position = dodge) +
  facet_wrap(~ panel, scales = "free_y") +
  scale_y_log10() +
  scale_colour_manual(values = meth_cols, name = NULL) +
  scale_shape_manual(values = meth_shapes, name = NULL) +
  labs(x = NULL, y = "hazard ratio (log)",
       title = "The illness-death fit sits on the truth in every cell",
       subtitle = "dashed: the true hazard ratio") +
  theme_datasheet() + theme(legend.position = "none", strip.text = element_text(colour = te_ink, face = "bold"))
p_cov <- ggplot(summ, aes(factor(dv), cover, colour = method, shape = method)) +
  geom_hline(yintercept = 0.95, colour = te_ink, linetype = "dashed", linewidth = 0.5) +
  geom_point(size = 2.4, stroke = 1, position = dodge) +
  facet_wrap(~ panel) +
  scale_y_continuous(limits = c(0, 1)) +
  scale_colour_manual(values = meth_cols, name = NULL) +
  scale_shape_manual(values = meth_shapes, name = NULL) +
  labs(x = "years between visits", y = "coverage") +
  theme_datasheet() + theme(legend.position = "bottom", strip.text = element_blank())
p_est / p_cov + plot_layout(heights = c(1.4, 1)) + plot_annotation(theme = theme_datasheet())

## ---- identity ----
all_reps <- do.call(rbind, reps)
pred_mid <- with(all_reps, rr_det * pt1 / (pt1 + moved) * (pt0 - moved) / pt0)
id_err   <- max(abs(pred_mid - all_reps$rr_mid))
moved_ok <- max(abs(all_reps$moved - all_reps$n_seen * rep(cells$dv, each = n_rep) / 2))
n_cox_lower <- sum(all_reps$b_mid < all_reps$b_det)
null_y <- reps[[cell_of(1, 1)]]
rr_mid_null  <- median(null_y$rr_mid)
cox_mid_null <- exp(median(null_y$b_mid))
share_cox_below_rr <- mean(exp(all_reps$b_mid) < all_reps$rr_mid)

## ---- fp-guard-1 ----
stopifnot(id_err < 1e-8)

## ---- fig-identity ----
null_df <- do.call(rbind, lapply(dv_grid, function(v) {
  r <- reps[[cell_of(1, v)]]
  data.frame(dv = sprintf("%s yr between visits", as.character(v)),
             pred = with(r, rr_det * pt1 / (pt1 + moved) * (pt0 - moved) / pt0),
             cox = exp(r$b_mid), det = exp(r$b_det))
}))
null_df$dv <- factor(null_df$dv, levels = sprintf("%s yr between visits", as.character(dv_grid)))
ggplot(null_df, aes(pred, cox, colour = dv)) +
  geom_abline(slope = 1, intercept = 0, colour = te_ink, linetype = "dashed", linewidth = 0.5) +
  geom_hline(yintercept = 1, colour = te_body, linewidth = 0.3) +
  geom_vline(xintercept = 1, colour = te_body, linewidth = 0.3) +
  geom_point(size = 1.3, alpha = 0.6) +
  scale_x_log10() + scale_y_log10() +
  scale_colour_manual(values = c(te_gold, te_forest, te_rust), name = NULL) +
  labs(x = "crude rate ratio predicted by the identity (log scale)",
       y = "Cox hazard ratio, midpoint coding (log scale)",
       title = "True hazard ratio 1, read through the midpoint",
       subtitle = "dashed: equality") +
  guides(colour = guide_legend(override.aes = list(size = 2.5, alpha = 1))) +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- ageing ----
gl_nodes <- function(m) {                      # Gauss-Legendre nodes and weights on [0, 1]
  b <- seq_len(m - 1) / sqrt(4 * seq_len(m - 1)^2 - 1)
  J <- matrix(0, m, m); J[cbind(1:(m - 1), 2:m)] <- b; J[cbind(2:m, 1:(m - 1))] <- b
  e <- eigen(J, symmetric = TRUE)
  list(x = (e$values + 1) / 2, w = e$vectors[1, ]^2)
}
gl16 <- gl_nodes(16)

wb_probs <- function(s, e, a, lam, k, hr) {
  cumh <- function(x, y) lam * (y^k - x^k)
  U <- outer(e - s, gl16$x) + s                # quadrature nodes, one row per stretch
  integrand <- exp(-a * (U - s) - cumh(s, U)) * a * exp(-hr * cumh(U, e))
  list(P00 = exp(-a * (e - s) - cumh(s, e)), P11 = exp(-hr * cumh(s, e)),
       P01 = as.numeric(integrand %*% gl16$w) * (e - s))
}
wb_negll <- function(p, dat) {
  if (any(!is.finite(p)) || any(abs(p) > 30)) return(1e10)
  a <- exp(p[1]); lam <- exp(p[2]); k <- exp(p[3]); hr <- exp(p[4])
  g <- wb_probs(dat$g_s, dat$g_e, a, lam, k, hr)
  f <- wb_probs(dat$d_s, dat$d_e, a, lam, k, hr)
  h0 <- lam * k * dat$d_e^(k - 1)
  lik_d <- ifelse(dat$d_st == 1, f$P11 * hr * h0, (f$P00 + f$P01 * hr) * h0)
  ll <- sum(dat$n00 * log(g$P00)) + sum(dat$n01 * log(g$P01)) + sum(dat$n11 * log(g$P11)) +
    sum(log(lik_d))
  if (is.finite(ll)) -ll else 1e10
}
fit_wb <- function(d, dv) {
  kk <- seq_len(round(tau_follow / dv)); j <- ceiling(d$t_change / dv); dd <- d$dead == 1
  dat <- list(g_s = (kk - 1) * dv, g_e = kk * dv,     # visit gaps are no longer interchangeable
              n00 = sapply(kk, function(k) sum(k <= ifelse(d$seen, j - 1, d$n_vis))),
              n01 = sapply(kk, function(k) sum(d$seen & j == k)),
              n11 = sapply(kk, function(k) sum(d$seen & k > j & k <= d$n_vis)),
              d_s = d$n_vis[dd] * dv, d_e = d$t_obs[dd], d_st = as.integer(d$seen[dd]))
  crude <- sum(d$dead) / sum(d$t_obs)
  starts <- list(c(log(0.4), log(crude), 0, 0), c(0, log(crude / 3), log(2), log(3)),
                 c(log(0.1), log(crude * 2), log(0.6), log(1 / 3)))
  fits <- lapply(starts, function(st) optim(st, wb_negll, dat = dat, method = "BFGS",
                                            control = list(maxit = 500)))
  vals <- sapply(fits, `[[`, "value"); best <- fits[[which.min(vals)]]
  v <- solve(optimHess(best$par, wb_negll, dat = dat))
  c(b = best$par[4], s = sqrt(v[4, 4]), k = exp(best$par[3]), spread = max(vals) - min(vals),
    a = exp(best$par[1]), lam = exp(best$par[2]))
}

n_rep_age <- 100
age_cells <- data.frame(shape = c(1.6, 1.6, 1), hr = c(1, 3, 3))
set.seed(60331)
age_reps <- lapply(seq_len(nrow(age_cells)), function(i) {
  as.data.frame(t(replicate(n_rep_age, {
    d <- sim_panel(n_animal, age_cells$hr[i], 1, age_cells$shape[i])
    fd <- cox_coded(d, d$t_detect); fm <- cox_coded(d, d$t_mid)
    fi <- fit_idm(d, 1); fw <- fit_wb(d, 1)
    c(b_det = fd[["b"]], s_det = fd[["s"]], b_mid = fm[["b"]], s_mid = fm[["s"]],
      b_idm = fi[["b"]], s_idm = fi[["s"]], b_wb = fw[["b"]], s_wb = fw[["s"]],
      k_wb = fw[["k"]], spread_wb = fw[["spread"]], a_wb = fw[["a"]], lam_wb = fw[["lam"]])
  })))
})
age_methods <- c(det = "detection visit", mid = "midpoint", idm = "illness-death, constant",
                 wb = "illness-death, Weibull")
age_summ <- do.call(rbind, lapply(seq_len(nrow(age_cells)), function(i) {
  r <- age_reps[[i]]; hr <- age_cells$hr[i]
  do.call(rbind, lapply(names(age_methods), function(m) {
    b <- r[[paste0("b_", m)]]; s <- r[[paste0("s_", m)]]
    data.frame(shape = age_cells$shape[i], hr = hr, method = age_methods[[m]],
               med = exp(median(b)), q10 = exp(quantile(b, 0.1)), q90 = exp(quantile(b, 0.9)),
               cover = mean(abs(b - log(hr)) < 1.96 * s))
  }))
}))
rownames(age_summ) <- NULL
av <- function(shape, hr, m, col = "med") age_summ[[col]][age_summ$shape == shape & age_summ$hr == hr &
                                                          age_summ$method == age_methods[[m]]]
k_med <- sapply(age_reps, function(r) median(r$k_wb))
wb_spread_max <- max(sapply(age_reps, function(r) max(r$spread_wb)))
haz_1 <- haz_base * 1.6 * 1^0.6; haz_4 <- haz_base * 1.6 * 4^0.6
width_ratio <- median(age_reps[[3]]$s_wb / age_reps[[3]]$s_idm)

# quadrature against integrate() at every fitted Weibull parameter set: the four visit gaps
# and the stretches of a quarter, half and three quarters of a year after each visit
quad_stretch <- expand.grid(s = 0:3, len = c(0.25, 0.5, 0.75, 1))
quad_relerr <- function(a, lam, k, hr) {
  q <- wb_probs(quad_stretch$s, quad_stretch$s + quad_stretch$len, a, lam, k, hr)$P01
  ex <- mapply(function(s, e) integrate(function(u) exp(-a * (u - s) - lam * (u^k - s^k)) * a *
                 exp(-hr * lam * (e^k - u^k)), s, e, rel.tol = 1e-10)$value,
               quad_stretch$s, quad_stretch$s + quad_stretch$len)
  max(abs(q - ex) / ex)
}
quad_err <- max(unlist(lapply(age_reps, function(r)
  mapply(quad_relerr, r$a_wb, r$lam_wb, r$k_wb, exp(r$b_wb)))))
n_quad_sets <- sum(sapply(age_reps, nrow))

## ---- fig-ageing ----
age_summ$method <- factor(age_summ$method, levels = unname(age_methods))
age_levels <- c("rising baseline, true HR 1", "rising baseline, true HR 3", "constant baseline, true HR 3")
age_summ$panel <- factor(sprintf("%s baseline, true HR %s", ifelse(age_summ$shape == 1, "constant", "rising"),
                                 as.character(age_summ$hr)), levels = age_levels)
age_cols <- setNames(c(te_gold, te_rust, te_ink, te_forest), unname(age_methods))
age_shapes <- setNames(c(16, 16, 1, 16), unname(age_methods))
age_truth <- data.frame(panel = factor(age_levels, levels = age_levels), hr = c(1, 3, 3))
ggplot(age_summ, aes(method, med, colour = method, shape = method)) +
  geom_hline(data = age_truth, aes(yintercept = hr), colour = te_ink, linetype = "dashed", linewidth = 0.5) +
  geom_errorbar(aes(ymin = q10, ymax = q90), width = 0, linewidth = 0.9) +
  geom_point(size = 2.6, stroke = 1.1) +
  facet_wrap(~ panel) +
  scale_y_log10() +
  scale_colour_manual(values = age_cols, name = NULL) +
  scale_shape_manual(values = age_shapes, name = NULL) +
  labs(x = NULL, y = "estimated hazard ratio (log scale)",
       title = "A constant-rate repair breaks when mortality rises",
       subtitle = "dashed: the true hazard ratio") +
  guides(colour = guide_legend(nrow = 2)) +
  theme_datasheet() +
  theme(legend.position = "bottom", axis.text.x = element_blank(),
        strip.text = element_text(colour = te_ink, face = "bold"))

## ---- ageing-mild ----
mild_cells <- expand.grid(hr = c(1, 3), shape = c(1.1, 1.2, 1.3))
set.seed(60332)
mild_reps <- lapply(seq_len(nrow(mild_cells)), function(i) as.data.frame(t(replicate(n_rep_age, {
  d <- sim_panel(n_animal, mild_cells$hr[i], 1, mild_cells$shape[i])
  fi <- fit_idm(d, 1)
  c(b = fi[["b"]], s = fi[["s"]])
}))))
mild_cells$med   <- sapply(mild_reps, function(r) exp(median(r$b)))
mild_cells$cover <- sapply(seq_along(mild_reps), function(i)
  mean(abs(mild_reps[[i]]$b - log(mild_cells$hr[i])) < 1.96 * mild_reps[[i]]$s))
mv <- function(shape, hr, col = "med") mild_cells[[col]][mild_cells$shape == shape & mild_cells$hr == hr]
rise_of <- function(shape) 4^(shape - 1)     # death rate at four years over the rate at one year
