# Fitting a senescence model to individual records
# https://tidyecology.com/posts/fitting-a-senescence-model/
#
# 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-11-16

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

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

## ---- 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 ----
n_year    <- 20      # breeding seasons in the study
n_pre     <- 8       # hatch years before the first season that still supply breeders
n_recruit <- 30      # recruits per hatch year, all breeding from age 1
phi_mean  <- 0.65    # annual survival of an average female
sd_id     <- 4       # among-female SD of laying date, days
sd_yr     <- 3       # among-season SD, days
sd_e      <- 5       # residual SD, days
mu_lay    <- 110     # mean laying date, day of year

# A: linear age term, Q: quadratic age term, C: trend across hatch years (days per year),
# beta_sel: log odds of annual survival per among-female SD of earlier laying
sim_study <- function(A = 0, Q = 0, C = 0, beta_sel = 0, n_seasons = n_year) {
  hatch <- (-n_pre):(n_seasons - 2)
  n_fem <- length(hatch) * n_recruit
  coh   <- rep(hatch, each = n_recruit)
  u     <- rnorm(n_fem, 0, sd_id)
  phi_i <- plogis(qlogis(phi_mean) - beta_sel * u / sd_id)
  last  <- 1 + rgeom(n_fem, 1 - phi_i)          # age at the last breeding attempt
  y_dev <- rnorm(n_seasons, 0, sd_yr)
  id    <- rep(seq_len(n_fem), last)
  age   <- sequence(last)
  yr    <- coh[id] + age
  keep  <- yr >= 0 & yr <= n_seasons - 1
  dat <- data.frame(id = id[keep], cohort = coh[id][keep], age = age[keep], year = yr[keep])
  dat$u   <- u[dat$id]
  dat$lay <- mu_lay + A * dat$age + Q * dat$age^2 + C * dat$cohort + dat$u +
    y_dev[dat$year + 1] + rnorm(nrow(dat), 0, sd_e)
  dat$alr  <- ave(dat$age, dat$id, FUN = max)     # observed age at last reproduction
  dat$mage <- ave(dat$age, dat$id, FUN = mean)    # mean age over the female's own records
  dat$alive_end <- as.numeric(ave(dat$year, dat$id, FUN = max) == n_seasons - 1)
  dat$fyear <- factor(dat$year); dat$fid <- factor(dat$id); dat$fcoh <- factor(dat$cohort)
  dat
}
ctl <- lmeControl(returnObject = TRUE, msMaxIter = 200)

## ---- one-study ----
a_lin    <- 0.3      # true within-female ageing slope, days later per year of age
beta_sel <- 1        # log odds of survival per among-female SD of earlier laying
min_n_plot <- 10     # ages with fewer records are left out of the figure
set.seed(3301)
one <- sim_study(A = a_lin, beta_sel = beta_sel)
one_fem <- one[!duplicated(one$id), ]
n_rec_one <- nrow(one); n_fem_one <- nrow(one_fem)
share_end <- mean(one_fem$alive_end)
by_age <- aggregate(cbind(lay, u) ~ age, data = one, FUN = mean)
by_age$n <- as.vector(table(one$age))
max_age_plot <- max(by_age$age[by_age$n >= min_n_plot])
u_age1 <- by_age$u[by_age$age == 1]; u_age6 <- by_age$u[by_age$age == 6]
max_age_one <- max(one$age)
pop_one   <- coef(lm(lay ~ age + fyear, data = one))[["age"]]
naive_one <- fixef(lme(lay ~ age + fyear, random = ~ 1 | fid, data = one, control = ctl))[["age"]]

