# Checking a survival model
# https://tidyecology.com/posts/checking-a-survival-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-10-07

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

## ---- ph-test ----
set.seed(4260)
n <- 400
x_np <- rbinom(n, 1, 0.5)
t_np <- exp(log(2) - 0.6 * x_np + 0.6 * qlogis(runif(n)))
o_np <- pmin(t_np, 3.5); d_np <- as.integer(t_np <= 3.5)
zph_np <- cox.zph(coxph(Surv(o_np, d_np) ~ x_np))

x_p <- rbinom(n, 1, 0.5); a <- 1.4; lam0 <- 2
t_p <- lam0 * exp(-log(2) * x_p / a) * (-log(runif(n)))^(1 / a)
o_p <- pmin(t_p, 4); d_p <- as.integer(t_p <= 4)
zph_p <- cox.zph(coxph(Surv(o_p, d_p) ~ x_p))

p_np <- zph_np$table["x_np", "p"]
p_p <- zph_p$table["x_p", "p"]

## ---- functional-form ----
set.seed(4261)
nb <- 500; z <- runif(nb, 0, 4)
t_b <- -log(runif(nb)) / (0.4 * exp(0.9 * (z - 2)^2))
o_b <- pmin(t_b, 3); d_b <- as.integer(t_b <= 3)
mart_null <- residuals(coxph(Surv(o_b, d_b) ~ 1), type = "martingale")
sm <- lowess(z, mart_null, f = 0.5)
z_min <- sm$x[which.min(sm$y)]
aic_lin <- AIC(coxph(Surv(o_b, d_b) ~ z))
aic_poly <- AIC(coxph(Surv(o_b, d_b) ~ poly(z, 2)))

## ---- fig-cox-diag ----
sch_df <- rbind(
  data.frame(time = zph_np$x, resid = as.numeric(zph_np$y[, 1]), cov = "converging (non-PH)"),
  data.frame(time = zph_p$x, resid = as.numeric(zph_p$y[, 1]), cov = "constant (PH)"))
p1 <- ggplot(sch_df, aes(time, resid, colour = cov)) +
  geom_hline(yintercept = 0, colour = LINE, linewidth = 0.5) +
  geom_point(size = 0.7, alpha = 0.4) +
  geom_smooth(method = "lm", formula = y ~ x, se = FALSE, linewidth = 1) +
  scale_colour_manual(values = c("converging (non-PH)" = RUST, "constant (PH)" = FOREST)) +
  annotate("text", x = 0.02, y = 1.3, label = "converging (non-PH)", colour = RUST, hjust = 0, size = 3.1) +
  annotate("text", x = 0.55, y = 1.3, label = "constant (PH)", colour = FOREST, hjust = 0, size = 3.1) +
  labs(title = "Schoenfeld residuals vs time", x = "time (transformed)", y = "scaled residual") +
  scale_x_continuous(breaks = seq(0, 0.75, 0.25)) +
  coord_cartesian(ylim = c(-3.2, 5.2)) + theme_te()

ff_df <- data.frame(z = z, m = mart_null)
sm_df <- data.frame(z = sm$x, m = sm$y)
p2 <- ggplot(ff_df, aes(z, m)) +
  geom_point(colour = SAGE, size = 0.7, alpha = 0.4) +
  geom_line(data = sm_df, aes(z, m), colour = FOREST, linewidth = 1.1) +
  geom_vline(xintercept = 2, colour = GOLD, linewidth = 0.5, linetype = "dashed") +
  annotate("text", x = 2.1, y = -2.2, label = "true minimum", colour = "#8a7420", hjust = 0, size = 3.1) +
  labs(title = "Martingale residuals vs covariate", x = "covariate z", y = "martingale residual") +
  theme_te()
two_panel(p1, p2)

