Applied Health Economics, RWE & HTA
Overview / Module 3 / Day 26
Module 3 · Causal inference for RWE · Day 26 of 100

Sustained Strategies: Censoring Weights and Marginal Structural Models

Days 22 to 25 compared starting Renavex in a given month with not starting, and then let routine care take over: an intention-to-treat question. The payer's model needs something else: the risk if patients stay on Renavex for three years, and the risk if they never take it. Following a strategy over time brings a new problem. eGFR drives the decision to start, and Renavex slows the fall in eGFR: eGFR is a confounder and on the causal path. Ordinary adjustment cannot handle that. Today you learn the three g-methods that can: inverse probability weighting of censoring, marginal structural models, and the g-formula.

▶
Video for Day 26 coming soon

By the end of today you can

  • recognize treatment–confounder feedback and say why regression fails with it
  • define strategies completely, co-treatments included
  • never censor at deviation without censoring weights
  • fit an MSM with stabilized weights and a dose–response that matches how the drug works
  • compare IPW and the parametric g-formula and say when I would use each

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:40
26.1 Treatment–confounder feedback
0:40–1:25
26.2 'Never': censor and re-weight
1:25–1:40
Break
1:40–2:00
26.3 Censoring without weights
2:00–2:55
26.4 A marginal structural model for 'always' vs 'never'
2:55–3:10
Break
3:10–3:35
26.5 The g-formula, the third g-method
3:35–4:05
26.6 Truth check and weight truncation
4:05–4:50
26.7 Mini-project: risk curves for the HTA model
4:50–5:00
26.8 Save your work
5:00–5:30
Bloc français

In this lesson

26.1 Treatment–confounder feedback (40 min)

Take two months. A0 is Renavex in month 0. L1 is "eGFR fell below 30 by month 1": A0 makes it less likely, and it makes A1 (Renavex in month 1) more likely. Y is eGFR lost by month 2. An unmeasured kidney "fragility" U raises both L1 and Y.

  • Leave L1 out of a regression, and A1's effect is confounded by L1.
  • Put L1 in, and you block the part of A0's effect that goes through L1, and you condition on a collider (L1 is caused by both A0 and U), which opens a path from A0 to Y through U.

No regression model gets "always" vs "never" right. The g-methods do:

"""Day 26.1 and 26.5: treatment-confounder feedback in two months, and three ways to handle it.

A0 = Renavex in month 0; L1 = eGFR fell below 30 by month 1 (A0 makes that less likely, and it makes
A1 more likely); A1 = Renavex in month 1; Y = eGFR lost by month 2. U (unmeasured kidney 'fragility')
raises both L1 and Y. Target: mean Y under 'always' (A0 = A1 = 1) minus under 'never'.
"""

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
import statsmodels.formula.api as smf  # noqa: E402
from scipy.special import expit  # noqa: E402

rng = np.random.default_rng(26)
n = 400_000

def world(a0=None, a1=None):
    u = rng.normal(size=n)
    A0 = rng.binomial(1, 0.3, n) if a0 is None else np.full(n, a0)
    L1 = rng.binomial(1, expit(-1 + 1.2 * u - 0.8 * A0))
    A1 = rng.binomial(1, expit(-1.5 + 2.0 * L1 + 1.5 * A0)) if a1 is None else np.full(n, a1)
    Y = 3 + 2.0 * u + 1.5 * L1 - 1.0 * A0 - 1.0 * A1 + rng.normal(size=n)
    return pd.DataFrame({"A0": A0, "L1": L1, "A1": A1, "Y": Y})

truth = world(1, 1).Y.mean() - world(0, 0).Y.mean()
d = world()
print(f"true effect, always vs never: {truth:.2f} (A0's own -1.0, A1's -1.0, and A0's benefit through L1)\n")
# 1. ordinary regression, with and without the time-varying confounder
for label, f in (("regression on A0 + A1", "Y ~ A0 + A1"), ("regression on A0 + A1 + L1", "Y ~ A0 + A1 + L1")):
    b = smf.ols(f, d).fit().params
    print(f"{label:<34}{b.A0 + b.A1:>7.2f}")