## ---- fig-selection ----
plot_age <- by_age[by_age$n >= min_n_plot, ]
p_lay <- ggplot(plot_age, aes(age, lay)) +
  annotate("segment", x = 1, xend = max_age_plot, y = plot_age$lay[1],
           yend = plot_age$lay[1] + a_lin * (max_age_plot - 1),
           colour = te_forest, linetype = "dashed", linewidth = 0.8) +
  geom_point(aes(size = n), colour = te_rust, alpha = 0.85) +
  scale_size_area(max_size = 6, name = "records") +
  scale_x_continuous(breaks = seq_len(max_age_plot)) +
  labs(x = "age (years)", y = "mean laying date (day of year)",
       title = "The population curve",
       subtitle = "dashed: what each female does") +
  theme_datasheet() + theme(legend.position = "bottom")
p_u <- ggplot(plot_age, aes(age, u)) +
  geom_hline(yintercept = 0, colour = te_body, linewidth = 0.4) +
  geom_line(colour = te_gold, linewidth = 0.9) +
  geom_point(aes(size = n), colour = te_gold) +
  scale_size_area(max_size = 6, guide = "none") +
  scale_x_continuous(breaks = seq_len(max_age_plot)) +
  labs(x = "age (years)", y = "mean female effect (days)",
       title = "Who is still breeding",
       subtitle = "negative: earlier-laying females") +
  theme_datasheet()
p_lay + p_u + plot_annotation(theme = theme_datasheet())

## ---- sel-sim ----
fit_age <- function(fml, dat)
  fixef(lme(fml, random = ~ 1 | fid, data = dat, control = ctl))[["age"]]
sel_study <- function() {
  d <- sim_study(A = a_lin, beta_sel = beta_sel)
  d$entered_old <- as.numeric(ave(d$age, d$id, FUN = min) > 1)   # first recorded older than one
  d_dead <- d[d$alive_end == 0, ]
  d_mlay <- ave(d$lay, d$id)
  c(population = coef(lm(lay ~ age + fyear, data = d))[["age"]],
    naive      = fit_age(lay ~ age + fyear, d),
    alr        = fit_age(lay ~ age + alr + fyear, d),
    alr_flag   = fit_age(lay ~ age + alr + alive_end + fyear, d),
    alr_dead   = fit_age(lay ~ age + alr + fyear, d_dead),
    mage       = fit_age(lay ~ age + mage + fyear, d),
    mage_flag  = fit_age(lay ~ age + mage + alive_end + fyear, d),
    within     = sum((d$age - d$mage) * (d$lay - d_mlay)) / sum((d$age - d$mage)^2),
    mage_entry = fit_age(lay ~ age + mage + alive_end + entered_old + fyear, d))
}
n_draw <- 5; n_per_draw <- 8
set.seed(3302)
sel_raw <- do.call(rbind, lapply(seq_len(n_draw), function(k)
  data.frame(draw = k, t(replicate(n_per_draw, sel_study())))))
mods <- setdiff(names(sel_raw), "draw")
mods_fig <- setdiff(mods, "mage_entry")     # the ninth fit is reported in the text only
draw_med <- aggregate(sel_raw[, mods], by = list(draw = sel_raw$draw), FUN = median)
sel_sum <- data.frame(model = mods,
  med  = sapply(mods, function(m) median(draw_med[[m]])),
  lo   = sapply(mods, function(m) min(draw_med[[m]])),
  hi   = sapply(mods, function(m) max(draw_med[[m]])),
  mean = colMeans(sel_raw[, mods]),
  sdev = apply(sel_raw[, mods], 2, sd),
  mcse = apply(sel_raw[, mods], 2, sd) / sqrt(nrow(sel_raw)))
st <- function(m, col = "med") sel_sum[m, col]
n_studies <- nrow(sel_raw)
naive_z  <- (st("naive", "mean") - a_lin) / st("naive", "mcse")
closer_draws <- sum(abs(draw_med$alr - a_lin) < abs(draw_med$naive - a_lin))
z_of <- function(m) (st(m, "mean") - a_lin) / st(m, "mcse")

## ---- fig-slopes ----
mod_lab <- c(population = "no female term",
             naive      = "age + (1 | female)",
             alr        = "+ last breeding age, as recorded",
             alr_flag   = "+ last breeding age + still-breeding flag",
             alr_dead   = "+ last breeding age, dead females only",
             mage       = "+ mean age, as recorded",
             mage_flag  = "+ mean age + still-breeding flag",
             within     = "within female only, no season term")
