Applied Health Economics, RWE & HTA
Overview / Course data

Course data

The course uses one synthetic population, Corridor Health: 250,000 adults in Ontario (62%) and Quebec (38%), with administrative-style tables shaped like the files at ICES, CIHI and RAMQ. Everything is generated by the script below, using only Python's standard library and a fixed seed, so everyone gets byte-identical files.

Run it once from the course folder:

python data/make_data.py      # about 2.5 minutes, about 280 MB
FileWhat it holds
persons.csvRegistry: encrypted ID, province, region, sex, birth date, income quintile, rurality, registry start, death date
drug_plan_eligibility.csvPeriods on a public drug plan (ODB, OHIP+, RAMQ)
physician_claims_2024.csvPhysician claims: date, fee code, 3-digit ICD-9 diagnosis, specialty, amount paid
hospital_discharges_2024.csvHospital abstracts: dates, ICD-10 diagnoses, CCI-style intervention, CMG, RIW, disposition
drug_claims_2024.csvPublic drug plan claims: DIN, quantity, days' supply, costs, patient and plan shares
lookupsdrugs, atc, icd9_dx, icd10, icd10_chapters, cci, cci_sections, cmg, fee_codes, drug_plans, pharmacy_pricing, provinces, regions
Renavexrenavex_milestones.csv (the fictional drug's route to listing), personas.csv
Day 4: more yearsphysician_claims_YYYY.csv.gz, hospital_discharges_YYYY.csv.gz, drug_claims_YYYY.csv.gz for 2019–2023 and 2025
Day 4: registryregistry_deceased_2019_2023.csv (people who died before 2024), registry_updates_2025.csv (2025 deaths), drug_plan_eligibility_updates.csv
Day 7: pricescpwc_by_year.csv (cost per weighted case by province and year), cpi_health.csv (health price index, 2019–2025)
Day 14: Renavex trialrenavex_trial.csv: the sponsor's pivotal trial extract (3,000 patients; randomization, kidney failure and death dates, last contact)
Day 17: trial visitsrenavex_trial_visits.csv: visits at months 0, 12 and 24 with EQ-5D-5L answers, a kidney symptom score and 12-month costs (some missing, as in a real trial)
Day 16: surveycchs_2024.csv (a CCHS-style survey: 2,806 respondents, final weight wts_m) and cchs_2024_bootstrap.csv.gz (500 bootstrap weights)
Days 21-30: Renavex RWE extractrwe_persons.csv, rwe_labs.csv (eGFR, UACR), rwe_dispensations.csv (Renavex, new SGLT2 inhibitors), rwe_events.csv (kidney failure, hospitalization, death): 9,805 adults with diabetes and CKD followed 2026-2028
Day 28: frailty substudyrwe_frailty_substudy.csv: a chart review of 1,000 people in the RWE extract that recorded frailty (Clinical Frailty Scale 5 or more), with the errors of a real chart review
Days 31-40: policy paneldrug_utilization_monthly.csv (11 regions x 84 months, 2021-2027: people with diabetes, new SGLT2 and Renavex users, UACR tests; whole-population aggregate counts) and kidney_clinic_rollout.csv (the month each region opened a kidney care clinic)
Days 34-35: more policy dataprovincial_diabetes_quarterly.csv (10 provinces x 48 quarters: emergency visits for glycemic emergencies; Ontario covers continuous glucose monitors from 2024 Q1) and young_adults_t1d_2024.csv (person-months for young adults with type 1 diabetes around Ontario's age-25 coverage rule)
Days 37-38: evaluation and equitykidney_clinic_costs.csv (each clinic's yearly program cost) and provincial_diabetes_quarterly_by_income.csv (the provincial glycemic emergency counts by income quintile and rurality)
truth/Hidden health states, diagnosis dates, drug start dates, the trial's true event times and the survey's sampling frame, used to check your answers. Don't open it.

Later lessons add tables with new generator functions. Files from earlier days stay byte-identical.

The generator: data/make_data.py

"""Corridor Health: the course data generator.

Builds a synthetic population of adults in Ontario and Quebec and the
administrative-style tables a health economist works with. Everything here is
invented: people, codes marked as course codes, prices, fees and plan rules.
Real coding systems (ICD-10, ICD-9, ATC) are used where noted, simplified.

Standard library only. Same seed -> byte-identical files.

    python data/make_data.py          # writes data/*.csv, data/*.csv.gz and data/truth/*.csv

Do not open data/truth/: it holds the hidden "true" health states that later
lessons ask you to recover from the claims.
"""

import csv
import datetime as dt
import hashlib
import math
import os
import random

SEED = 2026
N_PEOPLE = 250_000
YEAR = 2024
HERE = os.path.dirname(os.path.abspath(__file__))
TRUTH = os.path.join(HERE, "truth")

START, END = dt.date(YEAR, 1, 1), dt.date(YEAR, 12, 31)


def write(name, header, rows, folder=HERE):
    os.makedirs(folder, exist_ok=True)
    with open(os.path.join(folder, name), "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f, lineterminator="\n")
        w.writerow(header)
        w.writerows(rows)


def logistic(x):
    return 1 / (1 + math.exp(-x))


def poisson(rng, lam):
    """Knuth's method; fine for the small means used here."""
    if lam <= 0:
        return 0
    limit, k, p = math.exp(-lam), 0, 1.0
    while True:
        p *= rng.random()
        if p <= limit:
            return k
        k += 1


def money(x):
    return f"{x:.2f}"


# ---------------------------------------------------------------------------
# Reference tables (Days 1-3)
# ---------------------------------------------------------------------------

PROVINCES = [
    # province, name, physician plan, public drug plan, share of course population,
    # cost per weighted case ($, course value)
    ("ON", "Ontario", "OHIP", "Ontario Drug Benefit (ODB)", 0.62, 6800.00),
    ("QC", "Quebec", "RAMQ", "Public Prescription Drug Insurance Plan (RAMQ)", 0.38, 6400.00),
]

REGIONS = [
    # region, province, name, share of province, rural share
    ("ON-TOR", "ON", "Toronto", 0.21, 0.00),
    ("ON-CEN", "ON", "Central", 0.30, 0.06),
    ("ON-EST", "ON", "East (incl. Ottawa)", 0.26, 0.17),
    ("ON-WST", "ON", "West", 0.18, 0.18),
    ("ON-NTH", "ON", "North", 0.05, 0.42),
    ("QC-06", "QC", "Montréal", 0.24, 0.00),
    ("QC-16", "QC", "Montérégie", 0.18, 0.16),
    ("QC-03", "QC", "Capitale-Nationale", 0.09, 0.10),
    ("QC-13", "QC", "Laval", 0.05, 0.00),
    ("QC-07", "QC", "Outaouais", 0.05, 0.27),
    ("QC-OTH", "QC", "Other regions", 0.39, 0.38),
]

AGE_BANDS = [  # (low, high, weight): adults, roughly Canada's age structure
    (18, 24, 9.5), (25, 29, 7.5), (30, 34, 8.3), (35, 39, 8.2), (40, 44, 7.9),
    (45, 49, 7.3), (50, 54, 7.4), (55, 59, 7.8), (60, 64, 7.9), (65, 69, 6.9),
    (70, 74, 5.9), (75, 79, 4.6), (80, 84, 3.0), (85, 89, 1.8), (90, 99, 1.0),
]

# Public drug plan rules (course values; real plans change their amounts every year).
DRUG_PLANS = [
    # plan_id, province, name, who, deductible, deductible_period, copay_per_rx,
    # coinsurance, max_out_of_pocket, max_period, public
    ("ODB-65", "ON", "ODB seniors", "Ontario residents 65+ (single, above the low-income threshold)",
     100.00, "year", 6.11, 0.00, "", "", 1),
    ("ODB-65L", "ON", "ODB seniors, low income", "Ontario residents 65+ below the low-income threshold",
     0.00, "", 2.00, 0.00, "", "", 1),
    ("ODB-SA", "ON", "ODB social assistance", "Ontario Works / ODSP recipients",
     0.00, "", 2.00, 0.00, "", "", 1),
    ("OHIP+", "ON", "OHIP+", "Ontario residents under 25 with no private drug plan",
     0.00, "", 0.00, 0.00, "", "", 1),
    ("ON-PRIV", "ON", "Ontario private group plan (typical)", "Employees and dependants with a workplace plan",
     0.00, "", 0.00, 0.20, "", "", 0),
    ("ON-NONE", "ON", "No drug coverage", "Ontario residents under 65 with no plan (may apply to Trillium)",
     0.00, "", 0.00, 1.00, "", "", 0),
    ("RAMQ-PUB", "QC", "RAMQ public plan", "Quebec residents with no access to a private plan, and most 65+",
     22.90, "month", 0.00, 0.32, 96.25, "month", 1),
    ("RAMQ-SA", "QC", "RAMQ, last-resort financial assistance", "Social assistance recipients",
     0.00, "", 0.00, 0.00, "", "", 1),
    ("QC-PRIV", "QC", "Quebec private group plan (typical)", "Anyone with access to a group plan must join it",
     0.00, "", 0.00, 0.32, 96.25, "month", 0),
]

PHARMACY = {  # province: (markup on drug cost, dispensing fee) - course values
    "ON": (0.08, 8.83),
    "QC": (0.065, 9.25),
}

# Drug products. Ingredients and ATC codes are real; DINs (all starting 0990) and
# prices are invented. Renavex is a fictional drug.
DRUGS = [
    # din, brand/product, ingredient, strength, form, atc, unit price, units per day
    ("09900015", "Metformin 500", "metformin", "500 mg", "tablet", "A10BA02", 0.0450, 2),
    ("09900023", "Metformin 850", "metformin", "850 mg", "tablet", "A10BA02", 0.0610, 2),
    ("09900031", "Gliclazide MR 30", "gliclazide", "30 mg", "tablet", "A10BB09", 0.1120, 2),
    ("09900058", "Sitagliptin 100", "sitagliptin", "100 mg", "tablet", "A10BH01", 1.2900, 1),
    ("09900066", "Empagliflozin 10", "empagliflozin", "10 mg", "tablet", "A10BK03", 2.4400, 1),
    ("09900074", "Dapagliflozin 10", "dapagliflozin", "10 mg", "tablet", "A10BK01", 2.3100, 1),
    ("09900082", "Semaglutide pen", "semaglutide", "1 mg/dose", "pen (4 doses)", "A10BJ06", 217.0000, 1 / 28),
    ("09900090", "Insulin glargine", "insulin glargine", "100 U/mL", "pen (300 U)", "A10AE04", 21.5000, 1 / 10),
    ("09900104", "Ramipril 5", "ramipril", "5 mg", "capsule", "C09AA05", 0.1050, 1),
    ("09900112", "Amlodipine 5", "amlodipine", "5 mg", "tablet", "C08CA01", 0.0890, 1),
    ("09900120", "Atorvastatin 20", "atorvastatin", "20 mg", "tablet", "C10AA05", 0.1340, 1),
    ("09900139", "Rosuvastatin 10", "rosuvastatin", "10 mg", "tablet", "C10AA07", 0.1210, 1),
    ("09900147", "Furosemide 40", "furosemide", "40 mg", "tablet", "C03CA01", 0.0330, 1),
    ("09900155", "Salbutamol inhaler", "salbutamol", "100 mcg/dose", "inhaler (200 doses)", "R03AC02", 6.2500, 1 / 50),
    ("09900163", "Tiotropium inhaler", "tiotropium", "18 mcg", "capsule (inhaled)", "R03BB04", 1.7900, 1),
    ("09900171", "Renavex 25", "renavexiban (fictional)", "25 mg", "tablet", "A10BX99", 3.8500, 1),
]

ATC = [  # code, level, name (WHO ATC names; A10BX99 is the course's fictional code)
    ("A", 1, "Alimentary tract and metabolism"),
    ("A10", 2, "Drugs used in diabetes"),
    ("A10A", 3, "Insulins and analogues"),
    ("A10AE", 4, "Insulins and analogues for injection, long-acting"),
    ("A10AE04", 5, "insulin glargine"),
    ("A10B", 3, "Blood glucose lowering drugs, excl. insulins"),
    ("A10BA", 4, "Biguanides"),
    ("A10BA02", 5, "metformin"),
    ("A10BB", 4, "Sulfonylureas"),
    ("A10BB09", 5, "gliclazide"),
    ("A10BH", 4, "Dipeptidyl peptidase 4 (DPP-4) inhibitors"),
    ("A10BH01", 5, "sitagliptin"),
    ("A10BJ", 4, "Glucagon-like peptide-1 (GLP-1) analogues"),
    ("A10BJ06", 5, "semaglutide"),
    ("A10BK", 4, "Sodium-glucose co-transporter 2 (SGLT2) inhibitors"),
    ("A10BK01", 5, "dapagliflozin"),
    ("A10BK03", 5, "empagliflozin"),
    ("A10BX", 4, "Other blood glucose lowering drugs, excl. insulins"),
    ("A10BX99", 5, "renavexiban (fictional, course only)"),
    ("C", 1, "Cardiovascular system"),
    ("C03", 2, "Diuretics"),
    ("C03C", 3, "High-ceiling diuretics"),
    ("C03CA", 4, "Sulfonamides, plain"),
    ("C03CA01", 5, "furosemide"),
    ("C08", 2, "Calcium channel blockers"),
    ("C08C", 3, "Selective calcium channel blockers with mainly vascular effects"),
    ("C08CA", 4, "Dihydropyridine derivatives"),
    ("C08CA01", 5, "amlodipine"),
    ("C09", 2, "Agents acting on the renin-angiotensin system"),
    ("C09A", 3, "ACE inhibitors, plain"),
    ("C09AA", 4, "ACE inhibitors, plain"),
    ("C09AA05", 5, "ramipril"),
    ("C10", 2, "Lipid modifying agents"),
    ("C10A", 3, "Lipid modifying agents, plain"),
    ("C10AA", 4, "HMG CoA reductase inhibitors"),
    ("C10AA05", 5, "atorvastatin"),
    ("C10AA07", 5, "rosuvastatin"),
    ("R", 1, "Respiratory system"),
    ("R03", 2, "Drugs for obstructive airway diseases"),
    ("R03A", 3, "Adrenergics, inhalants"),
    ("R03AC", 4, "Selective beta-2-adrenoreceptor agonists"),
    ("R03AC02", 5, "salbutamol"),
    ("R03B", 3, "Other drugs for obstructive airway diseases, inhalants"),
    ("R03BB", 4, "Anticholinergics"),
    ("R03BB04", 5, "tiotropium bromide"),
]

# Physician-claim diagnosis codes: 3-digit ICD-9 categories (both OHIP and RAMQ
# physician claims carry ICD-9-based diagnosis codes; the course uses one list).
ICD9 = [
    ("250", "Diabetes mellitus", "diabetes"),
    ("401", "Essential hypertension", "hypertension"),
    ("410", "Acute myocardial infarction", "ami"),
    ("428", "Heart failure", "heart_failure"),
    ("496", "Chronic airway obstruction, not elsewhere classified", "copd"),
    ("585", "Chronic kidney disease", "ckd"),
    ("300", "Anxiety, dissociative and somatoform disorders", "general"),
    ("311", "Depressive disorder, not elsewhere classified", "general"),
    ("460", "Acute nasopharyngitis (common cold)", "general"),
    ("724", "Other and unspecified disorders of back", "general"),
    ("780", "General symptoms", "general"),
    ("786", "Symptoms involving respiratory system and other chest symptoms", "general"),
]

GENERAL_DX_WEIGHTS = [14, 12, 22, 18, 20, 14]  # 300, 311, 460, 724, 780, 786

# Hospital diagnosis codes: WHO ICD-10 four-character codes, written without the
# dot as in hospital abstracts. ICD-10-CA extends some of these with more characters.
ICD10 = [
    ("E112", "Type 2 diabetes mellitus with renal complications", "E", "diabetes"),
    ("E119", "Type 2 diabetes mellitus without complications", "E", "diabetes"),
    ("E109", "Type 1 diabetes mellitus without complications", "E", "other"),
    ("I10", "Essential (primary) hypertension", "I", "hypertension"),
    ("I219", "Acute myocardial infarction, unspecified", "I", "ami"),
    ("I500", "Congestive heart failure", "I", "heart_failure"),
    ("I639", "Cerebral infarction, unspecified", "I", "stroke"),
    ("J189", "Pneumonia, unspecified", "J", "other"),
    ("J441", "Chronic obstructive pulmonary disease with acute exacerbation", "J", "copd"),
    ("N179", "Acute kidney failure, unspecified", "N", "aki"),
    ("N183", "Chronic kidney disease, stage 3", "N", "ckd"),
    ("N184", "Chronic kidney disease, stage 4", "N", "ckd"),
    ("N185", "Chronic kidney disease, stage 5", "N", "ckd"),
    ("N390", "Urinary tract infection, site not specified", "N", "other"),
    ("A419", "Sepsis, unspecified", "A", "other"),
    ("K358", "Acute appendicitis, other and unspecified", "K", "other"),
    ("R074", "Chest pain, unspecified", "R", "other"),
    ("S720", "Fracture of neck of femur", "S", "other"),
    ("Z491", "Extracorporeal dialysis", "Z", "ckd"),
]

ICD10_CHAPTERS = [
    ("A", "Certain infectious and parasitic diseases (A00-B99)"),
    ("E", "Endocrine, nutritional and metabolic diseases (E00-E90)"),
    ("I", "Diseases of the circulatory system (I00-I99)"),
    ("J", "Diseases of the respiratory system (J00-J99)"),
    ("K", "Diseases of the digestive system (K00-K93)"),
    ("N", "Diseases of the genitourinary system (N00-N99)"),
    ("R", "Symptoms, signs and abnormal findings (R00-R99)"),
    ("S", "Injury, poisoning and certain other consequences of external causes (S00-T98)"),
    ("Z", "Factors influencing health status and contact with health services (Z00-Z99)"),
]

# Interventions: written in the CCI format (section.group.intervention.qualifiers),
# but these are illustrative course codes, not CIHI's official list.
CCI = [
    ("1.PZ.21.^^", 1, "Dialysis (course code)"),
    ("1.IJ.50.^^", 1, "Dilation of coronary arteries (course code)"),
    ("1.VA.53.^^", 1, "Implantation of hip prosthesis (course code)"),
    ("1.NT.87.^^", 1, "Excision of appendix (course code)"),
    ("3.IP.10.^^", 3, "X-ray of heart with coronary arteries (course code)"),
    ("2.PZ.71.^^", 2, "Biopsy of kidney (course code)"),
]

CCI_SECTIONS = [
    (1, "Physical/physiological therapeutic interventions"),
    (2, "Diagnostic interventions"),
    (3, "Diagnostic imaging interventions"),
    (5, "Obstetrical and fetal interventions"),
    (6, "Cognitive, psychosocial and sensory therapeutic interventions"),
    (7, "Other healthcare interventions"),
    (8, "Therapeutic interventions strengthening the immune system and/or genetic composition"),
]

# Case-mix groups: course groups with course resource intensity weights (RIW).
CMG = [
    # cmg, description, mean RIW, mean length of stay (days)
    ("CH01", "Heart failure", 1.45, 7.5),
    ("CH02", "Acute myocardial infarction, with coronary intervention", 2.10, 4.5),
    ("CH03", "Stroke", 2.35, 11.0),
    ("CH04", "COPD exacerbation", 1.20, 6.0),
    ("CH05", "Pneumonia", 1.15, 6.5),
    ("CH06", "Acute kidney injury", 1.30, 6.5),
    ("CH07", "Chronic kidney disease / dialysis complications", 1.60, 7.0),
    ("CH08", "Diabetes with complications", 1.05, 5.0),
    ("CH09", "Sepsis", 2.60, 10.0),
    ("CH10", "Appendectomy", 0.95, 2.5),
    ("CH11", "Hip fracture with replacement", 2.45, 12.0),
    ("CH12", "Chest pain, investigated", 0.55, 1.8),
    ("CH13", "Urinary tract infection", 0.85, 4.5),
]

# Physician fee codes. In Ontario, A001, A003, A007 and K030 follow the
# descriptions of real OHIP codes; all fees, and every code starting with CH or Q,
# are course values only.
FEES = [
    # province, code, description, specialty, fee, source
    ("ON", "A001", "Minor assessment", "family_medicine", 25.00, "OHIP code, course fee"),
    ("ON", "A007", "Intermediate assessment", "family_medicine", 40.00, "OHIP code, course fee"),
    ("ON", "A003", "General assessment", "family_medicine", 90.00, "OHIP code, course fee"),
    ("ON", "K030", "Diabetic management assessment", "family_medicine", 45.00, "OHIP code, course fee"),
    ("ON", "CH101", "Specialist consultation", "specialist", 160.00, "course code"),
    ("ON", "CH102", "Specialist follow-up visit", "specialist", 75.00, "course code"),
    ("ON", "CH103", "Dialysis session supervision", "nephrology", 95.00, "course code"),
    ("QC", "Q0001", "Visite ordinaire (ordinary visit)", "family_medicine", 32.00, "course code"),
    ("QC", "Q0002", "Examen complet (complete examination)", "family_medicine", 85.00, "course code"),
    ("QC", "Q0003", "Suivi de clientèle vulnérable (vulnerable patient follow-up)", "family_medicine", 50.00, "course code"),
    ("QC", "Q0101", "Consultation par un spécialiste (specialist consultation)", "specialist", 150.00, "course code"),
    ("QC", "Q0102", "Visite de suivi, spécialiste (specialist follow-up)", "specialist", 70.00, "course code"),
    ("QC", "Q0103", "Supervision d'hémodialyse (dialysis supervision)", "nephrology", 90.00, "course code"),
]

# Renavex: the course's fictional drug and its (fictional) route to public coverage.
MILESTONES = [
    ("health_canada_noc", "Health Canada issues a Notice of Compliance (market authorization)", "ALL", "2024-05-14"),
    ("cda_submission", "Sponsor files with Canada's Drug Agency (CDA-AMC)", "ALL", "2024-03-25"),
    ("inesss_submission", "Sponsor files with INESSS", "QC", "2024-04-15"),
    ("cda_recommendation", "CDA-AMC recommends: reimburse with conditions and a price reduction", "ALL", "2024-12-10"),
    ("inesss_avis", "INESSS avis: list with conditions (médicament d'exception)", "QC", "2025-02-03"),
    ("pcpa_start", "pCPA negotiation starts", "ALL", "2025-03-03"),
    ("pcpa_loi", "pCPA letter of intent signed", "ALL", "2025-07-22"),
    ("on_listing", "Listed on the Ontario Drug Benefit Formulary (Limited Use)", "ON", "2025-10-01"),
    ("qc_listing", "Listed on RAMQ's List of Medications (exception drug)", "QC", "2026-02-04"),
]

PERSONAS = [
    # persona, province, age, plan, low_income, household_income, note
    ("Margaret", "ON", 72, "ODB-65", 0, 48000, "Retired teacher in Kingston, single"),
    ("Joseph", "ON", 69, "ODB-65L", 1, 19000, "Lives alone in Sudbury on a small pension"),
    ("Priya", "ON", 52, "ON-PRIV", 0, 96000, "Accountant in Mississauga with a workplace plan"),
    ("Daniel", "ON", 58, "ON-NONE", 0, 41000, "Self-employed contractor in London, no drug plan"),
    ("Sylvie", "QC", 74, "RAMQ-PUB", 0, 39000, "Retired nurse in Québec City"),
    ("Karim", "QC", 47, "QC-PRIV", 0, 72000, "Engineer in Laval with a group plan"),
    ("Nathalie", "QC", 55, "RAMQ-PUB", 0, 34000, "Part-time retail worker in Gatineau, no group plan"),
]


# ---------------------------------------------------------------------------
# Cost sharing (the same rules Day 1 asks you to code)
# ---------------------------------------------------------------------------

PLAN = {p[0]: p for p in DRUG_PLANS}


def share_cost(plan_id, total, state, month):
    """Split one prescription's total cost into (patient, plan).

    state carries the year-to-date amounts that deductibles and maximums need:
    {"deductible_paid": {...period: $}, "oop": {...period: $}}.
    """
    _, _, _, _, ded, ded_period, copay, coins, max_oop, max_period, _ = PLAN[plan_id]
    key_d = month if ded_period == "month" else "year"
    key_m = month if max_period == "month" else "year"
    patient = 0.0
    remaining = total
    if ded:
        left = ded - state["ded"].get(key_d, 0.0)
        take = min(max(left, 0.0), remaining)
        state["ded"][key_d] = state["ded"].get(key_d, 0.0) + take
        patient += take
        remaining -= take
    patient += min(copay, remaining) + coins * max(remaining - min(copay, remaining), 0.0)
    if max_oop != "":
        room = max(float(max_oop) - state["oop"].get(key_m, 0.0), 0.0)
        patient = min(patient, room)
    patient = round(patient, 2)
    state["oop"][key_m] = state["oop"].get(key_m, 0.0) + patient
    return patient, round(total - patient, 2)


# ---------------------------------------------------------------------------
# Days 1-3: population and 2024 claims
# ---------------------------------------------------------------------------

def person_id(i):
    return "P" + hashlib.sha256(f"corridor-{SEED}-{i}".encode()).hexdigest()[:10].upper()


def pick(rng, items, weights):
    return rng.choices(items, weights=weights, k=1)[0]


def random_date(rng, a, b):
    return a + dt.timedelta(days=rng.randrange((b - a).days + 1))


def make_days_01_03():
    rng = random.Random(SEED)
    prov_codes = [p[0] for p in PROVINCES]
    prov_w = [p[4] for p in PROVINCES]
    regions = {p: [r for r in REGIONS if r[1] == p] for p in prov_codes}
    bands = [(lo, hi) for lo, hi, _ in AGE_BANDS]
    band_w = [w for _, _, w in AGE_BANDS]
    drug_by_ing = {}
    for d in DRUGS:
        drug_by_ing.setdefault(d[2], []).append(d)

    persons, truth, elig = [], [], []
    phys, hosp, rx = [], [], []
    fee_by = {(f[0], f[1]): f for f in FEES}
    icd9_by_cond = {}
    for c, _, cond in ICD9:
        icd9_by_cond.setdefault(cond, []).append(c)
    n_claim = n_abs = n_rx = 0

    for i in range(N_PEOPLE):
        pid = person_id(i)
        prov = pick(rng, prov_codes, prov_w)
        reg = pick(rng, regions[prov], [r[3] for r in regions[prov]])
        rural = int(rng.random() < reg[4])
        lo, hi = pick(rng, bands, band_w)
        age = rng.randint(lo, hi)  # age on 2024-01-01
        birth = dt.date(YEAR - age - 1, 1, 1) + dt.timedelta(days=rng.randrange(365))
        sex = "F" if rng.random() < 0.51 else "M"
        q = rng.randint(1, 5)
        start = dt.date(2019, 1, 1) if rng.random() > 0.06 else random_date(rng, dt.date(2019, 1, 2), dt.date(2024, 6, 30))
        if birth + dt.timedelta(days=365 * 18 + 5) > start:
            start = max(start, dt.date(birth.year + 18, birth.month, min(birth.day, 28)))
        frailty = rng.lognormvariate(0, 0.45)

        # latent health (hidden truth)
        dm = rng.random() < logistic(-5.3 + 0.056 * age + 0.12 * (3 - q) + (0.15 if sex == "M" else 0))
        dm_year = ""
        if dm:
            dm_year = max(YEAR - int(rng.expovariate(1 / 7)), birth.year + 25)
            dm_year = min(dm_year, YEAR)
        dm_dur = (YEAR - dm_year) if dm else 0
        if dm:
            ckd = rng.random() < logistic(-3.3 + 0.038 * age + 0.06 * dm_dur)
        else:
            ckd = rng.random() < logistic(-8.2 + 0.07 * age)
        ckd_stage = ""
        if ckd:
            ckd_stage = pick(rng, ["3a", "3b", "4", "5"], [50, 28, 15, 7])
        dialysis = ckd_stage == "5" and rng.random() < 0.6
        htn = rng.random() < logistic(-4.7 + 0.066 * age + 0.8 * dm + 0.6 * ckd)
        hf = rng.random() < logistic(-9.0 + 0.08 * age + 0.7 * dm + 0.7 * (ckd_stage in ("4", "5")))
        copd = rng.random() < logistic(-7.6 + 0.062 * age + 0.18 * (3 - q))
        ami = rng.random() < logistic(-9.6 + 0.06 * age + 0.6 * dm + 0.4 * htn) * 0.6
        death_p = logistic(-10.6 + 0.09 * age + 0.6 * hf + 0.5 * (ckd_stage in ("4", "5")) + 0.25 * dm + 0.3 * copd + 0.2 * math.log(frailty + 0.01))
        death = random_date(rng, START, END) if rng.random() < death_p else None
        if death and death < start:
            death = None

        persons.append((pid, prov, reg[0], sex, birth.isoformat(), q, rural, start.isoformat(),
                        death.isoformat() if death else ""))
        truth.append((pid, int(dm), dm_year, ckd_stage, int(dialysis), int(htn), int(hf), int(copd),
                      int(ami), round(frailty, 4)))

        obs_a = max(START, start)
        obs_b = death or END
        if obs_b < obs_a:
            continue
        obs_days = (obs_b - obs_a).days + 1
        frac = obs_days / 366

        # ---- public drug plan eligibility (only public plans appear in admin data)
        cover = []  # (plan, start, end) within the year
        d65 = dt.date(birth.year + 65, birth.month, 1) + dt.timedelta(days=32)
        d65 = d65.replace(day=1)  # first day of the month after the 65th birthday
        if prov == "ON":
            low = rng.random() < (0.45 if q == 1 else 0.20 if q == 2 else 0.04)
            sa = q <= 2 and rng.random() < (0.30 if q == 1 else 0.07)
            private = (not sa) and rng.random() < (0.50 + 0.07 * q)
            if age < 25 and not private and not sa:
                cover.append(("OHIP+", start, dt.date(birth.year + 25, birth.month, 1) - dt.timedelta(days=1)))
            if sa:
                cover.append(("ODB-SA", start, d65 - dt.timedelta(days=1)))
            cover.append(("ODB-65L" if low else "ODB-65", max(d65, start), None))
        else:
            sa = q <= 2 and rng.random() < (0.22 if q == 1 else 0.05)
            private = (not sa) and rng.random() < (0.40 + 0.08 * q)
            if sa:
                cover.append(("RAMQ-SA", start, None))
            else:
                if not private:
                    cover.append(("RAMQ-PUB", start, d65 - dt.timedelta(days=1)))
                if rng.random() < 0.90 or not private:
                    cover.append(("RAMQ-PUB", max(d65, start), None))
        merged = []
        for plan, a, b in cover:
            if (b is not None and b < a) or a > END or (death and a > death):
                continue
            if merged and merged[-1][0] == plan and (merged[-1][2] is not None) and merged[-1][2] + dt.timedelta(days=1) >= a:
                merged[-1] = (plan, merged[-1][1], b)
            else:
                merged.append((plan, a, b))
        for plan, a, b in merged:
            elig.append((pid, plan, a.isoformat(), b.isoformat() if b else ""))

        # ---- physician claims
        visits = []
        base = (1.3 + 0.026 * age) * frailty
        n_general = poisson(rng, base * frac)
        for _ in range(n_general):
            visits.append(("general", "family_medicine"))
        for cond, flag, lam, spec in (
            ("diabetes", dm and dm_year <= YEAR, 3.2, "family_medicine"),
            ("hypertension", htn, 1.4, "family_medicine"),
            ("heart_failure", hf, 2.6, "family_medicine"),
            ("copd", copd, 1.8, "family_medicine"),
            ("ckd", ckd, 1.0, "family_medicine"),
            ("ami", ami, 0.6, "family_medicine"),
        ):
            if flag:
                visits += [(cond, spec)] * poisson(rng, lam * frac)
        if ckd_stage in ("3b", "4", "5") and not dialysis:
            visits += [("ckd", "nephrology")] * poisson(rng, (2.5 if ckd_stage != "3b" else 1.2) * frac)
        if dm and rng.random() < 0.25:
            visits += [("diabetes", "internal_medicine")] * poisson(rng, 1.5 * frac)
        if hf:
            visits += [("heart_failure", "cardiology")] * poisson(rng, 2.0 * frac)
        general_done = False
        for cond, spec in visits:
            day = random_date(rng, obs_a, obs_b)
            if cond == "general":
                dx = rng.choices(icd9_by_cond["general"], weights=GENERAL_DX_WEIGHTS, k=1)[0]
            else:
                dx = icd9_by_cond[cond][0]
            if prov == "ON":
                if spec == "family_medicine":
                    if not general_done and rng.random() < 0.35:
                        code, general_done = "A003", True
                    elif cond == "diabetes" and rng.random() < 0.6:
                        code = "K030"
                    else:
                        code = "A007" if rng.random() < 0.7 else "A001"
                else:
                    code = "CH101" if rng.random() < 0.25 else "CH102"
            else:
                if spec == "family_medicine":
                    if not general_done and rng.random() < 0.35:
                        code, general_done = "Q0002", True
                    elif cond != "general" and rng.random() < 0.5:
                        code = "Q0003"
                    else:
                        code = "Q0001"
                else:
                    code = "Q0101" if rng.random() < 0.25 else "Q0102"
            n_claim += 1
            phys.append((f"C{n_claim:08d}", pid, prov, day.isoformat(), code, dx, spec,
                         money(fee_by[(prov, code)][4])))
        if dialysis:
            code = "CH103" if prov == "ON" else "Q0103"
            d = obs_a + dt.timedelta(days=rng.randrange(3))
            while d <= obs_b:
                if rng.random() < 0.97:
                    n_claim += 1
                    phys.append((f"C{n_claim:08d}", pid, prov, d.isoformat(), code, "585", "nephrology",
                                 money(fee_by[(prov, code)][4])))
                d += dt.timedelta(days=2 if d.weekday() in (0, 2) else 3)

        # ---- hospital discharges
        stays = []
        lam_h = (0.025 + 0.0009 * age) * frailty
        causes = [("other", lam_h)]
        if hf:
            causes.append(("heart_failure", 0.40))
        if copd:
            causes.append(("copd", 0.22))
        if ami:
            causes.append(("ami", 0.10))
        if dm:
            causes.append(("diabetes", 0.04))
        if ckd_stage in ("4", "5"):
            causes.append(("ckd", 0.30))
        if ckd:
            causes.append(("aki", 0.06))
        if htn or dm:
            causes.append(("stroke", 0.008 * (age / 50)))
        for cause, lam in causes:
            stays += [cause] * poisson(rng, lam * frac)
        if death and rng.random() < 0.55:
            stays.append("terminal")
        for cause in stays:
            if cause == "other":
                mrdx, cmg, cci = pick(rng, [("J189", "CH05", ""), ("N390", "CH13", ""), ("A419", "CH09", ""),
                                            ("K358", "CH10", "1.NT.87.^^"), ("R074", "CH12", ""),
                                            ("S720", "CH11", "1.VA.53.^^")],
                                       [28, 20, 10, 8, 22, 12 * (age / 60)])
            elif cause == "terminal":
                mrdx, cmg, cci = pick(rng, [("J189", "CH05", ""), ("A419", "CH09", ""), ("I500", "CH01", ""),
                                            ("I639", "CH03", "")], [3, 3, 2 + 3 * hf, 2])
            else:
                mrdx, cmg, cci = {
                    "heart_failure": ("I500", "CH01", ""),
                    "copd": ("J441", "CH04", ""),
                    "ami": ("I219", "CH02", "1.IJ.50.^^"),
                    "diabetes": ("E112" if ckd else "E119", "CH08", ""),
                    "ckd": ("N185" if ckd_stage == "5" else "N184", "CH07", "1.PZ.21.^^" if dialysis else ""),
                    "aki": ("N179", "CH06", ""),
                    "stroke": ("I639", "CH03", "3.IP.10.^^" if rng.random() < 0.2 else ""),
                }[cause]
            _, _, riw_mean, los_mean = next(c for c in CMG if c[0] == cmg)
            los = max(1, round(rng.gammavariate(2.0, los_mean / 2.0)))
            if cause == "terminal" and death:
                discharge = death
                admit = max(obs_a, death - dt.timedelta(days=los - 1))
                disp = "died"
            else:
                admit = random_date(rng, obs_a, obs_b)
                discharge = admit + dt.timedelta(days=los - 1)
                if death and discharge >= death:
                    discharge, disp = death, "died"
                else:
                    disp = pick(rng, ["home", "home_support", "transfer"], [70, 20, 10])
            los = (discharge - admit).days + 1
            riw = round(riw_mean * (0.55 + 0.45 * los / los_mean) * rng.lognormvariate(0, 0.15), 4)
            sec = []
            if dm and mrdx[:3] != "E11":
                sec.append("E112" if ckd else "E119")
            if ckd and mrdx[:3] != "N18":
                sec.append({"3a": "N183", "3b": "N183", "4": "N184", "5": "N185"}[ckd_stage])
            if htn and mrdx != "I10":
                sec.append("I10")
            while len(sec) < 3:
                sec.append("")
            n_abs += 1
            hosp.append((f"H{n_abs:07d}", pid, prov, admit.isoformat(), discharge.isoformat(), los,
                         mrdx, sec[0], sec[1], sec[2], cci, cmg, f"{riw:.4f}", disp))

        # ---- drug claims (only while covered by a public plan)
        regimen = []
        if dm:
            if rng.random() < 0.85:
                regimen.append("metformin")
            if rng.random() < 0.18 + 0.20 * ckd + 0.15 * hf:
                regimen.append(rng.choice(["empagliflozin", "dapagliflozin"]))
            if rng.random() < 0.18:
                regimen.append("sitagliptin")
            if rng.random() < 0.15:
                regimen.append("gliclazide")
            if rng.random() < 0.08:
                regimen.append("semaglutide")
            if rng.random() < 0.10 + 0.002 * dm_dur * 10:
                regimen.append("insulin glargine")
        if htn or (dm and ckd):
            regimen.append("ramipril" if rng.random() < 0.62 else "amlodipine")
        if (dm and age >= 40 and rng.random() < 0.72) or (ami and rng.random() < 0.85) or (htn and rng.random() < 0.25):
            regimen.append("atorvastatin" if rng.random() < 0.6 else "rosuvastatin")
        if hf and rng.random() < 0.75:
            regimen.append("furosemide")
        if copd:
            regimen.append("salbutamol")
            if rng.random() < 0.55:
                regimen.append("tiotropium")
        if not regimen:
            continue
        supply = 90 if rng.random() < 0.35 else 30
        adherence = min(1.0, rng.betavariate(8, 1.6))
        fills = []
        for ing in regimen:
            prod = drug_by_ing[ing][0] if ing != "metformin" else drug_by_ing[ing][rng.random() < 0.4]
            first = obs_a - dt.timedelta(days=rng.randrange(supply))
            d = first
            while d <= obs_b:
                if d >= obs_a and rng.random() < adherence:
                    fills.append((d, prod))
                d += dt.timedelta(days=supply + rng.choice([-2, -1, 0, 0, 1, 2, 4]))
        fills.sort()
        state = {}
        for d, prod in fills:
            plan = None
            for p, a, b in merged:
                if a <= d and (b is None or d <= b):
                    plan = p
            if plan is None:
                continue
            din, _, _, _, _, _, unit, per_day = prod
            qty = max(1, round(per_day * supply)) if per_day >= 1 else max(1, math.ceil(per_day * supply))
            cost = round(unit * qty, 2)
            mk_rate, fee = PHARMACY[prov]
            markup = round(cost * mk_rate, 2)
            total = round(cost + markup + fee, 2)
            st = state.setdefault(plan, {"ded": {}, "oop": {}})
            patient, payer = share_cost(plan, total, st, d.strftime("%Y-%m"))
            n_rx += 1
            rx.append((f"R{n_rx:08d}", pid, prov, plan, d.isoformat(), din, qty, supply,
                       money(cost), money(markup), money(fee), money(total), money(patient), money(payer)))

    # ---- write
    write("provinces.csv", ["province", "name", "physician_plan", "public_drug_plan", "cost_per_weighted_case"],
          [(p[0], p[1], p[2], p[3], money(p[5])) for p in PROVINCES])
    write("regions.csv", ["region", "province", "name"], [r[:3] for r in REGIONS])
    write("persons.csv", ["person_id", "province", "region", "sex", "birth_date", "income_quintile",
                          "rural", "registry_start", "death_date"], persons)
    write("drug_plan_eligibility.csv", ["person_id", "plan_id", "start_date", "end_date"], elig)
    write("physician_claims_2024.csv", ["claim_id", "person_id", "province", "service_date", "fee_code",
                                         "dx_code", "specialty", "paid_amount"], phys)
    write("hospital_discharges_2024.csv", ["abstract_id", "person_id", "province", "admit_date",
                                            "discharge_date", "los_days", "mrdx", "dx2", "dx3", "dx4",
                                            "main_intervention", "cmg", "riw", "discharge_disposition"], hosp)
    write("drug_claims_2024.csv", ["rx_id", "person_id", "province", "plan_id", "dispense_date", "din",
                                    "quantity", "days_supply", "drug_cost", "markup", "dispensing_fee",
                                    "total_cost", "patient_paid", "plan_paid"], rx)
    write("drug_plans.csv", ["plan_id", "province", "name", "who", "deductible", "deductible_period",
                             "copay_per_rx", "coinsurance", "max_out_of_pocket", "max_period", "public"],
          [(p[0], p[1], p[2], p[3], money(p[4]), p[5], money(p[6]), f"{p[7]:.2f}",
            money(p[8]) if p[8] != "" else "", p[9], p[10]) for p in DRUG_PLANS])
    write("pharmacy_pricing.csv", ["province", "markup_rate", "dispensing_fee"],
          [(k, f"{v[0]:.3f}", money(v[1])) for k, v in PHARMACY.items()])
    write("drugs.csv", ["din", "product", "ingredient", "strength", "form", "atc", "unit_price", "units_per_day"],
          [(d[0], d[1], d[2], d[3], d[4], d[5], f"{d[6]:.4f}", f"{d[7]:.4f}") for d in DRUGS])
    write("atc.csv", ["atc", "level", "name"], ATC)
    write("icd9_dx.csv", ["dx_code", "description", "group"], ICD9)
    write("icd10.csv", ["code", "description", "chapter", "group"], ICD10)
    write("icd10_chapters.csv", ["chapter", "name"], ICD10_CHAPTERS)
    write("cci.csv", ["code", "section", "description"], CCI)
    write("cci_sections.csv", ["section", "name"], CCI_SECTIONS)
    write("cmg.csv", ["cmg", "description", "mean_riw", "mean_los"], CMG)
    write("fee_codes.csv", ["province", "fee_code", "description", "specialty", "fee", "source"],
          [(f[0], f[1], f[2], f[3], money(f[4]), f[5]) for f in FEES])
    write("renavex_milestones.csv", ["milestone", "description", "jurisdiction", "date"], MILESTONES)
    write("personas.csv", ["persona", "province", "age", "plan_id", "low_income", "household_income", "note"],
          PERSONAS)
    write("persons_truth.csv", ["person_id", "diabetes", "diabetes_dx_year", "ckd_stage", "dialysis",
                                "hypertension", "heart_failure", "copd", "ami_history", "frailty"],
          truth, folder=TRUTH)


# ---------------------------------------------------------------------------
# Days 4-6: more years (2019-2023, 2025), people who died before 2024,
# 2025 registry updates and Renavex's first claims (Ontario, from 2025-10-01)
# ---------------------------------------------------------------------------

YEARS_EXTRA = (2019, 2020, 2021, 2022, 2023, 2025)
RENAVEX_ON = dt.date(2025, 10, 1)


def write_gz(name, header, rows):
    """Gzipped CSV with a fixed timestamp, so the bytes never change between runs."""
    import gzip
    import io
    with open(os.path.join(HERE, name), "wb") as raw:
        with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0, compresslevel=6) as gz:
            with io.TextIOWrapper(gz, encoding="utf-8", newline="") as f:
                w = csv.writer(f, lineterminator="\n")
                w.writerow(header)
                w.writerows(rows)


def read_csv_rows(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def first_of_month_after_65(birth):
    d = dt.date(birth.year + 65, birth.month, 1) + dt.timedelta(days=32)
    return d.replace(day=1)


def public_periods(rng, prov, q, age_ref, birth, start):
    """Public drug plan periods (plan, start, end or None), using the Day 1 rules."""
    cover = []
    d65 = first_of_month_after_65(birth)
    if prov == "ON":
        low = rng.random() < (0.45 if q == 1 else 0.20 if q == 2 else 0.04)
        sa = q <= 2 and rng.random() < (0.30 if q == 1 else 0.07)
        private = (not sa) and rng.random() < (0.50 + 0.07 * q)
        if age_ref < 25 and not private and not sa:
            cover.append(("OHIP+", start, dt.date(birth.year + 25, birth.month, 1) - dt.timedelta(days=1)))
        if sa:
            cover.append(("ODB-SA", start, d65 - dt.timedelta(days=1)))
        cover.append(("ODB-65L" if low else "ODB-65", max(d65, start), None))
    else:
        sa = q <= 2 and rng.random() < (0.22 if q == 1 else 0.05)
        private = (not sa) and rng.random() < (0.40 + 0.08 * q)
        if sa:
            cover.append(("RAMQ-SA", start, None))
        else:
            if not private:
                cover.append(("RAMQ-PUB", start, d65 - dt.timedelta(days=1)))
            if rng.random() < 0.90 or not private:
                cover.append(("RAMQ-PUB", max(d65, start), None))
    return [(p, a, b) for p, a, b in cover if b is None or b >= a]


class Person:
    __slots__ = ("pid", "prov", "region", "sex", "birth", "q", "rural", "start", "death", "frailty",
                 "dm", "dm_from", "ckd_stage", "ckd_from", "dialysis_from", "htn", "hf", "copd", "ami",
                 "cover", "renavex_from", "regimen", "supply", "adherence", "met850", "met_other")


DIABETES_INGS = {"metformin", "empagliflozin", "dapagliflozin", "sitagliptin", "gliclazide", "semaglutide",
                 "insulin glargine"}


def draw_regimen(rng, dm, ckd, htn, hf, copd, ami, age):
    """Which drugs a person takes (the Day 1-3 probabilities), whoever pays for them."""
    out = []
    if dm:
        if rng.random() < 0.85:
            out.append("metformin")
        if rng.random() < 0.18 + 0.20 * ckd + 0.15 * hf:
            out.append(rng.choice(["empagliflozin", "dapagliflozin"]))
        if rng.random() < 0.18:
            out.append("sitagliptin")
        if rng.random() < 0.15:
            out.append("gliclazide")
        if rng.random() < 0.08:
            out.append("semaglutide")
        if rng.random() < 0.12:
            out.append("insulin glargine")
    if htn or (dm and ckd):
        out.append("ramipril" if rng.random() < 0.62 else "amlodipine")
    if (dm and age >= 40 and rng.random() < 0.72) or (ami and rng.random() < 0.85) or (htn and rng.random() < 0.25):
        out.append("atorvastatin" if rng.random() < 0.6 else "rosuvastatin")
    if hf and rng.random() < 0.75:
        out.append("furosemide")
    if copd:
        out.append("salbutamol")
        if rng.random() < 0.55:
            out.append("tiotropium")
    return out


def start_dates(rng, ings, dm_from, last_year, start_floor):
    """A start date for each drug; diabetes drugs start after the diagnosis."""
    out = []
    for ing in ings:
        lo = max(start_floor, dm_from.year) if ing in DIABETES_INGS else start_floor
        y = rng.randint(min(lo, last_year), last_year)
        start = dt.date(y, 1, 1) + dt.timedelta(days=rng.randrange(365))
        if ing in DIABETES_INGS and start < dm_from:
            start = dm_from + dt.timedelta(days=rng.randrange(60))
        out.append([ing, start, None])
    return out


def year_claims(rng, p, year, counters, out):
    """One person's physician, hospital and drug records for one calendar year."""
    y0, y1 = dt.date(year, 1, 1), dt.date(year, 12, 31)
    obs_a = max(y0, p.start)
    obs_b = min(y1, p.death) if p.death else y1
    if obs_b < obs_a:
        return
    frac = ((obs_b - obs_a).days + 1) / ((y1 - y0).days + 1)
    age = year - p.birth.year - 1          # age on 1 January, as in Days 1-3
    dm = p.dm and p.dm_from <= obs_b
    ckd = bool(p.ckd_stage) and p.ckd_from <= year
    dialysis = p.dialysis_from is not None and p.dialysis_from <= year
    stage = p.ckd_stage if ckd else ""
    prov = p.prov

    # physician claims
    visits = [("general", "family_medicine")] * poisson(rng, (1.3 + 0.026 * age) * p.frailty * frac)
    for cond, flag, lam in (("diabetes", dm, 3.2), ("hypertension", p.htn, 1.4), ("heart_failure", p.hf, 2.6),
                            ("copd", p.copd, 1.8), ("ckd", ckd, 1.0), ("ami", p.ami, 0.6)):
        if flag:
            visits += [(cond, "family_medicine")] * poisson(rng, lam * frac)
    if stage in ("3b", "4", "5") and not dialysis:
        visits += [("ckd", "nephrology")] * poisson(rng, (2.5 if stage != "3b" else 1.2) * frac)
    if dm and rng.random() < 0.25:
        visits += [("diabetes", "internal_medicine")] * poisson(rng, 1.5 * frac)
    if p.hf:
        visits += [("heart_failure", "cardiology")] * poisson(rng, 2.0 * frac)
    # rule-out visits: a test for diabetes or kidney disease, billed with that code, in people without it
    if not dm and age >= 35 and rng.random() < 0.035 * frac:
        visits.append(("diabetes_ruleout", "family_medicine"))
    if not ckd and (dm or p.htn) and age >= 50 and rng.random() < 0.03 * frac:
        visits.append(("ckd_ruleout", "family_medicine"))
    dx_for = {"diabetes": "250", "hypertension": "401", "heart_failure": "428", "copd": "496", "ckd": "585",
              "ami": "410", "diabetes_ruleout": "250", "ckd_ruleout": "585"}
    general = [c for c, _, g in ICD9 if g == "general"]
    first_general = True
    for cond, spec in visits:
        day = random_date(rng, obs_a, obs_b)
        if cond == "diabetes" and p.dm_from > day:
            day = random_date(rng, max(obs_a, p.dm_from), obs_b)
        dx = rng.choices(general, weights=GENERAL_DX_WEIGHTS, k=1)[0] if cond == "general" else dx_for[cond]
        if prov == "ON":
            if spec == "family_medicine":
                if first_general and rng.random() < 0.35:
                    code, first_general = "A003", False
                elif cond == "diabetes" and rng.random() < 0.6:
                    code = "K030"
                else:
                    code = "A007" if rng.random() < 0.7 else "A001"
            else:
                code = "CH101" if rng.random() < 0.25 else "CH102"
        else:
            if spec == "family_medicine":
                if first_general and rng.random() < 0.35:
                    code, first_general = "Q0002", False
                elif cond != "general" and rng.random() < 0.5:
                    code = "Q0003"
                else:
                    code = "Q0001"
            else:
                code = "Q0101" if rng.random() < 0.25 else "Q0102"
        counters["claim"] += 1
        out["phys"].append((f"C{year}{counters['claim']:07d}", p.pid, prov, day.isoformat(), code, dx, spec,
                            money(FEE_BY[(prov, code)][4])))
    if dialysis:
        code = "CH103" if prov == "ON" else "Q0103"
        d = obs_a + dt.timedelta(days=rng.randrange(3))
        while d <= obs_b:
            if rng.random() < 0.97:
                counters["claim"] += 1
                out["phys"].append((f"C{year}{counters['claim']:07d}", p.pid, prov, d.isoformat(), code, "585",
                                    "nephrology", money(FEE_BY[(prov, code)][4])))
            d += dt.timedelta(days=2 if d.weekday() in (0, 2) else 3)

    # hospital stays
    causes = [("other", (0.025 + 0.0009 * age) * p.frailty)]
    if p.hf:
        causes.append(("heart_failure", 0.40))
    if p.copd:
        causes.append(("copd", 0.22))
    if p.ami:
        causes.append(("ami", 0.10))
    if dm:
        causes.append(("diabetes", 0.04))
    if stage in ("4", "5"):
        causes.append(("ckd", 0.30))
    if ckd:
        causes.append(("aki", 0.06))
    if p.htn or dm:
        causes.append(("stroke", 0.008 * (age / 50)))
    stays = []
    for cause, lam in causes:
        stays += [cause] * poisson(rng, lam * frac)
    died_now = p.death is not None and y0 <= p.death <= y1
    if died_now and rng.random() < 0.55:
        stays.append("terminal")
    for cause in stays:
        if cause == "other":
            mrdx, cmg, cci = pick(rng, [("J189", "CH05", ""), ("N390", "CH13", ""), ("A419", "CH09", ""),
                                        ("K358", "CH10", "1.NT.87.^^"), ("R074", "CH12", ""),
                                        ("S720", "CH11", "1.VA.53.^^")], [28, 20, 10, 8, 22, 12 * (age / 60)])
        elif cause == "terminal":
            mrdx, cmg, cci = pick(rng, [("J189", "CH05", ""), ("A419", "CH09", ""), ("I500", "CH01", ""),
                                        ("I639", "CH03", "")], [3, 3, 2 + 3 * p.hf, 2])
        else:
            mrdx, cmg, cci = {
                "heart_failure": ("I500", "CH01", ""), "copd": ("J441", "CH04", ""),
                "ami": ("I219", "CH02", "1.IJ.50.^^"),
                "diabetes": ("E112" if ckd else "E119", "CH08", ""),
                "ckd": ("N185" if stage == "5" else "N184", "CH07", "1.PZ.21.^^" if dialysis else ""),
                "aki": ("N179", "CH06", ""),
                "stroke": ("I639", "CH03", "3.IP.10.^^" if rng.random() < 0.2 else ""),
            }[cause]
        _, _, riw_mean, los_mean = CMG_BY[cmg]
        los = max(1, round(rng.gammavariate(2.0, los_mean / 2.0)))
        if cause == "terminal":
            discharge, admit, disp = p.death, max(obs_a, p.death - dt.timedelta(days=los - 1)), "died"
        else:
            admit = random_date(rng, obs_a, obs_b)
            discharge = admit + dt.timedelta(days=los - 1)
            if p.death and discharge >= p.death:
                discharge, disp = p.death, "died"
            else:
                disp = pick(rng, ["home", "home_support", "transfer"], [70, 20, 10])
        los = (discharge - admit).days + 1
        riw = round(riw_mean * (0.55 + 0.45 * los / los_mean) * rng.lognormvariate(0, 0.15), 4)
        sec = []
        if dm and mrdx[:3] != "E11":
            sec.append("E112" if ckd else "E119")
        if ckd and mrdx[:3] != "N18":
            sec.append({"3a": "N183", "3b": "N183", "4": "N184", "5": "N185"}[stage])
        if p.htn and mrdx != "I10":
            sec.append("I10")
        sec += [""] * (3 - len(sec))
        counters["abs"] += 1
        out["hosp"].append((f"H{year}{counters['abs']:06d}", p.pid, prov, admit.isoformat(), discharge.isoformat(),
                            los, mrdx, sec[0], sec[1], sec[2], cci, cmg, f"{riw:.4f}", disp))

    # drug claims, only while on a public plan (each person's regimen persists across years)
    regimen = []
    for ing, start, stop_year in p.regimen:
        if start > obs_b or (stop_year is not None and year > stop_year):
            continue
        if ing in DIABETES_INGS and not dm and not (ing == "metformin" and p.met_other):
            continue
        regimen.append((ing, start if start >= obs_a else obs_a, start < obs_a))
    if p.renavex_from and p.renavex_from <= obs_b:
        regimen.append(("renavexiban (fictional)", max(obs_a, p.renavex_from), p.renavex_from < obs_a))
    if not regimen or not p.cover:
        return
    supply, adherence = p.supply, p.adherence
    fills = []
    for ing, from_day, ongoing in regimen:
        prods = DRUG_BY_ING[ing]
        prod = prods[p.met850] if ing == "metformin" else prods[0]
        d = from_day - dt.timedelta(days=rng.randrange(supply)) if ongoing else from_day
        while d <= obs_b:
            if d >= obs_a and rng.random() < adherence:
                fills.append((d, prod))
            d += dt.timedelta(days=supply + rng.choice([-2, -1, 0, 0, 1, 2, 4]))
    fills.sort()
    state = {}
    for d, prod in fills:
        plan = None
        for pl, a, b in p.cover:
            if a <= d and (b is None or d <= b):
                plan = pl
        if plan is None:
            continue
        din, _, _, _, _, _, unit, per_day = prod
        qty = max(1, round(per_day * supply)) if per_day >= 1 else max(1, math.ceil(per_day * supply))
        cost = round(unit * qty, 2)
        mk_rate, fee = PHARMACY[prov]
        markup = round(cost * mk_rate, 2)
        total = round(cost + markup + fee, 2)
        st = state.setdefault(plan, {"ded": {}, "oop": {}})
        patient, payer = share_cost(plan, total, st, d.strftime("%Y-%m"))
        counters["rx"] += 1
        out["rx"].append((f"R{year}{counters['rx']:07d}", p.pid, prov, plan, d.isoformat(), din, qty, supply,
                          money(cost), money(markup), money(fee), money(total), money(patient), money(payer)))


FEE_BY = {(f[0], f[1]): f for f in FEES}
CMG_BY = {c[0]: c for c in CMG}
DRUG_BY_ING = {}
for _d in DRUGS:
    DRUG_BY_ING.setdefault(_d[2], []).append(_d)

PHYS_HEADER = ["claim_id", "person_id", "province", "service_date", "fee_code", "dx_code", "specialty", "paid_amount"]
HOSP_HEADER = ["abstract_id", "person_id", "province", "admit_date", "discharge_date", "los_days", "mrdx", "dx2",
               "dx3", "dx4", "main_intervention", "cmg", "riw", "discharge_disposition"]
RX_HEADER = ["rx_id", "person_id", "province", "plan_id", "dispense_date", "din", "quantity", "days_supply",
             "drug_cost", "markup", "dispensing_fee", "total_cost", "patient_paid", "plan_paid"]


def make_days_04_06():
    d = lambda s: dt.date.fromisoformat(s) if s else None  # noqa: E731
    persons = read_csv_rows(os.path.join(HERE, "persons.csv"))
    truth = {r["person_id"]: r for r in read_csv_rows(os.path.join(TRUTH, "persons_truth.csv"))}
    elig = {}
    for r in read_csv_rows(os.path.join(HERE, "drug_plan_eligibility.csv")):
        elig.setdefault(r["person_id"], []).append((r["plan_id"], d(r["start_date"]), d(r["end_date"])))

    ing_by_din = {x[0]: x[2] for x in DRUGS}
    seen_2024 = {}
    with open(os.path.join(HERE, "drug_claims_2024.csv"), newline="", encoding="utf-8") as f:
        for r in csv.DictReader(f):
            seen_2024.setdefault(r["person_id"], set()).add(ing_by_din[r["din"]])

    rng = random.Random(2004)
    people, history, updates, new_elig, drug_starts = [], [], [], [], []
    for r in persons:
        t = truth[r["person_id"]]
        p = Person()
        p.pid, p.prov, p.region, p.sex = r["person_id"], r["province"], r["region"], r["sex"]
        p.birth, p.q, p.rural = d(r["birth_date"]), int(r["income_quintile"]), int(r["rural"])
        p.start, p.death = d(r["registry_start"]), d(r["death_date"])
        p.frailty = float(t["frailty"])
        p.dm = t["diabetes"] == "1"
        p.dm_from = dt.date(int(t["diabetes_dx_year"]), 1, 1) if p.dm else dt.date(9999, 1, 1)
        if p.dm:  # the diagnosis month within the year
            p.dm_from = p.dm_from + dt.timedelta(days=rng.randrange(365))
        p.ckd_stage = t["ckd_stage"]
        p.ckd_from = rng.randint(max(2014, p.dm_from.year if p.dm else 2014), 2024) if p.ckd_stage else 9999
        p.dialysis_from = rng.randint(max(p.ckd_from, 2017), 2024) if t["dialysis"] == "1" else None
        p.htn, p.hf, p.copd, p.ami = (t[k] == "1" for k in ("hypertension", "heart_failure", "copd", "ami_history"))
        p.cover = elig.get(p.pid, [])
        age25 = 2025 - p.birth.year - 1
        new_dm = False
        if p.death is None:
            # 2025: deaths and new diabetes
            hazard = logistic(-10.6 + 0.09 * age25 + 0.6 * p.hf + 0.5 * (p.ckd_stage in ("4", "5"))
                              + 0.25 * p.dm + 0.3 * p.copd + 0.2 * math.log(p.frailty + 0.01))
            if rng.random() < hazard:
                p.death = random_date(rng, dt.date(2025, 1, 1), dt.date(2025, 12, 31))
                updates.append((p.pid, p.death.isoformat()))
            if not p.dm and rng.random() < logistic(-5.3 + 0.056 * age25 + 0.12 * (3 - p.q)) * 0.19:
                p.dm, new_dm = True, True
                p.dm_from = random_date(rng, dt.date(2025, 1, 1), p.death or dt.date(2025, 12, 31))
            # public plan periods that begin in 2025 (turning 65)
            d65 = first_of_month_after_65(p.birth)
            if dt.date(2025, 1, 1) <= d65 <= dt.date(2025, 12, 31) and (p.death is None or p.death >= d65):
                plan = None
                if p.prov == "ON":
                    plan = "ODB-65L" if rng.random() < (0.45 if p.q == 1 else 0.20 if p.q == 2 else 0.04) else "ODB-65"
                elif not any(pl == "RAMQ-SA" for pl, _, _ in p.cover) and rng.random() < 0.92:
                    plan = "RAMQ-PUB"
                if plan:
                    p.cover = p.cover + [(plan, d65, None)]
                    new_elig.append((p.pid, plan, d65.isoformat(), ""))
        # Renavex (Ontario, listed 2025-10-01): adults with diabetes and CKD 3a-4 on ODB
        p.renavex_from = None
        if (p.prov == "ON" and p.dm and p.ckd_stage in ("3a", "3b", "4") and not new_dm
                and any(a <= dt.date(2025, 12, 31) and (b is None or b >= RENAVEX_ON) for _, a, b in p.cover)
                and rng.random() < 0.16):
            start = random_date(rng, RENAVEX_ON, dt.date(2025, 12, 31))
            if p.death is None or start < p.death:
                p.renavex_from = start
        # drug regimen: what 2024 claims show for people on a public plan, otherwise a fresh draw
        covered_2024 = any(a <= dt.date(2024, 12, 31) and (b is None or b >= max(dt.date(2024, 1, 1), p.start))
                           for _, a, b in elig.get(p.pid, []))
        if covered_2024:
            ings = sorted(seen_2024.get(p.pid, ()))
        else:
            ings = draw_regimen(rng, p.dm and not new_dm, bool(p.ckd_stage), p.htn, p.hf, p.copd, p.ami,
                                2024 - p.birth.year)
        p.regimen = start_dates(rng, ings, p.dm_from if p.dm and not new_dm else dt.date(2012, 1, 1), 2023, 2012)
        for item in p.regimen:                    # 2025: some stop
            if rng.random() < 0.07:
                item[2] = 2024
        if new_dm and rng.random() < 0.7:        # new diagnoses in 2025 mostly start metformin
            p.regimen.append(["metformin", p.dm_from + dt.timedelta(days=rng.randrange(1, 90)), None])
        if p.dm and not new_dm and "empagliflozin" not in ings and "dapagliflozin" not in ings \
                and rng.random() < 0.05 + 0.08 * bool(p.ckd_stage):   # some start an SGLT2 inhibitor in 2025
            p.regimen.append([rng.choice(["empagliflozin", "dapagliflozin"]),
                              random_date(rng, dt.date(2025, 1, 1), dt.date(2025, 12, 31)), None])
        p.supply = 90 if rng.random() < 0.35 else 30
        p.adherence = min(1.0, rng.betavariate(8, 1.6))
        p.met850 = int(rng.random() < 0.4)
        # metformin without diabetes (e.g. polycystic ovary syndrome, prediabetes), started in 2019-2025
        p.met_other = (not p.dm and not covered_2024 and "metformin" not in ings
                       and rng.random() < (0.012 if p.sex == "F" and 2024 - p.birth.year < 45 else 0.004))
        if p.met_other:
            p.regimen.append(["metformin", random_date(rng, dt.date(2019, 1, 1), dt.date(2025, 12, 31)), None])
        for ing, start, _ in p.regimen:
            drug_starts.append((p.pid, ing, start.isoformat()))
        people.append(p)
        history.append((p.pid, p.dm_from.isoformat() if p.dm else "", int(new_dm),
                        p.ckd_from if p.ckd_stage else "", p.dialysis_from or "",
                        p.renavex_from.isoformat() if p.renavex_from else ""))

    # people who died in 2019-2023 (not in persons.csv, which lists people alive on 2024-01-01)
    rng = random.Random(2019)
    prov_codes = [x[0] for x in PROVINCES]
    regions = {pc: [x for x in REGIONS if x[1] == pc] for pc in prov_codes}
    bands = [(lo, hi) for lo, hi, _ in AGE_BANDS]
    deceased, deceased_truth = [], []
    for i in range(N_PEOPLE):
        prov = pick(rng, prov_codes, [x[4] for x in PROVINCES])
        reg = pick(rng, regions[prov], [x[3] for x in regions[prov]])
        lo, hi = pick(rng, bands, [w for _, _, w in AGE_BANDS])
        age19 = rng.randint(lo, hi)
        birth = dt.date(2019 - age19 - 1, 1, 1) + dt.timedelta(days=rng.randrange(365))
        sex = "F" if rng.random() < 0.51 else "M"
        q = rng.randint(1, 5)
        rural = int(rng.random() < reg[4])
        frailty = rng.lognormvariate(0, 0.45)
        dm = rng.random() < logistic(-5.3 + 0.056 * age19 + 0.12 * (3 - q) + (0.15 if sex == "M" else 0))
        dm_year = max(min(2019 - int(rng.expovariate(1 / 7)), 2019), birth.year + 25) if dm else None
        ckd = rng.random() < (logistic(-3.3 + 0.038 * age19 + 0.06 * (2019 - dm_year)) if dm
                              else logistic(-8.2 + 0.07 * age19))
        stage = pick(rng, ["3a", "3b", "4", "5"], [50, 28, 15, 7]) if ckd else ""
        dial = stage == "5" and rng.random() < 0.6
        htn = rng.random() < logistic(-4.7 + 0.066 * age19 + 0.8 * dm + 0.6 * ckd)
        hf = rng.random() < logistic(-9.0 + 0.08 * age19 + 0.7 * dm + 0.7 * (stage in ("4", "5")))
        copd = rng.random() < logistic(-7.6 + 0.062 * age19 + 0.18 * (3 - q))
        ami = rng.random() < logistic(-9.6 + 0.06 * age19 + 0.6 * dm + 0.4 * htn) * 0.6
        death = None
        for year in range(2019, 2024):
            a = year - birth.year - 1
            hz = logistic(-10.6 + 0.09 * a + 0.6 * hf + 0.5 * (stage in ("4", "5")) + 0.25 * dm + 0.3 * copd
                          + 0.2 * math.log(frailty + 0.01))
            if rng.random() < hz:
                death = random_date(rng, dt.date(year, 1, 1), dt.date(year, 12, 31))
                break
        if death is None:
            continue
        p = Person()
        p.pid = "D" + hashlib.sha256(f"corridor-deceased-{SEED}-{i}".encode()).hexdigest()[:10].upper()
        p.prov, p.region, p.sex, p.birth, p.q, p.rural = prov, reg[0], sex, birth, q, rural
        p.start = max(dt.date(2019, 1, 1), dt.date(birth.year + 18, birth.month, min(birth.day, 28)))
        p.death, p.frailty = death, frailty
        p.dm = dm
        p.dm_from = dt.date(dm_year, 1, 1) + dt.timedelta(days=rng.randrange(365)) if dm else dt.date(9999, 1, 1)
        p.ckd_stage = stage
        p.ckd_from = rng.randint(max(2014, dm_year or 2014), 2019) if stage else 9999
        p.dialysis_from = rng.randint(max(p.ckd_from, 2015), 2019) if dial else None
        p.htn, p.hf, p.copd, p.ami = htn, hf, copd, ami
        p.renavex_from = None
        p.cover = [(pl, a, min(b, death) if b else death) for pl, a, b in
                   public_periods(rng, prov, q, age19, birth, p.start) if a <= death]
        for pl, a, b in p.cover:
            new_elig.append((p.pid, pl, a.isoformat(), b.isoformat()))
        ings = draw_regimen(rng, dm, bool(stage), htn, hf, copd, ami, death.year - birth.year)
        p.regimen = [it for it in start_dates(rng, ings, p.dm_from if dm else dt.date(2010, 1, 1), death.year, 2010)
                     if it[1] < death]
        p.supply = 90 if rng.random() < 0.35 else 30
        p.adherence = min(1.0, rng.betavariate(8, 1.6))
        p.met850 = int(rng.random() < 0.4)
        p.met_other = False
        for ing, start, _ in p.regimen:
            drug_starts.append((p.pid, ing, start.isoformat()))
        deceased.append((p.pid, prov, reg[0], sex, birth.isoformat(), q, rural, p.start.isoformat(),
                         death.isoformat()))
        deceased_truth.append((p.pid, int(dm), dm_year or "", stage, int(dial), int(htn), int(hf), int(copd),
                               int(ami), round(frailty, 4)))
        history.append((p.pid, p.dm_from.isoformat() if dm else "", 0, p.ckd_from if stage else "",
                        p.dialysis_from or "", ""))
        people.append(p)

    write("registry_deceased_2019_2023.csv", ["person_id", "province", "region", "sex", "birth_date",
                                               "income_quintile", "rural", "registry_start", "death_date"], deceased)
    write("registry_updates_2025.csv", ["person_id", "death_date"], updates)
    write("drug_plan_eligibility_updates.csv", ["person_id", "plan_id", "start_date", "end_date"], new_elig)
    write("persons_truth_deceased.csv", ["person_id", "diabetes", "diabetes_dx_year", "ckd_stage", "dialysis",
                                         "hypertension", "heart_failure", "copd", "ami_history", "frailty"],
          deceased_truth, folder=TRUTH)
    write("drug_starts.csv", ["person_id", "ingredient", "start_date"], drug_starts, folder=TRUTH)
    write("history.csv", ["person_id", "diabetes_from", "diabetes_new_2025", "ckd_from_year", "dialysis_from_year",
                          "renavex_from"], history, folder=TRUTH)

    for year in YEARS_EXTRA:
        rng = random.Random(SEED * 1000 + year)
        counters = {"claim": 0, "abs": 0, "rx": 0}
        out = {"phys": [], "hosp": [], "rx": []}
        for p in people:
            year_claims(rng, p, year, counters, out)
        write_gz(f"physician_claims_{year}.csv.gz", PHYS_HEADER, out["phys"])
        write_gz(f"hospital_discharges_{year}.csv.gz", HOSP_HEADER, out["hosp"])
        write_gz(f"drug_claims_{year}.csv.gz", RX_HEADER, out["rx"])
        print(f"  {year}: {len(out['phys']):,} physician claims, {len(out['hosp']):,} stays, "
              f"{len(out['rx']):,} drug claims")



# ---------------------------------------------------------------------------
# Days 7-9: prices change - cost per weighted case by year and a health price index
# ---------------------------------------------------------------------------

CPWC_BY_YEAR = {  # course values; the Day 3 provinces.csv value is the 2024 one
    "ON": {2019: 5950.00, 2020: 6080.00, 2021: 6210.00, 2022: 6420.00, 2023: 6630.00, 2024: 6800.00, 2025: 6960.00},
    "QC": {2019: 5620.00, 2020: 5730.00, 2021: 5850.00, 2022: 6050.00, 2023: 6250.00, 2024: 6400.00, 2025: 6560.00},
}
CPI_HEALTH = {2019: 131.4, 2020: 133.2, 2021: 135.9, 2022: 141.3, 2023: 146.1, 2024: 149.8, 2025: 153.4}


def make_days_07_09():
    write("cpwc_by_year.csv", ["province", "year", "cost_per_weighted_case"],
          [(p, y, money(v)) for p, ys in CPWC_BY_YEAR.items() for y, v in ys.items()])
    write("cpi_health.csv", ["year", "index"], [(y, f"{v:.1f}") for y, v in CPI_HEALTH.items()])


# ---------------------------------------------------------------------------
# Days 14-16: the Renavex pivotal trial (time-to-event extract) and a CCHS-style survey
# ---------------------------------------------------------------------------

TRIAL_N = 3000
TRIAL_START, TRIAL_CUT = dt.date(2021, 3, 1), dt.date(2024, 3, 1)
# true hazards, time t in years since randomization
KF_LAMBDA, KF_SHAPE = 0.045, 1.25            # kidney failure: Weibull
KF_BETA = {"renavex": -0.36, "egfr": -0.045, "age": -0.01}
DEATH_A, DEATH_B = 0.022, 0.085              # death before kidney failure: Gompertz a * exp(b t)
DEATH_BETA = {"renavex": -0.12, "egfr": -0.01, "age": 0.075}
DEATH_AFTER_KF = 3.5                         # hazard ratio for death once kidney failure has happened
TRIAL_DROPOUT = 0.03                         # per year, exponential


def _weibull_time(u, lam, k, lp):
    return (-math.log(u) / (lam * math.exp(lp))) ** (1 / k)


def _gompertz_time(u, a, b, lp, t0=0.0):
    """Time of an event with hazard a * exp(lp) * exp(b t), given survival to t0."""
    return math.log(math.exp(b * t0) - b * math.log(u) / (a * math.exp(lp))) / b


def make_trial(rng):
    rows, truth = [], []
    span = (TRIAL_CUT - TRIAL_START).days
    for i in range(TRIAL_N):
        pid = f"T{i + 1:04d}"
        arm = "renavex" if rng.random() < 0.5 else "placebo"
        age = min(85, max(40, round(rng.gauss(66, 9))))
        sex = "M" if rng.random() < 0.62 else "F"
        egfr = round(rng.uniform(25, 60), 1)
        country = pick(rng, ["Canada", "United States", "Europe", "Asia-Pacific", "Latin America"], [18, 30, 30, 14, 8])
        entry = TRIAL_START + dt.timedelta(days=rng.randrange(548))          # 18 months of enrolment
        trt = arm == "renavex"
        lp_kf = KF_BETA["renavex"] * trt + KF_BETA["egfr"] * (egfr - 40) + KF_BETA["age"] * (age - 66)
        lp_d = DEATH_BETA["renavex"] * trt + DEATH_BETA["egfr"] * (egfr - 40) + DEATH_BETA["age"] * (age - 66)
        t_kf = _weibull_time(1 - rng.random(), KF_LAMBDA, KF_SHAPE, lp_kf)
        t_d0 = _gompertz_time(1 - rng.random(), DEATH_A, DEATH_B, lp_d)
        u_after = 1 - rng.random()
        if t_kf < t_d0:
            t_death = _gompertz_time(u_after, DEATH_A, DEATH_B, lp_d + math.log(DEATH_AFTER_KF), t_kf)
        else:
            t_kf, t_death = None, t_d0
        t_drop = rng.expovariate(TRIAL_DROPOUT)
        t_cut = (TRIAL_CUT - entry).days / 365.25
        t_last = min(t_cut, t_drop)

        def date_of(t):
            return entry + dt.timedelta(days=int(t * 365.25))

        kf_seen = t_kf is not None and t_kf <= t_last
        death_seen = t_death <= t_last
        last = date_of(min(t_last, t_death))
        rows.append((pid, arm, age, sex, f"{egfr:.1f}", country, entry.isoformat(),
                     date_of(t_kf).isoformat() if kf_seen else "",
                     date_of(t_death).isoformat() if death_seen else "", last.isoformat(),
                     "died" if death_seen else ("data cut" if t_cut <= t_drop else "withdrew")))
        truth.append((pid, f"{t_kf:.4f}" if t_kf is not None else "", f"{t_death:.4f}"))
    write("renavex_trial.csv", ["patient_id", "arm", "age", "sex", "egfr", "region", "randomized",
                                "kidney_failure_date", "death_date", "last_contact", "end_reason"], rows)
    write("trial_event_times.csv", ["patient_id", "t_kidney_failure", "t_death"], truth, folder=TRUTH)
    print(f"  renavex_trial.csv: {len(rows):,} patients")


CCHS_AREAS, CCHS_AREAS_SAMPLED, CCHS_PER_AREA, CCHS_REPLICATES = 30, 10, 45, 500
CCHS_AGE_GROUPS = [(18, 34), (35, 49), (50, 64), (65, 79), (80, 120)]


def _age_group(age):
    return next(k for k, (lo, hi) in enumerate(CCHS_AGE_GROUPS) if lo <= age <= hi)


def _cchs_weights(resp, base, cells, totals):
    """Nonresponse adjustment within region x age group, then post-stratification to population
    counts by province x age group x sex. `base` holds design weights of everyone sampled."""
    sampled, responded = {}, {}
    for i, w in base.items():
        k = cells[i]["nr"]
        sampled[k] = sampled.get(k, 0.0) + w
        if i in resp:
            responded[k] = responded.get(k, 0.0) + w
    w1 = {i: base[i] * sampled[cells[i]["nr"]] / responded[cells[i]["nr"]] for i in resp if base[i] > 0}
    sums = {}
    for i, w in w1.items():
        sums[cells[i]["ps"]] = sums.get(cells[i]["ps"], 0.0) + w
    return {i: w * totals[cells[i]["ps"]] / sums[cells[i]["ps"]] for i, w in w1.items()}


def make_cchs(rng):
    persons = read_csv_rows(os.path.join(HERE, "persons.csv"))
    truth = {r["person_id"]: r for r in read_csv_rows(os.path.join(TRUTH, "persons_truth.csv"))}
    ref = dt.date(2024, 7, 1)
    regions = [r[0] for r in REGIONS]
    area_u = {(r, a): (rng.gauss(0, 0.6), rng.gauss(0, 0.4)) for r in regions for a in range(CCHS_AREAS)}
    frame, totals = [], {}
    for p in persons:
        if p["death_date"] and dt.date.fromisoformat(p["death_date"]) < ref:
            continue
        if dt.date.fromisoformat(p["registry_start"]) > ref:
            continue
        t = truth[p["person_id"]]
        birth = dt.date.fromisoformat(p["birth_date"])
        age = ref.year - birth.year - ((ref.month, ref.day) < (birth.month, birth.day))
        q, rural, qc = int(p["income_quintile"]), int(p["rural"]), p["province"] == "QC"
        dm = t["diabetes"] == "1" and int(t["diabetes_dx_year"] or 9999) <= 2024
        htn, hf, copd, ckd = t["hypertension"] == "1", t["heart_failure"] == "1", t["copd"] == "1", t["ckd_stage"] != ""
        frailty = float(t["frailty"])
        area = rng.randrange(CCHS_AREAS)
        u1, u2 = area_u[(p["region"], area)]
        # what this person would answer (drawn for everyone, so population values are known exactly)
        dm_self = rng.random() < (0.93 if dm else 0.01)
        htn_self = rng.random() < (0.85 if htn else 0.03)
        provider = rng.random() < logistic(1.3 + 0.03 * (age - 50) - 0.4 * rural - 0.7 * qc + 0.15 * (q - 3) + u1)
        flu = rng.random() < logistic(-1.6 + 0.045 * (age - 50) + 0.6 * provider + 0.1 * (q - 3) + u2)
        latent = (0.02 * (age - 50) + 0.6 * math.log(frailty) + 0.5 * dm + 0.6 * hf + 0.4 * copd + 0.3 * ckd
                  - 0.12 * (q - 3) + math.log(1 / (1 - rng.random()) - 1))
        srh = 1 + sum(latent > c for c in (-0.6, 0.7, 2.0, 3.2))        # 1 excellent ... 5 poor
        respond_p = logistic(0.35 + 0.02 * (age - 50) + 0.15 * (q - 3) - 0.35 * (srh >= 4))
        g = _age_group(age)
        totals[(p["province"], g, p["sex"])] = totals.get((p["province"], g, p["sex"]), 0) + 1
        frame.append({"pid": p["person_id"], "region": p["region"], "province": p["province"], "area": area,
                      "age": age, "g": g, "sex": p["sex"], "q": q, "rural": rural,
                      "dm": int(dm_self), "htn": int(htn_self), "provider": int(provider), "flu": int(flu),
                      "srh": srh, "rp": respond_p})
    # stage 1: 10 of 30 areas per region; stage 2: 45 people per sampled area
    by_area = {}
    for k, f in enumerate(frame):
        by_area.setdefault((f["region"], f["area"]), []).append(k)
    sampled, base, psu = [], {}, {}
    for r in regions:
        for a in sorted(rng.sample(range(CCHS_AREAS), CCHS_AREAS_SAMPLED)):
            people = by_area[(r, a)]
            take = rng.sample(people, min(CCHS_PER_AREA, len(people)))
            for k in sorted(take):
                sampled.append(k)
                base[k] = (CCHS_AREAS / CCHS_AREAS_SAMPLED) * len(people) / len(take)
                psu[k] = (r, a)
    resp = {k for k in sampled if rng.random() < frame[k]["rp"]}
    cells = {k: {"nr": (frame[k]["region"], frame[k]["g"]),
                 "ps": (frame[k]["province"], frame[k]["g"], frame[k]["sex"])} for k in sampled}
    final = _cchs_weights(resp, base, cells, totals)
    # Rao-Wu rescaled bootstrap: in each region draw n-1 of its n sampled areas with replacement
    reps = []
    for _ in range(CCHS_REPLICATES):
        mult = {}
        for r in regions:
            areas = sorted({psu[k][1] for k in sampled if psu[k][0] == r})
            n = len(areas)
            draws = [rng.choice(areas) for _ in range(n - 1)]
            for a in areas:
                mult[(r, a)] = draws.count(a) * n / (n - 1)
        bw = {k: base[k] * mult[psu[k]] for k in sampled}
        reps.append(_cchs_weights(resp, bw, cells, totals))
    order = sorted(resp, key=lambda k: frame[k]["pid"])
    ids = {k: f"R{n + 1:05d}" for n, k in enumerate(rng.sample(order, len(order)))}   # no link to person_id
    order = sorted(order, key=lambda k: ids[k])
    labels = ["18-34", "35-49", "50-64", "65-79", "80+"]
    write("cchs_2024.csv", ["resp_id", "province", "region", "age_group", "sex", "income_quintile", "rural",
                            "diabetes", "high_blood_pressure", "regular_provider", "flu_shot_past_year",
                            "self_rated_health", "wts_m"],
          [(ids[k], frame[k]["province"], frame[k]["region"], labels[frame[k]["g"]], frame[k]["sex"],
            frame[k]["q"], frame[k]["rural"], frame[k]["dm"], frame[k]["htn"], frame[k]["provider"],
            frame[k]["flu"], frame[k]["srh"], f"{final[k]:.4f}") for k in order])
    write_gz("cchs_2024_bootstrap.csv.gz", ["resp_id"] + [f"bsw{b + 1}" for b in range(CCHS_REPLICATES)],
             [[ids[k]] + [f"{rep.get(k, 0.0):.4f}" for rep in reps] for k in order])
    # truth: the population values, the design and everyone's answers (for a repeated-sampling check)
    pops = []
    for prov in ("ON", "QC", "All"):
        fr = [f for f in frame if prov == "All" or f["province"] == prov]
        pops.append((prov, len(fr)) + tuple(f"{sum(f[v] for f in fr) / len(fr):.6f}" for v in ("dm", "htn", "provider", "flu"))
                    + (f"{sum(f['srh'] >= 4 for f in fr) / len(fr):.6f}",))
    write("cchs_population_values.csv", ["province", "adults", "diabetes", "high_blood_pressure", "regular_provider",
                                         "flu_shot_past_year", "fair_or_poor_health"], pops, folder=TRUTH)
    write_gz("truth/cchs_frame.csv.gz", ["person_id", "province", "region", "area", "age_group", "sex", "diabetes",
                                         "high_blood_pressure", "regular_provider", "flu_shot_past_year",
                                         "self_rated_health", "response_probability"],
             [(f["pid"], f["province"], f["region"], f["area"], labels[f["g"]], f["sex"], f["dm"], f["htn"],
               f["provider"], f["flu"], f["srh"], f"{f['rp']:.4f}") for f in frame])
    print(f"  cchs_2024.csv: {len(order):,} respondents of {len(sampled):,} sampled; {CCHS_REPLICATES} bootstrap weights")


def make_days_14_16():
    rng = random.Random(SEED + 14)
    make_trial(rng)
    make_cchs(rng)


# ---------------------------------------------------------------------------
# Days 17-19: Renavex trial visits - EQ-5D-5L, a kidney symptom score and 12-month costs, with gaps
# ---------------------------------------------------------------------------

EQ_SHIFT = {"mo": 0.0, "sc": -0.9, "ua": -0.3, "pd": 0.45, "ad": -0.15}
EQ_CUTS = (0.35, 1.35, 2.35, 3.2)
RENAVEX_PRICE = 2400.0      # course list price per patient-year
DIALYSIS_YEAR = 60000.0     # course cost of a year of dialysis


def make_days_17_19():
    rng = random.Random(SEED + 17)
    trial = read_csv_rows(os.path.join(HERE, "renavex_trial.csv"))
    times = {r["patient_id"]: r for r in read_csv_rows(os.path.join(TRUTH, "trial_event_times.csv"))}
    seen, full = [], []
    for p in trial:
        tt = times[p["patient_id"]]
        t_kf = float(tt["t_kidney_failure"]) if tt["t_kidney_failure"] else None
        t_death = float(tt["t_death"])
        age, egfr, trt = int(p["age"]), float(p["egfr"]), p["arm"] == "renavex"
        entry = dt.date.fromisoformat(p["randomized"])
        last = dt.date.fromisoformat(p["last_contact"])
        u = rng.gauss(0, 0.8)                        # the person's own level of health (stable)
        z_prev = None
        for month in (0, 12, 24):
            t = month / 12
            if t >= t_death:
                break
            kf_now = t_kf is not None and t_kf <= t
            z = (0.35 + 0.03 * (age - 66) - 0.02 * (egfr - 40) + u + 0.15 * t - 0.08 * trt * t
                 + 1.1 * kf_now + rng.gauss(0, 0.45))
            levels = [1 + sum(z + EQ_SHIFT[d] + rng.gauss(0, 0.6) > c for c in EQ_CUTS) for d in EQ_SHIFT]
            kss = min(100.0, max(0.0, 74 - 10 * z + rng.gauss(0, 7)))
            cost = ""
            if month:
                a, b = t - 1, t
                on_dialysis = 0.0 if t_kf is None else max(0.0, min(b, t_death) - max(a, t_kf))
                stays = poisson(rng, max(0.0, 0.18 + 0.12 * z))
                c = (900 + 350 * max(z, 0) + (RENAVEX_PRICE if trt else 0) + DIALYSIS_YEAR * on_dialysis
                     + sum(rng.gammavariate(2.0, 4500) for _ in range(stays)))
                cost = round(c * rng.lognormvariate(0, 0.25), 2)
            date = entry + dt.timedelta(days=round(month * 30.44))
            row = [p["patient_id"], month, date.isoformat(), *levels, f"{kss:.1f}", cost]
            full.append(row)
            if date <= last:                         # visit happened before follow-up ended
                prev = z if z_prev is None else z_prev
                miss_q = month > 0 and rng.random() < logistic(-2.3 + 0.75 * prev + 0.35 * z + 0.5 * kf_now)
                miss_c = month > 0 and rng.random() < logistic(-2.6 + 0.6 * prev + 0.4 * kf_now)
                out = row[:3] + ([""] * 6 if miss_q else row[3:9]) + ["" if miss_c else row[9]]
                seen.append(out)
            z_prev = z
    head = ["patient_id", "visit_month", "visit_date", "mo", "sc", "ua", "pd", "ad", "kss", "cost_12m"]
    write("renavex_trial_visits.csv", head, seen)
    write("trial_visits_complete.csv", head, full, folder=TRUTH)
    print(f"  renavex_trial_visits.csv: {len(seen):,} visits")


# ---------------------------------------------------------------------------
# Days 21-30: the Renavex real-world extract, 2026-2028 (labs, dispensations, outcomes)
# ---------------------------------------------------------------------------

RWE_START, RWE_MONTHS = dt.date(2026, 1, 1), 36
QC_LISTING = dt.date(2026, 2, 4)
RWE_EFFECTS = {"renavex_kf": 0.75, "renavex_slope": 0.6, "renavex_death": 0.89,
               "sglt2_kf": 0.85, "sglt2_slope": 0.8}       # hazard ratios / multipliers of eGFR decline
STATIC = ("never", "renavex", "sglt2", "renavex_itt")
SEQ_TRIALS, SEQ_FOLLOW = 12, 24                            # monthly trials Jan-Dec 2026, 24 months each


def _month_first(m):
    return dt.date(RWE_START.year + (RWE_START.month - 1 + m) // 12, (RWE_START.month - 1 + m) % 12 + 1, 1)


def _month_date(rng, m):
    return _month_first(m) + dt.timedelta(days=rng.randrange(28))


def _last_lab(x, path, m):
    """The most recent eGFR result before month m (true value then + measurement error), and its age."""
    past = [lm for lm in x["lab_months"] if lm < m]
    if not past:
        return None, None
    lm = past[-1]
    true = x["egfr0"] + x["slope"] * (-lm) / 12 if lm < 0 else path[lm]
    return true + x["noise"][lm], m - lm


def _rwe_course(u, x, strategy, k=None):
    """One person's 36 months under a strategy, driven by pre-drawn uniforms u (the same luck under
    every strategy). Strategies: 'observed' (the initiation and stopping rules of routine care),
    'never', 'renavex' (from month 0, never stop), 'sglt2', 'renavex_itt' (start at month 0, stop as
    in routine care), and ('start', k) / ('no_start', k): routine care, except that Renavex is (or is
    not) started at month k. Returns kf month, death month, the eGFR path and the log of actions."""
    egfr, slope = x["egfr0"], x["slope"]
    ren, sg = x["ren0"], x["sglt0"]
    kf = death = None
    path, log = [], []
    for m in range(RWE_MONTHS):
        r = u[m]
        path.append(egfr)
        routine = strategy in ("observed", "start", "no_start")
        if strategy == "never":
            ren = False
        elif strategy == "renavex":
            ren = True
        elif strategy == "sglt2":
            ren, sg = False, True
        elif strategy == "renavex_itt":
            if m == 0:
                ren = True
            elif ren and r["stop"] < (0.012 + 0.01 * (egfr < 20)):
                ren = False
        if routine:
            lab, _ = _last_lab(x, path, m)
            lab = egfr if lab is None else lab
            listed = x["province"] == "ON" or _month_first(m) >= QC_LISTING
            p_start = logistic(-5.8 + 0.07 * (45 - lab) + 0.9 * x["a3"] + 0.6 * x["neph"] + x["pref"] + 0.3 * sg
                               - 0.02 * (x["age"] - 70) - 0.7 * (x["frailty"] > 1.6) + 0.025 * m)
            start = not ren and listed and kf is None and r["start"] < p_start
            if m == k and not ren and kf is None:
                start = strategy == "start"
            if start:
                ren = True
                log.append(("start_renavex", m))
            elif ren and m != k and r["stop"] < (0.012 + 0.01 * (egfr < 20)):
                ren = False
                log.append(("stop_renavex", m))
            if not sg and kf is None and r["sg"] < logistic(-5.6 + 0.04 * (45 - lab) + 0.5 * x["a3"] + 0.4 * x["neph"]
                                                            + 0.6 * x["pref"] - 0.5 * ren):
                sg = True
                log.append(("start_sglt2", m))
        mult = (RWE_EFFECTS["renavex_slope"] if ren else 1) * (RWE_EFFECTS["sglt2_slope"] if sg else 1)
        egfr = egfr - slope * mult / 12
        if kf is None:
            h = 0.0012 * math.exp(0.18 * (30 - egfr)) * (RWE_EFFECTS["renavex_kf"] if ren else 1) \
                * (RWE_EFFECTS["sglt2_kf"] if sg else 1)
            if r["kf"] < 1 - math.exp(-h):
                kf = m
        hd = x["death_m"] * (3.5 if kf is not None else 1) * (RWE_EFFECTS["renavex_death"] if ren else 1) \
            * math.exp(0.02 * max(0, 40 - egfr))
        if r["death"] < 1 - math.exp(-hd):
            death = m
            break
        if r["hosp"] < 1 - math.exp(-x["hosp_m"] * (2.0 if kf is not None else 1)):
            log.append(("hospitalization", m))
    return kf, death, path, log


def _eligible_seq(x, path, log, kf, death, k):
    """Truth for the sequential trials: alive, no kidney failure and never on Renavex at the start of
    month k, with an eGFR of 25-60 measured in the previous 12 months."""
    if (death is not None and death < k) or (kf is not None and kf < k) or x["ren0"]:
        return False
    if any(kind == "start_renavex" and mm < k for kind, mm in log):
        return False
    lab, age_months = _last_lab(x, path, k)
    return lab is not None and age_months <= 12 and 20 <= lab <= 60


def make_days_21_30():
    rng = random.Random(SEED + 21)
    persons = {r["person_id"]: r for r in read_csv_rows(os.path.join(HERE, "persons.csv"))}
    truth = {r["person_id"]: r for r in read_csv_rows(os.path.join(TRUTH, "persons_truth.csv"))}
    hist = {r["person_id"]: r for r in read_csv_rows(os.path.join(TRUTH, "history.csv"))}
    died25 = {r["person_id"] for r in read_csv_rows(os.path.join(HERE, "registry_updates_2025.csv"))}
    sglt = {r["person_id"] for r in read_csv_rows(os.path.join(TRUTH, "drug_starts.csv"))
            if r["ingredient"] in ("empagliflozin", "dapagliflozin") and r["start_date"] <= "2025-12-31"}
    regions = [r[0] for r in REGIONS]
    prescribers = {reg: [(f"DR{reg.replace('-', '')}{k:02d}", rng.gauss(0, 0.8)) for k in range(25)] for reg in regions}
    people, labs, disp, events, truth_rows, static_rows, seq_rows = [], [], [], [], [], [], []
    for pid in sorted(persons):
        p, t = persons[pid], truth[pid]
        if p["death_date"] or pid in died25 or t["diabetes"] != "1" or t["ckd_stage"] not in ("3a", "3b", "4") \
                or hist[pid]["dialysis_from_year"]:
            continue
        age = 2026 - dt.date.fromisoformat(p["birth_date"]).year - 1
        stage = t["ckd_stage"]
        lo, hi = {"3a": (45, 59.9), "3b": (30, 44.9), "4": (15, 29.9)}[stage]
        egfr0 = rng.uniform(lo, hi)
        a3 = rng.random() < {"3a": 0.15, "3b": 0.25, "4": 0.40}[stage]
        slope = max(0.0, 1.0 + 1.2 * (stage != "3a") + 1.3 * a3 + rng.gauss(0, 0.8))
        frailty = float(t["frailty"])
        neph = rng.random() < {"3a": 0.15, "3b": 0.45, "4": 0.85}[stage]
        doc, pref = rng.choice(prescribers[p["region"]])
        death_y = logistic(-10.6 + 0.09 * age + 0.6 * (t["heart_failure"] == "1") + 0.25
                           + 0.3 * (t["copd"] == "1") + 0.2 * math.log(frailty + 0.01))
        lab_months, m = [], -24 + rng.randrange(6)
        while m < RWE_MONTHS:
            lab_months.append(m)
            m += rng.choice([3, 4, 6]) if egfr0 < 30 or neph else rng.choice([4, 6, 9])
        x = {"egfr0": egfr0, "slope": slope, "a3": a3, "neph": neph, "pref": pref, "age": age, "frailty": frailty,
             "province": p["province"], "ren0": bool(hist[pid]["renavex_from"]), "sglt0": pid in sglt,
             "death_m": -math.log(1 - death_y) / 12,
             "hosp_m": 0.012 * frailty * (1.6 if t["heart_failure"] == "1" else 1),
             "lab_months": lab_months, "noise": {lm: rng.gauss(0, 3.5) for lm in lab_months}}
        u = [{k: rng.random() for k in ("start", "stop", "sg", "kf", "death", "hosp")} for _ in range(RWE_MONTHS)]
        kf, death, path, log = _rwe_course(u, x, "observed")
        end_m = death if death is not None else RWE_MONTHS
        for lm in lab_months:
            if lm < end_m and (kf is None or lm <= kf):
                val, _ = _last_lab(x, path, lm + 1)
                day = _month_date(rng, lm) if lm >= 0 else \
                    dt.date(2026 + lm // 12, lm % 12 + 1, 1) + dt.timedelta(days=rng.randrange(28))
                labs.append((pid, day.isoformat(), "egfr", f"{max(5.0, val):.1f}"))
                if lab_months.index(lm) % 3 == 0:
                    uacr = math.exp(rng.gauss(math.log(60 if a3 else 12), 0.6))
                    labs.append((pid, day.isoformat(), "uacr", f"{uacr:.1f}"))
        starts = {"renavex": 0 if x["ren0"] else None, "sglt2": None}
        for kind, mm in log:
            if kind == "start_renavex":
                starts["renavex"] = mm
            elif kind == "stop_renavex":
                for m3 in range(starts["renavex"], mm, 3):
                    disp.append((pid, _month_date(rng, m3).isoformat(), "renavex", 90, doc))
                starts["renavex"] = None
            elif kind == "start_sglt2":
                starts["sglt2"] = mm
            elif kind == "hospitalization":
                events.append((pid, _month_date(rng, mm).isoformat(), "hospitalization"))
        for drug in ("renavex", "sglt2"):
            if starts[drug] is not None:
                for m3 in range(starts[drug], end_m, 3):
                    disp.append((pid, _month_date(rng, m3).isoformat(), drug, 90, doc))
        if kf is not None:
            events.append((pid, _month_date(rng, kf).isoformat(), "kidney_failure"))
        if death is not None:
            events.append((pid, _month_date(rng, death).isoformat(), "death"))
        people.append((pid, doc, int(neph), hist[pid]["renavex_from"] or ""))
        truth_rows.append((pid, f"{egfr0:.2f}", f"{slope:.3f}", int(a3), f"{pref:.3f}", f"{frailty:.4f}",
                           int(x["sglt0"]), "" if kf is None else kf, "" if death is None else death))
        # counterfactual courses with the same random numbers
        for sname in STATIC:
            kf_s, death_s, _, _ = _rwe_course(u, x, sname)
            static_rows.append((pid, sname, "" if kf_s is None else kf_s, "" if death_s is None else death_s))
        for k in range(SEQ_TRIALS):
            if not _eligible_seq(x, path, log, kf, death, k):
                continue
            started = any(kind == "start_renavex" and mm == k for kind, mm in log)
            out = []
            for sname in ("start", "no_start"):
                kf_s, death_s, _, _ = _rwe_course(u, x, sname, k)
                out += [int(kf_s is not None and kf_s < k + SEQ_FOLLOW), int(death_s is not None and death_s < k + SEQ_FOLLOW)]
            seq_rows.append((pid, k, int(started), *out))
    write("rwe_persons.csv", ["person_id", "usual_prescriber", "nephrology_care", "renavex_start_2025"], people)
    write("rwe_labs.csv", ["person_id", "lab_date", "test", "value"], sorted(labs))
    write("rwe_dispensations.csv", ["person_id", "dispense_date", "drug", "days_supply", "prescriber_id"], sorted(disp))
    write("rwe_events.csv", ["person_id", "event_date", "event"], sorted(events))
    write("rwe_truth.csv", ["person_id", "egfr0", "slope", "uacr_a3", "prescriber_pref", "frailty",
                            "sglt2_before_2026", "kf_month", "death_month"], truth_rows, folder=TRUTH)
    write("rwe_strategies.csv", ["person_id", "strategy", "kf_month", "death_month"], static_rows, folder=TRUTH)
    write("rwe_sequential_truth.csv", ["person_id", "trial", "started", "kf24_start", "death24_start",
                                       "kf24_no_start", "death24_no_start"], seq_rows, folder=TRUTH)
    print(f"  rwe extract: {len(people):,} people, {len(labs):,} lab results, {len(disp):,} dispensations, "
          f"{len(events):,} events")


def make_days_27_29():
    """Day 28: a chart-review substudy that measured frailty (Clinical Frailty Scale >= 5) in a random 1,000
    of the RWE extract's people, with the misclassification of a real chart review (sensitivity 0.85,
    specificity 0.95). Reads the truth file written by make_days_21_30, so it runs after it."""
    rng = random.Random(SEED + 27)
    with open(os.path.join(TRUTH, "rwe_truth.csv"), encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    sample = sorted(rng.sample([r["person_id"] for r in rows], 1000))
    frail = {r["person_id"]: float(r["frailty"]) > 1.6 for r in rows}
    out = []
    for pid in sample:
        u = rng.random()
        out.append((pid, int(u < 0.85) if frail[pid] else int(u < 0.05)))
    write("rwe_frailty_substudy.csv", ["person_id", "frail_cfs5"], out)
    print(f"  frailty substudy: {len(out):,} people, {sum(r[1] for r in out)} recorded as frail")


POLICY_MONTHS = 84                          # January 2021 to December 2027
CLINIC_ROLLOUT = {"ON-TOR": ("2023-10-01", 1.4), "ON-EST": ("2024-07-01", 1.2), "QC-06": ("2024-07-01", 1.2),
                  "ON-CEN": ("2025-04-01", 1.0), "QC-16": ("2025-04-01", 1.0), "QC-03": ("2026-01-01", 0.8),
                  "ON-WST": ("2026-10-01", 0.6)}
SEASON = {1: 0.88, 7: 0.93, 8: 0.90, 12: 0.94}


def make_days_31_33():
    """Module 4: a monthly regional panel of drug use and kidney testing among adults with diabetes
    (like NPDUIS / CIHI aggregate tables), 2021-2027, and the rollout dates of regional kidney care clinics.
    The aggregate tables cover each region's whole population (40 times the person-level sample's count).
    Truth: expected rates per 1,000 under what happened and under no listing / no clinic."""

    def count(lam):                              # Poisson; normal approximation for the large regional counts
        return poisson(rng, lam) if lam < 500 else max(0, round(rng.gauss(lam, math.sqrt(lam))))

    rng = random.Random(SEED + 31)
    with open(os.path.join(HERE, "regions.csv"), encoding="utf-8") as f:
        regions = [(r["region"], r["province"]) for r in csv.DictReader(f)]
    dm = {}
    with open(os.path.join(TRUTH, "persons_truth.csv"), encoding="utf-8") as f:
        diabetic = {r["person_id"] for r in csv.DictReader(f) if r["diabetes"] == "1"}
    with open(os.path.join(HERE, "persons.csv"), encoding="utf-8") as f:
        for r in csv.DictReader(f):
            if r["person_id"] in diabetic:
                dm[r["region"]] = dm.get(r["region"], 0) + 1
    listing = {"ON": 57, "QC": 61}               # October 2025, February 2026
    rows, truth = [], []
    for region, prov in regions:
        f_s, f_r, f_u = (math.exp(rng.gauss(0, 0.1)), math.exp(rng.gauss(0, 0.1)), math.exp(rng.gauss(0, 0.08)))
        clinic = CLINIC_ROLLOUT.get(region)
        c = None if clinic is None else (int(clinic[0][:4]) - 2021) * 12 + int(clinic[0][5:7]) - 1
        e_s = e_u = 0.0
        for m in range(POLICY_MONTHS):
            month = f"{2021 + m // 12}-{m % 12 + 1:02d}-01"
            season = SEASON.get(m % 12 + 1, 1.0)
            e_s = 0.5 * e_s + rng.gauss(0, 0.06)
            e_u = 0.5 * e_u + rng.gauss(0, 0.04)
            n = round(40 * dm[region] * 1.0025 ** (m - 36))
            ramp = 1 - math.exp(-(m - listing[prov] + 1) / 4) if m >= listing[prov] else 0.0
            sglt2_cf = ((4.0 if prov == "ON" else 3.0) + 0.04 * m) * f_s * season * math.exp(e_s)
            sglt2 = sglt2_cf * (1 - 0.15 * ramp)
            renavex = 1.6 * ramp * f_r * season
            uacr_cf = ((36.5 if prov == "ON" else 29.5) + 0.06 * m) * f_u * season * math.exp(e_u)
            uacr = uacr_cf + (0.0 if c is None or m < c else (2 + 0.5 * min(m - c, 23)) * clinic[1] * season)
            rows.append((region, prov, month, n, count(sglt2 * n / 1000), count(renavex * n / 1000),
                         count(uacr * n / 1000)))
            truth.append((region, month, f"{sglt2:.4f}", f"{sglt2_cf:.4f}", f"{renavex:.4f}", f"{uacr:.4f}", f"{uacr_cf:.4f}"))
    write("drug_utilization_monthly.csv", ["region", "province", "month", "people_with_diabetes", "sglt2_starts",
                                           "renavex_starts", "uacr_tests"], rows)
    write("kidney_clinic_rollout.csv", ["region", "clinic_opened"],
          [(r, CLINIC_ROLLOUT[r][0] if r in CLINIC_ROLLOUT else "") for r, _ in regions])
    write("policy_truth.csv", ["region", "month", "sglt2_rate", "sglt2_rate_no_listing", "renavex_rate",
                               "uacr_rate", "uacr_rate_no_clinic"], truth, folder=TRUTH)
    print(f"  policy panel: {len(rows)} region-months, {sum(1 for r in regions if r[0] in CLINIC_ROLLOUT)} clinics")


SC_PROVINCES = {"BC": 450_000, "AB": 330_000, "SK": 100_000, "MB": 110_000, "ON": 1_400_000, "QC": 850_000,
                "NB": 80_000, "NS": 90_000, "PE": 15_000, "NL": 60_000}           # adults with diabetes
SC_QUARTERS = 48                            # 2016 Q1 to 2027 Q4
SC_POLICIES = {"ON": 32, "SK": 38}          # continuous glucose monitor coverage: ON 2024 Q1, SK 2025 Q3


def make_days_34_36():
    """Module 4, Days 34-36 (course scenarios, invented):
    - provincial_diabetes_quarterly.csv: 10 provinces x 48 quarters, ED visits for glycemic emergencies among
      adults with diabetes. Ontario starts covering continuous glucose monitors (CGM) in 2024 Q1;
      Saskatchewan does the same in 2025 Q3. Rates follow a factor model; Ontario's loadings are a mix of
      BC, SK and NS.
    - young_adults_t1d_2024.csv: person-months in 2024 for young adults (21-29) with type 1 diabetes in
      Ontario and Quebec: public drug coverage, insulin fills, ED visits for DKA. Ontario's OHIP+ covers
      people under 25 without a private plan; Quebec's public plan covers anyone without one at any age.
    Truth: expected values under each scenario."""
    rng = random.Random(SEED + 34)
    # --- synthetic control panel
    load = {}
    for prov in SC_PROVINCES:
        load[prov] = (rng.uniform(3.6, 6.4), rng.uniform(0.5, 1.5), rng.uniform(-0.6, 0.6), rng.uniform(0.6, 1.4))
    mix = {"BC": 0.4, "SK": 0.35, "NS": 0.25}
    load["ON"] = tuple(sum(w * load[k][j] for k, w in mix.items()) for j in range(4))
    rows, truth = [], []
    for prov, n in SC_PROVINCES.items():
        a, b, c, d = load[prov]
        e = 0.0
        for q in range(SC_QUARTERS):
            year, qq = 2016 + q // 4, q % 4 + 1
            f1 = -0.025 * q                                       # slow improvement in care
            f2 = math.sin(2 * math.pi * q / 20)                   # a five-year cycle
            covid = -0.9 if 17 <= q <= 20 else 0.0                # 2020 Q2 - 2021 Q1: people stayed away
            e = 0.4 * e + rng.gauss(0, 0.04)
            season = {1: 0.15, 2: -0.05, 3: -0.15, 4: 0.05}[qq]
            cf = max(0.5, a + b * f1 + c * f2 + d * covid + season + e)
            g = SC_POLICIES.get(prov)
            ramp = 0.0 if g is None or q < g else 1 - math.exp(-(q - g + 1) / 3)
            rate = cf * (1 - 0.12 * ramp)
            visits = max(0, round(rng.gauss(rate * n / 1000, math.sqrt(rate * n / 1000))))
            rows.append((prov, f"{year}Q{qq}", n, visits))
            truth.append((prov, f"{year}Q{qq}", f"{rate:.4f}", f"{cf:.4f}"))
    write("provincial_diabetes_quarterly.csv", ["province", "quarter", "adults_with_diabetes", "glycemic_ed_visits"], rows)
    write("cgm_policy_truth.csv", ["province", "quarter", "rate_per_1000", "rate_no_cgm_policy"], truth, folder=TRUTH)
    # --- OHIP+ young adults
    rows, truth = [], []
    for prov, n_people in (("ON", 20_000), ("QC", 8_000)):
        for i in range(n_people):
            pid = f"Y{prov}{i:05d}"
            age0 = rng.uniform(21.0, 29.0)                        # age on 1 January 2024
            private = rng.random() < 0.40 + 0.04 * (age0 - 25)
            trillium = rng.random() < 0.08
            u = rng.gauss(0, 0.08)
            for m in range(12):
                age = age0 + m / 12
                if prov == "ON":
                    public = (not private) and (age < 25 or trillium)
                else:
                    public = not private
                insured = private or public
                p_ins = min(0.99, max(0.02, 0.82 + u - 0.005 * (age - 25)))
                p_unins = min(0.99, max(0.02, p_ins - 0.22))
                d_ins, d_unins = 0.006 + 0.0002 * (age - 25), 0.011 + 0.0002 * (age - 25)
                p, dk = (p_ins, d_ins) if insured else (p_unins, d_unins)
                rows.append((pid, prov, f"2024-{m + 1:02d}-01", f"{age:.4f}", int(public), int(rng.random() < p),
                             int(rng.random() < dk)))
                truth.append((pid, f"2024-{m + 1:02d}-01", int(private), f"{p_ins:.4f}", f"{p_unins:.4f}",
                              f"{d_ins:.4f}", f"{d_unins:.4f}"))
    write("young_adults_t1d_2024.csv", ["person_id", "province", "month", "age", "public_coverage", "insulin_fill",
                                        "dka_ed_visit"], rows)
    write("young_adults_truth.csv", ["person_id", "month", "private_plan", "p_fill_insured", "p_fill_uninsured",
                                     "p_dka_insured", "p_dka_uninsured"], truth, folder=TRUTH)
    print(f"  CGM panel: {len(SC_PROVINCES)} provinces x {SC_QUARTERS} quarters; young adults: {len(rows):,} person-months")


INCOME_SHARE = [0.26, 0.22, 0.20, 0.17, 0.15]            # adults with diabetes by income quintile (1 = lowest)
INCOME_RATE = [1.45, 1.20, 1.00, 0.85, 0.70]             # relative rate of glycemic ED visits
INCOME_EFFECT = [1.6, 1.3, 1.0, 0.6, 0.35]               # relative size of the CGM effect (private plans already paid)
RURAL_SHARE = {"BC": .14, "AB": .16, "SK": .33, "MB": .27, "ON": .14, "QC": .19, "NB": .48, "NS": .41, "PE": .52,
               "NL": .40}


def make_days_37_39():
    """Module 4, Days 37-39 (course scenarios, invented):
    - kidney_clinic_costs.csv: yearly program cost of each regional kidney care clinic (start-up + operating).
    - provincial_diabetes_quarterly_by_income.csv: Day 34's provincial counts split by income quintile and
      rurality; strata add up exactly to the provincial file. Lower-income and rural adults have higher rates;
      Ontario's CGM coverage helps lower-income adults most (higher incomes often had private coverage) and
      rural adults less (fewer diabetes educators to start CGM).
    Truth: expected stratum rates with and without the CGM policy."""
    rng = random.Random(SEED + 37)
    # --- clinic costs, calendar years 2023-2027
    with open(os.path.join(HERE, "drug_utilization_monthly.csv"), encoding="utf-8") as f:
        people = {}
        for r in csv.DictReader(f):
            people[(r["region"], int(r["month"][:4]))] = int(r["people_with_diabetes"])
    rows = []
    for region, (opened, _) in CLINIC_ROLLOUT.items():
        y0, m0 = int(opened[:4]), int(opened[5:7])
        for y in range(y0, 2028):
            months = 12 - m0 + 1 if y == y0 else 12
            operating = 6.0 * people[(region, y)] * months / 12 * rng.uniform(0.9, 1.1)
            startup = 800_000 if y == y0 else 0
            rows.append((region, y, months, round(startup + operating)))
    write("kidney_clinic_costs.csv", ["region", "year", "months_open", "program_cost_cad"], rows)
    # --- CGM panel by income quintile and rurality
    with open(os.path.join(TRUTH, "cgm_policy_truth.csv"), encoding="utf-8") as f:
        tr = {(r["province"], r["quarter"]): (float(r["rate_per_1000"]), float(r["rate_no_cgm_policy"])) for r in csv.DictReader(f)}
    with open(os.path.join(HERE, "provincial_diabetes_quarterly.csv"), encoding="utf-8") as f:
        prov_rows = list(csv.DictReader(f))
    strata = [(q, rur) for q in range(1, 6) for rur in (0, 1)]
    out, truth = [], []
    for r in prov_rows:
        prov, quarter, n, visits = r["province"], r["quarter"], int(r["adults_with_diabetes"]), int(r["glycemic_ed_visits"])
        rate, cf = tr[(prov, quarter)]
        ramp = 0.0 if cf == 0 else 1 - rate / cf / 1.0               # = 0.12 x ramp for treated provinces, else 0
        share = {s: INCOME_SHARE[s[0] - 1] * (RURAL_SHARE[prov] if s[1] else 1 - RURAL_SHARE[prov]) for s in strata}
        rel = {s: INCOME_RATE[s[0] - 1] * (1.25 if s[1] else 1.0) for s in strata}
        norm = sum(share[s] * rel[s] for s in strata)
        cf_s = {s: cf * rel[s] / norm for s in strata}                # stratum rates averaging to the provincial rate
        h = {s: INCOME_EFFECT[s[0] - 1] * (0.6 if s[1] else 1.0) for s in strata}
        wsum = sum(share[s] * cf_s[s] * h[s] for s in strata) / cf
        act = {s: cf_s[s] * (1 - ramp * h[s] / wsum) for s in strata}
        tot = sum(share[s] * act[s] for s in strata)
        left, rem = visits, 1.0
        ns = {}
        n_left = n
        for k, s in enumerate(strata):
            ns[s] = n_left if k == len(strata) - 1 else round(n * share[s])
            n_left -= ns[s] if k < len(strata) - 1 else 0
        for k, s in enumerate(strata):                                 # multinomial split of the provincial count
            p = share[s] * act[s] / tot
            v = left if k == len(strata) - 1 else _binomial(rng, left, min(1.0, p / rem))
            left -= v
            rem -= p
            out.append((prov, quarter, s[0], s[1], ns[s], v))
            truth.append((prov, quarter, s[0], s[1], f"{act[s]:.4f}", f"{cf_s[s]:.4f}"))
    write("provincial_diabetes_quarterly_by_income.csv", ["province", "quarter", "income_quintile", "rural",
                                                          "adults_with_diabetes", "glycemic_ed_visits"], out)
    write("cgm_policy_truth_by_income.csv", ["province", "quarter", "income_quintile", "rural", "rate_per_1000",
                                             "rate_no_cgm_policy"], truth, folder=TRUTH)
    print(f"  clinic costs: {len(rows)} region-years; CGM by income: {len(out):,} rows")


def _binomial(rng, n, p):
    """Binomial draw; normal approximation for large n."""
    if n <= 0 or p <= 0:
        return 0
    if p >= 1:
        return n
    if n * p * (1 - p) > 50:
        return min(n, max(0, round(rng.gauss(n * p, math.sqrt(n * p * (1 - p))))))
    return sum(rng.random() < p for _ in range(n))

if __name__ == "__main__":
    make_days_01_03()
    print("Days 1-3 tables written; now Days 4-6 (about 3 minutes)...")
    make_days_04_06()
    make_days_07_09()
    print("Days 14-16: the Renavex trial extract and the CCHS-style survey (about 1 minute)...")
    make_days_14_16()
    make_days_17_19()
    print("Days 21-30: the Renavex real-world extract, 2026-2028 (about 30 seconds)...")
    make_days_21_30()
    make_days_27_29()
    make_days_31_33()
    make_days_34_36()
    make_days_37_39()
    print("Corridor Health data written to", HERE)