# 2. IPW for the MSM  E[Y(a0, a1)] = b0 + b1 a0 + b2 a1
p0 = smf.logit("A0 ~ 1", d).fit(disp=0).predict(d)
p1 = smf.logit("A1 ~ L1 * A0", d).fit(disp=0).predict(d)
w = 1 / np.where(d.A0 == 1, p0, 1 - p0) / np.where(d.A1 == 1, p1, 1 - p1)
b = smf.wls("Y ~ A0 + A1", d, weights=w).fit().params
print(f"{'IPW marginal structural model':<34}{b.A0 + b.A1:>7.2f}")
# 3. parametric g-formula: model L1 given A0, Y given everything, then simulate the strategies
lm = smf.logit("L1 ~ A0", d).fit(disp=0)
ym = smf.ols("Y ~ A0 + L1 + A1", d).fit()

def g(a):
    pl = lm.predict(pd.DataFrame({"A0": [a]}))[0]                 # P(L1 = 1) if A0 = a
    y = lambda l1: ym.predict(pd.DataFrame({"A0": [a], "L1": [l1], "A1": [a]}))[0]  # noqa: E731
    return pl * y(1) + (1 - pl) * y(0)

print(f"{'parametric g-formula':<34}{g(1) - g(0):>7.2f}")
true effect, always vs never: -2.17 (A0's own -1.0, A1's -1.0, and A0's benefit through L1)

regression on A0 + A1               -1.21
regression on A0 + A1 + L1          -1.76
IPW marginal structural model       -2.16
parametric g-formula                -2.17

Both regressions are wrong, in different directions from the truth (−2.17). Inverse probability weighting models the treatment decisions, A0 and then A1 given L1, and re-weights so that treatment no longer depends on L1. It never conditions on L1 in the outcome model, so it neither blocks the effect nor opens the collider. The g-formula (26.5) models L1 instead and simulates it. Both recover the truth.

The same structure is in the Corridor data: eGFR falls, doctors start Renavex, Renavex slows the fall. Day 23's time-varying Cox model, adjusted for the latest eGFR, gave a hazard ratio of 0.80. That is a conditional, "direct" effect, not the effect of a strategy.


26.2 'Never': censor and re-weight (45 min)

Start with the simplest strategy: never take Renavex. The generator's version of "never" also holds the SGLT2 inhibitor at its 2025 status, so following "never" means starting neither drug. A strategy must say what happens to co-treatments, or the truth and the estimate answer different questions.

People follow "never" until they start one of the two drugs. At that month, censor them: their later follow-up no longer tells us about "never". The people who remain are those who did not start, and they are not a random subset. Give each remaining person-month a weight of 1 / P(still following "never" up to now | history): the inverse probability of censoring weight (IPCW). People who look like those who started (low eGFR, albuminuria) count for more, standing in for those censored.

Build the person-months first: people not on Renavex in 2025, with SGLT2 status, the previous month's treatment, and years on Renavex so far (m3/msm_months.parquet, person-level, never leaves the secure environment):

def prepare(con):
    """Person-months of non-prevalent users with current SGLT2 status, lagged treatment and filled eGFR."""
    import duckdb
    base = baseline(con)
    pm = duckdb.sql(f"SELECT * FROM read_parquet('{PERSON_MONTHS}')").df()
    b = base[base.renavex_2025 == 0][["person_id", "new_sglt2_date"]]
    pm = pm.merge(b, on="person_id")
    pm["month12"] = pm.month / 12
    pm["egfr_now10"] = pm.egfr_now10.fillna(pm.egfr10)
    pm["on_sglt2"] = ((pm.sglt2_2025 == 1) | (pm.new_sglt2_date < pm.m_start)).astype(int)
    g = pm.groupby("person_id")
    pm["prev_on"] = g.on_renavex.shift(1).fillna(0)
    pm["prev_sglt2"] = g.on_sglt2.shift(1).fillna(pm.sglt2_2025)
    pm["cum_on"] = pm.groupby("person_id").prev_on.cumsum() / 12                # years on Renavex before this month
    dev = ((pm.started == 1) | (pm.on_sglt2 != pm.sglt2_2025)).astype(int)    # left 'never' this month
    pm["deviates"] = dev
    pm["dev_before"] = dev.groupby(pm.person_id).cumsum() - dev                   # deviations in earlier months
    return pm.sort_values(["person_id", "month"]).reset_index(drop=True)
297,617 person-months for 9,018 people (m3/msm_months.parquet)
on Renavex 18.4% of months; on an SGLT2 inhibitor 38.3%; 411 kidney failures, 1085 deaths

The risk is a cumulative incidence with death as a competing event: in each month, the weighted hazards of kidney failure and of death, then the probability of reaching the month free of both times the hazard of kidney failure.

def cumulative_incidence(d, w=None, curve=False):
    """Kidney failure risk by month 36 from (weighted) monthly hazards, with death as a competing event
    (curve=True: the whole curve, by month)."""
    w = np.ones(len(d)) if w is None else np.asarray(w)
    g = pd.DataFrame({"month": d.month, "w": w, "kf": w * d.kf, "death": w * d.death * (1 - d.kf)})
    g = g.groupby("month").sum()
    h_kf, h_d = g.kf / g.w, g.death / g.w
    surv = (1 - h_kf - h_d).cumprod().shift(1, fill_value=1.0)
    cif = (surv * h_kf).cumsum()
    return cif if curve else float(cif.iloc[-1])

def ipcw_never(pm, time_varying=True):
    """Censor each person when they leave 'never'; weight the rest by 1 / P(still adherent | history)."""
    risk = pm[pm.dev_before == 0].copy()                        # rows at risk of deviating (incl. the month they do)
    x = ADJUST + (" + cr(egfr_now10, df=4)" if time_varying else "")
    m = smf.logit(f"deviates ~ {x} + {MONTH}", risk).fit(disp=0, method="newton", maxiter=50)
    risk["p_stay"] = 1 - np.asarray(m.predict(risk))
    adh = risk[risk.deviates == 0].copy()
    adh["w"] = 1 / adh.groupby("person_id").p_stay.cumprod()
    return adh, m
"""Day 26.2: the 'never' strategy by cloning-free censoring - censor people when they deviate, then
re-weight the people who stay by 1 / P(still following 'never' | their history)."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import warehouse  # noqa: E402
from corridor.msm import cumulative_incidence, ipcw_never, prepare  # noqa: E402

pm = prepare(warehouse())
risk = pm[pm.dev_before == 0]
print(f"{pm.person_id.nunique():,} people not on Renavex in 2025; {int(risk.deviates.sum()):,} leave 'never' "
      f"(start Renavex or a new SGLT2 inhibitor) within 36 months")
for label, tv in (("baseline covariates only", False), ("+ latest eGFR each month", True)):
    adh, m = ipcw_never(pm, tv)
    w = adh.w
    print(f"\ncensoring model with {label}:")
    print(f"  weights: mean {w.mean():.2f}, 99th percentile {w.quantile(0.99):.1f}, largest {w.max():.0f}")
    print(f"  36-month kidney failure risk under 'never': {cumulative_incidence(adh, w):.4f}")
9,018 people not on Renavex in 2025; 3,588 leave 'never' (start Renavex or a new SGLT2 inhibitor) within 36 months

censoring model with baseline covariates only:
  weights: mean 1.30, 99th percentile 3.7, largest 278
  36-month kidney failure risk under 'never': 0.0553

censoring model with + latest eGFR each month:
  weights: mean 1.30, 99th percentile 3.8, largest 90
  36-month kidney failure risk under 'never': 0.0562

3,588 of 9,018 people leave "never" within three years. With the censoring model updated monthly with the latest eGFR, the 36-month risk under "never" is 5.6%. The censoring model with baseline covariates only gives a similar answer (5.5%) with weights up to 278, against 90: over three years, baseline eGFR already predicts most of who starts. The latest eGFR matters more when kidney function changes faster than here, or when follow-up is longer.


26.3 Censoring without weights (20 min)

Bug of the day. A "per-protocol" analysis that censors people when they deviate and stops there:

"""Day 26 bug of the day: 'per-protocol' = drop people's follow-up when they start treatment, and stop there."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import warehouse  # noqa: E402
from corridor.msm import cumulative_incidence, ipcw_never, prepare  # noqa: E402

pm = prepare(warehouse())
adh, _ = ipcw_never(pm)
first = pm[pm.dev_before == 0]
who = first.groupby("person_id").agg(left=("deviates", "max"), egfr10=("egfr10", "first"))
print("people who leave 'never' vs those who stay: mean baseline eGFR "
      f"{45 - 10 * who.egfr10[who.left == 1].mean():.1f} vs {45 - 10 * who.egfr10[who.left == 0].mean():.1f}")
print(f"risk under 'never', censored, unweighted : {cumulative_incidence(adh):.4f}")
print(f"risk under 'never', censored, IPCW       : {cumulative_incidence(adh, adh.w):.4f}")
print(f"risk in routine care, nobody censored   : {cumulative_incidence(pm):.4f}")
people who leave 'never' vs those who stay: mean baseline eGFR 37.8 vs 47.7
risk under 'never', censored, unweighted : 0.0279
risk under 'never', censored, IPCW       : 0.0562
risk in routine care, nobody censored   : 0.0456

People who leave "never" start with eGFR 38; those who stay, 48. Censoring them without weights leaves the healthiest people in the "never" arm, and the risk under "never" comes out at 2.8%, half the weighted 5.6%, and lower even than the 4.6% of routine care, in which 40% of people started one of the two drugs. Censoring that depends on prognosis is informative. Censoring is only half of a per-protocol analysis; the weights are the other half.

Why it matters at work: per-protocol and "on-treatment" analyses are routinely requested by HTA reviewers, and the unweighted version is the most common way they are done wrong. If a submission reports a per-protocol effect, the first question is how deviations were handled.

Where you'll meet this: per-protocol analyses of pragmatic trials; switching adjustment in oncology HTA (IPCW is one of the methods NICE's Decision Support Unit describes for treatment switching); dialysis and transplant registries