mod_grp <- c(population = "ignores selection", naive = "ignores selection",
             alr = "repair, censoring ignored", mage = "repair, censoring ignored",
             alr_flag = "repair, censoring handled", mage_flag = "repair, censoring handled",
             alr_dead = "repair, censoring handled", within = "no season term")
long_sel <- data.frame(model = rep(mods_fig, each = n_studies),
                       est = unlist(sel_raw[, mods_fig], use.names = FALSE))
long_sel$label <- factor(mod_lab[long_sel$model], levels = rev(mod_lab))
long_sel$group <- factor(mod_grp[long_sel$model], levels = unique(mod_grp))
med_sel <- aggregate(est ~ label, data = long_sel, FUN = median)
ggplot(long_sel, aes(est, label, colour = group, shape = group)) +
  geom_vline(xintercept = a_lin, colour = te_forest, linetype = "dashed", linewidth = 0.7) +
  geom_vline(xintercept = 0, colour = te_body, linetype = "dotted", linewidth = 0.5) +
  geom_point(position = position_jitter(height = 0.15, width = 0, seed = 1),
             size = 1.4, alpha = 0.65) +
  geom_errorbar(data = med_sel, aes(xmin = est, xmax = est, y = label), inherit.aes = FALSE,
                width = 0.6, linewidth = 1.1, colour = te_ink) +
  scale_colour_manual(values = c(te_rust, te_gold, te_forest, te_body), name = NULL) +
  scale_shape_manual(values = c(16, 16, 16, 1), name = NULL) +
  guides(colour = guide_legend(nrow = 2), shape = guide_legend(nrow = 2)) +
  labs(x = "linear ageing slope (days per year of age)", y = NULL,
       title = "Selective disappearance and its repair",
       subtitle = "dashed: the true within-female slope") +
  theme_datasheet() + theme(legend.position = "bottom")

## ---- prime-sim ----
a_q <- -1.2; q_q <- 0.12            # quadratic age curve, earliest laying at age 5
prime_true <- -a_q / (2 * q_q)
len_grid <- c(10, 20, 40); n_len <- 30
quad_fit <- function(d) {
  f <- fixef(lme(lay ~ age + I(age^2) + fyear, random = ~ 1 | fid, data = d, control = ctl))
  c(a = f[["age"]], q = f[["I(age^2)"]], prime = -f[["age"]] / (2 * f[["I(age^2)"]]))
}
set.seed(3303)
prime_tab <- do.call(rbind, lapply(len_grid, function(ny) do.call(rbind, lapply(seq_len(n_len), function(i) {
  d <- sim_study(A = a_q, Q = q_q, n_seasons = ny)
  data.frame(seasons = ny, n_rec = nrow(d), n_old = sum(d$age >= 8), t(quad_fit(d)))
}))))
pq <- function(ny, p) unname(quantile(prime_tab$prime[prime_tab$seasons == ny], p))
pm <- function(ny, col) median(prime_tab[[col]][prime_tab$seasons == ny])
within1 <- function(ny) mean(abs(prime_tab$prime[prime_tab$seasons == ny] - prime_true) <= 0.5)

## ---- stick-sim ----
knot_true <- 3; b_before <- -1.5; b_after <- 0.6
knot_grid <- 2:6
stick_fit <- function(d, k) {
  d$pre <- pmin(d$age, k); d$post <- pmax(d$age - k, 0)
  m <- lme(lay ~ pre + post + fyear, random = ~ 1 | fid, data = d, control = ctl, method = "ML")
  c(ll = as.numeric(logLik(m)), before = fixef(m)[["pre"]], after = fixef(m)[["post"]])
}
set.seed(3304)
arm_tab <- do.call(rbind, lapply(seq_len(n_len), function(i) {
  d <- sim_study()
  d$lay <- d$lay + b_before * pmin(d$age, knot_true) + b_after * pmax(d$age - knot_true, 0)
  qf <- quad_fit(d)
  sf <- sapply(knot_grid, function(k) stick_fit(d, k))
  best <- which.max(sf["ll", ])
  data.frame(q_prime = qf[["prime"]], q_slope9 = qf[["a"]] + 2 * qf[["q"]] * 9,
             knot = knot_grid[best], before = sf["before", best], after = sf["after", best])
}))
knot_hit <- mean(arm_tab$knot == knot_true)