## ---- cox-snell ----
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; o_c <- pmin(t_ll, cc); d_c <- as.integer(t_ll <= cc)
fit_w  <- survreg(Surv(o_c, d_c) ~ 1, dist = "weibull")
fit_ll <- survreg(Surv(o_c, d_c) ~ 1, dist = "loglogistic")
cs_w  <- { a <- 1 / fit_w$scale;  l <- exp(coef(fit_w)[1]); (o_c / l)^a }
cs_ll <- { b <- 1 / fit_ll$scale; al <- exp(coef(fit_ll)[1]); log(1 + (o_c / al)^b) }
na_dev <- function(cs, d) {
  sf <- survfit(Surv(cs, d) ~ 1); H <- sf$cumhaz
  max(abs(H - sf$time))
}
dev_w <- na_dev(cs_w, d_c); dev_ll <- na_dev(cs_ll, d_c)

## ---- power-limit ----
power_zph <- function(nn, B = 200, seed = 7) {
  set.seed(seed); k <- 0
  for (b in 1:B) {
    x <- rbinom(nn, 1, 0.5); tt <- exp(log(2) - 0.6 * x + 0.6 * qlogis(runif(nn)))
    oo <- pmin(tt, 3.5); dd <- as.integer(tt <= 3.5)
    if (cox.zph(coxph(Surv(oo, dd) ~ x))$table["x", "p"] < 0.05) k <- k + 1
  }
  k / B
}
ns <- c(80, 200, 500, 1000)
pw <- sapply(ns, power_zph)

## ---- omitted-limit ----
set.seed(4262); B <- 250; flag_omit <- flag_full <- 0
for (b in 1:B) {
  nd <- 350; x1 <- rbinom(nd, 1, 0.5); x2 <- rnorm(nd)
  td <- lam0 * exp(-(log(2) * x1 + 1.5 * x2) / a) * (-log(runif(nd)))^(1 / a)
  od <- pmin(td, 4); dd <- as.integer(td <= 4)
  if (cox.zph(coxph(Surv(od, dd) ~ x1))$table["x1", "p"] < 0.05) flag_omit <- flag_omit + 1
  if (cox.zph(coxph(Surv(od, dd) ~ x1 + x2))$table["x1", "p"] < 0.05) flag_full <- flag_full + 1
}
rate_omit <- flag_omit / B; rate_full <- flag_full / B

## ---- fig-limits ----
na_curve <- function(cs, d, lab) {
  sf <- survfit(Surv(cs, d) ~ 1)
  data.frame(cs = sf$time, H = sf$cumhaz, what = lab)
}
cs_df <- rbind(na_curve(cs_w, d_c, "Weibull"), na_curve(cs_ll, d_c, "log-logistic"))
lim <- max(cs_df$cs)
p3 <- ggplot(cs_df, aes(cs, H, colour = what)) +
  geom_abline(slope = 1, intercept = 0, colour = LINE, linewidth = 0.6, linetype = "dashed") +
  geom_step(linewidth = 1) +
  scale_colour_manual(values = c("Weibull" = RUST, "log-logistic" = FOREST)) +
  annotate("text", x = 0.3 * lim, y = 0.9 * lim, label = "Weibull", colour = RUST, hjust = 0, size = 3.4) +
  annotate("text", x = 0.55 * lim, y = 0.35 * lim, label = "log-logistic", colour = FOREST, hjust = 0, size = 3.4) +
  labs(title = "Cox-Snell residuals vs 45 degrees", x = "Cox-Snell residual", y = "cumulative hazard") +
  coord_cartesian(xlim = c(0, lim), ylim = c(0, lim)) + theme_te()

pw_df <- data.frame(n = ns, power = pw)
p4 <- ggplot(pw_df, aes(n, power)) +
  geom_hline(yintercept = 0.8, colour = LINE, linewidth = 0.5, linetype = "dashed") +
  geom_line(colour = FOREST, linewidth = 1) + geom_point(colour = FOREST, size = 2) +
  annotate("text", x = 300, y = 0.84, label = "0.8", colour = "#8a8a80", size = 3.1) +
  labs(title = "Power of the PH test", x = "animals", y = "detection rate") +
  coord_cartesian(ylim = c(0, 1)) + theme_te()
two_panel(p3, p4)