26.4 A marginal structural model for 'always' vs 'never' (55 min)

"Always Renavex" is harder to emulate by censoring, because hardly anyone starts in month 0 and stays on for three years. A marginal structural model (MSM) borrows strength across patterns of use instead. It models the hazard of kidney failure as a function of treatment history, fitted on all person-months, re-weighted so that treatment no longer depends on eGFR.

The stabilized weights are, month by month, the probability of the treatment the person actually received given baseline covariates (numerator) over the same probability given baseline covariates and the latest eGFR (denominator), multiplied over the months so far. Three models give these probabilities: starting Renavex, staying on it, and starting an SGLT2 inhibitor.

def treatment_weights(pm):
    """Stabilized weights for current Renavex (start and stay-on models) and current SGLT2 (start model):
    numerators use baseline covariates and month, denominators add the latest eGFR. Months with
    deterministic treatment (already on an SGLT2 inhibitor, which nobody stops) contribute 1."""
    d = pm.copy()
    sw = np.ones(len(d))
    models = (("on_renavex", "prev_on == 0"), ("on_renavex", "prev_on == 1"), ("on_sglt2", "prev_sglt2 == 0"))
    for exposure, rows in models:                   # start Renavex, stay on Renavex, start an SGLT2 inhibitor
        sub = d.query(rows)
        x = ADJUST.replace(" + sglt2_2025", "") if exposure == "on_sglt2" else ADJUST   # constant in these rows
        for extra, sign in (("", 1), (" + cr(egfr_now10, df=4)", -1)):
            m = smf.logit(f"{exposure} ~ {x}{extra} + {MONTH}", sub).fit(disp=0, method="newton", maxiter=50)
            p = np.asarray(m.predict(sub))
            lik = np.where(sub[exposure] == 1, p, 1 - p)
            r = pd.Series(1.0, index=d.index)
            r[sub.index] = lik
            sw = sw * r.to_numpy() ** sign
    d["sw"] = pd.Series(sw).groupby(d.person_id.to_numpy()).cumprod().to_numpy()
    return d

