Immortal Time: Complications, Survival, and Multistate Models#

Here’s a question from Cross Validated, the statistics Q&A site:

I am analysing a cohort of patients receiving a durable left ventricular assist device (LVAD). […] I would like to assess whether complications such as gastrointestinal bleeding, neurological events, device-related infection, and device dysfunction are associated with subsequent mortality. […]

If I classify patients as having “ever” or “never” experienced a complication, those in the first group must have survived long enough to experience it. […] I am considering a Cox model with time-dependent covariates, but I have also been reading about landmark analysis. […] Would landmark analysis be useful, either on its own or as a complement? If so, how would you justify the choice of landmark time – for example, 90, 180, or 365 days after implantation?

An LVAD is a pump implanted to support a failing heart. Patients who have one are at risk of complications – bleeding, strokes, infections, and problems with the device – and the question is whether patients who have a complication are more likely to die afterward.

The OP has already spotted the trap. A patient who has a complication had to be alive when it happened, so if we put patients into “ever” and “never” groups, the “ever” group gets credit for the time before the complication, when they were alive by definition. That time is called immortal time, and it can make a harmful complication look harmless, or even protective.

The data aren’t available, so I’ll simulate a cohort where we know the truth: complications double the hazard of death. Then I’ll run four analyses, each answering a different question:

  1. Ever vs never, which shows the bias.

  2. A Cox model with a time-dependent covariate, which answers the question about association.

  3. Landmark analysis, which answers a question about prediction.

  4. A multistate model, which answers both.

The main lesson is that the time-dependent Cox model and the landmark analysis estimate different things, and the choice between them depends on the question.

Click here to run this notebook on Colab.

I’ll download a utilities module with some of my frequently-used functions, install PyMC if we’re running on Colab, and then import the libraries we’ll need.

Hide code cell content

from os.path import basename, exists

def download(url):
    filename = basename(url)
    if not exists(filename):
        from urllib.request import urlretrieve

        local, _ = urlretrieve(url, filename)
        print("Downloaded " + str(local))
    return filename

download('https://github.com/AllenDowney/DataQnA/raw/main/nb/utils.py');

Hide code cell content

# on Colab, upgrade the sampling stack together (PyMC 6 uses nutpie when it's installed)

import sys

if "google.colab" in sys.modules:
    %pip install -q "pymc>=6" "arviz>=1.1" nutpie

Hide code cell content

import numpy as np
np.set_printoptions(legacy='1.25')
import matplotlib.pyplot as plt
import pandas as pd

import pymc as pm
import statsmodels.api as sm
from scipy.linalg import expm
from statsmodels.duration.hazard_regression import PHReg

from utils import decorate

BLUE, ORANGE, GRAY = "#2a78d6", "#eb6834", "#888888"

The simulation#

I’ll model each patient as being in one of three states: alive without a complication (state 0), alive after a complication (state 1), or dead. There are three transitions:

  • complication, from state 0 to state 1, with hazard \(\lambda(t)\);

  • death without a complication, from state 0, with hazard \(\mu(t)\);

  • death after a complication, from state 1, with hazard \(\mu(t) \cdot \text{HR}\).

Time \(t\) is days since implantation, and I’ll set the hazard ratio, HR, to 2: in this simulation, a complication doubles the instantaneous hazard of death. That doesn’t mean it doubles the probability of dying in any particular period; we’ll see how those differ.

To make the hazards realistic, I chose them to match the MOMENTUM 3 trial of a current LVAD (the HeartMate 3 arm, 515 patients followed for 2 years, from the paper and its supplementary appendix):

  • Survival was about 97% at 1 month, 93% at 3 months, 90% at 6 months, 86.6% at 1 year, and 79.0% at 2 years.

  • The hazard of a first major bleed was highest right after surgery and fell steadily for 18 months; strokes followed a similar pattern. I used that shape for the hazard of a first complication.

  • Over 2 years, 58% of patients had an infection, 25% a gastrointestinal bleed, 10% a stroke, and 12% another neurologic event. The trial doesn’t report how many had at least one, and these are proportions of patients observed to have an event before transplant or the end of follow-up, so they understate the probability of an event. Taking both into account, I assumed that, without censoring, 70% of patients would have at least one complication by 2 years.

  • 23% of patients received a heart transplant within 2 years. In this simulation, transplants and withdrawals are censored at a constant rate, chosen so that 23% of patients would be censored by 2 years if none died.

So the simulation is calibrated to the trial approximately, which is all we need here: it doesn’t have to match the trial exactly, only to be realistic.

The hazards are constant within five intervals – 0-30 days, 30-90, 90-180, 180-365, and 365-730 – so they are easy to simulate and, later, easy to estimate. Here are the rates, in events per patient-year.

