Survival II: Parametric Models and Extrapolation
A cost-effectiveness model of a chronic disease runs for a lifetime. The trial behind it ran for three years. Something has to fill the gap. Today you fit five parametric survival models to the Renavex trial and see that they agree inside the trial and disagree wildly outside it, by up to 15 years of mean survival. AIC cannot choose between them. You then borrow the hazard's shape from Corridor Health's own mortality data and check every option against the generator's true lifetimes.
By the end of today you can
- fit exponential, Weibull, Gompertz, log-logistic and log-normal models to censored data and compare their AIC
- explain why AIC within the trial does not choose an extrapolation
- check the hazard each model implies against clinical sense and external data
- report RMST within the trial and mean survival only from an extrapolated curve
- present extrapolation and treatment-waning scenarios, discounted and undiscounted
Today's 5.5-hour plan
In this lesson
- 14.1 The Renavex trial: three years of data, a lifetime question
- 14.2 Five parametric models
- 14.3 Look at the hazard
- 14.4 Borrow the shape from external data
- 14.5 Truth check: which extrapolation was right?
- 14.6 The treatment effect inside and beyond the trial
- 14.7 Mean survival from a Kaplan–Meier curve
- 14.8 Mini-project: survival scenarios for the Renavex model
14.1 The Renavex trial: three years of data, a lifetime question (30 min)
The generator now writes renavex_trial.csv, the sponsor's pivotal trial as a CDA-AMC reviewer would receive it. It has 3,000 adults with type 2 diabetes and CKD (eGFR 25–60), randomized 1:1 to Renavex or placebo between March 2021 and August 2022, with a data cut on 1 March 2024. Each row has the randomization date, the dates of kidney failure and death if they happened, the last contact and why follow-up ended. The true event times, without censoring, are in data/truth/trial_event_times.csv.
"""Days 14-15: the Renavex pivotal trial extract (data/renavex_trial.csv).
Times are in years from randomization (days / 365.25). Follow-up ends at death, withdrawal or the
data cut (1 March 2024), whichever comes first.
"""
import os
import duckdb
from corridor.db import DATA
TRIAL = os.path.join(DATA, "renavex_trial.csv").replace("\\", "/")
TRIAL_SQL = f"""
SELECT patient_id, arm, (arm = 'renavex')::INT AS renavex, age, sex, egfr, region, randomized,
date_diff('day', randomized, last_contact) / 365.25 AS t_end,
(death_date IS NOT NULL)::INT AS died,
date_diff('day', randomized, coalesce(kidney_failure_date, last_contact)) / 365.25 AS t_kf,
(kidney_failure_date IS NOT NULL)::INT AS kf,
end_reason
FROM read_csv('{TRIAL}', types = {{'kidney_failure_date': 'DATE', 'death_date': 'DATE'}})
ORDER BY patient_id"""
def load(con=None):
"""One row per patient: t_end/died (overall survival), t_kf/kf (kidney failure; death or the end
of follow-up censors)."""
con = con or duckdb.connect()
df = con.sql(TRIAL_SQL).df()
df["t_end"] = df["t_end"].clip(lower=1 / 365.25) # a death on the day of randomization counts as day 1
df["t_kf"] = df["t_kf"].clip(lower=1 / 365.25)
return df
"""Day 14.1: the Renavex trial extract - what three years of follow-up can and cannot tell us."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.parametric import rmst_km # noqa: E402
from corridor.survival import km, surv_at # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
print(f"{len(df):,} patients randomized 2021-03-01 to 2022-08-31; data cut 2024-03-01")
print(f"{'arm':<9}{'patients':>9}{'deaths':>8}{'kidney failure':>16}{'withdrew':>10}{'person-years':>14}"
f"{'max years':>11}{'S(3) KM':>9}{'RMST(3)':>9}")
for arm, g in df.groupby("arm"):
tab = km(g.t_end, g.died)
print(f"{arm:<9}{len(g):>9,}{g.died.sum():>8}{g.kf.sum():>16}{(g.end_reason == 'withdrew').sum():>10}"
f"{g.t_end.sum():>14,.0f}{g.t_end.max():>11.2f}{surv_at(tab, 3):>9.3f}{rmst_km(tab, 3):>9.3f}")
reverse = km(df.t_end, 1 - df.died) # reverse Kaplan-Meier: "event" = being censored
median_fu = reverse.time[reverse.surv <= 0.5].iloc[0]
print(f"\nmedian follow-up (reverse Kaplan-Meier): {median_fu:.2f} years")
print("Kaplan-Meier never reaches 50% in either arm: median survival is not estimable from the trial.")
3,000 patients randomized 2021-03-01 to 2022-08-31; data cut 2024-03-01
arm patients deaths kidney failure withdrew person-years max years S(3) KM RMST(3)
placebo 1,485 101 152 100 3,075 3.00 0.892 2.858
renavex 1,515 91 116 99 3,176 3.00 0.907 2.876
median follow-up (reverse Kaplan-Meier): 2.16 years
Kaplan-Meier never reaches 50% in either arm: median survival is not estimable from the trial.
Follow-up ends at the data cut for most patients. Because enrolment took 18 months, that cut falls between 1.5 and 3 years after randomization: this is administrative censoring, and it is staggered, unlike Module 2's cohort. The median follow-up, estimated by the reverse Kaplan–Meier method (treat censoring as the "event"), is 2.2 years. About 89% of placebo patients are alive at 3 years, so the trial cannot estimate median survival, let alone mean survival.
A cost-utility model needs mean survival: the area under the survival curve over a lifetime. The trial gives the curve for 3 years. The rest is extrapolation, and NICE DSU Technical Support Document 14 and the CDA-AMC guidelines both ask you to justify it.
14.2 Five parametric models (40 min)
A parametric model gives $S(t)$ a formula. Each one fixes how the hazard can change over time:
| Model | $S(t)$ | Hazard over time |
|---|---|---|
| Exponential | $e^{-\lambda t}$ | constant |
| Weibull | $e^{-\lambda t^k}$ | always rising ($k>1$) or always falling ($k<1$) |
| Gompertz | $\exp!\left(-\frac{a}{b}(e^{bt}-1)\right)$ | rises (or falls) exponentially: $h(t) = a e^{bt}$ |
| Log-logistic | $1 / (1 + (t/\alpha)^\beta)$ | can rise, then fall |
| Log-normal | $1 - \Phi!\left(\frac{\log t - \mu}{\sigma}\right)$ | rises, then falls |
With censoring, each person contributes $\log h(t_i)$ if they had the event and $-H(t_i)$ either way, where $H$ is the cumulative hazard. corridor/parametric.py maximizes that log-likelihood:
def _exp(p, t):
lam = np.exp(p[0])
return np.log(lam) + 0 * t, lam * t
def _weibull(p, t): # S(t) = exp(-lam t^k)
lam, k = np.exp(p[0]), np.exp(p[1])
return np.log(lam * k) + (k - 1) * np.log(t), lam * t**k
def _gompertz(p, t): # h(t) = a exp(b t); b may be negative
a, b = np.exp(p[0]), p[1]
H = a * t if abs(b) < 1e-9 else a / b * np.expm1(b * t)
return np.log(a) + b * t, H
def _loglogistic(p, t): # S(t) = 1 / (1 + (t / alpha)^beta)
alpha, beta = np.exp(p[0]), np.exp(p[1])
z = (t / alpha) ** beta
return np.log(beta / alpha) + (beta - 1) * np.log(t / alpha) - np.log1p(z), np.log1p(z)
def _lognormal(p, t): # log T ~ Normal(mu, sigma)
mu, sigma = p[0], np.exp(p[1])
z = (np.log(t) - mu) / sigma
log_s = stats.norm.logsf(z)
return stats.norm.logpdf(z) - np.log(sigma * t) - log_s, -log_s
DISTRIBUTIONS = {
"exponential": (_exp, [np.log(0.05)]),
"Weibull": (_weibull, [np.log(0.05), 0.0]),
"Gompertz": (_gompertz, [np.log(0.05), 0.0]),
"log-logistic": (_loglogistic, [np.log(20.0), 0.0]),
"log-normal": (_lognormal, [3.0, 0.0]),
}
class Fit:
def __init__(self, name, time, event):
self.name = name
f, start = DISTRIBUTIONS[name]
t, d = np.asarray(time, float), np.asarray(event, float)
def nll(p):
log_h, H = f(p, t)
return -(d * log_h - H).sum()
res = optimize.minimize(nll, start, method="Nelder-Mead",
options={"xatol": 1e-9, "fatol": 1e-9, "maxiter": 20_000})
self.params, self._f = res.x, f
self.loglik = -res.fun
self.k = len(start)
self.aic = 2 * self.k - 2 * self.loglik
self.bic = self.k * np.log(len(t)) - 2 * self.loglik
def hazard(self, t):
return np.exp(self._f(self.params, np.maximum(np.asarray(t, float), 1e-9))[0])
def surv(self, t):
return np.exp(-self._f(self.params, np.maximum(np.asarray(t, float), 1e-9))[1])
def mean(self, horizon=35.0, step=0.01, discount=0.0):
"""Mean survival restricted to `horizon` years: the area under S(t) (trapezoid rule).
With `discount` (e.g. 0.015), each year is weighted by (1 + discount)^-t: discounted life-years."""
return area(self.surv, horizon, step, discount)
def area(surv, horizon=35.0, step=0.01, discount=0.0):
"""Area under a survival function from 0 to `horizon`, optionally discounted continuously."""
grid = np.arange(0, horizon + step / 2, step)
s = np.concatenate([[1.0], surv(grid[1:])]) * (1 + discount) ** -grid
return float(np.trapezoid(s, dx=step))
def rmst_km(km_table, tau):
"""Restricted mean survival time: the area under a Kaplan-Meier step curve up to tau."""
times = [0.0] + [t for t in km_table["time"] if t < tau] + [tau]
surv = [1.0] + [s for t, s in zip(km_table["time"], km_table["surv"]) if t < tau]
return float(sum(s * (b - a) for s, a, b in zip(surv, times[:-1], times[1:])))
Fit all five to each arm, and look at the fit inside the trial and the predictions far outside it:
"""Day 14.2-14.3: five parametric models per arm - fit inside the trial, disagreement outside it."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib # noqa: E402
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.parametric import DISTRIBUTIONS, Fit # noqa: E402
from corridor.survival import km, surv_at # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
colours = {"exponential": "#9aa6bf", "Weibull": "#4f9cf9", "Gompertz": "#e5484d",
"log-logistic": "#f5a524", "log-normal": "#3ecf8e"}
fig, ax = plt.subplots(1, 2, figsize=(10, 3.8), sharey=True)
for i, (arm, g) in enumerate(df.groupby("arm")):
tab = km(g.t_end, g.died)
print(f"--- {arm}: {len(g):,} patients, {g.died.sum()} deaths; Kaplan-Meier S(3) = {surv_at(tab, 3):.3f}")
print(f"{'model':<14}{'AIC':>8}{'BIC':>8}{'S(3)':>7}{'S(10)':>7}{'S(20)':>7}{'mean (35 y)':>12}")
for name in DISTRIBUTIONS:
f = Fit(name, g.t_end, g.died)
print(f"{name:<14}{f.aic:>8.1f}{f.bic:>8.1f}{f.surv(3):>7.3f}{f.surv(10):>7.3f}{f.surv(20):>7.3f}{f.mean():>12.1f}")
grid = np.linspace(0, 30, 301)
ax[i].plot(grid, f.surv(grid), color=colours[name], lw=1.6, label=name)
ax[i].step([0] + list(tab.time), [1] + list(tab.surv), where="post", color="black", lw=1.4, label="Kaplan-Meier")
ax[i].axvspan(0, df.t_end.max(), color="#888", alpha=0.12)
ax[i].set(title=f"{arm}: overall survival", xlabel="years since randomization", ylim=(0, 1), xlim=(0, 30))
ax[0].set_ylabel("proportion alive")
ax[1].legend(fontsize=8, loc="upper right")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day14_extrapolations.png"), dpi=130)
--- placebo: 1,485 patients, 101 deaths; Kaplan-Meier S(3) = 0.892
model AIC BIC S(3) S(10) S(20) mean (35 y)
exponential 894.0 899.3 0.906 0.720 0.518 20.8
Weibull 896.0 906.6 0.906 0.715 0.508 20.5
Gompertz 895.3 905.9 0.902 0.580 0.101 11.6
log-logistic 896.3 907.0 0.907 0.737 0.578 22.6
log-normal 901.9 912.5 0.912 0.802 0.712 26.3
--- renavex: 1,515 patients, 91 deaths; Kaplan-Meier S(3) = 0.907
model AIC BIC S(3) S(10) S(20) mean (35 y)
exponential 830.6 835.9 0.918 0.751 0.564 22.1
Weibull 832.6 843.2 0.918 0.751 0.564 22.1
Gompertz 831.5 842.1 0.913 0.568 0.042 10.9
log-logistic 833.0 843.6 0.918 0.768 0.621 23.8
log-normal 838.3 849.0 0.923 0.826 0.745 27.3