Then weighted pooled logistic models for kidney failure and death, and a prediction for everyone under "always" and "never":

def msm_risks(d, weight="sw", extra="", dose=True):
    """Weighted pooled logistic models for kidney failure and death given treatment (current Renavex, and
    with dose=True also years on Renavex so far), month and baseline covariates; then everyone's risk with
    Renavex always on vs never (SGLT2 held at its 2025 status), averaged.
    Returns {"always": risk by month 36, "never": ..., "curves": DataFrame by month, "kf_model": fit}."""
    w = np.ones(len(d)) if weight is None else d[weight].to_numpy()
    f = f"~ on_renavex{' + cum_on' if dose else ''} + on_sglt2 + {ADJUST}{extra} + {MONTH}"
    fits = {y: sm.GLM.from_formula(f"{y} {f}", d, family=sm.families.Binomial(), freq_weights=w).fit()
            for y in ("kf", "death")}
    people = d[d.month == 0].copy()
    curves = {}
    for name, on in (("always", 1), ("never", 0)):
        surv, risk, curve = np.ones(len(people)), np.zeros(len(people)), []
        for month in range(36):
            g = people.assign(on_renavex=on, cum_on=on * month / 12, on_sglt2=people.sglt2_2025, month12=month / 12)
            hk, hd = np.asarray(fits["kf"].predict(g)), np.asarray(fits["death"].predict(g))
            risk += surv * hk
            surv *= 1 - hk - hd * (1 - hk)
            curve.append(risk.mean())
        curves[name] = curve
    c = pd.DataFrame(curves).rename_axis("month")
    return {"always": float(c.always.iloc[-1]), "never": float(c.never.iloc[-1]), "curves": c, "kf_model": fits["kf"]}