edges = np.array([0, 30, 90, 180, 365, 730])
widths = np.diff(edges)

lam = np.array([1.83, 1.52, 1.12, 0.71, 0.35]) / 365    # complication
mu = np.array([0.35, 0.21, 0.095, 0.049, 0.055]) / 365  # death without a complication
hr = 2.0                                               # hazard ratio after a complication
cens_rate = 0.13 / 365                                 # transplant and withdrawal
def plot_rates(rates, **options):
    plt.stairs(rates * 365, edges, baseline=None, **options)


plot_rates(lam, color=GRAY, label="complication")
plot_rates(mu, color=BLUE, label="death, no complication")
plot_rates(mu * hr, color=ORANGE, label="death after a complication")
decorate(xlabel="Days since implantation", ylabel="Hazard (per patient-year)", yscale="log")
_images/4c6d628eacb42a9201ed2620d5ddafb4e7cb86a602194c1c8305c945b4d5ce70.png

Complications are much more common than deaths, especially in the first few months. Both hazards fall over time.

To compute probabilities from these hazards, I’ll use the transition matrix. For a period of length \(\Delta t\) when the hazards are constant, the probabilities of moving between states are given by the matrix exponential, \(\exp(Q \Delta t)\), where \(Q\) is the matrix of transition rates. To make it easy to count deaths with and without a complication, I’ll split death into two states, so the matrix is 4×4.

def rate_matrix(lam_j, mu_j, hr):
    """Transition rates among: no complication, complication, died (no comp), died (comp)."""
    return np.array([
        [-(lam_j + mu_j), lam_j, mu_j, 0],
        [0, -mu_j * hr, 0, mu_j * hr],
        [0, 0, 0, 0],
        [0, 0, 0, 0],
    ])


def transition_matrix(lam, mu, hr, s, t):
    """P[a, b] is the probability of being in state b at time t, given state a at time s."""
    if not edges[0] <= s <= t <= edges[-1]:
        raise ValueError("The model only covers days 0 to 730")
    P = np.eye(4)
    for j in range(len(widths)):
        lo, hi = max(edges[j], s), min(edges[j + 1], t)
        if hi > lo:
            P = P @ expm(rate_matrix(lam[j], mu[j], hr) * (hi - lo))
    return P

Here’s what the model implies at the times the trial reported.

def model_summary(lam, mu, hr):
    rows = {}
    for t in edges[1:]:
        p = transition_matrix(lam, mu, hr, 0, t)[0]
        rows[t] = {
            "survival": p[0] + p[1],
            "had a complication": p[1] + p[3],
            "died, no complication": p[2],
            "died after a complication": p[3],
        }
    return pd.DataFrame(rows).T.rename_axis("day")


model_summary(lam, mu, hr).round(3)
survival had a complication died, no complication died after a complication
day
30 0.970 0.138 0.026 0.004
90 0.929 0.320 0.051 0.019
180 0.899 0.470 0.064 0.037
365 0.865 0.609 0.074 0.061
730 0.788 0.700 0.088 0.124

Survival matches the trial, and the probability of a complication by 2 years is 70%, as assumed. (These are probabilities without censoring; the proportions observed in a censored cohort would be smaller.) Notice that most of the early deaths are deaths without a complication: in the first month, patients are more likely to die than to have a complication and then die. That’s where the immortal time comes from.

Now let’s simulate a cohort of 1000 patients. From state 0, complication and death compete: the time of the first event depends on the sum of the two hazards; which event it is depends on their relative sizes. The following function finds the time when the cumulative hazard reaches a random value from an exponential distribution, which is a standard way to generate event times when the hazard varies over time.

def event_times(rates, start, rng):
    """Times of events with piecewise-constant rates, starting at `start` (inf if after 730)."""
    cum_hazard = np.concatenate([[0], np.cumsum(rates * widths)])
    goal = np.interp(start, edges, cum_hazard) + rng.exponential(size=len(start))
    t = np.interp(goal, cum_hazard, edges)
    return np.where(goal > cum_hazard[-1], np.inf, t)


def simulate(n, lam, mu, hr, rng, start=0, state=0):
    """Simulate complication and death times (inf if none by day 730)."""
    start = np.full(n, float(start))
    if state == 1:
        return np.full(n, np.nan), event_times(mu * hr, start, rng)

    t0 = event_times(lam + mu, start, rng)
    j = np.clip(np.searchsorted(edges, t0, side="right") - 1, 0, len(widths) - 1)
    is_comp = np.isfinite(t0) & (rng.random(n) < lam[j] / (lam[j] + mu[j]))

    t_death = t0.copy()
    t_death[is_comp] = event_times(mu * hr, t0[is_comp], rng)
    t_comp = np.where(is_comp, t0, np.nan)
    return t_comp, t_death


