Competing Risks and Multi-State Models
Kidney failure is Renavex's primary outcome, but a patient who dies first can never reach it. Today you estimate the cumulative incidence of kidney failure with death as a competing risk. You compare cause-specific and Fine–Gray models, and build the illness–death model (no kidney failure → kidney failure → death) that becomes the backbone of Module 6's Markov model. The mini-project turns the trial's rates into annual transition probabilities and checks the model's trace against the data.
By the end of today you can
- report the cumulative incidence (Aalen–Johansen), not 1 − KM, when other events can happen first
- explain the difference between a cause-specific HR and a Fine–Gray subdistribution HR, and which one a Markov model needs
- estimate state probabilities in an illness–death model and a time-varying effect of an intermediate event
- turn competing rates into transition probabilities with the total rate, not one exit at a time
- validate a model's trace against the data it was built from
Today's 5.5-hour plan
In this lesson
15.1 Competing risks: what 1 − KM gets wrong (30 min)
Each patient's first event is kidney failure, death without kidney failure, or neither by the end of follow-up. Day 13 treated death as censoring for admission. That is fine for a hazard: "how fast does kidney failure happen among people still alive?". It is wrong for a probability. Kaplan–Meier assumes censored people could still have the event later. A dead patient cannot. So $1 - \text{KM}$ with death censored estimates the risk of kidney failure in a world where nobody dies first. That is a hypothetical quantity, and it is always higher than the share of patients who actually reach kidney failure.
The cumulative incidence function (CIF) answers the real question: what share of patients have kidney failure by time $t$, given that some die first?
15.2 The cumulative incidence function (40 min)
At each event time $t_j$, with $n_j$ at risk and $d_{kj}$ events of cause $k$, the Aalen–Johansen estimator is
where $\hat S$ is the Kaplan–Meier curve for any first event. You can only fail from cause $k$ at $t_j$ if you have survived everything up to then.
def cif(time, cause, k):
"""Aalen-Johansen cumulative incidence of cause k. Returns a table: time, at_risk, events, cif."""
t, c = np.asarray(time, float), np.asarray(cause, int)
s, total, rows = 1.0, 0.0, []
for u in np.unique(t[c > 0]):
n = int((t >= u).sum())
d_all = int(((t == u) & (c > 0)).sum())
d_k = int(((t == u) & (c == k)).sum())
total += s * d_k / n
s *= 1 - d_all / n
rows.append((u, n, d_k, total))
return pd.DataFrame(rows, columns=["time", "at_risk", "events", "cif"])
def value_at(table, col, t):
before = table[table["time"] <= t]
return 0.0 if before.empty else float(before[col].iloc[-1])
"""Day 15.2: the cumulative incidence of kidney failure, with death as a competing risk."""
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.competing import cif, value_at # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.survival import km, surv_at # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
df["cause"] = np.where(df.kf == 1, 1, np.where(df.died == 1, 2, 0)) # first event: 1 kidney failure, 2 death
print("First event during follow-up:")
print(df.groupby("arm").cause.value_counts().unstack().rename(columns={0: "none (censored)", 1: "kidney failure",
2: "death first"}).to_string())
fig, ax = plt.subplots(figsize=(6, 3.8))
print(f"\n{'arm':<9}{'year':>5}{'1 - KM (kidney failure)':>25}{'CIF kidney failure':>20}{'CIF death first':>17}")
for arm, g in df.groupby("arm"):
k, c1, c2 = km(g.t_kf, g.kf), cif(g.t_kf, g.cause, 1), cif(g.t_kf, g.cause, 2)
for y in (1, 2, 3):
print(f"{arm:<9}{y:>5}{1 - surv_at(k, y):>25.4f}{value_at(c1, 'cif', y):>20.4f}{value_at(c2, 'cif', y):>17.4f}")
colour = "#e5484d" if arm == "placebo" else "#4f9cf9"
ax.step([0] + list(k.time), [0] + list(1 - k.surv), where="post", color=colour, ls="--", lw=1.2,
label=f"{arm}: 1 - KM")
ax.step([0] + list(c1.time), [0] + list(c1.cif), where="post", color=colour, lw=1.8, label=f"{arm}: CIF")
ax.set(xlabel="years since randomization", ylabel="kidney failure", xlim=(0, 3), title="Kidney failure")
ax.legend(fontsize=8)
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day15_cif.png"), dpi=130)
First event during follow-up:
cause none (censored) kidney failure death first
arm
placebo 1245 152 88
renavex 1319 116 80
arm year 1 - KM (kidney failure) CIF kidney failure CIF death first
placebo 1 0.0486 0.0479 0.0301
placebo 2 0.0957 0.0930 0.0572
placebo 3 0.1514 0.1446 0.0808
renavex 1 0.0313 0.0309 0.0248
renavex 2 0.0684 0.0666 0.0451
renavex 3 0.1127 0.1082 0.0816