Inside the grey band, the five curves sit on top of the Kaplan–Meier curve and on top of each other. Every AIC is within 8 points, and the exponential, the simplest, has the lowest AIC. Outside it, at 20 years, they predict between 10% and 71% of placebo patients alive, and mean survival from 11.6 to 26.3 years. Fit statistics measure how well a model describes the data you have. They say nothing about the 32 years you don't have.
Check it in R. flexsurv fits the same models, plus a generalized gamma and a Royston–Parmar spline:
# Day 14: the same models with flexsurv, plus two Python doesn't have: generalized gamma and a spline.
suppressPackageStartupMessages({ library(survival); library(flexsurv) })
tr <- read.csv("data/renavex_trial.csv")
tr$t_end <- pmax(as.numeric(as.Date(tr$last_contact) - as.Date(tr$randomized)) / 365.25, 1 / 365.25)
tr$died <- as.integer(tr$death_date != "")
pla <- subset(tr, arm == "placebo")
dists <- c(exponential = "exp", Weibull = "weibull", Gompertz = "gompertz", `log-logistic` = "llogis",
`log-normal` = "lnorm", `generalized gamma` = "gengamma")
cat(sprintf("%-20s %9s %8s %7s %7s\n", "placebo model", "logLik", "AIC", "S(10)", "S(20)"))
for (nm in names(dists)) {
f <- flexsurvreg(Surv(t_end, died) ~ 1, data = pla, dist = dists[[nm]])
s <- summary(f, t = c(10, 20), ci = FALSE)[[1]]$est
cat(sprintf("%-20s %9.2f %8.1f %7.3f %7.3f\n", nm, f$loglik, f$AIC, s[1], s[2]))
}
sp <- flexsurvspline(Surv(t_end, died) ~ 1, data = pla, k = 1, scale = "hazard")
s <- summary(sp, t = c(10, 20), ci = FALSE)[[1]]$est
cat(sprintf("%-20s %9.2f %8.1f %7.3f %7.3f\n", "spline, 1 knot", sp$loglik, sp$AIC, s[1], s[2]))
placebo model logLik AIC S(10) S(20)
exponential -446.01 894.0 0.720 0.518
Weibull -446.00 896.0 0.715 0.508
Gompertz -445.66 895.3 0.580 0.101
log-logistic -446.17 896.3 0.737 0.578
log-normal -448.93 901.9 0.802 0.712
generalized gamma -445.83 897.7 0.686 0.392
spline, 1 knot -445.47 896.9 0.680 0.436
The log-likelihoods match Python's to the second decimal. The two flexible models land in the middle (39–44% alive at 20 years). Flexible is not the same as right: they still extrapolate a shape guessed from three years.
14.3 Look at the hazard (35 min)
The models differ in one thing: what they assume the hazard does after year 3. So look at the hazard the data show, as deaths per 100 person-years in each interval:
"""Day 14.4: look at the hazard - what each model assumes, and what the data show."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.parametric import DISTRIBUTIONS, Fit # noqa: E402
from corridor.trial import load # noqa: E402
g = load().query("arm == 'placebo'")
cuts = [0, 0.5, 1.0, 1.5, 2.0, 3.0]
fits = {n: Fit(n, g.t_end, g.died) for n in DISTRIBUTIONS}
print("Placebo deaths per 100 person-years, by interval of follow-up, and each model's hazard at the midpoint")
print(f"{'years':<10}{'deaths':>7}{'PY':>7}{'rate':>7}{'95% CI':>14}" + "".join(f"{n[:8]:>9}" for n in fits))
for a, b in zip(cuts[:-1], cuts[1:]):
py = (np.clip(g.t_end, a, b) - a).sum()
d = ((g.died == 1) & (g.t_end > a) & (g.t_end <= b)).sum()
lo, hi = (100 * np.exp(np.log(d / py) + z / np.sqrt(d)) for z in (-1.96, 1.96))
mid = (a + b) / 2
print(f"{a:.1f}-{b:.1f} {d:>7}{py:>7.0f}{100 * d / py:>7.2f}{lo:>7.2f}-{hi:<6.2f}"
+ "".join(f"{100 * f.hazard(mid):>9.2f}" for f in fits.values()))
print("\nModel hazards per 100 person-years at 10 and 20 years:")
for n, f in fits.items():
print(f" {n:<13} {100 * f.hazard(10):6.2f} {100 * f.hazard(20):6.2f}")
Placebo deaths per 100 person-years, by interval of follow-up, and each model's hazard at the midpoint
years deaths PY rate 95% CI exponent Weibull Gompertz log-logi log-norm
0.0-0.5 19 732 2.60 1.66-4.07 3.28 3.23 2.96 3.25 3.87
0.5-1.0 28 709 3.95 2.73-5.72 3.28 3.28 3.13 3.31 3.54
1.0-1.5 20 683 2.93 1.89-4.54 3.28 3.30 3.32 3.31 3.19
1.5-2.0 19 545 3.48 2.22-5.46 3.28 3.32 3.52 3.29 2.92
2.0-3.0 15 407 3.69 2.22-6.12 3.28 3.33 3.84 3.25 2.61
Model hazards per 100 person-years at 10 and 20 years:
exponential 3.28 3.28
Weibull 3.40 3.43
Gompertz 9.22 29.59
log-logistic 2.71 2.18
log-normal 1.45 1.00
The observed rates move between 2.6 and 4.0 per 100 person-years, with confidence intervals wide enough to hold every model's hazard. Three years of data cannot tell a flat hazard from a rising one. But the models' hazards at 10 and 20 years differ by a factor of 30: the log-normal says 1 death per 100 person-years at 20 years, the Gompertz says 30.
Ask the clinical question instead. These patients are 66 on average at entry. Will their death rate in their eighties be lower than in their sixties? Every model except the Gompertz says it will stay flat or fall. That is implausible for an aging population, and it is the kind of argument a reviewer expects in the extrapolation section.
14.4 Borrow the shape from external data (40 min)
The trial cannot tell you how fast the hazard rises, but other data can. Mortality in a cohort rises with age, and a cohort followed for $t$ years is $t$ years older. Module 2's Corridor Health cohort (adults 66+ with diabetes and CKD) tells you how fast. Fix the Gompertz slope $b$ at that value and estimate only the level $a$ from the trial:
class AnchoredGompertz:
"""Gompertz with the slope b fixed from external data (how fast mortality rises with age);
only the level a is estimated from the trial."""
name = "Gompertz, b fixed"
def __init__(self, time, event, b):
t, d = np.asarray(time, float), np.asarray(event, float)
self.b = b
nll = lambda la: -(d * (la + b * t) - np.exp(la) / b * np.expm1(b * t)).sum() # noqa: E731
res = optimize.minimize_scalar(nll, bounds=(-15, 2), method="bounded", options={"xatol": 1e-10})
self.a = float(np.exp(res.x))
self.loglik, self.k = -res.fun, 1
self.aic = 2 - 2 * self.loglik
def hazard(self, t):
return self.a * np.exp(self.b * np.asarray(t, float))
def surv(self, t):
return np.exp(-self.a / self.b * np.expm1(self.b * np.asarray(t, float)))
mean = Fit.mean
"""Day 14.5: borrow the shape from external data - how fast mortality rises with age in Corridor Health."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.m2 import load as load_cohort # noqa: E402
from corridor.parametric import AnchoredGompertz, Fit # noqa: E402
from corridor.trial import load # noqa: E402
cohort = load_cohort() # Module 2 analysis file: 6,224 people, 432 deaths in 2025
cox = PHReg.from_formula("t_end ~ age", cohort, status=cohort.died, ties="efron").fit()
b, se = float(cox.params[0]), float(cox.bse[0])
print(f"External evidence: in the Corridor Health CKD-diabetes cohort, each year of age multiplies the "
f"death hazard by {np.exp(b):.3f} (log HR {b:.4f}, SE {se:.4f}).")
print("A cohort that is followed for t years is t years older, so a Gompertz hazard a*exp(b t) with this b"
" ages the trial population at the rate seen in the population.\n")
df = load()
print(f"{'arm':<9}{'model':<20}{'AIC':>8}{'S(10)':>7}{'S(20)':>7}{'mean (35 y)':>12}")
for arm, g in df.groupby("arm"):
for f in (Fit("Gompertz", g.t_end, g.died), AnchoredGompertz(g.t_end, g.died, b)):
print(f"{arm:<9}{f.name:<20}{f.aic:>8.1f}{f.surv(10):>7.3f}{f.surv(20):>7.3f}{f.mean():>12.1f}")
free = Fit("Gompertz", g.t_end, g.died)
print(f"{'':<9}free Gompertz b = {free.params[1]:.3f}; anchored b = {b:.3f}")
External evidence: in the Corridor Health CKD-diabetes cohort, each year of age multiplies the death hazard by 1.099 (log HR 0.0942, SE 0.0054).
A cohort that is followed for t years is t years older, so a Gompertz hazard a*exp(b t) with this b ages the trial population at the rate seen in the population.
arm model AIC S(10) S(20) mean (35 y)
placebo Gompertz 895.3 0.580 0.101 11.6
placebo Gompertz, b fixed 893.3 0.613 0.174 12.7
free Gompertz b = 0.117; anchored b = 0.094
renavex Gompertz 831.5 0.568 0.042 10.9
renavex Gompertz, b fixed 829.6 0.653 0.218 13.6
free Gompertz b = 0.153; anchored b = 0.094
In the administrative data, each year of age multiplies the death hazard by 1.099 ($b$ = 0.094). The free Gompertz fits had estimated a steeper rise from the trial alone (0.117 for placebo, 0.153 for Renavex), with very wide uncertainty. The anchored model has one parameter fewer and a lower AIC. It gives a mean survival of 12.7 years on placebo and 13.6 on Renavex.
This is what HTA guidance means by using external data: registry or population mortality to set the long-run shape, with the trial setting the level and the treatment effect. In practice the external source is Statistics Canada life tables, a disease registry or an ICES cohort. Here it is your own Module 1 cohort.
Why it matters at work: In most cost-utility models of a chronic condition, the extrapolation of survival is the assumption that moves the ICER most. CDA-AMC reviewers routinely re-run the sponsor's model with a different curve, and the choice is argued in committee.
Where you'll meet this: every partitioned survival and Markov model built on trial data (Module 6) · CDA-AMC clinical and economic review reports · NICE DSU TSD 14 and TSD 21 (flexible methods)
14.5 Truth check: which extrapolation was right? (25 min)
The generator knows every patient's true lifetime, uncensored. Compare each model's prediction with it:
"""Day 14.6 (truth check): which extrapolation was right? The generator knows every patient's death time."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import numpy as np # noqa: E402
from corridor.parametric import DISTRIBUTIONS, AnchoredGompertz, Fit # noqa: E402
from corridor.trial import load # noqa: E402
from corridor.truth import TRUTH # noqa: E402
B_EXTERNAL = 0.0942 # from day14/anchored_gompertz.py
df = load()
true = duckdb.sql(f"SELECT patient_id, t_death FROM read_csv('{TRUTH}/trial_event_times.csv')").df()
df = df.merge(true, on="patient_id")
for arm, g in df.groupby("arm"):
t = g.t_death.to_numpy()
print(f"--- {arm}: TRUE S(10) {np.mean(t > 10):.3f} S(20) {np.mean(t > 20):.3f} "
f"mean (35 y) {np.minimum(t, 35).mean():.1f}")
fits = [Fit(n, g.t_end, g.died) for n in DISTRIBUTIONS] + [AnchoredGompertz(g.t_end, g.died, B_EXTERNAL)]
for f in sorted(fits, key=lambda f: abs(f.mean() - np.minimum(t, 35).mean())):
print(f" {f.name:<18} S(10) {f.surv(10):.3f} S(20) {f.surv(20):.3f} mean {f.mean():5.1f} "
f"error {f.mean() - np.minimum(t, 35).mean():+5.1f} years AIC {f.aic:.1f}")
--- placebo: TRUE S(10) 0.565 S(20) 0.154 mean (35 y) 12.2
Gompertz, b fixed S(10) 0.613 S(20) 0.174 mean 12.7 error +0.5 years AIC 893.3
Gompertz S(10) 0.580 S(20) 0.101 mean 11.6 error -0.6 years AIC 895.3
Weibull S(10) 0.715 S(20) 0.508 mean 20.5 error +8.3 years AIC 896.0
exponential S(10) 0.720 S(20) 0.518 mean 20.8 error +8.6 years AIC 894.0
log-logistic S(10) 0.737 S(20) 0.578 mean 22.6 error +10.4 years AIC 896.3
log-normal S(10) 0.802 S(20) 0.712 mean 26.3 error +14.1 years AIC 901.9
--- renavex: TRUE S(10) 0.620 S(20) 0.203 mean (35 y) 13.4
Gompertz, b fixed S(10) 0.653 S(20) 0.218 mean 13.6 error +0.2 years AIC 829.6
Gompertz S(10) 0.568 S(20) 0.042 mean 10.9 error -2.5 years AIC 831.5
exponential S(10) 0.751 S(20) 0.564 mean 22.1 error +8.7 years AIC 830.6
Weibull S(10) 0.751 S(20) 0.564 mean 22.1 error +8.7 years AIC 832.6
log-logistic S(10) 0.768 S(20) 0.621 mean 23.8 error +10.5 years AIC 833.0
log-normal S(10) 0.826 S(20) 0.745 mean 27.3 error +14.0 years AIC 838.3
In both arms the anchored Gompertz is closest: within 0.5 years of the true mean (12.2 and 13.4 years). The models with the best AIC (exponential and Weibull) overstate mean survival by more than 8 years. The free Gompertz has the right shape but a slope estimated from too few deaths, so in the Renavex arm it is 2.5 years too pessimistic. The log-normal, with a hazard that falls in old age, is 14 years off.
The ranking by AIC and the ranking by accuracy are almost opposite. In real work you never get this table. You get the arguments in 14.3 and 14.4, which pointed to the right answer without it.
14.6 The treatment effect inside and beyond the trial (30 min)
"""Day 14.7: the treatment effect - restricted mean survival inside the trial, mean survival beyond it."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.parametric import AnchoredGompertz, Fit, rmst_km # noqa: E402
from corridor.survival import km # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
cox = PHReg.from_formula("t_end ~ renavex", df, status=df.died, ties="efron").fit()
lo, hi = np.exp(cox.params[0] - 1.96 * cox.bse[0]), np.exp(cox.params[0] + 1.96 * cox.bse[0])
print(f"Cox HR for death, Renavex vs placebo: {np.exp(cox.params[0]):.3f} (95% CI {lo:.3f} to {hi:.3f})")
def rmst_diff(d, tau=3.0):
r = {a: rmst_km(km(g.t_end, g.died), tau) for a, g in d.groupby("arm")}
return r["renavex"] - r["placebo"]
rng = np.random.default_rng(2026)
boot = [rmst_diff(df.iloc[rng.integers(0, len(df), len(df))]) for _ in range(500)]
print(f"RMST to 3 years, Renavex minus placebo: {365.25 * rmst_diff(df):.1f} days "
f"(bootstrap 95% CI {365.25 * np.quantile(boot, 0.025):.1f} to {365.25 * np.quantile(boot, 0.975):.1f})")
print("\nLifetime (35-year) mean survival gain from separate fits to each arm:")
for name in ("exponential", "Weibull", "Gompertz", "log-logistic", "log-normal"):
m = {a: Fit(name, g.t_end, g.died).mean() for a, g in df.groupby("arm")}
print(f" {name:<18} placebo {m['placebo']:5.1f} Renavex {m['renavex']:5.1f} gain {m['renavex'] - m['placebo']:+5.2f} years")
m = {a: AnchoredGompertz(g.t_end, g.died, 0.0942).mean() for a, g in df.groupby("arm")}
print(f" {'Gompertz, b fixed':<18} placebo {m['placebo']:5.1f} Renavex {m['renavex']:5.1f} gain {m['renavex'] - m['placebo']:+5.2f} years")
Cox HR for death, Renavex vs placebo: 0.869 (95% CI 0.655 to 1.154)
RMST to 3 years, Renavex minus placebo: 6.8 days (bootstrap 95% CI -7.5 to 19.6)
Lifetime (35-year) mean survival gain from separate fits to each arm:
exponential placebo 20.8 Renavex 22.1 gain +1.30 years
Weibull placebo 20.5 Renavex 22.1 gain +1.59 years
Gompertz placebo 11.6 Renavex 10.9 gain -0.66 years
log-logistic placebo 22.6 Renavex 23.8 gain +1.25 years
log-normal placebo 26.3 Renavex 27.3 gain +1.01 years
Gompertz, b fixed placebo 12.7 Renavex 13.6 gain +0.93 years
Inside the trial the survival benefit is small and uncertain. The hazard ratio is 0.87 (95% CI 0.66 to 1.15). The restricted mean survival time (RMST) to 3 years, the area under each Kaplan–Meier curve, differs by 6.8 days (−7.5 to 19.6). RMST is the honest within-trial summary: it needs no proportional hazards assumption and no extrapolation.
Beyond the trial, the gain depends on the model: from −0.66 years (free Gompertz, whose curves cross) to +1.59 years (Weibull). The true gain is about 1.2 years. Fitting separate models to each arm lets the curves take different shapes, which is flexible but can produce effects that change direction for no clinical reason. Day 14's mini-project compares that with applying the trial HR to one curve.
Try it (15 min). Fit Weibull and exponential models to time to kidney failure in each arm. Is the kidney failure hazard rising? Which model would you carry into the economic model?
Solution
"""Day 14 try it: a Weibull model for time to kidney failure. Is the hazard rising?"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.parametric import Fit # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
for arm, g in df.groupby("arm"):
w, e = Fit("Weibull", g.t_kf, g.kf), Fit("exponential", g.t_kf, g.kf)
print(f"{arm:<8} {g.kf.sum()} kidney failures Weibull shape k = {np.exp(w.params[1]):.2f} "
f"AIC Weibull {w.aic:.1f} vs exponential {e.aic:.1f} 5-year risk {1 - w.surv(5):.3f} (Weibull) "
f"{1 - e.surv(5):.3f} (exponential)")
placebo 152 kidney failures Weibull shape k = 1.08 AIC Weibull 1205.4 vs exponential 1204.3 5-year risk 0.243 (Weibull) 0.229 (exponential)
renavex 116 kidney failures Weibull shape k = 1.22 AIC Weibull 991.2 vs exponential 993.8 5-year risk 0.203 (Weibull) 0.172 (exponential)
The Weibull shape is 1.08 for placebo and 1.22 for Renavex, so the hazard may be rising slowly, but AIC barely separates the models. The generator's true shape is 1.25 in both arms. With 116–152 events, the trial cannot pin down the shape. Two different shapes per arm would imply a treatment effect that changes over time, so a reviewer would expect one shape for both arms unless there is a clinical reason.
14.7 Mean survival from a Kaplan–Meier curve (15 min)
Bug of the day. An analyst needs placebo mean survival for the model, and computes the area under the Kaplan–Meier curve:
"""Day 14 bug of the day: "mean survival" read off the Kaplan-Meier curve."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.parametric import rmst_km # noqa: E402
from corridor.survival import km # noqa: E402
from corridor.trial import load # noqa: E402
g = load().query("arm == 'placebo'")
tab = km(g.t_end, g.died)
print(f"area under the placebo Kaplan-Meier curve: {rmst_km(tab, g.t_end.max()):.2f} years <- reported as 'mean survival'")
print("the curve stops at 3 years with 89% still alive; the area under it is the mean RESTRICTED to 3 years")
area under the placebo Kaplan-Meier curve: 2.86 years <- reported as 'mean survival'
the curve stops at 3 years with 89% still alive; the area under it is the mean RESTRICTED to 3 years
2.86 years against a true mean of 12.2. The area under a curve that stops at 3 years is the mean restricted to 3 years, whatever the software calls it. Some packages report it as "mean survival" with a footnote. Report it as RMST with its time limit, and extrapolate if you need the mean.
14.8 Mini-project: survival scenarios for the Renavex model (45 min)
Build the survival inputs for the Module 6 model: a base case and the scenarios a reviewer will ask for. Report life-years over a 35-year horizon, undiscounted and discounted at 1.5% a year (the CDA-AMC reference case rate).
"""Day 14 mini-project: survival inputs for the Renavex model - a base case and scenarios.
Life-years over a 35-year horizon, undiscounted and discounted at 1.5% a year (CDA-AMC reference case).
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.parametric import AnchoredGompertz, Fit, area # noqa: E402
from corridor.trial import load # noqa: E402
B = 0.0942
df = load()
arms = {a: g for a, g in df.groupby("arm")}
hr = float(np.exp(PHReg.from_formula("t_end ~ renavex", df, status=df.died, ties="efron").fit().params[0]))
pla = AnchoredGompertz(arms["placebo"].t_end, arms["placebo"].died, B)
ren = AnchoredGompertz(arms["renavex"].t_end, arms["renavex"].died, B)
pooled = AnchoredGompertz(df.t_end, df.died, B)
def waning(t, years=3.0):
"""Renavex at the trial HR for the first `years`, then the placebo hazard (the effect stops)."""
t = np.asarray(t, float)
early = pla.surv(t) ** hr
late = pla.surv(years) ** hr * pla.surv(t) / pla.surv(years)
return np.where(t <= years, early, late)
SCENARIOS = {
"Base: Gompertz b fixed, separate arms": (pla.surv, ren.surv),
"Gompertz b fixed, placebo + trial HR for life": (pla.surv, lambda t: pla.surv(t) ** hr),
"Effect stops after 3 years": (pla.surv, waning),
"Weibull, separate arms": (Fit("Weibull", arms["placebo"].t_end, arms["placebo"].died).surv,
Fit("Weibull", arms["renavex"].t_end, arms["renavex"].died).surv),
"Gompertz (free b), separate arms": (Fit("Gompertz", arms["placebo"].t_end, arms["placebo"].died).surv,
Fit("Gompertz", arms["renavex"].t_end, arms["renavex"].died).surv),
}
print(f"trial HR (Cox) = {hr:.3f}; pooled Gompertz a = {pooled.a:.4f}, b = {B}")
print(f"{'scenario':<46}{'LY placebo':>11}{'LY Renavex':>11}{'gain':>7}{'gain, 1.5%':>12}")
for name, (sp, sr) in SCENARIOS.items():
lp, lr = area(sp), area(sr)
gain_d = area(sr, discount=0.015) - area(sp, discount=0.015)
print(f"{name:<46}{lp:>11.2f}{lr:>11.2f}{lr - lp:>7.2f}{gain_d:>12.2f}")
trial HR (Cox) = 0.869; pooled Gompertz a = 0.0276, b = 0.0942
scenario LY placebo LY Renavex gain gain, 1.5%
Base: Gompertz b fixed, separate arms 12.70 13.63 0.93 0.74
Gompertz b fixed, placebo + trial HR for life 12.70 13.65 0.95 0.76
Effect stops after 3 years 12.70 12.85 0.15 0.13
Weibull, separate arms 20.52 22.12 1.59 1.17
Gompertz (free b), separate arms 11.58 10.93 -0.66 -0.49
- Base case and the PH version agree (gain 0.93 vs 0.95 years): with the shape anchored, separate arms and "placebo curve plus trial HR" tell the same story.
- Treatment waning dominates. If Renavex's effect stops at 3 years, the gain falls to 0.15 years. Whether a treatment effect persists after the trial is often a bigger uncertainty than which curve you fit, and reviewers test it routinely.
- Unanchored models swing the gain from −0.66 to +1.59 years.
Write the extrapolation paragraph for the dossier: the curve you chose, the external evidence for its shape, the scenarios, and which assumption matters most.
14.9 Save your work
python -m pytest -q
git add .
git commit -m "Day 14: parametric survival, anchored extrapolation, RMST, scenarios"
Day 14 checklist
- I can fit exponential, Weibull, Gompertz, log-logistic and log-normal models to censored data and compare their AIC
- I can explain why AIC within the trial does not choose an extrapolation
- I check the hazard each model implies against clinical sense and external data
- I report RMST within the trial and mean survival only from an extrapolated curve
- I present extrapolation and treatment-waning scenarios, discounted and undiscounted
Bloc français (30 min)
Thème : extrapoler la survie.
L'essai a suivi les patients pendant trois ans, mais le modèle économique couvre toute la vie. Il faut donc extrapoler la courbe de survie. Les modèles paramétriques s'ajustent tous bien aux données observées, mais leurs prédictions divergent après la fin de l'essai. Le critère d'information d'Akaike ne permet pas de choisir l'extrapolation. On utilise plutôt des données externes, comme la mortalité selon l'âge, et la plausibilité clinique.
| Français | English |
|---|---|
| extrapoler | to extrapolate |
| un modèle paramétrique | a parametric model |
| la loi de Weibull, la loi de Gompertz | the Weibull, Gompertz distribution |
| le risque instantané | the hazard |
| la survie moyenne | mean survival |
| la survie moyenne restreinte | restricted mean survival time (RMST) |
| le critère d'information d'Akaike (AIC) | the Akaike information criterion |
| les données externes | external data |
| la plausibilité clinique | clinical plausibility |
| l'horizon temporel | the time horizon |
| l'atténuation de l'effet du traitement | treatment effect waning |
| l'analyse de scénarios | scenario analysis |
Exercices
- Translate: "All five models fit the trial data well, but they disagree after year three."
- Translate: « Si l'effet du traitement cesse après trois ans, le gain de survie diminue fortement. »
- In three French sentences, justify the choice of the Gompertz model to a committee.
Réponses
- Les cinq modèles s'ajustent bien aux données de l'essai, mais ils divergent après la troisième année.
- "If the treatment effect stops after three years, the survival gain falls sharply."
- Example: Le risque de décès augmente avec l'âge dans la population atteinte de diabète et d'insuffisance rénale chronique. Le modèle de Gompertz est le seul qui reproduit cette hausse. Nous avons fixé la pente à partir des données administratives et estimé le niveau à partir de l'essai.