def observe(t_comp, t_death, cens_rate, rng):
    """Apply censoring; return what a researcher would see."""
    t_cens = np.minimum(rng.exponential(1 / cens_rate, size=len(t_death)), edges[-1])
    t_end = np.minimum(t_death, t_cens)
    seen = t_comp < t_end
    return pd.DataFrame({
        "t_comp": np.where(seen, t_comp, np.nan),
        "t_end": t_end,
        "died": (t_death <= t_cens).astype(int),
    })
rng = np.random.default_rng(17)
t_comp, t_death = simulate(1000, lam, mu, hr, rng)
df = observe(t_comp, t_death, cens_rate, rng)
df["ever"] = df["t_comp"].notna().astype(int)
df.head()
t_comp t_end died ever
0 NaN 730.000000 0 0
1 7.344753 389.560444 1 1
2 74.493611 433.455228 1 1
3 NaN 108.022275 0 0
4 NaN 66.254777 1 0

Each row is a patient: the day of their complication (if one was observed), the day follow-up ended, and whether it ended with death.

df[["ever", "died"]].sum()
ever    668
died    191
dtype: int64

To see where the immortal time comes from, here are the timelines of the first 20 patients.

def plot_timelines(df):
    for i, row in enumerate(df.itertuples()):
        end = row.t_comp if row.ever else row.t_end
        plt.plot([0, end], [i, i], color=BLUE)
        if row.ever:
            plt.plot([row.t_comp, row.t_end], [i, i], color=ORANGE)
            plt.plot(row.t_comp, i, "|", color=ORANGE, ms=8)
        marker = "x" if row.died else "o"
        plt.plot(row.t_end, i, marker, color="black", mfc="white", ms=5)
    plt.yticks([])


plot_timelines(df.head(20))
decorate(xlabel="Days since implantation", ylabel="Patient")
_images/1650c382beba55c56a18201cc5293e3f668398a51864dba43d9b576944f519f7.png

Blue segments are time without a complication, orange segments are time after a complication, an x marks a death and a circle marks censoring.

In an ever-vs-never analysis, every patient with an orange segment goes in the “ever” group, so the blue segment to the left of it counts as time in the “ever” group. During that time, those patients could not have died, because if they had, they would never have had the complication. Meanwhile, patients who died early, before they had a chance to have a complication, all go in the “never” group.

Ever vs never#

First, the analysis the OP wants to avoid. The question it seems to answer is: do patients who have a complication have higher mortality?

Here are Kaplan-Meier survival curves for the two groups.

def plot_km(durations, events, **options):
    sf = sm.SurvfuncRight(durations, events)
    times = np.concatenate([[0], sf.surv_times])
    probs = np.concatenate([[1], sf.surv_prob])
    plt.step(times, probs, where="post", **options)


plot_km(df.query("ever == 0")["t_end"], df.query("ever == 0")["died"], color=BLUE, label="never")
plot_km(df.query("ever == 1")["t_end"], df.query("ever == 1")["died"], color=ORANGE, label="ever")
decorate(xlabel="Days since implantation", ylabel="Survival")
_images/5be87b00110dd6a952af1b8e3be2c99db68febbe5cfb4b935da4e0305698df31.png

Patients who had a complication appear to survive longer. And a Cox model with “ever” as a covariate agrees.

def hazard_ratio(result, i=0):
    """Hazard ratio and 90% CI from a PHReg result."""
    est = result.params[i]
    se = result.bse[i]
    return np.exp([est, est - 1.645 * se, est + 1.645 * se])


naive = PHReg(df["t_end"], df[["ever"]], status=df["died"]).fit()
hazard_ratio(naive).round(2)
array([0.42, 0.33, 0.54])

The estimated hazard ratio is about 0.42, with a 90% interval from about 0.33 to 0.54. If we took it at face value, we’d conclude that complications cut the hazard of death by more than half, when in fact they double it.

To check that this is bias, not bad luck, let’s simulate a much larger cohort.

rng_big = np.random.default_rng(18)
big = observe(*simulate(100_000, lam, mu, hr, rng_big), cens_rate, rng_big)
big["ever"] = big["t_comp"].notna().astype(int)

naive_big = PHReg(big["t_end"], big[["ever"]], status=big["died"]).fit()
hazard_ratio(naive_big).round(2)
array([0.51, 0.5 , 0.52])

With 100,000 patients, the interval is narrow, and it is nowhere near 2. More data doesn’t help; the analysis converges to the wrong answer.

The problem is that the classification uses information from the future. On the day of implantation, nobody knows which group a patient belongs to.

Time-dependent Cox#

