# Parametric survival and the AFT model
# https://tidyecology.com/posts/parametric-survival-aft/
#
# 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-14

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

FOREST <- "#275139"; GOLD <- "#c9b458"; RUST <- "#b5534e"; SAGE <- "#93a87f"
INK <- "#16241d"; BODY <- "#2c3a31"; LINE <- "#dad9ca"

theme_te <- function() {
  theme_minimal(base_size = 12) +
    theme(plot.title = element_text(colour = INK, face = "bold", size = 12),
          plot.subtitle = element_text(colour = BODY, size = 10),
          axis.title = element_text(colour = BODY),
          axis.text = element_text(colour = BODY),
          legend.position = "none",
          panel.grid.minor = element_blank(),
          panel.grid.major = element_line(colour = LINE, linewidth = 0.3),
          plot.background = element_rect(fill = "#f5f4ee", colour = NA),
          panel.background = element_rect(fill = "#f5f4ee", colour = NA))
}
two_panel <- function(pa, pb) {
  grid.newpage(); pushViewport(viewport(layout = grid.layout(1, 2)))
  print(pa, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))
  print(pb, vp = viewport(layout.pos.row = 1, layout.pos.col = 2))
}
haz_weib <- function(t, fit) { a <- 1 / fit$scale; l <- exp(coef(fit)[1]); (a / l) * (t / l)^(a - 1) }
haz_llog <- function(t, fit) { b <- 1 / fit$scale; al <- exp(coef(fit)[1]); ((b / al) * (t / al)^(b - 1)) / (1 + (t / al)^b) }
surv_weib <- function(t, fit) { a <- 1 / fit$scale; l <- exp(coef(fit)[1]); exp(-(t / l)^a) }
surv_llog <- function(t, fit) { b <- 1 / fit$scale; al <- exp(coef(fit)[1]); 1 / (1 + (t / al)^b) }

## ---- fit-a ----
set.seed(4257)
n <- 400; shape_true <- 1.5; scale0 <- 2; log_hr_true <- log(2)
x <- rbinom(n, 1, 0.5)
u <- runif(n)
t_true <- scale0 * exp(-log_hr_true * x / shape_true) * (-log(u))^(1 / shape_true)
cens <- 3.0
obs <- pmin(t_true, cens); dead <- as.integer(t_true <= cens)

wb <- survreg(Surv(obs, dead) ~ x, dist = "weibull")
b_aft <- coef(wb)["x"]; sigma <- wb$scale
accel <- exp(b_aft)
weib_shape <- 1 / sigma
weib_hr <- exp(-b_aft / sigma)

V <- vcov(wb)
ib <- which(names(coef(wb)) == "x"); ils <- which(rownames(V) == "Log(scale)")
grad <- c(-1 / sigma, b_aft / sigma)
se_loghr_w <- sqrt(as.numeric(t(grad) %*% V[c(ib, ils), c(ib, ils)] %*% grad))
weib_hr_ci <- exp(log(weib_hr) + c(-1, 1) * 1.96 * se_loghr_w)

cox <- coxph(Surv(obs, dead) ~ x)
cox_hr <- exp(coef(cox)); cox_hr_ci <- exp(confint(cox))

## ---- predict-a ----
med <- predict(wb, data.frame(x = c(0, 1)), type = "quantile", p = 0.5)
med_ratio <- med[2] / med[1]

## ---- efficiency-b ----
eff_ratio <- function(cens_at, B = 300, seed = 1) {
  set.seed(seed); cl <- wl <- cf <- numeric(B)
  for (b in 1:B) {
    xx <- rbinom(n, 1, 0.5); uu <- runif(n)
    tt <- scale0 * exp(-log_hr_true * xx / shape_true) * (-log(uu))^(1 / shape_true)
    ob <- pmin(tt, cens_at); dd <- as.integer(tt <= cens_at); cf[b] <- mean(1 - dd)
    ww <- survreg(Surv(ob, dd) ~ xx, dist = "weibull")
    cl[b] <- coef(coxph(Surv(ob, dd) ~ xx)); wl[b] <- -coef(ww)["xx"] / ww$scale
  }
  c(cens = mean(cf), cox_sd = sd(cl), weib_sd = sd(wl), ratio = sd(wl) / sd(cl))
}
eff_light <- eff_ratio(3.0, seed = 300)
eff_heavy <- eff_ratio(0.55, seed = 55)

## ---- fig-aft ----
km <- survfit(Surv(obs, dead) ~ x)
km_df <- data.frame(time = km$time, surv = km$surv,
                    grp = rep(c("x = 0", "x = 1"), km$strata))
tg <- seq(0, 3, length = 200)
lam0 <- exp(coef(wb)[1]); lam1 <- exp(coef(wb)[1] + coef(wb)["x"]); aa <- 1 / sigma
par_df <- rbind(
  data.frame(time = tg, surv = exp(-(tg / lam0)^aa), grp = "x = 0"),
  data.frame(time = tg, surv = exp(-(tg / lam1)^aa), grp = "x = 1"))