"""Day 26.3-26.4: a marginal structural model for 'always Renavex' vs 'never', fitted with stabilized IPTW."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import warehouse  # noqa: E402
from corridor.msm import msm_risks, prepare, treatment_weights  # noqa: E402

d = treatment_weights(prepare(warehouse()))
print(f"stabilized weights: mean {d.sw.mean():.3f}, 1st-99th percentile {d.sw.quantile(0.01):.2f}-{d.sw.quantile(0.99):.2f}, "
      f"largest {d.sw.max():.1f}")
print(f"\n{'model for the monthly hazard':<52}{'always':>8}{'never':>8}{'ratio':>7}")
rows = (("current Renavex, unweighted", None, "", False),
        ("current Renavex, + latest eGFR (conditional)", None, " + egfr_now10", False),
        ("current Renavex, weighted (MSM)", "sw", "", False),
        ("current + years on Renavex, unweighted", None, "", True),
        ("current + years on Renavex, weighted (MSM)", "sw", "", True))
for label, w, extra, dose in rows:
    r = msm_risks(d, w, extra, dose)
    print(f"{label:<52}{r['always']:>8.4f}{r['never']:>8.4f}{r['always'] / r['never']:>7.2f}")
stabilized weights: mean 1.001, 1st-99th percentile 0.60-1.53, largest 5.9

model for the monthly hazard                          always   never  ratio
current Renavex, unweighted                           0.0409  0.0479   0.85
current Renavex, + latest eGFR (conditional)          0.0326  0.0392   0.83
current Renavex, weighted (MSM)                       0.0387  0.0513   0.76
current + years on Renavex, unweighted                0.0351  0.0500   0.70
current + years on Renavex, weighted (MSM)            0.0318  0.0543   0.59

Stabilized weights are well behaved (mean 1.00, largest 5.9). Read the five rows in pairs.

  • Weighting matters. With current Renavex only, weighting moves the ratio from 0.85 to 0.76. Adjusting for the latest eGFR instead, the conventional approach, gives 0.83: it blocks the benefit that comes through slower eGFR decline.
  • The MSM must describe how the drug works. Renavex lowers the hazard while taken and slows the decline in eGFR, so its benefit grows with time on it. A model with only "on Renavex this month" cannot express that. With years on Renavex added, the weighted MSM gives 3.2% vs 5.4%, a ratio of 0.59.

An MSM is only as good as its dose–response assumption. Before fitting it, ask how the treatment could act: immediately, cumulatively, with a lag, or with a lasting effect after stopping.

Check it in R (weights from glm(), then a weighted pooled logistic model; ns() and cr() splines differ slightly, so R gives 0.58):

# Day 26: the stabilized-weight MSM by hand in R - glm() for the weights and for the weighted pooled logistic.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(splines) })
con <- dbConnect(duckdb(shared_home = FALSE))
pm <- dbGetQuery(con, "SELECT * FROM read_parquet('m3/msm_months.parquet') ORDER BY person_id, month")
dbDisconnect(con, shutdown = TRUE)
# prev_on, prev_sglt2 and cum_on are rebuilt here as a check on the Python lags
lag1 <- function(x, fill) { y <- ave(x, pm$person_id, FUN = function(v) c(NA, head(v, -1))); ifelse(is.na(y), fill, y) }
pm$prev_on <- lag1(pm$on_renavex, 0); pm$prev_sglt2 <- lag1(pm$on_sglt2, pm$sglt2_2025)
pm$cum_on <- ave(pm$prev_on, pm$person_id, FUN = cumsum) / 12
adj <- "egfr10 + albuminuria + sglt2_2025 + age10 + male + qc + nephrology_care + heart_failure + copd + prior_stays"
mon <- "month12 + I(month12^2)"
lik <- rep(1, nrow(pm))
for (m in list(c("on_renavex", "prev_on == 0"), c("on_renavex", "prev_on == 1"), c("on_sglt2", "prev_sglt2 == 0"))) {
  rows <- with(pm, eval(parse(text = m[2])))
  x <- if (m[1] == "on_sglt2") sub(" \\+ sglt2_2025", "", adj) else adj
  num <- fitted(glm(as.formula(paste(m[1], "~", x, "+", mon)), binomial, data = pm[rows, ]))
  den <- fitted(glm(as.formula(paste(m[1], "~", x, "+ ns(egfr_now10, df = 4) +", mon)), binomial, data = pm[rows, ]))
  a <- pm[[m[1]]][rows]
  lik[rows] <- lik[rows] * ifelse(a == 1, num / den, (1 - num) / (1 - den))
}
pm$sw <- ave(lik, pm$person_id, FUN = cumprod)
cat(sprintf("stabilized weights: mean %.3f, largest %.1f\n", mean(pm$sw), max(pm$sw)))
f <- paste("~ on_renavex + cum_on + on_sglt2 +", adj, "+", mon)
fk <- suppressWarnings(glm(as.formula(paste("kf", f)), binomial, data = pm, weights = sw))
fd <- suppressWarnings(glm(as.formula(paste("death", f)), binomial, data = pm, weights = sw))
p0 <- pm[pm$month == 0, ]
risk <- sapply(c(always = 1, never = 0), function(on) {
  s <- rep(1, nrow(p0)); r <- rep(0, nrow(p0))
  for (mo in 0:35) {
    g <- transform(p0, on_renavex = on, cum_on = on * mo / 12, on_sglt2 = sglt2_2025, month12 = mo / 12)
    hk <- predict(fk, g, type = "response"); hd <- predict(fd, g, type = "response")
    r <- r + s * hk; s <- s * (1 - hk - hd * (1 - hk))
  }
  mean(r)
})
cat(sprintf("MSM: always %.4f, never %.4f, ratio %.2f\n", risk["always"], risk["never"], risk["always"] / risk["never"]))
stabilized weights: mean 1.001, largest 5.9
MSM: always 0.0316, never 0.0543, ratio 0.58

26.5 The g-formula, the third g-method (25 min)

IPW models the treatment decisions. The parametric g-formula models everything else instead: eGFR next month given history and treatment, kidney failure and death given history and treatment. It then simulates each person's 36 months under "always" and "never", drawing each month's eGFR from its model and setting treatment by the strategy. In 26.1 it is two lines: P(L1 | A0) and E[Y | A0, L1, A1], combined by hand, and it recovered the truth exactly as IPW did.

IPW / MSMParametric g-formula
Modelstreatment (and censoring)time-varying confounders and outcome
Fails whentreatment models are wrong, or weights are extreme (poor positivity)any confounder or outcome model is wrong (errors compound over months)
Handles complex strategies ("start when eGFR < 30")with cloning and censoringnaturally: simulate the rule
Precisionlowerhigher

For the corridor, a g-formula would need a model of eGFR's monthly change, irregular lab timing included: a week's work, and many assumptions. That is why the MSM is the usual choice for a static strategy, and the g-formula for dynamic ones. When both are feasible, run both: agreement is reassuring because their assumptions are different. R's gfoRmula package implements it.


26.6 Truth check and weight truncation (30 min)

The generator ran every person's 36 months under each static strategy with the same random numbers. Average them over the same 9,018 people:

"""Day 26 truth check: 36-month kidney failure risks under 'never' and 'always Renavex' vs the generator."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import warehouse  # noqa: E402
from corridor.msm import cumulative_incidence, ipcw_never, msm_risks, prepare, treatment_weights, truth  # noqa: E402