The fix is to classify patients by what has happened so far. That answers a different question: at any given time, how does the hazard of death differ between patients who have and haven’t had a complication?

To fit this model, we split the follow-up of each patient who had a complication into two rows: one for the time before the complication, when the covariate is 0, and one for the time after, when it is 1. The second row “enters” the risk set at the time of the complication.

def split_rows(df):
    rows = []
    for i, r in enumerate(df.itertuples()):
        if r.ever:
            rows.append((i, 0.0, r.t_comp, 0, 0))
            rows.append((i, r.t_comp, r.t_end, 1, r.died))
        else:
            rows.append((i, 0.0, r.t_end, 0, r.died))
    return pd.DataFrame(rows, columns=["id", "start", "stop", "comp", "died"])


cp = split_rows(df)
cp.head()
id start stop comp died
0 0 0.000000 730.000000 0 0
1 1 0.000000 7.344753 0 0
2 1 7.344753 389.560444 1 1
3 2 0.000000 74.493611 0 0
4 2 74.493611 433.455228 1 1

With PHReg, the entry argument says when each row enters the risk set.

tdc = PHReg(cp["stop"], cp[["comp"]], status=cp["died"], entry=cp["start"]).fit()
hazard_ratio(tdc).round(2)
array([1.64, 1.25, 2.16])

Now the estimated hazard ratio is about 1.64, with a 90% interval from about 1.25 to 2.16. That includes the true value, 2. And with the large cohort:

cp_big = split_rows(big)
tdc_big = PHReg(cp_big["stop"], cp_big[["comp"]], status=cp_big["died"], entry=cp_big["start"]).fit()
hazard_ratio(tdc_big).round(2)
array([1.97, 1.91, 2.02])

The estimate converges to the true value.

This is the right model for the OP’s question about association. It uses all of the follow-up, and each moment of each patient’s time is counted in the state the patient was actually in.

In terms of the three-state model, the time-dependent Cox model describes the two transitions into death. It assumes their hazards are proportional, \(\mu(t)\) and \(\mu(t) \cdot \text{HR}\), and estimates HR. It says nothing about the transition from state 0 to state 1 – how often complications happen.

That’s a limitation if we want to make predictions. Suppose a patient is alive at 6 months and has not had a complication. What is the chance they survive another year? The answer depends on whether they will have a complication during that year, and when – and the Cox model doesn’t tell us that.

Landmark analysis#

Landmark analysis answers the prediction question directly: given what we know about a patient now, what can we say about their future survival?

We choose a landmark time, select the patients who are alive and still under observation at that time, classify them by whether they have had a complication by then, and follow them from the landmark onward. A complication after the landmark doesn’t change the group a patient is in, because at the landmark we didn’t know it would happen.

Here are the Kaplan-Meier estimates of survival for one year after a landmark at 180 days. With the limit of 2 years of follow-up, the latest landmark with a full year of follow-up afterward is 365 days.

def km_at(durations, events, t):
    """Kaplan-Meier survival at time t, with its standard error."""
    sf = sm.SurvfuncRight(durations, events)
    i = np.searchsorted(sf.surv_times, t, side="right") - 1
    if i < 0:
        return 1.0, 0.0
    return sf.surv_prob[i], sf.surv_prob_se[i]


def landmark_data(df, s):
    at = df[df["t_end"] > s].copy()
    at["comp"] = (at["t_comp"] <= s).astype(int)
    at["time"] = at["t_end"] - s
    return at


def landmark_km(df, s, horizon=365):
    at = landmark_data(df, s)
    rows = {}
    for state, group in at.groupby("comp"):
        p, se = km_at(group["time"], group["died"], horizon)
        rows[state] = {"landmark": s, "patients": len(group), "survival": p,
                       "low": p - 1.645 * se, "high": p + 1.645 * se}
    return pd.DataFrame(rows).T.rename_axis("complication by landmark")


landmark_km(df, 180).round(3)
landmark patients survival low high
complication by landmark
0 180.0 438.0 0.927 0.905 0.948
1 180.0 413.0 0.910 0.886 0.934

Of the patients alive and under observation at 180 days, those who had already had a complication have an estimated 1-year survival of about 91%; those who hadn’t have about 93%.

Because the data are simulated, we can compute the true values. For a patient in state 0 at the landmark, survival includes both paths: staying in state 0, or moving to state 1 and surviving there.

def true_survival(s, horizon=365):
    P = transition_matrix(lam, mu, hr, s, s + horizon)
    return {0: P[0, 0] + P[0, 1], 1: P[1, 1]}


true_survival(180)
{0: 0.9365942554629961, 1: 0.9012993737775137}