p1 <- ggplot() +
  geom_step(data = km_df, aes(time, surv, colour = grp), linewidth = 0.5, alpha = 0.5) +
  geom_line(data = par_df, aes(time, surv, colour = grp), linewidth = 1) +
  geom_segment(aes(x = med[2], xend = med[2], y = 0, yend = 0.5), colour = FOREST, linetype = "dashed", linewidth = 0.4) +
  scale_colour_manual(values = c("x = 0" = SAGE, "x = 1" = FOREST)) +
  annotate("text", x = 2.05, y = 0.72, label = "x = 0", colour = "#5d7a5f", hjust = 0, size = 3.4) +
  annotate("text", x = 0.88, y = 0.30, label = "x = 1", colour = FOREST, hjust = 1, size = 3.4) +
  labs(title = "Weibull survival, two groups", x = "years", y = "survival probability") +
  coord_cartesian(ylim = c(0, 1)) + theme_te()

fr <- data.frame(model = factor(c("Weibull\n(implied)", "Cox"), levels = c("Cox", "Weibull\n(implied)")),
                 hr = c(weib_hr, cox_hr),
                 lo = c(weib_hr_ci[1], cox_hr_ci[1]), hi = c(weib_hr_ci[2], cox_hr_ci[2]))
p2 <- ggplot(fr, aes(hr, model)) +
  geom_vline(xintercept = 2, colour = LINE, linewidth = 0.5, linetype = "dashed") +
  geom_pointrange(aes(xmin = lo, xmax = hi), colour = FOREST, linewidth = 0.8, size = 0.6) +
  labs(title = "Same effect, two models", x = "hazard ratio", y = NULL) +
  coord_cartesian(xlim = c(1.4, 2.7)) + theme_te()
two_panel(p1, p2)

## ---- fit-c ----
set.seed(4259)
nc <- 500; mu_c <- log(2.2); s_c <- 0.55
t_ll <- exp(mu_c + s_c * qlogis(runif(nc)))
cc <- 3.5
obs_c <- pmin(t_ll, cc); dead_c <- as.integer(t_ll <= cc)

fit_w  <- survreg(Surv(obs_c, dead_c) ~ 1, dist = "weibull")
fit_ll <- survreg(Surv(obs_c, dead_c) ~ 1, dist = "loglogistic")
fit_ln <- survreg(Surv(obs_c, dead_c) ~ 1, dist = "lognormal")
aic <- c(weibull = AIC(fit_w), loglogistic = AIC(fit_ll), lognormal = AIC(fit_ln))
best <- names(which.min(aic))
tg2 <- seq(0.05, 3, length = 200)
hump_peak <- tg2[which.max(haz_llog(tg2, fit_ll))]

## ---- fig-hazard ----
haz_df <- rbind(
  data.frame(time = tg2, h = haz_weib(tg2, fit_w), what = "Weibull"),
  data.frame(time = tg2, h = haz_llog(tg2, fit_ll), what = "log-logistic"))
p3 <- ggplot(haz_df, aes(time, h, colour = what)) +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("Weibull" = RUST, "log-logistic" = FOREST)) +
  annotate("text", x = 1.9, y = 0.50, label = "Weibull", colour = RUST, hjust = 0, size = 3.4) +
  annotate("text", x = 0.9, y = 0.30, label = "log-logistic", colour = FOREST, hjust = 0, size = 3.4) +
  labs(title = "Hazard shape, right and wrong", x = "years", y = "hazard") +
  theme_te()

tg3 <- seq(0.05, 12, length = 300)
surv_df <- rbind(
  data.frame(time = tg3, s = surv_weib(tg3, fit_w), what = "Weibull"),
  data.frame(time = tg3, s = surv_llog(tg3, fit_ll), what = "log-logistic"))
p4 <- ggplot(surv_df, aes(time, s, colour = what)) +
  geom_vline(xintercept = cc, colour = LINE, linewidth = 0.5, linetype = "dashed") +
  geom_line(linewidth = 1) +
  scale_colour_manual(values = c("Weibull" = RUST, "log-logistic" = FOREST)) +
  annotate("text", x = 3.6, y = 0.55, label = "data limit", colour = "#8a8a80", hjust = 0, size = 3.1) +
  annotate("text", x = 7.5, y = 0.28, label = "log-logistic", colour = FOREST, hjust = 0, size = 3.4) +
  annotate("text", x = 6.0, y = 0.05, label = "Weibull", colour = RUST, hjust = 0, size = 3.4) +
  labs(title = "In-range agreement, tail divergence", x = "years", y = "survival probability") +
  theme_te()
two_panel(p3, p4)

## ---- tail-c ----
qs <- c(0.5, 0.9, 0.95)
q_w  <- predict(fit_w,  data.frame(z = 1)[1, , drop = FALSE], type = "quantile", p = qs)
q_ll <- predict(fit_ll, data.frame(z = 1)[1, , drop = FALSE], type = "quantile", p = qs)
tail_gap <- q_ll[3] - q_w[3]
