Capstone: An Emulated Trial of Renavex
Today you deliver what a payer asks for a year after listing: a real-world evidence report on whether Renavex works in routine care, written in the order of the CDA-AMC reporting guidance. One command builds it from Module 3's methods: the target trial with sequential monthly trials (Day 22), propensity scores and overlap weights (Day 24), AIPW (Day 25), the marginal structural model for sustained use (Day 26), subgroups (Day 27), and the negative control, E-values and frailty bias analysis (Day 28). Every number in the text comes from code. Six release checks run before anything leaves the secure environment, R and SAS check the key numbers, and the generator grades the result.
By the end of today you can
- build the whole RWE report with one command and rebuild it identically
- My report follows the 12 CDA-AMC sections and leads with absolute risks
- The primary analysis is the pre-specified one, and every estimate names its estimand
- My release checks cover small cells, identifiers, sections, consistency and reproducibility
- reproduce the cohort, Table 1 and the weighted estimate in SAS and R
Today's 5.5-hour plan
In this lesson
30.1 The brief (20 min)
The HEOR lead: "The payer listed Renavex on the strength of one trial and wants to know whether it works in routine care in Ontario and Quebec, in the patients doctors actually prescribe it to. They also want the inputs for the reassessment's economic model: the effect of staying on the drug for three years. CDA-AMC format, aggregate tables only, every assumption visible, and sensitivity analyses that put a number on what we could not measure."
That brief fixes the deliverable:
| The brief says | The report delivers | Built on |
|---|---|---|
| "works in routine care" | an emulated target trial, new users, intention to treat, 24-month kidney failure | Days 21–23 |
| "patients doctors prescribe it to" | the overlap population (primary) and the starters (AIPW ATT) | Days 24–25 |
| "staying on the drug for three years" | always vs never Renavex, MSM and IPCW | Day 26 |
| "where it is worth most" | pre-specified subgroups and baseline-risk groups | Day 27 |
| "what we could not measure" | negative control, E-values, frailty bias analysis | Day 28 |
| "CDA-AMC format" | the 12 reporting sections, the protocol and deviation log | Day 29 |
The comparator is usual care: in 2026, doctors' alternative to starting Renavex was not starting it, with or without an SGLT2 inhibitor (39% of starters and 35% of non-starters were already on one). An active-comparator design, Renavex vs a new SGLT2 inhibitor, answers a different question and is left as an extension.
30.2 One function, every output (40 min)
corridor/rwe_report.py follows the Day 10 and Day 20 pattern: a frozen Config, one run(), tables written as CSV, figures with no timestamps, a report filled in from a template with str.format, and a MANIFEST.txt of fingerprints.
@dataclass(frozen=True)
class Config:
out_dir: str = "capstone/m3_output"
max_egfr: float = 60 # eligibility: latest eGFR below this (60 = everyone; Day 30 try it: 45)
boot: int = 100 # person bootstrap for the primary analysis
seed: int = 2026
def run(config=Config(), root="."):
"""Build every output into config.out_dir. Returns the numbers the report quotes."""
from corridor.db import connect
out = os.path.join(root, config.out_dir)
os.makedirs(out, exist_ok=True)
con = connect()
t = _trials(con, config)
_, e = fit_ps(t)
est = estimates_table(t, e, config)
strat, curves, ipcw = strategy_table(config)
tables = {"attrition": attrition_table(con, t), "table1": table_one(t, weights(e, t.start, "overlap")),
"estimates": est, "subgroups": subgroup_table(t, e), "sensitivity": sensitivity_table(t, e, est),
"strategies": strat}
for name, tab in tables.items():
tab.to_csv(os.path.join(out, f"{name}.csv"), index=False)
_figures(t, e, curves, ipcw, out)
r = _numbers(tables, config, strat.attrs["people"])
with open(os.path.join(root, "capstone", "rwe_template.md"), encoding="utf-8") as f:
report = f.read().format(**r)
with open(os.path.join(out, "report.md"), "w", encoding="utf-8", newline="\n") as f:
f.write(report)
files = sorted(x for x in os.listdir(out) if x != "MANIFEST.txt")
with open(os.path.join(out, "MANIFEST.txt"), "w", encoding="utf-8", newline="\n") as f:
f.write("".join(f"{sha256(os.path.join(out, x))} {x}\n" for x in files))
return r
The estimates table puts the primary analysis first: overlap weights, with a 95% CI from bootstrapping people and refitting the propensity score each time. AIPW gives the effect in starters and in everyone eligible, for kidney failure, death and the negative control.
def estimates_table(t, e, config):
rows = []
def add(outcome, method, estimand, r1, r0, lo=None, hi=None):
rows.append({"outcome": outcome, "method": method, "estimand": estimand, "risk_start": round(r1, 4),
"risk_no_start": round(r0, 4), "difference_pts": round(100 * (r1 - r0), 2),
"ratio": round(r1 / r0, 3), "ci_low": None if lo is None else round(lo, 3),
"ci_high": None if hi is None else round(hi, 3)})
s = t.start == 1
add("kidney failure", "crude comparison", "none", t.kf24[s].mean(), t.kf24[~s].mean())
p = _overlap(t)
boot = cluster_bootstrap(t, _overlap, reps=config.boot, seed=config.seed)
rr = boot.r1 / boot.r0
add("kidney failure", "overlap weights (primary)", "ATO", p["r1"], p["r0"], np.quantile(rr, 0.025), np.quantile(rr, 0.975))
for y, name in (("kf24", "kidney failure"), ("death24", "death"), ("hosp24", "hospitalization (negative control)")):
q1, q0 = outcome_model(t, OUTCOME_FORMULA.replace("kf24", y))
r = aipw(t[y], t.start, e, q1, q0, t.person_id, "att")
add(name, "AIPW", "ATT", r["r1"], r["r0"], r["lo"], r["hi"])
if y == "kf24":
r = aipw(t[y], t.start, e, q1, q0, t.person_id, "ate")
add(name, "AIPW", "ATE", r["r1"], r["r0"], r["lo"], r["hi"])
add(name, "g-formula (outcome model)", "ATT", q1[s].mean(), q0[s].mean())
return pd.DataFrame(rows)
The subgroup table applies the release rules of Day 2 to event counts, and it is designed so that no suppressed count can be recovered (30.7):
def subgroup_table(t, e):
"""Pre-specified subgroups and risk groups. Risk quarters 1-3 are pooled and eGFR bands are not released:
their event counts are below 6 or could be recovered by subtraction (Day 30 bug of the day)."""
q1, q0 = outcome_model(t)
cut = np.quantile(q0[t.start == 1], 0.75)
t = t.assign(top_q=(q0 >= cut).astype(int))
groups = {"albuminuria": "albuminuria == 1", "no albuminuria": "albuminuria == 0", "Quebec": "qc == 1",
"Ontario": "qc == 0", "age < 70": "age < 70", "age >= 70": "age >= 70",
"baseline risk: lower three quarters": "top_q == 0", "baseline risk: top quarter": "top_q == 1"}
s = subgroup_effects(t, e, q1, q0, groups)
out = s[["subgroup", "starts", "events_in_starters"]].copy()
out["risk_no_start"] = s.risk_no_start.round(4)
out["difference_pts"] = (100 * s.rd).round(2)
out["ratio"], out["ci_low"], out["ci_high"] = s.rr.round(3), s.lo.round(3), s.hi.round(3)
small = (out.events_in_starters > 0) & (out.events_in_starters < SMALL)
out.loc[small, ["events_in_starters", "risk_no_start", "difference_pts", "ratio", "ci_low", "ci_high"]] = np.nan
out["events_in_starters"] = out.events_in_starters.astype("Int64")
return out
The report template (capstone/rwe_template.md) has one heading per CDA-AMC section. Each {field} is filled by _numbers(), and tests/test_day_30.py checks that every field in the template has a value.
30.3 Build it (25 min)
"""Day 30.3: build the Module 3 RWE report - one command, every output.
python day30/build_report.py [--max-egfr 60] [--out capstone/m3_output]
"""
import argparse
import os
import shutil
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import ROOT # noqa: E402
from corridor.rwe_report import Config, run # noqa: E402
parser = argparse.ArgumentParser(description="Build the Module 3 real-world evidence report.")
parser.add_argument("--max-egfr", type=float, default=60, help="keep person-trials with latest eGFR below this (default 60: all)")
parser.add_argument("--out", default="capstone/m3_output", help="output folder, relative to the repository")
args = parser.parse_args()
config = Config(out_dir=args.out, max_egfr=args.max_egfr)
r = run(config, root=ROOT)
print(f"Report built: {r['n_pt']} person-trials, {r['n_starts']} starts; outputs in {config.out_dir}/\n")
print(open(os.path.join(ROOT, config.out_dir, "MANIFEST.txt"), encoding="utf-8").read())
if config.out_dir == "capstone/m3_output": # the lesson notes show the two figures
for name in ("balance.png", "strategy_curves.png"):
shutil.copy(os.path.join(ROOT, config.out_dir, name), os.path.join(ROOT, "figures", f"day30_{name}"))
Report built: 88,890 person-trials, 1,041 starts; outputs in capstone/m3_output/
5e77dbcff36a4069 attrition.csv
a2d812554b988967 balance.png
b62a18874b00c913 estimates.csv
66c5adbcebb4b0e3 report.md
7b39b20255e0eea6 sensitivity.csv
38549f3865755d79 strategies.csv
c6bb1a1fda1da6da strategy_curves.png
50453a48da1e441e subgroups.csv
974c13b52517e311 table1.csv
About 80 seconds, most of it the person bootstrap and the MSM's weights. The two figures:


30.4 Read the report (40 min)
# Renavex in routine care: an emulated target trial
*Module 3 capstone. Real-world evidence report in the order of the CDA-AMC Guidance for Reporting Real-World Evidence (2023). Every number below is filled in by `corridor/rwe_report.py` from the tables in this folder.*
## Key findings
- Among people whose start could have gone either way (the overlap population), starting Renavex lowered the 24-month risk of kidney failure from 4.9% to 3.9%: risk ratio 0.80 (95% CI 0.51 to 1.00), 1.0 percentage points fewer, about 104 people treated for two years per kidney failure prevented.
- In the people who actually started, the doubly robust (AIPW) estimate was similar: 0.80 (95% CI 0.60 to 1.06).
- The absolute benefit is concentrated in people at the highest baseline risk (top quarter: 4.1 points fewer kidney failures, NNT about 24).
- Staying on Renavex for three years, compared with never taking it, is estimated to lower the 36-month risk from 5.4% to 3.2% (ratio 0.59), the input the economic model needs.
- A negative control outcome and a frailty substudy point to modest residual confounding by frailty; neither explains the kidney failure result.
## 1. Research question and study design
Does starting Renavex, compared with not starting it (usual care, which may include an SGLT2 inhibitor), lower the 24-month risk of kidney failure in adults with type 2 diabetes and CKD stage 3a-4 in routine care? Study design: an emulated target trial, repeated as twelve monthly sequential trials (January to December 2026), new users only, intention to treat. A secondary per-protocol question compares sustained strategies (always vs never Renavex) over 36 months.
## 2. Setting and context
Publicly funded care in Ontario (Renavex listed October 2025) and Quebec (listed February 2026); follow-up to 31 December 2028.
## 3. Data specifications: access, cleaning and linkage
Data access: analysts worked on a de-identified extract inside the secure environment; only aggregate tables leave it. Linkage: the RWE extract (labs, dispensings, events) is linked on a study person_id to the 2019-2025 warehouse (diagnoses, drugs, hospital stays). Cleaning and data completeness: an eGFR result within 365 days was available for 99-100% of people at each trial start; UACR for 66-81%, so people with no UACR result are classified as without albuminuria (see Limitations). Data fitness was assessed before analysis (Day 29).
## 4. Data sources, data dictionary and variables
Data sources: rwe_persons, rwe_labs, rwe_dispensations, rwe_events, and the warehouse. Data dictionary: variables as in Table 1 (table1.csv). The latest eGFR and UACR before each trial start are used; history covariates come from 2019-2025.
## 5. Participants
Of 9,805 people in the extract, 9,018 were not on Renavex in 2025, and 8,660 were eligible for at least one trial (alive, free of kidney failure, never dispensed Renavex, latest eGFR 20-60 within 12 months): 88,890 person-trials, 1,041 starts (attrition.csv). Starters had lower eGFR (mean 35.4 vs 44.5) and were more often under nephrology care (60.3% vs 31.5%).
## 6. Exposure definitions and comparators
Exposure: a first Renavex dispensing in the trial month. Comparator: no Renavex dispensing that month (usual care). For the sustained strategies, 'never' means no Renavex and no new SGLT2 inhibitor, and 'always' means Renavex from month 0, never stopped.
## 7. Outcomes
Primary outcome: kidney failure within 24 months of the trial start. Secondary outcome: death within 24 months. Negative control outcome: any hospitalization within 24 months.
## 8. Bias, confounding and effect modification
Confounding by indication was addressed with a propensity score (eGFR as a spline, albuminuria, SGLT2 inhibitor, age, sex, province, nephrology care, heart failure, COPD, prior hospital stays, trial month) and an outcome model with the same covariates. Overlap weights balanced every covariate (largest weighted standardized difference 0.000; balance.png). The usual prescriber, a strong predictor of starting, was deliberately left out (an instrument). Immortal time is avoided by aligning eligibility, treatment and time zero. Frailty is unmeasured; it was addressed with a negative control outcome and a chart-review substudy (section 10). Effect modification: pre-specified subgroups (albuminuria, province, age) and baseline-risk groups (subgroups.csv); subgroups with fewer than 6 events are not reported.
## 9. Statistical methods
Primary analysis: overlap-weighted risks, with 95% confidence intervals from 100 bootstraps of people (refitting the propensity score each time). Secondary: AIPW for the effect in starters and in everyone eligible, with influence-function confidence intervals summed within person; the g-formula. Sustained strategies: a marginal structural model (pooled logistic, current and cumulative Renavex use, stabilized weights for starting and stopping Renavex and starting an SGLT2 inhibitor) and inverse probability of censoring weights for 'never'. Sensitivity analyses: E-values, the negative control outcome, and a quantitative bias analysis for frailty with parameters from the chart-review substudy (1,000 people; sensitivity 0.85, specificity 0.95).
## 10. Study findings (results)
The crude comparison was misleading (risk ratio 2.38): starters were sicker. After overlap weighting, the risk ratio for kidney failure was 0.80 (95% CI 0.51 to 1.00). AIPW gave 0.80 (95% CI 0.60 to 1.06) in starters (4.0% vs 5.1%) and 0.62 (95% CI 0.44 to 0.89) for everyone eligible, an estimand with poor overlap at high eGFR. For death, AIPW gave 0.95 (95% CI 0.78 to 1.16).
Subgroups: no subgroup showed a reliably different relative effect. The absolute benefit was 4.1 percentage points in the top quarter of baseline risk (risk without Renavex 15.6%) and -0.01 points in the other three quarters.
Sustained strategies (9,018 people not on Renavex in 2025): 36-month kidney failure risk 3.2% always vs 5.4% never (ratio 0.59); 'never' by censoring weights 5.6% (strategy_curves.png).
Sensitivity analyses: an unmeasured confounder would need risk ratios of 1.80 with both starting Renavex and kidney failure to explain the primary estimate away (1.00 for its confidence interval). The negative control outcome gave 0.95 (95% CI 0.86 to 1.06); correcting for frailty with the substudy moved it to 0.98, so frailty explains the signal. The same correction gives 0.87 for kidney failure, but the substudy's frailty-kidney failure association rests on few events and is uncertain.
## 11. Interpretation and generalizability
Renavex reduced kidney failure in routine care by about the same relative amount as in its trial. The results apply to new users similar to the overlap population and the starters (Table 1); they do not apply to people with eGFR above 45, who rarely start and rarely reach kidney failure within two years. Value for money will depend on targeting: the absolute benefit, and therefore cost-effectiveness, is greatest at high baseline risk.
## 12. Limitations
Frailty is unmeasured in the extract; albuminuria is measured with error (missing UACR results); laboratory eGFR is measured every few months, not monthly; follow-up is 24 months for the trials and 36 months for the strategies; event counts are small (subgroups below 6 events are suppressed), so confidence intervals are wide.
## Registration, protocol deviations and design diagram
The protocol (docs/rwe_protocol.md) is to be registered on the Real-World Evidence Registry before the analysis is finalized. Protocol deviations, with dates, reasons and whether results had been seen, are logged in its amendments table. The design diagram is figures/day29_design_diagram.png.
Read it as the payer's reviewer would. The key findings come first and lead with the absolute risk, not the ratio. The primary analysis is the one the protocol named, even though it is not the most impressive estimate (Day 29). The ATE appears, but it is described for what it is: an estimand with poor overlap. The sensitivity paragraph says plainly that the frailty correction for kidney failure is uncertain. Limitations name what is wrong with the data, not generic caveats.
The tables behind it:
| File | Read it for |
|---|---|
estimates.csv | every estimate with its method and estimand |
subgroups.csv | effects by subgroup and risk group, small cells suppressed |
sensitivity.csv | E-values and frailty-corrected ratios |
strategies.csv | the inputs for Module 6's Markov model: 12-, 24- and 36-month risks under always and never |
Try it (15 min). CDA-AMC often recommends reimbursement with conditions, for example "eGFR below 45". Rebuild the report for that population in a second folder and compare.
Solution
"""Day 30 try it: rebuild the report for a reimbursement condition - latest eGFR below 45."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import pandas as pd # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.rwe_report import Config, run # noqa: E402
r = run(Config(out_dir="capstone/m3_output_egfr45", max_egfr=45), root=ROOT)
a = pd.read_csv(os.path.join(ROOT, "capstone", "m3_output", "estimates.csv")).set_index(["method", "estimand"])
b = pd.read_csv(os.path.join(ROOT, "capstone", "m3_output_egfr45", "estimates.csv")).set_index(["method", "estimand"])
print(f"eGFR < 45: {r['n_pt']} person-trials, {r['n_starts']} starts")
for key in (("overlap weights (primary)", "ATO"), ("AIPW", "ATT"), ("AIPW", "ATE")):
x, y = a.loc[key].iloc[0] if a.loc[key].ndim > 1 else a.loc[key], b.loc[key].iloc[0] if b.loc[key].ndim > 1 else b.loc[key]
print(f"{key[0] + ' ' + key[1]:<32} all: {x.ratio:.2f}, {x.difference_pts:+.2f} pts eGFR < 45: {y.ratio:.2f}, "
f"{y.difference_pts:+.2f} pts")
s = pd.read_csv(os.path.join(ROOT, "capstone", "m3_output_egfr45", "strategies.csv")).set_index("months")
print(f"MSM 36 months: always {s.always_msm[36]:.4f} vs never {s.never_msm[36]:.4f} (ratio {s.ratio_msm[36]:.2f})")
eGFR < 45: 39,989 person-trials, 814 starts
overlap weights (primary) ATO all: 0.80, -0.96 pts eGFR < 45: 0.81, -1.21 pts
AIPW ATT all: 0.80, -1.03 pts eGFR < 45: 0.80, -1.31 pts
AIPW ATE all: 0.62, -0.65 pts eGFR < 45: 0.64, -1.35 pts
MSM 36 months: always 0.0687 vs never 0.1156 (ratio 0.59)
The ratios barely change (0.80 to 0.81 for the primary analysis), as Day 27 predicted: the relative effect is constant. The absolute benefit grows. The overlap-weighted difference goes from 0.96 to 1.21 points, and the ATE difference doubles (0.65 to 1.35 points), because the population no longer contains thousands of low-risk people. Under sustained use, 36-month kidney failure falls from 11.6% to 6.9%. A reimbursement condition changes the economics more than the efficacy. capstone/m3_output_*/ is git-ignored: comparison folders are not for release.
30.5 Release checks (25 min)
"""Day 30.5: six checks before the RWE report leaves the secure environment."""
import shutil # noqa: E402
import tempfile # noqa: E402
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import pandas as pd # noqa: E402
from corridor.db import ROOT # noqa: E402
from corridor.privacy import SMALL # noqa: E402
from corridor.reporting import check_protocol # noqa: E402
from corridor.rwe_report import COUNT_COLUMNS, Config, run # noqa: E402
OUT = os.path.join(ROOT, "capstone", "m3_output")
results = []
def check(name, ok, detail):
results.append(ok)
print(f"{'PASS' if ok else 'FAIL'} {name:<62}{detail}")
tables = {f[:-4]: pd.read_csv(os.path.join(OUT, f)) for f in sorted(os.listdir(OUT)) if f.endswith(".csv")}
report = open(os.path.join(OUT, "report.md"), encoding="utf-8").read()
est = tables["estimates"].set_index("method")
# 1. the report is complete and quotes the tables
prim = est.loc["overlap weights (primary)"]
n_pt = int(tables["attrition"].person_trials.dropna().iloc[0])
ok = "{" not in report and f"{n_pt:,}" in report and f"{prim.ratio:.2f} (95% CI {prim.ci_low:.2f} to {prim.ci_high:.2f})" in report
check("report filled in, numbers match the tables", ok, f"{n_pt:,} person-trials, primary ratio {prim.ratio:.2f}")
# 2. no counts from 1 to 5
small = [(n, c, v) for n, t in tables.items() for c in t.columns if c in COUNT_COLUMNS
for v in t[c].dropna() if 0 < v < SMALL]
check("no released counts from 1 to 5", not small, f"{len(small)} small cells")
# 3. every CDA-AMC reporting section (and the five extra items) is in the report
found = check_protocol(report)
missing = [k for k, v in found.items() if v is None]
check("all CDA-AMC sections and extra items present", not missing, f"{len(found) - len(missing)} of {len(found)}")
# 4. nothing person-level in the outputs; person-level inputs git-ignored
headers = {c for t in tables.values() for c in t.columns}
ignore = open(os.path.join(ROOT, ".gitignore"), encoding="utf-8").read()
ok = not ({"person_id", "trial_id"} & headers) and "m3/*.parquet" in ignore and "sas_extract/" in ignore
check("no identifiers in outputs; m3/*.parquet, sas_extract/ ignored", ok, f"{len(os.listdir(OUT))} files")
# 5. internal consistency: CIs contain estimates, weighted balance, risks grow over time
e = tables["estimates"].dropna(subset=["ci_low"])
s = tables["strategies"]
smd = pd.to_numeric(tables["table1"].smd_weighted, errors="coerce").abs().max()
ok = ((e.ci_low <= e.ratio) & (e.ratio <= e.ci_high)).all() and smd < 0.1 and s.never_msm.is_monotonic_increasing and s.always_msm.is_monotonic_increasing
check("CIs contain estimates, weighted |SMD| < 0.1, risks increase", ok, f"largest weighted |SMD| {smd:.3f}")
# 6. a rebuild from scratch gives the same files
tmp = tempfile.mkdtemp()
os.makedirs(os.path.join(tmp, "capstone"))
shutil.copy(os.path.join(ROOT, "capstone", "rwe_template.md"), os.path.join(tmp, "capstone"))
run(Config(), root=tmp)
same = open(os.path.join(tmp, "capstone", "m3_output", "MANIFEST.txt")).read() == open(os.path.join(OUT, "MANIFEST.txt")).read()
shutil.rmtree(tmp)
check("rebuild in a fresh folder: identical fingerprints", same, "MANIFEST.txt compared")
print(f"\n{sum(results)}/{len(results)} checks passed")
PASS report filled in, numbers match the tables 88,890 person-trials, primary ratio 0.80
PASS no released counts from 1 to 5 0 small cells
PASS all CDA-AMC sections and extra items present 17 of 17
PASS no identifiers in outputs; m3/*.parquet, sas_extract/ ignored 10 files
PASS CIs contain estimates, weighted |SMD| < 0.1, risks increase largest weighted |SMD| 0.000
PASS rebuild in a fresh folder: identical fingerprints MANIFEST.txt compared
6/6 checks passed
Six checks, as on Day 20, adapted to RWE:
- Numbers. The report quotes the tables; no
{field}is left unfilled. - Small counts. No count from 1 to 5 in any count column.
- Sections. All 12 CDA-AMC sections and the 5 extra items are present (Day 29's checker).
- Identifiers. No person identifiers in the outputs, and the person-level files are git-ignored.
- Consistency. Every CI contains its estimate, weighted balance holds, and risks rise over time.
- Reproducibility. A rebuild from scratch gives identical fingerprints, including the seeded bootstrap.
Why it matters at work: at ICES, at the CIHI and Statistics Canada research data centres, and in sponsors' secure environments, results leave only after a vetting step. Checks you run yourself before vetting save days of back and forth. A reviewer at CDA-AMC can only trust a report whose numbers are traceable to code.
Where you'll meet this: output vetting at ICES and research data centres; reproducibility requests from CDA-AMC reviewers; the capstone repository you will show in interviews
30.6 Truth check (30 min)
"""Day 30 truth check: grade the report's estimates against the generator."""
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 corridor.db import ROOT, warehouse # noqa: E402
from corridor.msm import prepare, truth # noqa: E402
from corridor.ps import fit_ps # noqa: E402
from corridor.truth import TRUTH # noqa: E402
from corridor.tte import load # noqa: E402
OUT = os.path.join(ROOT, "capstone", "m3_output")
est = pd.read_csv(os.path.join(OUT, "estimates.csv"))
strat = pd.read_csv(os.path.join(OUT, "strategies.csv")).set_index("months")
t = load()
_, e = fit_ps(t)
tr = duckdb.sql(f"SELECT * FROM read_csv('{TRUTH}/rwe_sequential_truth.csv')").df()
d = t.assign(trial=t.trial.astype(int), e=e).merge(tr, on=["person_id", "trial"])
h = {"ATE": np.ones(len(d)), "ATT": d.start.to_numpy(), "ATO": (d.e * (1 - d.e)).to_numpy()}
rows = []
for _, r in est[est.estimand != "none"].iterrows():
y = {"kidney failure": "kf24", "death": "death24"}.get(r.outcome)
true = 1.0 if y is None else np.average(d[y + "_start"], weights=h[r.estimand]) / np.average(d[y + "_no_start"], weights=h[r.estimand])
covered = "" if pd.isna(r.ci_low) else ("yes" if r.ci_low <= true <= r.ci_high else "NO")
rows.append({"outcome": r.outcome, "method": r.method, "estimand": r.estimand, "estimate": r.ratio,
"truth": round(true, 3), "CI covers truth": covered})
st = truth(prepare(warehouse()))
rows.append({"outcome": "kidney failure, 36 months", "method": "MSM, always vs never", "estimand": "strategies",
"estimate": strat.ratio_msm[36], "truth": round(st["renavex"] / st["never"], 3), "CI covers truth": ""})
print(pd.DataFrame(rows).to_string(index=False))
print(f"\n36-month risks: never {strat.never_msm[36]:.4f} (truth {st['never']:.4f}), always {strat.always_msm[36]:.4f} "
f"(truth {st['renavex']:.4f}) (hospitalization: no effect by design, truth taken as 1)")
outcome method estimand estimate truth CI covers truth
kidney failure overlap weights (primary) ATO 0.803 0.729 yes
kidney failure AIPW ATT 0.797 0.774 yes
kidney failure AIPW ATE 0.625 0.728 yes
kidney failure g-formula (outcome model) ATT 0.807 0.774
death AIPW ATT 0.948 0.897 yes
hospitalization (negative control) AIPW ATT 0.953 1.000 yes
kidney failure, 36 months MSM, always vs never strategies 0.586 0.586
36-month risks: never 0.0543 (truth 0.0570), always 0.0318 (truth 0.0334) (hospitalization: no effect by design, truth taken as 1)
Every confidence interval covers its truth. The primary analysis (0.80) sits 0.07 above its truth (0.73), the AIPW in starters (0.80) 0.02 above (0.77), and the ATE (0.62) 0.10 below (0.73) with the widest interval. Death (0.95 vs 0.90) carries the residual confounding Day 28 found. The negative control's 0.95 against a true 1 is that confounding made visible. The MSM's 0.59 matches the true 0.59 for sustained use, with both absolute risks within 0.3 points of the truth. That is the number the economic model in Module 6 will use.
What the report got right comes from Module 3's discipline, not from a clever model: new users, aligned time zero, the estimand chosen before the estimator, and the uncertainty reported honestly.
30.7 A suppressed cell, recovered (20 min)
Bug of the day. The first draft of the subgroup table showed eGFR bands and suppressed the band with 4 events:
"""Day 30 bug of the day: suppressing a small cell is not enough if it can be recovered by subtraction."""
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 corridor.dr import outcome_model # noqa: E402
from corridor.hte import subgroup_effects # noqa: E402
from corridor.privacy import SMALL # noqa: E402
from corridor.ps import fit_ps # noqa: E402
from corridor.tte import load # noqa: E402
t = load()
_, e = fit_ps(t)
q1, q0 = outcome_model(t)
bands = {"eGFR < 30": "egfr < 30", "eGFR 30-44": "egfr >= 30 and egfr < 45", "eGFR >= 45": "egfr >= 45"}
s = subgroup_effects(t, e, q1, q0, bands)
shown = s[["subgroup", "starts", "events_in_starters"]].astype(object)
shown["risk_start"] = (100 * s.risk_start).round(2)
shown.loc[(s.events_in_starters > 0) & (s.events_in_starters < SMALL), "events_in_starters"] = f"<{SMALL}"
print("draft table, events 1-5 suppressed:")
print(shown.to_string(index=False))
total_events = round(0.0403 * 1041) # the report's starters' risk x starts
print(f"\nfrom the estimates table: risk in starters 4.03% of 1,041 starts -> {total_events} events")
print(f"by subtraction: eGFR 30-44 = {total_events} - {s.events_in_starters[0]} - {s.events_in_starters[2]} = "
f"{total_events - s.events_in_starters[0] - s.events_in_starters[2]}")
r = shown.iloc[1]
print(f"by multiplication: {r.risk_start}% of {r.starts} starts = {r.risk_start / 100 * r.starts:.1f} events")
draft table, events 1-5 suppressed:
subgroup starts events_in_starters risk_start
eGFR < 30 379 38 10.03
eGFR 30-44 435 <6 0.92
eGFR >= 45 227 0 0.00
from the estimates table: risk in starters 4.03% of 1,041 starts -> 42 events
by subtraction: eGFR 30-44 = 42 - 38 - 0 = 4
by multiplication: 0.92% of 435 starts = 4.0 events
The "<6" protects nothing. Anyone can subtract the other bands from the total (42 − 38 − 0 = 4), or multiply the band's observed risk by its starts (0.92% × 435 = 4.0). Day 2 called the first problem complementary disclosure. Here a third route exists: a released rate and its denominator.
The fix in subgroup_table() is to stop releasing what cannot be protected:
- eGFR bands are dropped, and their finding (benefit concentrated at low eGFR) is carried by the baseline-risk groups.
- Risk quarters 1–3 are pooled (12 events), so no group is small.
- For any row that is still small, the risks, difference and ratio are suppressed along with the count, because each of them would give the count back.
tests/test_day_30.py and release check 2 enforce the counts. The subtraction route needs a human reviewer's eye, which is why output vetting exists.
30.8 The SAS version (30 min)
Many HEOR and agency teams build the cohort and Table 1 in SAS. Write the person-trial extract (person-level, git-ignored), upload it to SAS OnDemand, and run the program:
"""Day 30.8: the person-trial extract SAS reads (sas_extract/m3_trials.csv: person-level, git-ignored)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import ROOT # noqa: E402
from corridor.tte import load # noqa: E402
COLS = ["person_id", "trial", "start", "egfr", "albuminuria", "sglt2", "age", "male", "qc", "nephrology_care",
"heart_failure", "copd", "prior_stays", "kf24", "death24"]
d = load()[COLS]
os.makedirs(os.path.join(ROOT, "sas_extract"), exist_ok=True)
path = os.path.join(ROOT, "sas_extract", "m3_trials.csv")
d.to_csv(path, index=False, float_format="%.4f")
print(f"sas_extract/m3_trials.csv: {len(d):,} rows, {len(COLS)} columns")
print(open(path, encoding="utf-8").readline().strip())
sas_extract/m3_trials.csv: 88,890 rows, 15 columns
person_id,trial,start,egfr,albuminuria,sglt2,age,male,qc,nephrology_care,heart_failure,copd,prior_stays,kf24,death24
/* Day 30.8: the cohort, Table 1 and the overlap-weighted estimate in SAS.
Upload sas_extract/m3_trials.csv to your corridor folder. The propensity score uses eGFR and eGFR squared
(Python's spline is not reproduced here), so the weighted results differ slightly from the report. */
%let path = /home/u00000000/corridor;
libname corr "&path";
data corr.m3;
infile "&path/m3_trials.csv" dsd firstobs=2 truncover;
length person_id $11;
input person_id $ trial start egfr albuminuria sglt2 age male qc nephrology_care heart_failure copd
prior_stays kf24 death24;
egfr2 = egfr * egfr;
run;
/* 1. the cohort: people, person-trials, starts */
proc sql;
select count(distinct person_id) as people format=comma9., count(*) as person_trials format=comma9.,
sum(start) as starts format=comma9.
from corr.m3;
quit;
/* 2. propensity score and overlap weights */
proc logistic data=corr.m3 noprint;
class trial / param=ref ref=first;
model start(event='1') = egfr egfr2 albuminuria sglt2 age male qc nephrology_care heart_failure copd
prior_stays trial;
output out=work.ps p=e;
run;
data work.ps;
set work.ps;
w = ifn(start = 1, 1 - e, e);
run;
/* 3. Table 1: means by group, before and after weighting */
proc means data=work.ps mean maxdec=3 nway;
class start;
var egfr albuminuria sglt2 age male qc nephrology_care heart_failure copd prior_stays;
title "Table 1, unweighted";
run;
proc means data=work.ps mean maxdec=3 nway;
class start;
weight w;
var egfr albuminuria sglt2 age male qc nephrology_care heart_failure copd prior_stays;
title "Table 1, overlap weighted";
run;
/* 4. overlap-weighted 24-month risks of kidney failure */
proc means data=work.ps mean maxdec=4 nway;
class start;
weight w;
var kf24 death24;
title "Overlap-weighted risks";
run;
title;
SAS has no cr() spline, so the program models eGFR as a quadratic. expected_sas.py fits the same model in Python, so you know exactly what SAS should print:
"""Day 30.8: what rwe_table1.sas should print, computed in Python with the same model (eGFR + eGFR squared)."""
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 corridor.ps import fit_ps, weights # noqa: E402
from corridor.tte import load # noqa: E402
t = load()
print(f"--- 1. cohort: {t.person_id.nunique():,} people, {len(t):,} person-trials, {int(t.start.sum()):,} starts")
f = ("start ~ egfr + I(egfr ** 2) + albuminuria + sglt2 + age + male + qc + nephrology_care + heart_failure + copd"
" + prior_stays + C(trial)")
_, e = fit_ps(t, f)
w = weights(e, t.start, "overlap")
cols = ["egfr", "albuminuria", "sglt2", "age", "male", "qc", "nephrology_care", "heart_failure", "copd", "prior_stays"]
un = t.groupby("start")[cols].mean().T
wt = pd.DataFrame({s: [np.average(t[c][t.start == s], weights=w[t.start == s]) for c in cols] for s in (0, 1)}, index=cols)
print("--- 3. Table 1 (unweighted | overlap weighted)")
print(pd.concat([un, wt], axis=1, keys=["unweighted", "weighted"]).round(3).to_string())
r = {y: [np.average(t[y][t.start == s], weights=w[t.start == s]) for s in (0, 1)] for y in ("kf24", "death24")}
print("--- 4. overlap-weighted risks (start = 0, start = 1)")
for y, (r0, r1) in r.items():
print(f"{y:<8} {r0:.4f} {r1:.4f} ratio {r1 / r0:.3f}")
--- 1. cohort: 8,660 people, 88,890 person-trials, 1,041 starts
--- 3. Table 1 (unweighted | overlap weighted)
unweighted weighted
start 0.0 1.0 0.0 1.0
egfr 44.526 35.433 35.618 35.618
albuminuria 0.220 0.393 0.387 0.387
sglt2 0.349 0.388 0.387 0.387
age 72.154 68.035 68.148 68.148
male 0.514 0.528 0.528 0.528
qc 0.410 0.393 0.393 0.393
nephrology_care 0.315 0.603 0.597 0.597
heart_failure 0.090 0.081 0.081 0.081
copd 0.043 0.040 0.040 0.040
prior_stays 0.283 0.350 0.348 0.348
--- 4. overlap-weighted risks (start = 0, start = 1)
kf24 0.0496 0.0392 ratio 0.789
death24 0.0768 0.0752 ratio 0.979
With the quadratic, the overlap-weighted ratio is 0.79 instead of 0.80, and the weighted means still balance exactly: overlap weights balance whatever is in the model.
30.9 Check it in R (15 min)
# Day 30: an independent check of the report's primary estimate and balance, with WeightIt and cobalt.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(WeightIt); library(cobalt); library(splines) })
con <- dbConnect(duckdb(shared_home = FALSE))
t <- dbGetQuery(con, "SELECT * FROM read_parquet('m3/trials.parquet')")
dbDisconnect(con, shutdown = TRUE)
t$age10 <- (t$age - 70) / 10
w <- weightit(start ~ ns(egfr, df = 4) + albuminuria + sglt2 + age10 + male + qc + nephrology_care + heart_failure +
copd + prior_stays + factor(trial), data = t, method = "glm", estimand = "ATO")
r1 <- weighted.mean(t$kf24[t$start == 1], w$weights[t$start == 1])
r0 <- weighted.mean(t$kf24[t$start == 0], w$weights[t$start == 0])
rep <- read.csv("capstone/m3_output/estimates.csv")
p <- rep[rep$method == "overlap weights (primary)", ]
cat(sprintf("overlap-weighted kidney failure: R %.4f vs %.4f, ratio %.3f; report %.3f\n", r1, r0, r1 / r0, p$ratio))
b <- bal.tab(w, un = TRUE, binary = "std", s.d.denom = "pooled")$Balance
cat(sprintf("largest |SMD| unweighted %.3f, weighted %.3f\n", max(abs(b$Diff.Un)), max(abs(b$Diff.Adj))))
overlap-weighted kidney failure: R 0.0392 vs 0.0489, ratio 0.803; report 0.803
largest |SMD| unweighted 0.888, weighted 0.025
WeightIt reproduces the primary estimate to three decimals. The largest weighted SMD in R (0.025) is not zero, because cobalt checks balance on the ns() spline's basis terms, while Python's Table 1 checks raw eGFR. Both are well under 0.1.
30.10 Module 3 in review (15 min)
| Day | Question | What went wrong without it |
|---|---|---|
| 21 | Which variables to adjust for? | Adjusting for a mediator or a collider; a crude rate ratio of 3.6 |
| 22 | What trial are we emulating? | A NULL treatment column turned the drug harmful (1.48) |
| 23 | When does follow-up start? | Immortal time made "ever users" look 78% protected |
| 24 | Are the groups comparable, and for whom? | An instrument in the propensity score (0.91) |
| 25 | Two models or one? | A copied line gave 0.12 |
| 26 | What if they stay on it? | Censoring without weights halved the "never" risk |
| 27 | Does it work better in some people? | Twenty-two subgroups and a winner's curse |
| 28 | What if we missed something? | E-values from the wrong limit; a bias analysis from 30 people |
| 29 | Can a reviewer trust the process? | The most favourable of 24 analyses, furthest from the truth |
| 30 | Can it leave the building? | A suppressed count recovered by subtraction |
Module 4 turns from individual treatment decisions to policies: Ontario listed Renavex four months before Quebec, a natural experiment for difference-in-differences. Day 36 uses the usual prescriber correctly, as an instrument.
30.11 Save your work
python -m pytest -q
python day30/release_checks.py
git add .
git commit -m "Day 30: Module 3 capstone - emulated target trial report"
Day 30 checklist
- I can build the whole RWE report with one command and rebuild it identically
- My report follows the 12 CDA-AMC sections and leads with absolute risks
- The primary analysis is the pre-specified one, and every estimate names its estimand
- My release checks cover small cells, identifiers, sections, consistency and reproducibility
- I can reproduce the cohort, Table 1 and the weighted estimate in SAS and R
Bloc français (30 min)
Thème : le rapport de données probantes du monde réel.
Chez les patients dont la décision de traitement aurait pu aller dans un sens ou dans l'autre, commencer le Renavex a réduit le risque d'insuffisance rénale à 24 mois de 4,9 % à 3,9 %. Le rapport de risques est de 0,80, avec un intervalle de confiance à 95 % de 0,51 à 1,00. Le bénéfice absolu se concentre chez les patients au risque de base le plus élevé. Les analyses de sensibilité suggèrent une confusion résiduelle modeste par la fragilité.
| Français | English |
|---|---|
| le rapport de données probantes du monde réel | the real-world evidence report |
| l'analyse principale | the primary analysis |
| l'analyse secondaire | the secondary analysis |
| la population de chevauchement | the overlap population |
| le rapport de risques | the risk ratio |
| l'intervalle de confiance | the confidence interval |
| le bénéfice absolu | the absolute benefit |
| la condition de remboursement | the reimbursement condition |
| la réévaluation | the reassessment |
| la vérification avant diffusion | output vetting |
| la divulgation par complémentarité | complementary disclosure |
| la reproductibilité | reproducibility |
Exercices
- Translate: "Every confidence interval covers its true value."
- Translate: « Une condition de remboursement modifie davantage l'économie que l'efficacité. »
- Write the report's first key finding in French, in two sentences, for an INESSS reviewer.
Réponses
- Chaque intervalle de confiance contient sa vraie valeur.
- "A reimbursement condition changes the economics more than the efficacy."
- Example: Dans la population de chevauchement, commencer le Renavex a réduit le risque d'insuffisance rénale à 24 mois de 4,9 % à 3,9 % (rapport de risques 0,80; IC à 95 % : 0,51 à 1,00). Il faut traiter environ 104 patients pendant deux ans pour éviter une insuffisance rénale.