At 3 years, 1 − KM says 15.1% of placebo patients have kidney failure; the CIF says 14.5%. The difference is small inside the trial because only 8% die first. The CIFs for kidney failure and for death first add up to the overall 1 − KM, which 1 − KM for each cause separately does not.
Try it (15 min). Compute the three-year CIFs of kidney failure and of death first by baseline eGFR (25–39 vs 40–60) and arm.
Solution
"""Day 15 try it: three-year cumulative incidence of kidney failure and of death first, by baseline eGFR."""
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.competing import cif, value_at # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
df["cause"] = np.where(df.kf == 1, 1, np.where(df.died == 1, 2, 0))
df["egfr_group"] = np.where(df.egfr < 40, "eGFR 25-39", "eGFR 40-60")
print(f"{'group':<12}{'arm':<9}{'people':>7}{'CIF KF':>8}{'CIF death first':>17}")
for (grp, arm), g in df.groupby(["egfr_group", "arm"]):
print(f"{grp:<12}{arm:<9}{len(g):>7}{value_at(cif(g.t_kf, g.cause, 1), 'cif', 3):>8.3f}"
f"{value_at(cif(g.t_kf, g.cause, 2), 'cif', 3):>17.3f}")
group arm people CIF KF CIF death first
eGFR 25-39 placebo 644 0.200 0.097
eGFR 25-39 renavex 636 0.143 0.103
eGFR 40-60 placebo 841 0.105 0.068
eGFR 40-60 renavex 879 0.082 0.064
Patients with lower eGFR have twice the risk of kidney failure (20.0% vs 10.5% on placebo). Renavex lowers it in both groups: by 5.7 percentage points with low eGFR and by 2.3 points with high eGFR. That is a similar relative effect but a larger absolute benefit where the risk is higher, which is what an HTA subgroup analysis should report.
15.3 Truth check: over a lifetime the gap grows (25 min)
The generator draws death and kidney failure independently, so here the "world without death first" is well defined, and the truth file lets you compute both quantities with no censoring at all:
"""Day 15.3 (truth check): over a lifetime, 1 - KM and the cumulative incidence part ways.
The generator knows every patient's true times with no censoring. Death and kidney failure are drawn
independently, so '1 - KM with death as censoring' estimates a real quantity here: the risk of kidney
failure in a world where nobody dies first. The cumulative incidence is the share who actually get it.
"""
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.survival import km, surv_at # noqa: E402
from corridor.trial import load # noqa: E402
from corridor.truth import TRUTH # noqa: E402
t = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/trial_event_times.csv')").df().merge(load()[["patient_id", "arm"]])
t["t_first"] = t[["t_kidney_failure", "t_death"]].min(axis=1)
t["kf_first"] = t["t_kidney_failure"].notna().astype(int)
print(f"{'arm':<9}{'year':>5}{'true CIF':>10}{'1 - KM, death censored':>24}{'gap':>7}")
for arm, g in t.groupby("arm"):
k = km(g.t_first, g.kf_first)
for y in (3, 10, 20):
true_cif = np.mean(g.t_kidney_failure.fillna(np.inf) <= y)
print(f"{arm:<9}{y:>5}{true_cif:>10.3f}{1 - surv_at(k, y):>24.3f}{1 - surv_at(k, y) - true_cif:>+7.3f}")
arm year true CIF 1 - KM, death censored gap
placebo 3 0.151 0.158 +0.007
placebo 10 0.439 0.513 +0.074
placebo 20 0.596 0.803 +0.207
renavex 3 0.117 0.122 +0.005
renavex 10 0.358 0.414 +0.055
renavex 20 0.520 0.700 +0.180
At 3 years the two differ by under one percentage point. At 20 years, 60% of placebo patients reach kidney failure, but 1 − KM says 80%. A lifetime model that took 1 − KM as the probability of dialysis would put 20% too many patients on dialysis and inflate dialysis costs by a third. The gap grows with time because more people die first, and economic models run for a lifetime.
15.4 Cause-specific hazards and Fine–Gray (45 min)
Two regression models, two questions:
- Cause-specific Cox model: the hazard of kidney failure among people alive and free of it, with death censoring. Its HR describes the biology: how fast does Renavex slow progression?
- Fine–Gray model: the hazard of the subdistribution, which keeps people who died in the risk set. Its HR describes the CIF: does Renavex change the share who end up with kidney failure? It mixes the effect on kidney failure with the effect on death.
"""Day 15.4: cause-specific Cox models - one model per cause, the other cause censors."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
df["death_first"] = ((df.kf == 0) & (df.died == 1)).astype(int)
df["egfr10"] = (df.egfr - 40) / 10
df["age10"] = (df.age - 66) / 10
TRUE = {"kidney failure": {"renavex": -0.36, "egfr10": -0.45, "age10": -0.10},
"death before kidney failure": {"renavex": -0.12, "egfr10": -0.10, "age10": 0.75}}
for label, event in (("kidney failure", "kf"), ("death before kidney failure", "death_first")):
m = PHReg.from_formula("t_kf ~ renavex + egfr10 + age10", df, status=df[event], ties="efron").fit()
ci = np.exp(m.conf_int())
t = pd.DataFrame({"HR": np.exp(m.params), "95% CI": [f"{a:.2f}-{b:.2f}" for a, b in ci],
"true HR": [np.exp(TRUE[label][v]) for v in m.model.exog_names]}, index=m.model.exog_names)
print(f"--- cause-specific hazard of {label} ({df[event].sum()} events)")
print(t.round(3).to_string())
--- cause-specific hazard of kidney failure (268 events)
HR 95% CI true HR
renavex 0.724 0.57-0.92 0.698
egfr10 0.704 0.62-0.80 0.638
age10 1.046 0.91-1.20 0.905
--- cause-specific hazard of death before kidney failure (168 events)
HR 95% CI true HR
renavex 0.867 0.64-1.17 0.887
egfr10 0.813 0.70-0.95 0.905
age10 2.223 1.85-2.67 2.117
The cause-specific HRs are close to the generator's: Renavex 0.72 for kidney failure (true 0.70), 0.87 for death first (true 0.89). Higher eGFR protects against kidney failure much more than against death. Age works the other way: it barely changes kidney failure but doubles death per decade.
Check it in R. The survival package gives the Aalen–Johansen CIF, a Fine–Gray model via finegray(), and the illness–death model in the next section:
# Day 15: cumulative incidence, Fine-Gray and the illness-death model with the survival package.
suppressPackageStartupMessages(library(survival))
tr <- read.csv("data/renavex_trial.csv")
yrs <- function(a, b) pmax(as.numeric(as.Date(b) - as.Date(a)) / 365.25, 1 / 365.25)
tr$t_end <- yrs(tr$randomized, tr$last_contact)
tr$kf <- as.integer(tr$kidney_failure_date != "")
tr$t_kf <- ifelse(tr$kf == 1, yrs(tr$randomized, tr$kidney_failure_date), tr$t_end)
tr$died <- as.integer(tr$death_date != "")
tr$cause <- factor(ifelse(tr$kf == 1, "kf", ifelse(tr$died == 1, "death", "censor")),
levels = c("censor", "kf", "death"))
tr$renavex <- as.integer(tr$arm == "renavex")
aj <- survfit(Surv(t_kf, cause) ~ arm, data = tr) # Aalen-Johansen
s <- summary(aj, times = 3)
cat("CIF at 3 years (rows: arm; columns: state)\n")
print(round(s$pstate, 4))
fg <- finegray(Surv(t_kf, cause) ~ ., data = tr[, c("t_kf", "cause", "renavex")], etype = "kf")
sh <- coxph(Surv(fgstart, fgstop, fgstatus) ~ renavex, weight = fgwt, data = fg)
cs <- coxph(Surv(t_kf, kf) ~ renavex, data = tr)
cat(sprintf("\nRenavex, kidney failure: cause-specific HR %.3f; Fine-Gray subdistribution HR %.3f\n",
exp(coef(cs)), exp(coef(sh))))
# illness-death: one row per interval, the state at the end of each interval
long <- do.call(rbind, lapply(seq_len(nrow(tr)), function(i) {
r <- tr[i, ]
if (r$kf == 1) data.frame(id = i, arm = r$arm, tstart = c(0, r$t_kf), tstop = c(r$t_kf, max(r$t_end, r$t_kf + 1e-6)),
state = c("kf", if (r$died == 1) "dead" else "censor"))
else data.frame(id = i, arm = r$arm, tstart = 0, tstop = r$t_end, state = if (r$died == 1) "dead" else "censor")
}))
long$state <- factor(long$state, levels = c("censor", "kf", "dead"))
ms <- survfit(Surv(tstart, tstop, state) ~ arm, data = long, id = id)
cat("\nIllness-death state occupation at 3 years:\n")
print(round(summary(ms, times = 3)$pstate, 3))
CIF at 3 years (rows: arm; columns: state)
(s0) kf death
[1,] 0.7747 0.1446 0.0808
[2,] 0.8102 0.1082 0.0816
Renavex, kidney failure: cause-specific HR 0.724; Fine-Gray subdistribution HR 0.728
Illness-death state occupation at 3 years:
(s0) kf dead
[1,] 0.775 0.109 0.117
[2,] 0.810 0.096 0.094
The CIFs match Python to four decimals. Here the Fine–Gray subdistribution HR (0.728) is almost the cause-specific HR (0.724), because few patients die first and Renavex hardly changes death. With a common competing event, or a treatment that also changes it, they can differ a lot. For a Markov or multi-state model, use cause-specific hazards: each transition is its own rate. Fine–Gray is for describing or predicting the CIF.
15.5 The illness–death model (45 min)
Three states: alive without kidney failure (0), alive with kidney failure (1), dead (2). Three transitions: 0→1, 0→2 and 1→2. This is the structure of most chronic disease models, and of Module 6's Renavex model.
def illness_death(t_ill, ill, t_end, dead):
"""State occupation probabilities for the illness-death model
(0 = alive without the illness, 1 = alive with it, 2 = dead), by Aalen-Johansen.
t_ill/ill: time of the illness (or of leaving state 0 without it) and whether it happened.
t_end/dead: end of follow-up and whether it ended in death. People with ill = 0 and dead = 1
died directly from state 0 at t_ill (= t_end).
Returns a table: time, p0, p1, p2.
"""
t_ill, ill = np.asarray(t_ill, float), np.asarray(ill, int)
t_end, dead = np.asarray(t_end, float), np.asarray(dead, int)
to1 = ill == 1
d01 = to1
d02 = (~to1) & (dead == 1)
d12 = to1 & (dead == 1)
times = np.unique(np.concatenate([t_ill[d01 | d02], t_end[d12]]))
p0, p1, rows = 1.0, 0.0, []
for u in times:
y0 = (t_ill >= u).sum()
y1 = (to1 & (t_ill < u) & (t_end >= u)).sum()
n01 = (d01 & (t_ill == u)).sum()
n02 = (d02 & (t_ill == u)).sum()
n12 = (d12 & (t_end == u)).sum()
a01 = n01 / y0 if y0 else 0.0
a02 = n02 / y0 if y0 else 0.0
a12 = n12 / y1 if y1 else 0.0
p0, p1 = p0 * (1 - a01 - a02), p1 * (1 - a12) + p0 * a01
rows.append((u, p0, p1, 1 - p0 - p1))
return pd.DataFrame(rows, columns=["time", "p0", "p1", "p2"])
"""Day 15.6: the illness-death model - no kidney failure -> kidney failure -> death."""
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
import pandas as pd # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.competing import illness_death, value_at # noqa: E402
from corridor.trial import load # noqa: E402
from corridor.truth import TRUTH # noqa: E402
df = load()
print("Transitions observed:")
print(f" no KF -> KF: {df.kf.sum()}")
print(f" no KF -> death: {((df.kf == 0) & (df.died == 1)).sum()}")
print(f" KF -> death: {((df.kf == 1) & (df.died == 1)).sum()} (of {df.kf.sum()} people with kidney failure)")
print("\nState occupation at 1, 2 and 3 years (Aalen-Johansen):")
print(f"{'arm':<9}{'year':>5}{'alive, no KF':>14}{'alive with KF':>15}{'dead':>7}")
for arm, g in df.groupby("arm"):
s = illness_death(g.t_kf, g.kf, g.t_end, g.died)
for y in (1, 2, 3):
print(f"{arm:<9}{y:>5}{value_at(s, 'p0', y):>14.3f}{value_at(s, 'p1', y):>15.3f}{value_at(s, 'p2', y):>7.3f}")
def split(d, t_kf, kf, t_end, died):
"""Counting-process rows (entry, exit, death, after_kf): one row before kidney failure, one after."""
rows = []
for r in d.itertuples():
a, k, e, dd = getattr(r, t_kf), getattr(r, kf), getattr(r, t_end), getattr(r, died)
if k:
rows.append((0.0, a, 0, 0, r.renavex, r.age))
rows.append((a, max(e, a + 1e-6), dd, 1, r.renavex, r.age))
else:
rows.append((0.0, e, dd, 0, r.renavex, r.age))
out = pd.DataFrame(rows, columns=["entry", "exit", "death", "after_kf", "renavex", "age"])
out["age10"] = (out.age - 66) / 10
return out
def death_hr(long):
m = PHReg.from_formula("exit ~ after_kf + renavex + age10", long, status=long.death, entry=long.entry,
ties="efron").fit()
j = m.model.exog_names.index("after_kf")
return np.exp(m.params[j]), np.exp(m.params[j] - 1.96 * m.bse[j]), np.exp(m.params[j] + 1.96 * m.bse[j])
hr, lo, hi = death_hr(split(df, "t_kf", "kf", "t_end", "died"))
print(f"\nDeath hazard after kidney failure vs before (Cox, time-varying): HR {hr:.2f} (95% CI {lo:.2f} to {hi:.2f})")
true = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/trial_event_times.csv')").df().merge(
df[["patient_id", "renavex", "age"]])
true["kf"] = true.t_kidney_failure.notna().astype(int)
true["t_kf"] = true.t_kidney_failure.fillna(true.t_death)
true["died"] = 1
hr, lo, hi = death_hr(split(true, "t_kf", "kf", "t_death", "died"))
print(f"Same model on the true, uncensored lifetimes: HR {hr:.2f} (95% CI {lo:.2f} to {hi:.2f}); generator 3.5")
Transitions observed:
no KF -> KF: 268
no KF -> death: 168
KF -> death: 24 (of 268 people with kidney failure)
State occupation at 1, 2 and 3 years (Aalen-Johansen):
arm year alive, no KF alive with KF dead
placebo 1 0.922 0.046 0.032
placebo 2 0.850 0.087 0.063
placebo 3 0.775 0.109 0.117
renavex 1 0.944 0.030 0.025
renavex 2 0.888 0.060 0.052
renavex 3 0.810 0.096 0.094
Death hazard after kidney failure vs before (Cox, time-varying): HR 3.08 (95% CI 1.99 to 4.78)
Same model on the true, uncensored lifetimes: HR 3.64 (95% CI 3.36 to 3.93); generator 3.5
At 3 years, 10.9% of placebo patients are alive with kidney failure and 11.7% are dead. R's multi-state survfit (15.4) gives the same state probabilities. The death hazard after kidney failure is 3.1 times the hazard before it (95% CI 2.0 to 4.8). That estimate rests on only 24 deaths after kidney failure. On the uncensored lifetimes the same Cox model gives 3.64 (3.36 to 3.93), around the generator's 3.5. The model uses time since randomization as its clock and kidney failure as a time-varying covariate, which matches the generator's "clock-forward" (Markov) structure.
Why it matters at work: "Death after kidney failure" is usually the least-informed transition in a CKD model, because trials stop soon after it. Sponsors take it from registries (the Canadian Organ Replacement Register, for example), and reviewers check that registry patients look like trial patients.
Where you'll meet this: Markov and multi-state models in Module 6 · cancer models (progression-free and post-progression survival) · CDA-AMC reviews that question a transition borrowed from another population
15.6 One probability per exit (15 min)
Bug of the day. A modeller has two rates out of "no kidney failure": 0.05 per year to kidney failure and 0.03 to death. They convert each with $p = 1 - e^{-r}$:
def exits(rates, cycle=1.0):
total = sum(rates)
leave = 1 - np.exp(-total * cycle)
return [r / total * leave for r in rates]
"""Day 15 bug of the day: each exit converted to a probability on its own."""
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.markov_preview import exits # noqa: E402
r01, r02 = 0.05, 0.03 # rates per year out of "no kidney failure"
for cycle in (1.0, 5.0):
wrong = [1 - np.exp(-r * cycle) for r in (r01, r02)]
right = exits([r01, r02], cycle)
print(f"cycle {cycle:.0f} year(s): separately {wrong[0]:.4f} + {wrong[1]:.4f} = {sum(wrong):.4f} "
f"jointly {right[0]:.4f} + {right[1]:.4f} = {sum(right):.4f} "
f"(true chance of leaving: {1 - np.exp(-(r01 + r02) * cycle):.4f})")
cycle 1 year(s): separately 0.0488 + 0.0296 = 0.0783 jointly 0.0481 + 0.0288 = 0.0769 (true chance of leaving: 0.0769)
cycle 5 year(s): separately 0.2212 + 0.1393 = 0.3605 jointly 0.2060 + 0.1236 = 0.3297 (true chance of leaving: 0.3297)
Converted separately, the exits add up to more than the chance of leaving the state: 0.0783 against 0.0769 for a one-year cycle, and 0.36 against 0.33 for a five-year cycle. Each conversion assumes the other exit cannot happen first. Convert the total rate to a probability of leaving, then split it in proportion to the rates.
15.7 Mini-project: Markov transition probabilities from the trial (60 min)
Estimate a constant rate for each transition (events / person-years in the state), build the annual transition matrix, run the cohort for three cycles, and compare the trace with the Aalen–Johansen state probabilities from the data. This is model validation: does the model reproduce the data it came from?
"""Day 15 mini-project: transition probabilities for an annual Markov model, checked against the data."""
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.competing import illness_death, value_at # noqa: E402
from corridor.markov_preview import illness_death_matrix, trace # noqa: E402
from corridor.trial import load # noqa: E402
df = load()
np.set_printoptions(precision=4, suppress=True)
for arm, g in df.groupby("arm"):
py0 = g.t_kf.sum() # person-years before kidney failure
py1 = (g.t_end - g.t_kf)[g.kf == 1].sum() # person-years after it
r01 = g.kf.sum() / py0
r02 = ((g.kf == 0) & (g.died == 1)).sum() / py0
r12 = ((g.kf == 1) & (g.died == 1)).sum() / py1
m = illness_death_matrix(r01, r02, r12)
tr = trace(m, 3)
aj = illness_death(g.t_kf, g.kf, g.t_end, g.died)
print(f"--- {arm}: rates per person-year KF {r01:.4f} death before KF {r02:.4f} death after KF {r12:.4f}")
print("annual transition matrix (rows: from no KF, KF, dead):")
print(m)
print(f"{'year':>6}{'Markov: no KF':>15}{'KF':>8}{'dead':>8} {'data (AJ): no KF':>17}{'KF':>8}{'dead':>8}")
for y in (1, 2, 3):
print(f"{y:>6}{tr[y, 0]:>15.3f}{tr[y, 1]:>8.3f}{tr[y, 2]:>8.3f} {value_at(aj, 'p0', y):>17.3f}"
f"{value_at(aj, 'p1', y):>8.3f}{value_at(aj, 'p2', y):>8.3f}")
--- placebo: rates per person-year KF 0.0521 death before KF 0.0302 death after KF 0.0832
annual transition matrix (rows: from no KF, KF, dead):
[[0.9211 0.05 0.0289]
[0. 0.9202 0.0798]
[0. 0. 1. ]]
year Markov: no KF KF dead data (AJ): no KF KF dead
1 0.921 0.050 0.029 0.922 0.046 0.032
2 0.848 0.092 0.060 0.850 0.087 0.063
3 0.781 0.127 0.092 0.775 0.109 0.117
--- renavex: rates per person-year KF 0.0378 death before KF 0.0261 death after KF 0.1008
annual transition matrix (rows: from no KF, KF, dead):
[[0.9381 0.0366 0.0253]
[0. 0.9041 0.0959]
[0. 0. 1. ]]
year Markov: no KF KF dead data (AJ): no KF KF dead
1 0.938 0.037 0.025 0.944 0.030 0.025
2 0.880 0.067 0.052 0.888 0.060 0.052
3 0.826 0.093 0.081 0.810 0.096 0.094
For one and two years the trace matches the data within about one percentage point. By year 3 the model has too few deaths (9.2% vs 11.7% on placebo) and too many patients with kidney failure. Constant rates cannot follow a death hazard that rises with age (Day 14), so they drift. Module 6 fixes it with time-dependent transitions. Write down which transition drifts and what you would change.
15.8 Save your work
python -m pytest -q
git add .
git commit -m "Day 15: competing risks, Fine-Gray, illness-death model, Markov inputs"
Day 15 checklist
- I report the cumulative incidence (Aalen–Johansen), not 1 − KM, when other events can happen first
- I can explain the difference between a cause-specific HR and a Fine–Gray subdistribution HR, and which one a Markov model needs
- I can estimate state probabilities in an illness–death model and a time-varying effect of an intermediate event
- I turn competing rates into transition probabilities with the total rate, not one exit at a time
- I validate a model's trace against the data it was built from
Bloc français (30 min)
Thème : les risques concurrents.
Un patient qui meurt avant l'insuffisance rénale terminale ne pourra jamais l'atteindre : le décès est un risque concurrent. L'incidence cumulée estime la proportion de patients qui atteignent réellement l'insuffisance rénale. Le complément de Kaplan-Meier surestime ce risque, surtout sur un horizon à vie. Le modèle multi-états décrit le passage de l'absence d'insuffisance rénale à l'insuffisance rénale, puis au décès.
| Français | English |
|---|---|
| les risques concurrents | competing risks |
| l'incidence cumulée | cumulative incidence |
| l'insuffisance rénale terminale | kidney failure (end-stage kidney disease) |
| la dialyse | dialysis |
| le risque spécifique à la cause | the cause-specific hazard |
| le modèle de Fine et Gray | the Fine–Gray model |
| le modèle multi-états | the multi-state model |
| le modèle maladie-décès | the illness–death model |
| la probabilité de transition | the transition probability |
| la matrice de transition | the transition matrix |
| le cycle annuel | the annual cycle |
| la validation interne | internal validation |
Exercices
- Translate: "Death is a competing risk for kidney failure."
- Translate: « Le complément de Kaplan-Meier surestime la proportion de patients qui atteignent la dialyse. »
- In three French sentences, explain to a modeller how to turn two competing rates into probabilities.
Réponses
- Le décès est un risque concurrent de l'insuffisance rénale terminale.
- "One minus Kaplan–Meier overestimates the share of patients who reach dialysis."
- Example: On additionne d'abord les deux taux pour obtenir le taux total de sortie de l'état. On calcule la probabilité de quitter l'état avec ce taux total. Ensuite, on répartit cette probabilité entre les deux sorties en proportion de leurs taux.