The landmark estimates are close to the truth. And notice that the true difference in 1-year survival is only about 3.5 percentage points, even though the hazard ratio is 2. By 6 months the hazard of death is low, and doubling a low hazard doesn’t change the probability of surviving a year by much.

Since the purpose of a landmark analysis is prediction, that also suggests how to choose landmark times: use the times when predictions are needed, like scheduled visits when clinicians make decisions or counsel patients – not the times that give the cleanest result.

The limitation of landmark analysis is that each landmark uses only the patients still under observation at that time, and only their state at that time. It doesn’t model the complications that will happen later; it averages over them.

Why not report landmark hazard ratios?#

Many landmark analyses report a hazard ratio rather than survival probabilities: a Cox model fit from the landmark onward, with complication status at the landmark as the covariate. It’s tempting to read that hazard ratio as another estimate of the effect of a complication, or as a check on the time-dependent Cox model. It’s neither. Under the model we’re using, even with unlimited data it’s smaller than the time-dependent hazard ratio, and it changes over time, so a single number summarizes it poorly. From a landmark analysis, it’s better to report predicted survival, as above.

To see why, here are the landmark hazard ratios at 90, 180, and 365 days.

landmarks = [90, 180, 365]

rows = {}
for s in landmarks:
    at = landmark_data(df, s)
    fit = PHReg(at["time"], at[["comp"]], status=at["died"]).fit()
    hr_est, low, high = hazard_ratio(fit)
    rows[s] = {"patients": len(at), "with complication": at["comp"].sum(),
               "HR": hr_est, "low": low, "high": high}

landmark_hrs = pd.DataFrame(rows).T.rename_axis("landmark")
landmark_hrs.round(2)
patients with complication HR low high
landmark
90 908.0 294.0 1.42 1.05 1.93
180 851.0 413.0 1.54 1.08 2.19
365 765.0 492.0 2.23 1.31 3.80

The estimates vary and the intervals are wide; the one at 365 days is above 2. Here are the estimates from the large cohort.

big_hrs = {}
for s in landmarks:
    at = landmark_data(big, s)
    fit = PHReg(at["time"], at[["comp"]], status=at["died"]).fit()
    big_hrs[s] = hazard_ratio(fit)

pd.DataFrame(big_hrs, index=["HR", "low", "high"]).T.round(2)
HR low high
90 1.41 1.37 1.46
180 1.51 1.46 1.56
365 1.75 1.67 1.83

With a large cohort, the estimates don’t converge to 2. They are between 1 and 2, and larger for later landmarks, because they estimate something different. The “no complication” group at the landmark includes patients who have a complication later, and after that their hazard is doubled. So under this model, the hazard in that group is a mixture:

\[h_\text{no}(t) = (1 - p_t)\, \mu(t) + p_t\, \text{HR}\, \mu(t)\]

where \(p_t\) is the fraction of the group’s survivors who have had a complication by time \(t\). The ratio of the hazards in the two groups is

\[\text{HR}_\text{LM}(t) = \frac{\text{HR}}{1 + p_t (\text{HR} - 1)}\]

which is between 1 and HR. In this example, \(p_t\) grows over time, so the ratio is not constant, so the proportional hazards assumption of the landmark Cox model doesn’t hold. Here’s what it looks like for each landmark.

def landmark_hr_curve(s, ts):
    out = []
    for t in ts:
        P = transition_matrix(lam, mu, hr, s, t)
        p_t = P[0, 1] / (P[0, 0] + P[0, 1])
        out.append(hr / (1 + p_t * (hr - 1)))
    return np.array(out)


for s, color in zip(landmarks, [GRAY, BLUE, ORANGE]):
    ts = np.linspace(s, 730, 101)
    plt.plot(ts, landmark_hr_curve(s, ts), color=color, label=f"landmark {s}")
plt.axhline(hr, color="black", ls=":", label="HR")
decorate(xlabel="Days since implantation", ylabel="Hazard ratio between landmark groups", ylim=[0.9, 2.1])
_images/256c4b5da864c3d9ede7f527c81b1db4084595d0b05cfeedf20efab60ecc614d.png

At the landmark, the two groups are cleanly separated, so the ratio is 2. As time goes on, more of the “no complication” group has a complication, and the ratio falls toward 1. For later landmarks it falls more slowly, because the hazard of complications is lower.

So the landmark hazard ratio is not a biased estimate of the time-dependent hazard ratio; it describes a different contrast, between patients grouped by their state at the landmark. But because that contrast changes over time, the single hazard ratio from a Cox model is an average that’s hard to interpret. The survival probabilities answer the landmark question directly.

Multistate model#

So we have one model that answers the association question but can’t make predictions, and another that makes predictions one landmark at a time. Can one model do both?