pm = prepare(warehouse())
tr = truth(pm)
adh, _ = ipcw_never(pm)
d = treatment_weights(pm)
cur, dose = msm_risks(d, dose=False), msm_risks(d)
print(f"{'method':<40}{'never':>8}{'always':>8}{'ratio':>7}")
print(f"{'censor at deviation, unweighted':<40}{cumulative_incidence(adh):>8.4f}")
print(f"{'IPCW (latest eGFR)':<40}{cumulative_incidence(adh, adh.w):>8.4f}")
print(f"{'MSM, current Renavex':<40}{cur['never']:>8.4f}{cur['always']:>8.4f}{cur['always'] / cur['never']:>7.2f}")
print(f"{'MSM, current + years on Renavex':<40}{dose['never']:>8.4f}{dose['always']:>8.4f}{dose['always'] / dose['never']:>7.2f}")
print(f"{'truth (generator, same people)':<40}{tr['never']:>8.4f}{tr['renavex']:>8.4f}{tr['renavex'] / tr['never']:>7.2f}")
print("\nfor comparison - Day 23 time-varying Cox, adjusted for latest eGFR: HR 0.80; generator's direct effect on the hazard: 0.75")
method                                     never  always  ratio
censor at deviation, unweighted           0.0279
IPCW (latest eGFR)                        0.0562
MSM, current Renavex                      0.0513  0.0387   0.76
MSM, current + years on Renavex           0.0543  0.0318   0.59
truth (generator, same people)            0.0570  0.0334   0.59

