Capstone: Burden-of-Illness Report
Today you deliver what a provincial ministry, a payer or an HTA sponsor commissions before any decision about a new kidney drug: a burden-of-illness report. Who has CKD in type 2 diabetes, what they cost the public payer, how much care they use, how many die or end up in hospital, and how Ontario and Quebec compare. One command builds the report from Module 2's methods: GLMs and two-part models for costs, count models, survival, the diabetes panel, the survey and the trial's utilities. Every number in the text comes from code. Six release checks run before anything leaves the secure environment, and then R and SAS check the key numbers independently.
By the end of today you can
python day20/build_report.pybuilds every table, both figures and the report, and a second run gives the same MANIFEST- Every number in
report.mdcomes from a table, and the release checks pass - explain each headline result and its main limitation to a ministry reader
- The R check and the SAS program reproduce the key numbers
- rebuild the report for a sub-population into a separate folder without touching the main one
Today's 5.5-hour plan
In this lesson
20.1 The brief (30 min)
The HEOR lead: "Before the Renavex budget impact model, the ministry wants a burden-of-illness picture of adults 66+ with diabetes and CKD in both provinces: what they cost, what care they use, how many die or are hospitalized, what their quality of life is, and where the provinces differ after adjusting for case mix. Aggregate tables only, two pages they can read, methods a reviewer can check. And I need to be able to rebuild it next year with new data."
That brief fixes the deliverable:
| Requirement | How |
|---|---|
| Costs a payer can budget with | means per person-year (Day 7), adjusted ratios and dollar differences (Day 11), two-part hospital costs (Day 12) |
| Use of care | visits and stays per person-year, rate ratios with offsets (Day 12) |
| Mortality and hospitalization | Kaplan–Meier and Cox (Day 13) |
| Context beyond the cohort | survey prevalence (Day 16), the cost of a new diagnosis (Day 19) |
| Quality of life | EQ-5D-5L utilities, with the missing-data caveat (Days 17–18) |
| Readable, checkable, rebuildable | a generated report, release checks, R and SAS checks, a manifest |
20.2 One pipeline, one command (45 min)
corridor/boi.py collects one function per table, then writes the report from a template. Each table function uses code you wrote on Days 11–19:
"""Day 20: the Module 2 capstone - a burden-of-illness report for CKD in type 2 diabetes, by province.
python day20/build_report.py # every output in capstone/m2_output/ (about a minute)
Inputs: the Module 2 analysis file (m2/analysis.parquet, Day 11), the diabetes panel (m2/panel.parquet,
Day 19), the CCHS-style survey (Day 16) and the Renavex trial visits (Day 17). Outputs are aggregate
tables, two figures, the report (report.md, numbers filled in by code) and MANIFEST.txt.
"""
import hashlib
import os
from dataclasses import dataclass
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor import m2, panel, survey # noqa: E402
from corridor.costmodels import COVARIATES, TwoPart, fit_glm, recycled_difference # noqa: E402
from corridor.missing import mice_pmm, wide # noqa: E402
from corridor.survival import admission_outcome, km, surv_at # noqa: E402
from corridor.trial import visits # noqa: E402
PROVINCES = ("ON", "QC")
SMALL = 6
@dataclass(frozen=True)
class Config:
out_dir: str = "capstone/m2_output"
min_age: int = 66 # the cohort is 66+; raise it for a sub-population (Day 20 try it)
boot: int = 200
seed: int = 2026
def sha256(path):
with open(path, "rb") as f:
return hashlib.sha256(f.read()).hexdigest()[:16]
def _rows_by_province(df, fn):
rows = [dict(province=p, **fn(df[df.province == p])) for p in PROVINCES]
rows.append(dict(province="All", **fn(df)))
return pd.DataFrame(rows)
def population_table(d):
return _rows_by_province(d, lambda g: {
"people": len(g), "mean_age": round(g.age.mean(), 1), "pct_female": round(100 * (g.sex == "F").mean(), 1),
"pct_heart_failure": round(100 * g.heart_failure.mean(), 1), "pct_copd": round(100 * g.copd.mean(), 1),
"person_years": round(g.py.sum(), 1), "deaths": int(g.died.sum()), "pct_died": round(100 * g.died.mean(), 1)})
def cost_table(d):
def fn(g):
py = g.py.sum()
return {"people": len(g), "person_years": round(py, 1),
"hospital_per_py": round(g.fu_hospital.sum() / py, 2), "physician_per_py": round(g.fu_physician.sum() / py, 2),
"drug_per_py": round(g.fu_drug.sum() / py, 2), "total_per_py": round(g.fu_cost.sum() / py, 2),
"median_per_person": round(g.fu_cost.median(), 2), "total_cost_millions": round(g.fu_cost.sum() / 1e6, 3)}
return _rows_by_province(d, fn)
def _model_estimates(d):
s = d[d.died == 0]
g = fit_glm(s, "fu_cost", "gamma")
_, _, qc = recycled_difference(g.predict, s, "qc")
_, _, hf = recycled_difference(g.predict, s, "heart_failure")
tp = TwoPart(s, "fu_hospital")
m_qc, m_on, _ = recycled_difference(tp.predict, s, "qc")
return {"cost_ratio_qc_on": float(np.exp(g.params["qc"])), "cost_difference_qc_on": qc,
"cost_heart_failure_increment": hf, "hospital_cost_on": m_on, "hospital_cost_qc": m_qc}
def model_table(d, boot, seed):
point = _model_estimates(d)
rng = np.random.default_rng(seed)
draws = pd.DataFrame([_model_estimates(d.iloc[rng.integers(0, len(d), len(d))]) for _ in range(boot)])
return pd.DataFrame([{"quantity": k, "estimate": round(v, 3 if "ratio" in k else 0),
"ci_low": round(draws[k].quantile(0.025), 3 if "ratio" in k else 0),
"ci_high": round(draws[k].quantile(0.975), 3 if "ratio" in k else 0)} for k, v in point.items()])
def _irr(d, y):
import statsmodels.api as sm
import statsmodels.formula.api as smf
m = smf.glm(f"{y} ~ {COVARIATES}", d, family=sm.families.Poisson(), offset=np.log(d.py)).fit(cov_type="HC1")
b, se = m.params["qc"], m.bse["qc"]
return np.exp(b), np.exp(b - 1.96 * se), np.exp(b + 1.96 * se)
def utilization_table(d):
t = _rows_by_province(d, lambda g: {"visits_per_py": round(g.fu_visits.sum() / g.py.sum(), 2),
"stays_per_100_py": round(100 * g.fu_stays.sum() / g.py.sum(), 1)})
for y, col in (("fu_visits", "visits"), ("fu_stays", "stays")):
irr, lo, hi = _irr(d, y)
t[f"{col}_irr_qc_vs_on"] = ["", f"{irr:.3f} ({lo:.3f}-{hi:.3f})", ""]
return t
def _hr_qc(d, t, e):
m = PHReg.from_formula(f"{t} ~ {COVARIATES}", d, status=d[e], ties="efron").fit()
j = m.model.exog_names.index("qc")
b, se = m.params[j], m.bse[j]
return f"{np.exp(b):.3f} ({np.exp(b - 1.96 * se):.3f}-{np.exp(b + 1.96 * se):.3f})"
def survival_table(d):
d = d.copy()
d["t_adm"], d["admitted"] = admission_outcome(d)
t = _rows_by_province(d, lambda g: {
"deaths": int(g.died.sum()), "survival_365": round(surv_at(km(g.t_end, g.died), 365), 4),
"first_admissions": int(g.admitted.sum()),
"admission_free_365": round(surv_at(km(g.t_adm, g.admitted), 365), 4)})
t["death_hr_qc_vs_on"] = ["", _hr_qc(d, "t_end", "died"), ""]
t["admission_hr_qc_vs_on"] = ["", _hr_qc(d, "t_adm", "admitted"), ""]
return t, d
def diabetes_cost_table():
p = panel.load()
rows = []
for prov, g in [(x, p[p.province == x]) for x in PROVINCES] + [("All", p)]:
r = panel.fe_cluster(g, "cost", ["dx", "age2"] + panel.YEARS).loc["dx"]
rows.append({"province": prov, "people": g.person_id.nunique(),
"diagnosed": int(g.groupby("person_id").dx_year.first().notna().sum()),
"extra_cost_per_year": round(r.coef), "ci_low": round(r.coef - 1.96 * r.se_cluster),
"ci_high": round(r.coef + 1.96 * r.se_cluster)})
return pd.DataFrame(rows)
def survey_table():
df, reps = survey.load()
w = df.wts_m.to_numpy()
rows = []
for item in ("diabetes", "high_blood_pressure", "regular_provider", "fair_or_poor_health"):
for prov in PROVINCES + ("All",):
for age in ("65+", "all adults"):
m = np.ones(len(df), bool) if prov == "All" else (df.province == prov).to_numpy()
if age == "65+":
m = m & df.age_group.isin(["65-79", "80+"]).to_numpy()
est, se = survey.estimate(survey.proportion(item, m), df, w, reps)
f = survey.flag(est, se, int(m.sum()))
ok = not f.startswith("F")
rows.append({"item": item, "province": prov, "ages": age, "respondents": int(m.sum()),
"percent": round(100 * est, 1) if ok else None,
"ci_low": round(100 * (est - 1.96 * se), 1) if ok else None,
"ci_high": round(100 * (est + 1.96 * se), 1) if ok else None, "flag": f})
return pd.DataFrame(rows)
def utility_table(seed):
v = visits()
obs = v.dropna(subset=["utility"])
rows = [{"state": s, "visits": int((obs.kf_now == k).sum()), "complete_case_mean": round(obs[obs.kf_now == k].utility.mean(), 3)}
for k, s in ((0, "no kidney failure"), (1, "kidney failure"))]
w = wide(v)
imps = [d for k, (_, g) in enumerate(w.groupby("arm")) for d in mice_pmm(g.reset_index(drop=True), m=20, seed=seed + k)]
mi = float(np.mean([pd.concat(imps[i::20]).u24.mean() for i in range(20)])) # pool arms within each imputation
t = pd.DataFrame(rows)
return t, {"u24_complete_case": round(float(w.u24.mean()), 3), "u24_mi": round(mi, 3),
"u24_missing_pct": round(100 * w.u24.isna().mean(), 1)}
def _figures(costs, sv, out):
fig, ax = plt.subplots(figsize=(6.4, 3.7))
c = costs.set_index("province").loc[list(PROVINCES) + ["All"]]
left = np.zeros(len(c))
for col, label, colour in (("hospital_per_py", "hospital", "#4f9cf9"), ("physician_per_py", "physician", "#a78bfa"),
("drug_per_py", "drugs", "#f5a524")):
ax.barh(c.index, c[col], left=left, color=colour, label=label)
left += c[col].to_numpy()
for i, v in enumerate(left):
ax.text(v + 60, i, f"${v:,.0f}", va="center", fontsize=9)
ax.set(xlabel="public payer cost per person-year, 2025 $", xlim=(0, left.max() * 1.18))
ax.invert_yaxis()
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.25), ncol=3, fontsize=8, frameon=False)
fig.tight_layout()
fig.savefig(os.path.join(out, "costs_by_province.png"), dpi=130, metadata={"Software": None})
plt.close(fig)
fig, ax = plt.subplots(1, 2, figsize=(9, 3.4))
for prov, colour in (("ON", "#4f9cf9"), ("QC", "#e5484d")):
g = sv[sv.province == prov]
for i, (t, e) in enumerate((("t_end", "died"), ("t_adm", "admitted"))):
k = km(g[t], g[e])
ax[i].step([0] + list(k.time), [1] + list(k.surv), where="post", color=colour, label=prov)
ax[0].set(title="Alive", xlabel="days since 1 January 2025", ylim=(0.85, 1), xlim=(0, 365))
ax[1].set(title="Not yet admitted to hospital", xlabel="days since 1 January 2025", ylim=(0.6, 1), xlim=(0, 365))
ax[0].legend()
fig.tight_layout()
fig.savefig(os.path.join(out, "survival_by_province.png"), dpi=130, metadata={"Software": None})
plt.close(fig)
def run(config=Config(), root="."):
"""Build every output. Returns the numbers used in the report."""
out = os.path.join(root, config.out_dir)
os.makedirs(out, exist_ok=True)
d = m2.load()
d = d[d.age >= config.min_age].reset_index(drop=True)
tables = {"population": population_table(d), "costs": cost_table(d),
"cost_models": model_table(d, config.boot, config.seed), "utilization": utilization_table(d)}
tables["survival"], sv = survival_table(d)
tables["diabetes_cost"] = diabetes_cost_table()
tables["survey"] = survey_table()
tables["utilities"], util = utility_table(config.seed)
for name, t in tables.items():
t.to_csv(os.path.join(out, f"{name}.csv"), index=False)
_figures(tables["costs"], sv, out)
r = _numbers(tables, util, config)
with open(os.path.join(root, "capstone", "boi_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
def _numbers(t, util, config):
"""Every number the report quotes, formatted, from the tables."""
pop = t["population"].set_index("province")
cost = t["costs"].set_index("province")
mod = t["cost_models"].set_index("quantity")
sur = t["survival"].set_index("province")
dia = t["diabetes_cost"].set_index("province")
sv = t["survey"].set_index(["item", "province", "ages"])
ut = t["utilities"].set_index("state")
util_rows = t["utilization"].set_index("province")
money = lambda x: f"${x:,.0f}" # noqa: E731
pct = lambda x: f"{x:.1f}%" # noqa: E731
r = {"min_age": config.min_age, "boot": config.boot,
"min_age_note": "" if config.min_age == 66 else f" This version keeps only people aged {config.min_age} or older.",
"n_all": f"{pop.people['All']:,}", "n_on": f"{pop.people['ON']:,}", "n_qc": f"{pop.people['QC']:,}",
"age_all": pop.mean_age["All"], "hf_all": pct(pop.pct_heart_failure["All"]),
"deaths_all": f"{pop.deaths['All']:,}", "py_all": f"{pop.person_years['All']:,.1f}",
"died_on": pct(pop.pct_died["ON"]), "died_qc": pct(pop.pct_died["QC"]),
"burden_all": f"${cost.total_cost_millions['All']:.1f} million",
"burden_on": f"${cost.total_cost_millions['ON']:.1f} million", "burden_qc": f"${cost.total_cost_millions['QC']:.1f} million",
"ppy_all": money(cost.total_per_py["All"]), "ppy_on": money(cost.total_per_py["ON"]), "ppy_qc": money(cost.total_per_py["QC"]),
"hosp_share": pct(100 * cost.hospital_per_py["All"] / cost.total_per_py["All"]),
"drug_on": money(cost.drug_per_py["ON"]), "drug_qc": money(cost.drug_per_py["QC"]),
"median_all": money(cost.median_per_person["All"]),
"ratio_qc": f"{mod.estimate['cost_ratio_qc_on']:.3f}",
"ratio_qc_ci": f"{mod.ci_low['cost_ratio_qc_on']:.3f} to {mod.ci_high['cost_ratio_qc_on']:.3f}",
"diff_qc_less": money(-mod.estimate["cost_difference_qc_on"]),
"diff_qc_less_ci": f"{money(-mod.ci_high['cost_difference_qc_on'])} to {money(-mod.ci_low['cost_difference_qc_on'])}",
"gap_ppy": money(cost.total_per_py["ON"] - cost.total_per_py["QC"]),
"drug_gap_share": pct(100 * (cost.drug_per_py["ON"] - cost.drug_per_py["QC"])
/ (cost.total_per_py["ON"] - cost.total_per_py["QC"])),
"hf_inc": money(mod.estimate["cost_heart_failure_increment"]),
"hf_inc_ci": f"{money(mod.ci_low['cost_heart_failure_increment'])} to {money(mod.ci_high['cost_heart_failure_increment'])}",
"hosp_on": money(mod.estimate["hospital_cost_on"]), "hosp_qc": money(mod.estimate["hospital_cost_qc"]),
"visits_all": util_rows.visits_per_py["All"], "stays_all": util_rows.stays_per_100_py["All"],
"visits_irr": util_rows.visits_irr_qc_vs_on["QC"], "stays_irr": util_rows.stays_irr_qc_vs_on["QC"],
"s365_on": pct(100 * sur.survival_365["ON"]), "s365_qc": pct(100 * sur.survival_365["QC"]),
"adm_on": pct(100 * sur.admission_free_365["ON"]), "adm_qc": pct(100 * sur.admission_free_365["QC"]),
"admitted_all": pct(100 * (1 - sur.admission_free_365["All"])),
"death_hr": sur.death_hr_qc_vs_on["QC"], "adm_hr": sur.admission_hr_qc_vs_on["QC"],
"dm_cost_all": money(dia.extra_cost_per_year["All"]),
"dm_cost_ci": f"{money(dia.ci_low['All'])} to {money(dia.ci_high['All'])}",
"dm_cost_on": money(dia.extra_cost_per_year["ON"]), "dm_cost_qc": money(dia.extra_cost_per_year["QC"]),
"dm_people": f"{dia.people['All']:,}", "dm_diagnosed": f"{dia.diagnosed['All']:,}",
"u_nokf": f"{ut.complete_case_mean['no kidney failure']:.3f}", "u_kf": f"{ut.complete_case_mean['kidney failure']:.3f}",
"u_kf_visits": int(ut.visits["kidney failure"]),
"u24_cc": f"{util['u24_complete_case']:.3f}", "u24_mi": f"{util['u24_mi']:.3f}", "u24_miss": pct(util["u24_missing_pct"])}
for prov in ("ON", "QC"):
for item, key in (("diabetes", "dm"), ("regular_provider", "rp")):
row = sv.loc[(item, prov, "65+")]
r[f"sv_{key}_{prov.lower()}"] = (f"{row.percent:.1f}% ({row.ci_low:.1f}-{row.ci_high:.1f})" + (f" {row.flag}" if row.flag else "")
if pd.notna(row.percent) else "suppressed")
return r
The report is a Markdown template with named placeholders. _numbers reads every quoted number from the tables, so the text cannot disagree with them:
# The burden of chronic kidney disease in type 2 diabetes: Ontario and Quebec, 2025
*Corridor Health course, Module 2 capstone. Synthetic data: no real person is described. Every number is filled in by the pipeline (`python day20/build_report.py`); do not edit numbers by hand.*
## Key findings
- **{n_all} adults aged {min_age} or older with type 2 diabetes and chronic kidney disease** were followed through 2025 ({n_on} in Ontario, {n_qc} in Quebec). They cost the public payer **{burden_all}** in 2025: {burden_on} in Ontario and {burden_qc} in Quebec.
- **Cost per person-year: {ppy_all}** ({ppy_on} in Ontario, {ppy_qc} in Quebec). Hospital care is {hosp_share} of it. The median person cost {median_all}: a minority with hospital stays drives the mean.
- **At the same case mix, a Quebec resident costs {diff_qc_less} less a year than an Ontarian** (95% CI {diff_qc_less_ci}; ratio of means {ratio_qc}, {ratio_qc_ci}). Public drug spending ({drug_qc} vs {drug_on} per person-year) is {drug_gap_share} of the unadjusted gap of {gap_ppy}: it reflects Quebec's patient cost-sharing, not less treatment.
- **Heart failure adds {hf_inc} a year** per person (95% CI {hf_inc_ci}).
- **One-year survival was {s365_on} in Ontario and {s365_qc} in Quebec** (adjusted hazard ratio for Quebec {death_hr}). {admitted_all} were admitted to hospital within the year.
- **A new diabetes diagnosis adds {dm_cost_all} a year** to public costs in adults aged 40–79 (95% CI {dm_cost_ci}).
- **Utility is {u_nokf} without kidney failure and {u_kf} with it** (EQ-5D-5L, Canadian value set, Renavex trial). Both are likely overstated, because sicker patients skip questionnaires.
"""Day 20.3: build the burden-of-illness report - one command, every output.
python day20/build_report.py [--min-age 66] [--out capstone/m2_output]
"""
import argparse
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.boi import Config, run # noqa: E402
from corridor.db import ROOT # noqa: E402
parser = argparse.ArgumentParser(description="Build the Module 2 burden-of-illness report.")
parser.add_argument("--min-age", type=int, default=66, help="youngest age kept (default 66, the whole cohort)")
parser.add_argument("--out", default="capstone/m2_output", help="output folder, relative to the repository")
args = parser.parse_args()
config = Config(out_dir=args.out, min_age=args.min_age)
r = run(config, root=ROOT)
print(f"Report built: {r['n_all']} people aged {config.min_age}+, outputs in {config.out_dir}/\n")
print(open(os.path.join(ROOT, config.out_dir, "MANIFEST.txt"), encoding="utf-8").read())
# the lesson notes show the report's two figures
import shutil # noqa: E402
for name in ("costs_by_province.png", "survival_by_province.png"):
shutil.copy(os.path.join(ROOT, config.out_dir, name), os.path.join(ROOT, "figures", f"day20_{name}"))
Three design choices are worth copying:
- Survivors for cost models, everyone for rates. Gamma GLMs need a full year of costs (Day 11); costs per person-year and count models use everyone, with follow-up time (Days 7 and 12).
- One seed for the bootstrap. The 200 bootstrap samples use a fixed seed, so a rebuild gives the same intervals and the same fingerprints.
- A config, not edits. The population and the output folder are arguments (
--min-age,--out), so a sub-population report never overwrites the main one.
20.3 Build it and read the report (50 min)
python day11/build_analysis_file.py # if m2/analysis.parquet is missing
python day19/build_panel.py # if m2/panel.parquet is missing
python day20/build_report.py
Report built: 6,224 people aged 66+, outputs in capstone/m2_output/
eadca272e2ba8ed7 cost_models.csv
781f7c392f112c58 costs.csv
128d90aa3d4d9ad9 costs_by_province.png
0c836625fe198cd5 diabetes_cost.csv
6a71e0fe5860419e population.csv
ef559a93d11b80a7 report.md
24b78a02442ad719 survey.csv
941dc8a083930f9e survival.csv
051bc425dc2667c1 survival_by_province.png
b0dff8a681ae519c utilities.csv
361dd9268a578e82 utilization.csv
The report, as generated (capstone/m2_output/report.md):
# The burden of chronic kidney disease in type 2 diabetes: Ontario and Quebec, 2025
*Corridor Health course, Module 2 capstone. Synthetic data: no real person is described. Every number is filled in by the pipeline (`python day20/build_report.py`); do not edit numbers by hand.*
## Key findings
- **6,224 adults aged 66 or older with type 2 diabetes and chronic kidney disease** were followed through 2025 (3,956 in Ontario, 2,268 in Quebec). They cost the public payer **$32.2 million** in 2025: $21.4 million in Ontario and $10.9 million in Quebec.
- **Cost per person-year: $5,368** ($5,582 in Ontario, $4,991 in Quebec). Hospital care is 71.3% of it. The median person cost $1,567: a minority with hospital stays drives the mean.
- **At the same case mix, a Quebec resident costs $604 less a year than an Ontarian** (95% CI $241 to $1,003; ratio of means 0.881, 0.804 to 0.950). Public drug spending ($797 vs $1,089 per person-year) is 49.4% of the unadjusted gap of $591: it reflects Quebec's patient cost-sharing, not less treatment.
- **Heart failure adds $4,315 a year** per person (95% CI $3,696 to $5,133).
- **One-year survival was 93.3% in Ontario and 92.6% in Quebec** (adjusted hazard ratio for Quebec 1.149 (0.947-1.395)). 30.6% were admitted to hospital within the year.
- **A new diabetes diagnosis adds $1,382 a year** to public costs in adults aged 40–79 (95% CI $1,313 to $1,452).
- **Utility is 0.813 without kidney failure and 0.594 with it** (EQ-5D-5L, Canadian value set, Renavex trial). Both are likely overstated, because sicker patients skip questionnaires.
## Data and methods
**Population.** The Module 1 capstone cohort: adults aged 66 or older on 1 January 2025 with type 2 diabetes (Ontario case definition) and chronic kidney disease, on a public drug plan for the year before, not on dialysis, followed to death or 31 December 2025.
**Costs** are public payer costs in 2025 dollars: hospital stays (RIW × cost per weighted case), physician claims, and public drug plan payments. Costs per person-year divide total costs by follow-up time, so people who died are counted for the time they were alive. Adjusted comparisons use a gamma GLM with a log link among people who survived the year (age, sex, province, heart failure, COPD, hypertension, nephrology visit, insulin, baseline cost), reported as ratios of means and as dollar differences from recycled predictions. Hospital costs use a two-part model (logit for any stay, gamma GLM for the cost of stays). Confidence intervals for model-based quantities come from 200 bootstrap samples of people.
**Utilization** is physician visits and hospital stays per person-year; provincial incidence rate ratios come from Poisson models with a log person-year offset and robust standard errors.
**Survival.** Kaplan–Meier estimates of survival and of time to first admission (death censors admission); Cox models with Efron ties give adjusted hazard ratios for Quebec vs Ontario.
**Cost of a diabetes diagnosis.** A person-year panel of adults aged 40–79 in 2019 without diabetes at the start (2019–2025), with person and year fixed effects and standard errors clustered by person. The diagnosis year is the first claims-based diagnosis.
**Survey context.** A CCHS-style survey of adults in mid-2024, weighted, with bootstrap variance (500 replicate weights). Estimates follow Statistics Canada's release rules: CV over 16.5% flagged E, over 33.3% or fewer than 10 respondents suppressed.
**Utilities.** EQ-5D-5L from the Renavex trial visits, scored with the Canadian value set (Xie et al. 2016).
**Privacy.** Only aggregate tables leave the secure environment; any count from 1 to 5 would be suppressed; person-level files are git-ignored.
## Results
### Who is in the cohort
6,224 people, mean age 79.2; 15.3% had heart failure. Over 6,003.8 person-years, 432 died (6.7% in Ontario, 7.4% in Quebec). Table: `population.csv`.
### What they cost

| | Ontario | Quebec | Both |
|---|---|---|---|
| Cost per person-year | $5,582 | $4,991 | $5,368 |
| Public drug plan per person-year | $1,089 | $797 | |
| Expected hospital cost per survivor (same case mix) | $3,425 | $3,108 | |
| Total 2025 public cost | $21.4 million | $10.9 million | $32.2 million |
Adjusted for case mix, Quebec residents cost $604 less a year (95% CI $241 to $1,003). Tables: `costs.csv`, `cost_models.csv`.
### How much care they use
11.16 physician visits and 38.7 hospital stays per 100 person-years. Adjusted rate ratios, Quebec vs Ontario: visits 0.992 (0.973-1.010), stays 0.980 (0.897-1.070). Table: `utilization.csv`.
### Survival and first admission

One-year survival: 93.3% (Ontario), 92.6% (Quebec); adjusted HR for death, Quebec vs Ontario: 1.149 (0.947-1.395). Admission-free at one year: 68.7% and 70.8%; adjusted HR for a first admission: 0.936 (0.851-1.030). Table: `survival.csv`.
### What a diabetes diagnosis costs
Among 121,421 adults aged 40–79 without diabetes in 2019, 15,270 were diagnosed during 2020–2025. A diagnosis adds $1,382 a year (95% CI $1,313 to $1,452): $1,403 in Ontario and $1,349 in Quebec. Table: `diabetes_cost.csv`.
### Survey context: adults 65 and older
| | Ontario | Quebec |
|---|---|---|
| Self-reported diabetes, % (95% CI) | 27.9% (21.9-33.9) | 22.3% (17.9-26.7) |
| Has a regular health care provider, % (95% CI) | 87.0% (83.8-90.3) | 78.9% (73.4-84.5) |
Table: `survey.csv` (all ages and 65+, four indicators, flags).
### Quality of life
EQ-5D-5L utility: 0.813 without kidney failure, 0.594 with kidney failure (145 questionnaires). Table: `utilities.csv`.
## Limitations
- **Synthetic data.** Corridor Health is invented; the methods transfer, the numbers do not.
- **One year of follow-up.** Costs and survival describe 2025 only; long-run survival needs extrapolation (Day 14).
- **Public payer only.** Private drug plans and out-of-pocket costs are invisible, so Quebec's lower public drug cost is partly a transfer to patients, not a saving.
- **Case definitions.** Diabetes and CKD come from claims; a claims diagnosis year is not onset (Day 19), which inflates the cost of a "new" diagnosis.
- **Utilities.** 20.6% of 24-month questionnaires are missing, and the people who skipped them were sicker: the complete-case mean utility at 24 months is 0.800, multiple imputation gives 0.765. The state utilities above are complete-case and therefore too high; the Module 6 model should use imputed values.
- **Provincial comparisons** adjust for observed case mix only.


Read it as the ministry would:
- The burden is $32.2 million a year for 6,224 people, $5,368 per person-year. Hospital care is 71%. The median person cost $1,567, so the burden sits with a minority who are admitted (Day 12: 30.6% were).
- Quebec costs $604 less per person at the same case mix (95% CI $241 to $1,003). Half the raw gap is public drug spending, which is RAMQ's cost-sharing moving cost to patients (Day 1). Visits, stays, admissions and survival don't differ clearly between the provinces. The report says so rather than finding a story in noise.
- The caveats are in the report, with numbers: one year of follow-up, public payer only, claims-based dates, complete-case utilities that are too high (0.800 vs 0.765 after imputation).
20.4 Release checks (35 min)
"""Day 20.5: six checks before the report leaves the secure environment."""
import csv
import shutil
import tempfile
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.boi import SMALL, Config, run # noqa: E402
from corridor.db import ROOT # noqa: E402
OUT = os.path.join(ROOT, "capstone", "m2_output")
results = []
def check(name, ok, detail):
results.append(ok)
print(f"{'PASS' if ok else 'FAIL'} {name:<57}{detail}")
def table(name):
with open(os.path.join(OUT, f"{name}.csv"), encoding="utf-8") as f:
return list(csv.DictReader(f))
report = open(os.path.join(OUT, "report.md"), encoding="utf-8").read()
pop = {r["province"]: r for r in table("population")}
cost = {r["province"]: r for r in table("costs")}
# 1. the report is complete and quotes the tables
n = int(pop["All"]["people"])
ppy = float(cost["All"]["total_per_py"])
ok = "{" not in report and f"{n:,}" in report and f"${ppy:,.0f}" in report
check("report filled in, numbers match the tables", ok, f"{n:,} people, ${ppy:,.0f} per person-year")
# 2. no counts from 1 to 5 anywhere
COUNT_COLS = {"people", "deaths", "first_admissions", "respondents", "visits", "diagnosed"}
small = [(f, k, v) for f in os.listdir(OUT) if f.endswith(".csv") for r in table(f[:-4])
for k, v in r.items() if k in COUNT_COLS and v and 0 < int(float(v)) < SMALL]
check("no released counts from 1 to 5", not small, f"{len(small)} small cells")
# 3. survey release rules
sv = table("survey")
bad = [r for r in sv if (r["flag"].startswith("F") and r["percent"]) or (r["percent"] and int(r["respondents"]) < 10)]
check("survey: F estimates suppressed, n >= 10 behind the rest", not bad,
f"{sum(1 for r in sv if r['percent'])} released, {sum(1 for r in sv if not r['percent'])} suppressed")
# 4. the tables add up
parts = max(abs(sum(float(c[k]) for k in ("hospital_per_py", "physician_per_py", "drug_per_py")) - float(c["total_per_py"]))
for c in cost.values())
people = int(pop["ON"]["people"]) + int(pop["QC"]["people"]) - int(pop["All"]["people"])
millions = float(cost["ON"]["total_cost_millions"]) + float(cost["QC"]["total_cost_millions"]) - float(cost["All"]["total_cost_millions"])
check("components add up, provinces add up", parts < 0.02 and people == 0 and abs(millions) < 0.002,
f"largest component gap ${parts:.2f}")
# 5. nothing person-level in the output, person-level inputs git-ignored
headers = [h for f in os.listdir(OUT) if f.endswith(".csv") for h in table(f[:-4])[0].keys()]
ignore = open(os.path.join(ROOT, ".gitignore"), encoding="utf-8").read()
ok = not ({"person_id", "patient_id", "resp_id"} & set(headers)) and "m2/*.parquet" in ignore
check("no identifiers in outputs; m2/*.parquet git-ignored", ok, f"{len(os.listdir(OUT))} files in capstone/m2_output")
# 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", "boi_template.md"), os.path.join(tmp, "capstone"))
run(Config(), root=tmp)
same = open(os.path.join(tmp, "capstone", "m2_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 6,224 people, $5,368 per person-year
PASS no released counts from 1 to 5 0 small cells
PASS survey: F estimates suppressed, n >= 10 behind the rest 24 released, 0 suppressed
PASS components add up, provinces add up largest component gap $0.01
PASS no identifiers in outputs; m2/*.parquet git-ignored 12 files in capstone/m2_output
PASS rebuild in a fresh folder: identical fingerprints MANIFEST.txt compared
6/6 checks passed
Each check answers a question a reviewer or a privacy officer will ask:
- Does the text match the tables? It's generated, but check anyway: a template edit can break it.
- Any small cells? No count from 1 to 5 leaves (Day 2's rule).
- Are the survey estimates releasable? F estimates suppressed, no estimate from fewer than 10 respondents (Day 16).
- Do the tables add up? Components to totals, provinces to "All". 20.5 shows what this check catches.
- Anything person-level? No identifier column in any output, and the person-level inputs are git-ignored.
- Can someone else rebuild it? A fresh build in an empty folder gives the same fingerprints.
20.5 The "All" row (15 min)
Bug of the day. An analyst fills in the "All" row of the cost table as the average of the two provinces:
"""Day 20 bug of the day: the 'All' row as the average of the provincial rates."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import csv # noqa: E402
from corridor.db import ROOT # noqa: E402
with open(os.path.join(ROOT, "capstone", "m2_output", "costs.csv"), encoding="utf-8") as f:
c = {r["province"]: r for r in csv.DictReader(f)}
avg = (float(c["ON"]["total_per_py"]) + float(c["QC"]["total_per_py"])) / 2
py = {k: float(c[k]["person_years"]) for k in ("ON", "QC")}
pooled = sum(float(c[k]["total_per_py"]) * py[k] for k in py) / sum(py.values())
print(f"average of the two provincial rates: ${avg:,.2f} per person-year")
print(f"pooled (weighted by person-years): ${pooled:,.2f} per person-year")
print(f"the table's All row: ${float(c['All']['total_per_py']):,.2f}")
print(f"budget for {sum(py.values()):,.1f} person-years: ${avg * sum(py.values()) / 1e6:.2f} M vs ${pooled * sum(py.values()) / 1e6:.2f} M")
average of the two provincial rates: $5,286.55 per person-year
pooled (weighted by person-years): $5,367.59 per person-year
the table's All row: $5,367.59
budget for 6,003.8 person-years: $31.74 M vs $32.23 M
$5,287 against the true $5,368, and a budget short by half a million dollars. Ontario has 64% of the person-years, so an unweighted average gives Quebec too much weight. Pool the numerators and the denominators; never average rates. Release check 4 compares the "All" row with the provinces; an analyst who typed the average into a spreadsheet would have no such check.
20.6 Check it in R and SAS (40 min)
R recomputes the key numbers from the analysis file, without the Python package:
# Day 20: an independent check of the report's key numbers in R, from the same analysis file.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(survival) })
con <- dbConnect(duckdb(shared_home = FALSE))
d <- dbGetQuery(con, "SELECT * FROM read_parquet('m2/analysis.parquet')")
dbDisconnect(con, shutdown = TRUE)
d <- transform(d, age10 = (age - 75) / 10, male = as.integer(sex == "M"), qc = as.integer(province == "QC"),
log_base = log(base_cost + 100), py = fu_days / 365.25)
x <- "age10 + male + qc + heart_failure + copd + hypertension + nephrology_visit + insulin + log_base"
ppy <- with(d, tapply(fu_cost, province, sum) / tapply(py, province, sum))
cat(sprintf("cost per person-year: ON %.2f QC %.2f All %.2f\n", ppy["ON"], ppy["QC"], sum(d$fu_cost) / sum(d$py)))
s <- subset(d, !died)
g <- glm(as.formula(paste("fu_cost ~", x)), family = Gamma(link = "log"), data = s)
pred <- function(v) mean(predict(g, transform(s, qc = v), type = "response"))
cat(sprintf("gamma GLM: QC/ON ratio %.3f, recycled difference %.0f\n", exp(coef(g)[["qc"]]), pred(1) - pred(0)))
km <- summary(survfit(Surv(t_end, died) ~ province, data = d), times = 365)
cat(sprintf("one-year survival: ON %.4f QC %.4f\n", km$surv[1], km$surv[2]))
cx <- coxph(as.formula(paste("Surv(t_end, died) ~", x)), data = d)
cat(sprintf("Cox HR for death, QC vs ON: %.3f\n", exp(coef(cx)[["qc"]])))
pv <- glm(as.formula(paste("fu_visits ~", x, "+ offset(log(py))")), family = poisson, data = d)
cat(sprintf("visits IRR, QC vs ON: %.3f\n", exp(coef(pv)[["qc"]])))
cost per person-year: ON 5582.10 QC 4991.00 All 5367.59
gamma GLM: QC/ON ratio 0.881, recycled difference -604
one-year survival: ON 0.9330 QC 0.9264
Cox HR for death, QC vs ON: 1.149
visits IRR, QC vs ON: 0.992
Costs per person-year, the gamma GLM's ratio and dollar difference, one-year survival, the Cox HR and the visits rate ratio all match the report.
SAS builds the main tables from a person-level extract (git-ignored, like every person-level file):
"""Day 20.6: the person-level extract SAS reads (sas_extract/m2_analysis.csv: git-ignored, never released)."""
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.m2 import load # noqa: E402
COLS = ["person_id", "province", "sex", "age", "heart_failure", "copd", "hypertension", "nephrology_visit",
"insulin", "base_cost", "died", "fu_days", "fu_hospital", "fu_physician", "fu_drug", "fu_cost",
"fu_visits", "fu_stays", "t_end", "t_admit"]
d = load()[COLS]
os.makedirs(os.path.join(ROOT, "sas_extract"), exist_ok=True)
path = os.path.join(ROOT, "sas_extract", "m2_analysis.csv")
d.to_csv(path, index=False, float_format="%.2f")
print(f"{path.replace(os.sep, '/').split('corridor-health/')[-1]}: {len(d):,} rows, {len(COLS)} columns")
print(open(path, encoding="utf-8").readline().strip())
sas_extract/m2_analysis.csv: 6,224 rows, 20 columns
person_id,province,sex,age,heart_failure,copd,hypertension,nephrology_visit,insulin,base_cost,died,fu_days,fu_hospital,fu_physician,fu_drug,fu_cost,fu_visits,fu_stays,t_end,t_admit
/* Day 20.6: the burden-of-illness tables in SAS. Upload sas_extract/m2_analysis.csv to your corridor folder. */
%let path = /home/u00000000/corridor;
libname corr "&path";
data corr.m2;
infile "&path/m2_analysis.csv" dsd firstobs=2 truncover;
length person_id $11 province $2 sex $1;
input person_id $ province $ sex $ age heart_failure copd hypertension nephrology_visit insulin base_cost
died fu_days fu_hospital fu_physician fu_drug fu_cost fu_visits fu_stays t_end t_admit;
age10 = (age - 75) / 10;
male = (sex = "M");
qc = (province = "QC");
log_base = log(base_cost + 100);
py = fu_days / 365.25;
log_py = log(py);
admitted = not missing(t_admit);
t_adm = coalesce(t_admit, t_end);
run;
/* 1. cost per person-year by province and for everyone */
proc sql;
create table work.costs as
select province, count(*) as people, sum(py) as person_years format=comma10.1,
sum(fu_hospital) / sum(py) as hospital_per_py format=dollar10.2,
sum(fu_physician) / sum(py) as physician_per_py format=dollar10.2,
sum(fu_drug) / sum(py) as drug_per_py format=dollar10.2,
sum(fu_cost) / sum(py) as total_per_py format=dollar10.2
from corr.m2 group by province
union all
select 'All', count(*), sum(py), sum(fu_hospital) / sum(py), sum(fu_physician) / sum(py),
sum(fu_drug) / sum(py), sum(fu_cost) / sum(py)
from corr.m2;
quit;
proc print data=work.costs noobs; run;
/* 2. gamma GLM with a log link, survivors */
proc genmod data=corr.m2(where=(died = 0));
model fu_cost = age10 male qc heart_failure copd hypertension nephrology_visit insulin log_base
/ dist=gamma link=log;
ods select ParameterEstimates;
run;
/* 3. physician visits: Poisson with a log person-year offset */
proc genmod data=corr.m2;
model fu_visits = age10 male qc heart_failure copd hypertension nephrology_visit insulin log_base
/ dist=poisson link=log offset=log_py;
ods select ParameterEstimates;
run;
/* 4. one-year survival by province (Kaplan-Meier) */
proc lifetest data=corr.m2 timelist=365 reduceout outsurv=work.km noprint;
time t_end*died(0);
strata province;
run;
proc print data=work.km noobs; var province t_end survival; run;
/* 5. Cox models for death and first admission (Efron ties, as in Python and R) */
proc phreg data=corr.m2;
model t_end*died(0) = age10 male qc heart_failure copd hypertension nephrology_visit insulin log_base / ties=efron;
ods select ParameterEstimates;
run;
proc phreg data=corr.m2;
model t_adm*admitted(0) = age10 male qc heart_failure copd hypertension nephrology_visit insulin log_base / ties=efron;
ods select ParameterEstimates;
run;
ods excel file="&path/boi_tables_sas.xlsx" options(sheet_name="Costs");
proc print data=work.costs noobs; run;
ods excel close;
What the SAS program should print:
"""Day 20.6: what boi_tables.sas should print, computed in Python from the same data.
GENMOD estimates the gamma scale by maximum likelihood and statsmodels by the Pearson statistic, so the
coefficients agree and the standard errors differ slightly; the comparison is on the coefficients.
"""
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.api as sm # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from statsmodels.duration.hazard_regression import PHReg # noqa: E402
from corridor.boi import cost_table # noqa: E402
from corridor.costmodels import COVARIATES # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.survival import admission_outcome, km, surv_at # noqa: E402
d = load()
print("--- 1. PROC SQL: cost per person-year")
print(cost_table(d)[["province", "people", "person_years", "hospital_per_py", "physician_per_py", "drug_per_py",
"total_per_py"]].to_string(index=False))
s = d[d.died == 0]
g = smf.glm(f"fu_cost ~ {COVARIATES}", s, family=sm.families.Gamma(sm.families.links.Log())).fit()
p = smf.glm(f"fu_visits ~ {COVARIATES}", d, family=sm.families.Poisson(), offset=np.log(d.py)).fit()
d["t_adm"], d["admitted"] = admission_outcome(d)
cd = PHReg.from_formula(f"t_end ~ {COVARIATES}", d, status=d.died, ties="efron").fit()
ca = PHReg.from_formula(f"t_adm ~ {COVARIATES}", d, status=d.admitted, ties="efron").fit()
t = pd.DataFrame({"2. GENMOD gamma": g.params, "3. GENMOD Poisson": p.params,
"5. PHREG death": pd.Series(cd.params, cd.model.exog_names),
"5. PHREG admission": pd.Series(ca.params, ca.model.exog_names)})
print("\n--- 2, 3, 5: parameter estimates (in the order SAS lists them)")
print(t.reindex(["Intercept"] + COVARIATES.split(" + ")).round(4).to_string(na_rep=""))
print("\n--- 4. PROC LIFETEST: survival at day 365")
for prov, x in d.groupby("province"):
print(f"{prov} {surv_at(km(x.t_end, x.died), 365):.4f}")
--- 1. PROC SQL: cost per person-year
province people person_years hospital_per_py physician_per_py drug_per_py total_per_py
ON 3956 3825.0 3930.48 562.44 1089.19 5582.10
QC 2268 2178.8 3646.69 547.39 796.92 4991.00
All 6224 6003.8 3827.49 556.98 983.12 5367.59
--- 2, 3, 5: parameter estimates (in the order SAS lists them)
2. GENMOD gamma 3. GENMOD Poisson 5. PHREG death 5. PHREG admission
Intercept 7.1179 2.1226
age10 -0.0135 0.0275 0.8927 0.0711
male -0.0108 -0.0076 0.0975 -0.0005
qc -0.1266 -0.0085 0.1391 -0.0659
heart_failure 0.7078 0.3461 0.4374 0.8313
copd 0.3577 0.1299 0.3251 0.3984
hypertension -0.0312 0.0599 -0.1478 0.0222
nephrology_visit 0.3256 0.1255 0.1957 0.3468
insulin 0.1480 -0.0001 0.0513 0.0510
log_base 0.1347 0.0149 0.0017 0.0459
--- 4. PROC LIFETEST: survival at day 365
ON 0.9330
QC 0.9264
PROC GENMOD, PROC LIFETEST and PROC PHREG (with ties=efron) give the same estimates. GENMOD's gamma standard errors use a maximum-likelihood scale, so they differ slightly from statsmodels'; compare the coefficients. tests/test_day_20.py checks that the SAS INPUT statement lists the extract's columns in order, so the program and the extract can't drift apart.
20.7 A sub-population in a second folder (30 min)
Try it (30 min). The ministry asks: "What about people 80 and older?" Rebuild the whole report for them into a second folder and compare the headline numbers.
Solution
"""Day 20 try it: rebuild the report for people aged 80 or older, in a second folder, and compare."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import csv # noqa: E402
from corridor.boi import Config, run # noqa: E402
from corridor.db import ROOT # noqa: E402
run(Config(out_dir="capstone/m2_output_80", min_age=80), root=ROOT)
for folder, label in (("m2_output", "66+"), ("m2_output_80", "80+")):
with open(os.path.join(ROOT, "capstone", folder, "costs.csv"), encoding="utf-8") as f:
c = {r["province"]: r for r in csv.DictReader(f)}
with open(os.path.join(ROOT, "capstone", folder, "survival.csv"), encoding="utf-8") as f:
s = {r["province"]: r for r in csv.DictReader(f)}
print(f"{label}: {int(c['All']['people']):,} people; cost per person-year ${float(c['All']['total_per_py']):,.0f} "
f"(hospital ${float(c['All']['hospital_per_py']):,.0f}); one-year survival {float(s['All']['survival_365']):.3f}; "
f"QC vs ON death HR {s['QC']['death_hr_qc_vs_on']}")
66+: 6,224 people; cost per person-year $5,368 (hospital $3,827); one-year survival 0.931; QC vs ON death HR 1.149 (0.947-1.395)
80+: 2,797 people; cost per person-year $6,042 (hospital $4,448); one-year survival 0.881; QC vs ON death HR 1.202 (0.965-1.497)
The 2,797 people aged 80+ cost $6,042 per person-year, $674 more than the whole cohort, almost all of it hospital care. One-year survival is 88.1% against 93.1%. The provincial difference in mortality is no clearer (HR 1.20, CI still includes 1). The whole report, release checks included, is one argument away. capstone/m2_output_*/ is git-ignored: comparisons are working files, the main report is the deliverable.
Why it matters at work: A burden-of-illness study is often the first paid deliverable in an HEOR project, and the inputs for the budget impact and cost-effectiveness models that follow. A pipeline that rebuilds every number with one command is what lets a team answer "can you redo it for 80+?" in a minute, not a week.
Where you'll meet this: HEOR and market-access consulting (burden studies before submissions) · ministries and Ontario Health (program planning) · ICES and INSPQ reports · the "epidemiology and burden" section of every CDA-AMC submission
20.8 Module 2 in review (25 min)
| Day | Method | The lesson that matters most |
|---|---|---|
| 11 | Gamma GLMs, smearing | exp(predicted log cost) is not the mean; budgets need means |
| 12 | Two-part and count models | dropping zeros changes the question; use offsets for follow-up time |
| 13 | Kaplan–Meier, Cox | status = 1 is the event; report events and CIs with every HR |
| 14 | Parametric survival | AIC cannot choose an extrapolation; external data and plausibility can |
| 15 | Competing risks, multi-state | 1 − KM is not a probability when other events come first |
| 16 | Survey weights | the bootstrap weights give the SE; flags decide what can be released |
| 17 | EQ-5D-5L | score each person with the Canadian value set, then average |
| 18 | Multiple imputation | complete cases were the healthy ones; MI fixes MAR, a tipping point handles MNAR |
| 19 | Panel fixed effects | compare people with themselves; cluster by person; a diagnosis date is not onset |
| 20 | The report | one command, tables before text, checks before release |
Module 3 turns from describing to comparing: does Renavex, used in routine care, work as well as in the trial? The cohort, costs, survival models and utilities from Modules 1 and 2 become the inputs of a target trial emulation.
Save your work
python day20/release_checks.py
python -m pytest -q
git add .
git commit -m "Day 20: Module 2 capstone - burden-of-illness report"
Day 20 checklist
-
python day20/build_report.pybuilds every table, both figures and the report, and a second run gives the same MANIFEST - Every number in
report.mdcomes from a table, and the release checks pass - I can explain each headline result and its main limitation to a ministry reader
- The R check and the SAS program reproduce the key numbers
- I can rebuild the report for a sub-population into a separate folder without touching the main one
Bloc français (30 min)
Thème : le fardeau de la maladie.
En 2025, les adultes de 66 ans et plus atteints de diabète de type 2 et d'insuffisance rénale chronique ont coûté 32,2 millions de dollars au payeur public. Les soins hospitaliers représentent 71 % de ce coût. À profil clinique égal, une personne au Québec coûte 604 $ de moins par année qu'en Ontario, surtout parce que la contribution des patients aux médicaments y est plus élevée. La survie à un an ne diffère pas clairement entre les deux provinces.
| Français | English |
|---|---|
| le fardeau de la maladie | the burden of illness |
| le payeur public | the public payer |
| le coût par personne-année | the cost per person-year |
| à profil clinique égal | at the same case mix |
| l'écart de coût | the cost gap |
| la contribution des patients | patient cost-sharing |
| la survie à un an | one-year survival |
| le rapport de risques ajusté | the adjusted hazard ratio |
| la reproductibilité | reproducibility |
| les contrôles avant diffusion | release checks |
| les petites cellules | small cells |
| le ministère de la Santé | the ministry of health |
Exercices
- Translate: "Hospital care accounts for 71% of the public cost."
- Translate: « Le rapport est reconstruit au complet par une seule commande. »
- In four French sentences, summarise the report's key findings for a Quebec ministry reader.
Réponses
- Les soins hospitaliers représentent 71 % du coût public.
- "The report is rebuilt in full by a single command."
- Example: En 2025, les 6 224 adultes de la cohorte ont coûté 32,2 millions de dollars au payeur public. À profil clinique égal, une personne au Québec coûte environ 600 $ de moins par année qu'en Ontario. Cet écart vient surtout des médicaments, car les patients québécois en paient une plus grande part. L'utilisation des soins et la survie à un an sont semblables dans les deux provinces.