To predict survival for a patient who has not had a complication, we have to consider two possibilities: they might have a complication later, or they might not. The time-dependent Cox model tells us what happens in each case, but not how likely each case is. For that, we need a model of complications as well as deaths.

That’s the three-state model we used to generate the data. To estimate it, we need, for each interval, the time patients spent in each state (the exposure) and the number of each kind of transition.

def aggregate(df):
    t0_end = np.where(df["ever"] == 1, df["t_comp"], df["t_end"])
    tc = df["t_comp"].fillna(np.inf).values
    rows = []
    for j in range(len(widths)):
        lo, hi = edges[j], edges[j + 1]
        in_j = lambda t: (t >= lo) & (t < hi)
        dead = df["died"] == 1
        rows.append({
            "interval": f"{lo}-{hi}",
            "E0": np.clip(np.minimum(t0_end, hi) - lo, 0, None).sum() / 365,
            "E1": np.clip(np.minimum(df["t_end"], hi) - np.maximum(tc, lo), 0, None).sum() / 365,
            "D01": in_j(df["t_comp"]).sum(),
            "D02": (dead & (df["ever"] == 0) & in_j(df["t_end"])).sum(),
            "D12": (dead & (df["ever"] == 1) & in_j(df["t_end"])).sum(),
        })
    return pd.DataFrame(rows).set_index("interval")


counts = aggregate(df)
counts.round(1)
E0 E1 D01 D02 D12
interval
0-30 75.3 5.3 116 26 0
30-90 118.3 35.8 197 27 18
90-180 127.7 88.8 145 14 16
180-365 175.9 232.7 128 13 18
365-730 208.8 474.7 82 10 49

E0 and E1 are patient-years in states 0 and 1. D01 is the number of complications, D02 deaths without a complication, and D12 deaths after a complication.

These 25 numbers are all the model needs. When hazards are constant within an interval, the likelihood of each hazard has the same form as a Poisson likelihood, with a mean equal to the hazard times the exposure. The counts aren’t really Poisson – each patient can have each transition at most once, and the exposures depend on when events happen – but as functions of the hazards, the likelihoods are the same, so we can estimate the hazards as if they were. In interval \(j\):

\[D_{01,j} \sim \text{Poisson}(E_{0,j}\, \lambda_j)\]
\[D_{02,j} \sim \text{Poisson}(E_{0,j}\, \mu_j)\]
\[D_{12,j} \sim \text{Poisson}(E_{1,j}\, \mu_j\, e^\beta)\]

where \(\beta\) is the log hazard ratio. With the death hazards modeled this way, this is the same model as the time-dependent Cox model, except that the baseline hazard is piecewise constant rather than unspecified. The difference is the first line, the model of complications.

For the priors, I’ll use lognormal distributions for the rates (per patient-year), with median 0.3 and a wide spread: the middle 95% runs from about 0.015 to 6 events per patient-year. For \(\beta\), a normal distribution centered at 0 with standard deviation 1, which puts the middle 95% of the hazard ratio between about 0.14 and 7.

with pm.Model() as model:
    log_lam = pm.Normal("log_lam", np.log(0.3), 1.5, shape=len(widths))
    log_mu = pm.Normal("log_mu", np.log(0.3), 1.5, shape=len(widths))
    beta = pm.Normal("beta", 0, 1)

    pm.Poisson("D01", counts["E0"].values * pm.math.exp(log_lam), observed=counts["D01"].values)
    pm.Poisson("D02", counts["E0"].values * pm.math.exp(log_mu), observed=counts["D02"].values)
    pm.Poisson("D12", counts["E1"].values * pm.math.exp(log_mu + beta), observed=counts["D12"].values)

    idata = pm.sample(random_seed=17, progressbar=False)
NUTS[nutpie]: [log_lam, log_mu, beta]

Here’s the posterior distribution of the hazard ratio.

def draws(name):
    """Posterior draws of a variable, with chains combined."""
    values = idata.posterior[name].values
    return values.reshape(-1, *values.shape[2:])


hr_post = np.exp(draws("beta"))
np.round([np.median(hr_post), *np.quantile(hr_post, [0.05, 0.95])], 2)
array([1.55, 1.19, 2.02])

It’s a little lower than the Cox estimate, but the difference is small compared to the width of the intervals.

The two estimates agree because they make the same comparison: both count each patient’s time in the state they were actually in, which is what removes the immortal time bias. So the Bayesian model is no better at estimating the hazard ratio. What it adds is the model of complications, which we’ll use for predictions.

Here are the hazard ratios from all of the analyses so far.

def plot_interval(y, est, low, high, color, label=None):
    plt.plot([low, high], [y, y], color=color)
    plt.plot(est, y, "o", color=color, label=label)