for comparison - Day 23 time-varying Cox, adjusted for latest eGFR: HR 0.80; generator's direct effect on the hazard: 0.75

The IPCW risk under "never" (5.6%) and the dose-aware MSM (5.4% vs 3.2%, ratio 0.59) match the truth (5.7% vs 3.3%, 0.59). The 0.59 is the number an economic model needs: the effect of three years on the drug, including its effect through slower decline. Day 23's 0.80 and the generator's direct effect of 0.75 are smaller effects of a different kind.

Try it (15 min). Truncate the stabilized weights at the 0.1st/99.9th, 1st/99th and 5th/95th percentiles. How much do the risks move?

Solution
"""Day 26 try it: truncate the stabilized weights - how much do the MSM's risks move?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import warehouse  # noqa: E402
from corridor.msm import msm_risks, prepare, treatment_weights  # noqa: E402

d = treatment_weights(prepare(warehouse()))
print(f"{'truncation':<22}{'largest weight':>15}{'always':>8}{'never':>8}{'ratio':>7}")
for label, q in (("none", None), ("0.1st-99.9th pct", 0.001), ("1st-99th pct", 0.01), ("5th-95th pct", 0.05)):
    d["swt"] = d.sw if q is None else d.sw.clip(d.sw.quantile(q), d.sw.quantile(1 - q))
    r = msm_risks(d, "swt")
    print(f"{label:<22}{d.swt.max():>15.2f}{r['always']:>8.4f}{r['never']:>8.4f}{r['always'] / r['never']:>7.2f}")
print("(truth: 0.0334 vs 0.0570, ratio 0.59)")
truncation             largest weight  always   never  ratio
none                             5.87  0.0318  0.0543   0.59
0.1st-99.9th pct                 2.10  0.0320  0.0541   0.59
1st-99th pct                     1.53  0.0322  0.0536   0.60
5th-95th pct                     1.20  0.0330  0.0527   0.63
(truth: 0.0334 vs 0.0570, ratio 0.59)

Mild truncation changes nothing, and 5%/95% starts to pull the ratio towards the null (0.63): truncation trades bias for variance, and heavy truncation brings back some of the confounding the weights removed. With weights this well behaved, report the untruncated estimate and the 1%/99% one as a sensitivity analysis.


26.7 Mini-project: risk curves for the HTA model (45 min)

Plot the 36-month cumulative incidence under each strategy, with the unweighted per-protocol curve for contrast and the truth at 36 months, and save it to figures/day26_strategy_curves.png:

"""Day 26 mini-project: the figure for the HTA submission - kidney failure risk over 36 months under
'never' (IPCW) and under 'always' vs 'never' (MSM), with the generator's truth at 36 months."""

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