## ---- fig-prime ----
prime_tab$len_lab <- factor(sprintf("%d seasons", prime_tab$seasons),
                            levels = sprintf("%d seasons", len_grid))
med_len <- aggregate(prime ~ len_lab, data = prime_tab, FUN = median)
p_len <- ggplot(prime_tab, aes(len_lab, prime)) +
  geom_hline(yintercept = prime_true, colour = te_forest, linetype = "dashed", linewidth = 0.7) +
  geom_point(position = position_jitter(width = 0.15, height = 0, seed = 2),
             colour = te_gold, size = 1.6, alpha = 0.8) +
  geom_errorbar(data = med_len, aes(x = len_lab, ymin = prime, ymax = prime),
                width = 0.5, linewidth = 1.1, colour = te_ink) +
  labs(x = NULL, y = "estimated prime age (years)", title = "Quadratic truth",
       subtitle = "dashed: true prime age") +
  theme_datasheet()
arm_long <- data.frame(fit = factor(rep(c("quadratic: prime age", "broken stick: knot"),
                                        each = nrow(arm_tab)),
                                    levels = c("quadratic: prime age", "broken stick: knot")),
                       age = c(arm_tab$q_prime, arm_tab$knot))
med_arm <- aggregate(age ~ fit, data = arm_long, FUN = median)
p_arm <- ggplot(arm_long, aes(fit, age, colour = fit)) +
  geom_hline(yintercept = knot_true, colour = te_forest, linetype = "dashed", linewidth = 0.7) +
  geom_point(position = position_jitter(width = 0.15, height = 0.05, seed = 3),
             size = 1.6, alpha = 0.8) +
  geom_errorbar(data = med_arm, aes(x = fit, ymin = age, ymax = age), inherit.aes = FALSE,
                width = 0.5, linewidth = 1.1, colour = te_ink) +
  scale_colour_manual(values = c(te_rust, te_forest), guide = "none") +
  labs(x = NULL, y = "estimated age (years)", title = "Broken-stick truth",
       subtitle = "dashed: true onset and prime age") +
  theme_datasheet()
p_len + p_arm + plot_annotation(theme = theme_datasheet())

## ---- identity ----
c_trend <- -0.3                      # days per hatch year; later hatch years lay earlier
set.seed(3305)
base  <- sim_study(A = a_q, Q = q_q)
trend <- base; trend$lay <- base$lay + c_trend * base$cohort
fit_pair <- function(d) {
  m1 <- lme(lay ~ age + I(age^2) + fyear, random = ~ 1 | fid, data = d, control = ctl)
  m2 <- lme(lay ~ age + I(age^2) + fyear, random = ~ 1 | fcoh / fid, data = d, control = ctl)
  c(a1 = fixef(m1)[["age"]], q1 = fixef(m1)[["I(age^2)"]],
    a2 = fixef(m2)[["age"]], q2 = fixef(m2)[["I(age^2)"]])
}
fp_base <- fit_pair(base); fp_trend <- fit_pair(trend)
fp_diff <- fp_trend - fp_base
prime_b <- -fp_base[["a1"]] / (2 * fp_base[["q1"]])
prime_t <- -fp_trend[["a1"]] / (2 * fp_trend[["q1"]])
prime_formula <- -(a_q - c_trend) / (2 * q_q)
shift_formula <- c_trend / (2 * q_q)
gap_lin  <- max(abs(fp_diff[c("a1", "a2")] - (-c_trend)))
gap_quad <- max(abs(fp_diff[c("q1", "q2")]))
stick_base  <- sapply(knot_grid, function(k) stick_fit(base, k))
stick_trend <- sapply(knot_grid, function(k) stick_fit(trend, k))
knot_b <- knot_grid[which.max(stick_base["ll", ])]
knot_t <- knot_grid[which.max(stick_trend["ll", ])]
gap_ll <- max(abs(stick_trend["ll", ] - stick_base["ll", ]))
change_b <- stick_base["after", ] - stick_base["before", ]
change_t <- stick_trend["after", ] - stick_trend["before", ]
gap_change <- max(abs(change_t - change_b))
gap_seg <- max(abs(c(stick_trend["before", ] - stick_base["before", ],
                     stick_trend["after", ] - stick_base["after", ]) - (-c_trend)))