estimates = {
    "ever vs never": hazard_ratio(naive),
    "time-dependent Cox": hazard_ratio(tdc),
    "multistate (Bayesian)": [np.median(hr_post), *np.quantile(hr_post, [0.05, 0.95])],
}
for s in landmarks:
    estimates[f"landmark {s}"] = landmark_hrs.loc[s, ["HR", "low", "high"]].values

labels = list(estimates)
for i, label in enumerate(labels):
    color = ORANGE if label.startswith("landmark") else BLUE
    plot_interval(-i, *estimates[label], color=color)
plt.axvline(hr, color="black", ls=":")
plt.axvline(1, color=GRAY, lw=0.5)
plt.axhline(-2.5, color=GRAY, lw=0.5)
plt.yticks(-np.arange(len(labels)), labels)
plt.xscale("log")
plt.minorticks_off()
plt.xticks([0.25, 0.5, 1, 2, 4], ["0.25", "0.5", "1", "2", "4"])
decorate(xlabel="Hazard ratio (90% interval)")
_images/aca829f1af01d84b8ab07d0a1fe2ec45ff99861198d82d2fc2f520b6951cedc0.png

The first three estimate the same quantity, the hazard ratio in the data-generating process, marked with the dotted line. The ever-vs-never analysis gets it badly wrong; the other two get it right, within the uncertainty of a cohort this size.

The landmark estimates, below the line, estimate something else – the contrast between groups defined at the landmark – so they shouldn’t be judged by how close they are to 2.

Dynamic predictions#

Now we can use the multistate model to predict survival for a patient in either state at any time, accounting for complications that haven’t happened yet. For each posterior draw, I’ll compute the probability of surviving one year from a landmark, using the same transition-matrix calculation we used for the true values.

def posterior_survival(s, horizon=365):
    lam_draws = np.exp(draws("log_lam")) / 365
    mu_draws = np.exp(draws("log_mu")) / 365
    hr_draws = np.exp(draws("beta"))
    out = {0: [], 1: []}
    for lam_d, mu_d, hr_d in zip(lam_draws, mu_draws, hr_draws):
        P = transition_matrix(lam_d, mu_d, hr_d, s, s + horizon)
        out[0].append(P[0, 0] + P[0, 1])
        out[1].append(P[1, 1])
    return {k: np.array(v) for k, v in out.items()}
rows = []
for s in landmarks:
    truth = true_survival(s)
    km_table = landmark_km(df, s)
    post_surv = posterior_survival(s)
    for state in [0, 1]:
        rows.append({
            "landmark": s, "complication": state, "truth": truth[state],
            "KM": km_table.loc[state, "survival"],
            "KM low": km_table.loc[state, "low"], "KM high": km_table.loc[state, "high"],
            "posterior": np.median(post_surv[state]),
            "post low": np.quantile(post_surv[state], 0.05),
            "post high": np.quantile(post_surv[state], 0.95),
        })

predictions = pd.DataFrame(rows).set_index(["landmark", "complication"])
predictions.round(3)
truth KM KM low KM high posterior post low post high
landmark complication
90 0 0.923 0.919 0.900 0.938 0.918 0.903 0.931
1 0.884 0.878 0.846 0.910 0.892 0.871 0.911
180 0 0.937 0.927 0.905 0.948 0.932 0.919 0.944
1 0.901 0.910 0.886 0.934 0.910 0.893 0.925
365 0 0.939 0.953 0.932 0.975 0.934 0.916 0.948
1 0.896 0.899 0.876 0.922 0.907 0.887 0.925
plt.figure(figsize=(6, 4.5))
for i, ((s, state), row) in enumerate(predictions.iterrows()):
    y = -i
    plot_interval(y + 0.15, row["KM"], row["KM low"], row["KM high"], GRAY,
                  label="landmark KM" if i == 0 else None)
    plot_interval(y - 0.15, row["posterior"], row["post low"], row["post high"], BLUE,
                  label="multistate posterior" if i == 0 else None)
    plt.plot(row["truth"], y, "|", color="black", ms=14, mew=2,
             label="truth" if i == 0 else None)

ylabels = [f"day {s}, {'complication' if state else 'no complication'}"
           for s, state in predictions.index]
plt.yticks(-np.arange(len(predictions)), ylabels)
decorate(xlabel="Probability of surviving one more year (90% interval)", legend=False)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, -0.18), ncol=3)
plt.tight_layout()
_images/fc65141ad876d712a572508c6eaef7609598043070123ae18e92a4b957045289.png

The landmark Kaplan-Meier estimates and the multistate posterior are both reasonably close to the true probabilities – in this cohort, which is one sample, not a test of how the methods perform in general.