from corridor.db import ROOT, warehouse  # noqa: E402
from corridor.msm import cumulative_incidence, ipcw_never, msm_risks, prepare, treatment_weights, truth  # noqa: E402

pm = prepare(warehouse())
tr = truth(pm)
adh, _ = ipcw_never(pm)
ipcw = cumulative_incidence(adh, adh.w, curve=True)
naive = cumulative_incidence(adh, curve=True)
msm = msm_risks(treatment_weights(pm))["curves"]
fig, ax = plt.subplots(figsize=(7.5, 4.6))
ax.plot(msm.index + 1, 100 * msm.never, color="#e5484d", lw=2.2, label="never Renavex (MSM)")
ax.plot(msm.index + 1, 100 * msm.always, color="#3ecf8e", lw=2.2, label="always Renavex (MSM)")
ax.plot(ipcw.index + 1, 100 * ipcw, color="#e5484d", lw=1.4, ls="--", label="never Renavex (IPCW)")
ax.plot(naive.index + 1, 100 * naive, color="#8b8d98", lw=1.2, ls=":", label="never, censored without weights")
ax.scatter([36, 36], [100 * tr["never"], 100 * tr["renavex"]], color="black", zorder=5, s=28, label="truth at 36 months")
ax.set_xlabel("months from 1 January 2026")
ax.set_ylabel("kidney failure, cumulative %")
ax.set_xlim(0, 37)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, fontsize=9, loc="upper left")
fig.tight_layout()
out = os.path.join(ROOT, "figures", "day26_strategy_curves.png")
fig.savefig(out, dpi=150)
print(f"wrote figures/day26_strategy_curves.png")
for m in (12, 24, 36):
    print(f"month {m}: never (MSM) {msm.never.iloc[m - 1]:.4f}, always (MSM) {msm.always.iloc[m - 1]:.4f}, never (IPCW) {ipcw.iloc[m - 1]:.4f}")
wrote figures/day26_strategy_curves.png
month 12: never (MSM) 0.0157, always (MSM) 0.0126, never (IPCW) 0.0146
month 24: never (MSM) 0.0322, always (MSM) 0.0221, never (IPCW) 0.0324
month 36: never (MSM) 0.0543, always (MSM) 0.0318, never (IPCW) 0.0562

Kidney failure risk under 'always' and 'never'

The curves separate slowly at first and then faster, the cumulative effect of 26.4. This is the shape Module 5's Markov model needs: transition probabilities to kidney failure that depend on time on treatment, not one hazard ratio. Write two sentences under the figure for a modeller: what each curve assumes, and why the unweighted per-protocol curve must not be used.

26.8 Save your work

python -m pytest -q
git add .
git commit -m "Day 26: IPCW, stabilized weights and a marginal structural model"

Day 26 checklist

  • I can recognize treatment–confounder feedback and say why regression fails with it
  • I define strategies completely, co-treatments included
  • I never censor at deviation without censoring weights
  • I fit an MSM with stabilized weights and a dose–response that matches how the drug works
  • I can compare IPW and the parametric g-formula and say when I would use each