## ---- fig-identity ----
age_seq <- seq(1, 12, by = 0.1)
curve_rel <- function(a, q) a * (age_seq - 1) + q * (age_seq^2 - 1)
curve_dat <- rbind(
  data.frame(age = age_seq, rel = curve_rel(a_q, q_q), fit = "true curve"),
  data.frame(age = age_seq, rel = curve_rel(fp_base[["a1"]], fp_base[["q1"]]), fit = "fitted, as simulated"),
  data.frame(age = age_seq, rel = curve_rel(fp_trend[["a1"]], fp_trend[["q1"]]), fit = "fitted, hatch-year trend added"))
curve_dat$fit <- factor(curve_dat$fit, levels = c("true curve", "fitted, as simulated",
                                                  "fitted, hatch-year trend added"))
prime_pts <- data.frame(age = c(prime_b, prime_t),
                        rel = c(fp_base[["a1"]] * (prime_b - 1) + fp_base[["q1"]] * (prime_b^2 - 1),
                                fp_trend[["a1"]] * (prime_t - 1) + fp_trend[["q1"]] * (prime_t^2 - 1)),
                        fit = factor(c("fitted, as simulated", "fitted, hatch-year trend added"),
                                     levels = levels(curve_dat$fit)))
fig_identity <- ggplot(curve_dat, aes(age, rel, colour = fit, linetype = fit)) +
  geom_line(linewidth = 1) +
  geom_point(data = prime_pts, size = 3, show.legend = FALSE) +
  scale_colour_manual(values = c(te_body, te_forest, te_rust), name = NULL) +
  scale_linetype_manual(values = c("dashed", "solid", "solid"), name = NULL) +
  scale_x_continuous(breaks = 1:12) +
  guides(colour = guide_legend(nrow = 2)) +
  labs(x = "age (years)", y = "laying date relative to age one (days)",
       title = "Same curvature, different prime age",
       subtitle = "the hatch-year trend enters as a straight line in age") +
  theme_datasheet() + theme(legend.position = "bottom")
fig_identity

## ---- lm-alias ----
lm_age_first <- coef(lm(lay ~ age + fyear + fid, data = base))
lm_age_last  <- coef(lm(lay ~ fyear + fid + age, data = base))
n_na_first <- sum(is.na(lm_age_first)); age_last_na <- is.na(lm_age_last[["age"]])

## ---- natal ----
k_nat <- 0.2                         # trend of the natal index per hatch year
nat_z <- k_nat * ((-n_pre):(n_year - 2)) + rnorm(n_year - 1 + n_pre)
base$natal <- nat_z[base$cohort + n_pre + 1]
natal_age <- function(s) {
  d <- base
  d$lay <- base$lay + (1 - s) * c_trend * base$cohort + s * (c_trend / k_nat) * base$natal
  fixef(lme(lay ~ age + natal + fyear, random = ~ 1 | fid, data = d, control = ctl))[["age"]]
}
nat_0 <- natal_age(0)
nat_ref <- fixef(lme(lay ~ age + natal + fyear, random = ~ 1 | fid, data = base, control = ctl))[["age"]]
shift_full <- natal_age(1) - nat_ref; shift_half <- natal_age(0.5) - nat_ref
shift_none <- nat_0 - nat_ref