The posterior intervals are narrower than the Kaplan-Meier intervals, partly because the multistate model uses all of the data for every prediction: the hazard of death after day 180 is estimated from every patient at risk after day 180, regardless of their state at the landmark, and the hazard of complications is estimated from the whole cohort. The landmark analysis uses only the patients in each group at each landmark. But the narrower intervals also depend on the model’s assumptions – proportional hazards, hazards that are constant within intervals, and the priors. Here the structural assumptions are true, because the data came from the model; with real data they might not be, and the intervals would not reflect that.

Pros and cons of the multistate model#

The main advantage of the multistate model is that it is a complete model of the process that generates the data, so one model answers all of the questions we’ve asked:

  • The hazard ratio, which answers the question about association.

  • Predictions for a patient in either state, starting at any time and over any horizon within the 2 years the model covers, without choosing landmarks in advance. The same model can answer other questions, like the probability of a complication in the next year, or the expected time alive without one.

  • Uncertainty for any of these quantities comes directly from the posterior: we compute the quantity for each posterior draw. No delta method or bootstrap is needed, even when the quantity is a complicated function of the parameters, like the survival probabilities computed with matrix exponentials.

  • The priors stabilize estimates where data are sparse. With a smaller cohort, a rarer complication, or finer intervals, some intervals have few or no events, and the priors keep the estimated hazards in a plausible range. A prior that links neighboring intervals could do more, letting the hazards change smoothly over time.

  • Extensions – more kinds of complication, transplant as another state, a hazard that depends on time since the complication, covariates – are changes to the generative model, and the predictions follow from the same calculation.

Some of these come from the multistate structure rather than from being Bayesian: a frequentist multistate model can also make dynamic predictions. The Bayesian version adds the direct propagation of uncertainty and the priors.

The costs:

  • More assumptions. The multistate model assumes the hazards are constant within intervals, that the effect of a complication is proportional and doesn’t depend on how long ago it happened, and that the future depends only on the current state. The Cox model leaves the baseline hazard unspecified, and the landmark Kaplan-Meier estimates make no assumptions about the hazards at all. As we saw, the narrower intervals depend on these assumptions.

  • More choices. The intervals and the priors have to be chosen, and they should be chosen before looking at the results, with a check that the conclusions aren’t sensitive to them.

  • Covariates make the data bigger. To adjust for patient characteristics, as the OP intends, we can’t reduce the data to 25 numbers; the model needs a row for each patient and interval, and a parameter for each covariate. That’s still feasible, but the model is slower to fit.

When the assumptions are doubtful, landmark analysis is a useful check, because it makes so few of them.

Discussion#

To answer the OP’s questions:

Which approach? For the association between complications and mortality, use a Cox model with a time-dependent covariate (or the equivalent multistate model). It uses all of the follow-up and counts each patient’s time in the state they were actually in, so there is no immortal time. In this simulation, ever vs never made a complication that doubles the hazard of death look like it cuts it in half.

Is landmark analysis useful? Yes, as a complement, for prediction: given a patient’s state at a particular time, what are their chances over the next year? But the landmark hazard ratio estimates a different quantity from the time-dependent hazard ratio. Report landmark results as conditional on surviving to the landmark, and don’t treat them as a check on the size of the time-dependent estimate.

Which landmark times? The times when predictions are needed: scheduled visits or decision points, like 3 or 6 months after implantation. Not the times that give the most favorable results, and not too late for the remaining follow-up to support the prediction horizon.

A few other things the OP should consider:

  • Transplant and device removal. How to handle them depends on the outcome. For death while on device support, transplant is a competing event; for all-cause mortality after implantation, it’s an intermediate state, since patients can die after a transplant. Censoring at transplant is fine for estimating a cause-specific hazard, as here, but Kaplan-Meier curves computed that way are not the probability of death in the presence of transplant. A multistate model handles these cases by adding states.

  • Several kinds of complication. Each can be its own time-dependent covariate or its own state, and recurrent complications can be coded as the number so far.

  • Time since complication. The hazard of death might be highest right after a complication and then fade. A constant hazard ratio averages over that; a model where the hazard depends on time since the complication can describe it.

  • Baseline severity. Patients who are sicker at implantation may have more complications and also higher mortality. That can create an association between complications and death, or distort one that exists, and in survival data the direction isn’t always obvious because the sickest patients die first. Adjusting for baseline severity matters even when the goal is description rather than causal inference.

More generally, a regression model can answer a question about the relationship between variables without being enough to predict how the system that generates them will evolve. For that, we need a model of the whole process.

A note on AI use: This notebook was developed primarily by Claude Code, with guidance and revisions by Allen Downey. ChatGPT reviewed the plan and the notebook.

Data Q&A: Answering the real questions with Python

Copyright 2026 Allen B. Downey

License: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International