Cohort Building II: Attrition, Baseline Characteristics and the Data Dictionary
Today you build the cohort that the rest of the course studies: adults aged 66 and over with type 2 diabetes and chronic kidney disease, on a public drug plan and not on dialysis, on 1 January 2025. Every criterion is applied one step at a time and counted, giving the attrition table and diagram that every study report starts with. Then come baseline characteristics from the year before index, a Table 1 comparing the provinces, a data dictionary generated from the data, and the cohort saved for later modules.
By the end of today you can
- My cohort is built one criterion at a time, and the attrition table and diagram match
- Every baseline window ends the day before the index date
- My Table 1 shows SMDs and hides small cells, and I can say why the SMD is better than a p-value here
- The data dictionary is generated from the data and saved with the cohort
warehouse/cohort_base.parquetholds 6,224 people with 20 columns
Today's 5.5-hour plan
In this lesson
6.1 Inclusion and exclusion, one step at a time (50 min)
The Attrition class keeps the cohort in a temporary table and applies one criterion at a time, recording how many people each step removes:
@dataclass
class Attrition:
"""Apply inclusion/exclusion steps one at a time to a temp table and record who is left.
con.execute(f"CREATE TEMP TABLE {name} AS ...") must hold the starting population, one row per person.
"""
con: object
table: str
steps: list = field(default_factory=list)
def __post_init__(self):
self.steps.append(("Start", self.count(), 0))
def count(self):
return self.con.sql(f"SELECT count(*) FROM {self.table}").fetchall()[0][0]
def keep(self, label, condition):
"""Keep the rows where `condition` (SQL on the table's columns) is true."""
before = self.count()
self.con.execute(f"DELETE FROM {self.table} WHERE NOT coalesce(({condition}), false)")
after = self.count()
self.steps.append((label, after, before - after))
return after
def table_rows(self):
return [(i, label, n, removed) for i, (label, n, removed) in enumerate(self.steps)]
def show(self):
print(f"{'step':<5}{'criterion':<62}{'remaining':>10}{'excluded':>10}")
for i, label, n, removed in self.table_rows():
print(f"{i:<5}{label:<62}{n:>10,}{(removed if i else 0):>10,}")
Two details matter. coalesce(condition, false) means that a person whose condition is unknown (NULL) is excluded, not silently kept. And the order of the steps is the order in the report, so put the broad criteria first (alive, registered, age), then the clinical ones.
The cohort builder reuses Day 5's definitions, with every date strictly before the index date:
def build_base_cohort(con, index_date=INDEX_DATE, table="cohort"):
"""Adults 66+ with diabetes and CKD, on a public drug plan, not on dialysis, on `index_date`.
Creates temp table `table` (one row per person, demographics + baseline covariates)
and returns the Attrition record.
"""
from corridor.windows import covered_days_sql
con.execute(f"""
CREATE OR REPLACE TEMP TABLE {table} AS
SELECT person_id, province, region, sex, birth_date, income_quintile, rural, registry_start, death_date,
DATE '{index_date}' AS index_date
FROM dim_person""")
a = Attrition(con, table)
before = f"DATE '{index_date}' - INTERVAL 1 DAY"
a.keep("Alive and registered on the index date",
f"registry_start <= DATE '{index_date}' AND (death_date IS NULL OR death_date >= DATE '{index_date}')")
a.keep("Registered for at least 365 days before the index date",
f"registry_start <= DATE '{index_date}' - INTERVAL 365 DAY")
a.keep("Aged 66 or older on the index date", f"age_on(birth_date, DATE '{index_date}') >= 66")
a.keep("Diabetes before the index date (Ontario definition)",
f"person_id IN (SELECT person_id FROM ({diabetes_case_dates(con, 'ontario', '2099-12-31')}) "
f"WHERE case_date <= {before})")
a.keep("Chronic kidney disease before the index date",
f"person_id IN (SELECT person_id FROM ({ckd_case_dates(con, 'two_claims_or_hospital', '2099-12-31')}) "
f"WHERE case_date <= {before})")
con.execute(f"CREATE OR REPLACE TEMP TABLE _cov AS {covered_days_sql(table)}")
a.keep("On a public drug plan for all 365 days before the index date",
"person_id IN (SELECT person_id FROM _cov WHERE covered_days >= 365)")
fees = ", ".join(f"'{f}'" for f in DIALYSIS_FEES)
a.keep("No dialysis before the index date",
f"person_id NOT IN (SELECT person_id FROM fct_physician_claims WHERE fee_code IN ({fees}) "
f"AND service_date <= {before}) AND person_id NOT IN (SELECT person_id FROM fct_hospital_diagnoses "
f"WHERE code = 'Z491' AND admit_date <= {before})")
con.execute(f"""
CREATE OR REPLACE TEMP TABLE {table} AS
SELECT c.person_id, c.province, c.region, c.sex, age_on(c.birth_date, c.index_date) AS age,
c.income_quintile, c.rural::BOOLEAN AS rural, c.index_date, b.* EXCLUDE (person_id)
FROM {table} c JOIN ({baseline_sql(table)}) b USING (person_id)
ORDER BY c.person_id""")
return a
"""Day 6.1: build the base cohort one criterion at a time, and draw the attrition diagram."""
import os
import sys
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import build_base_cohort # noqa: E402
from corridor.db import ROOT, warehouse # noqa: E402
con = warehouse()
attrition = build_base_cohort(con)
attrition.show()
# the diagram: one box per step, with the number excluded beside each arrow
steps = attrition.table_rows()
fig, ax = plt.subplots(figsize=(7.2, 0.95 * len(steps) + 0.4))
ax.set_xlim(0, 8.6)
ax.set_ylim(-len(steps) + 0.4, 0.8)
ax.axis("off")
for i, label, n, removed in steps:
y = -i
text = f"{'Everyone in the registry, 2019-2025' if i == 0 else label}\nn = {n:,}"
ax.text(3.6, y, text, ha="center", va="center", fontsize=8.5,
bbox=dict(boxstyle="round,pad=0.4", fc="#eef2ff", ec="#2563eb"))
if i:
ax.annotate("", xy=(3.6, y + 0.3), xytext=(3.6, y + 0.7), arrowprops=dict(arrowstyle="->", color="#555"))
ax.text(6.5, y + 0.5, f"excluded {removed:,}", ha="left", va="center", fontsize=8, color="#b91c1c")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day06_attrition.png"), dpi=130, metadata={"Software": None})
print("\nSaved figures/day06_attrition.png")
step criterion remaining excluded
0 Start 262,711 0
1 Alive and registered on the index date 247,521 15,190
2 Registered for at least 365 days before the index date 246,147 1,374
3 Aged 66 or older on the index date 58,608 187,539
4 Diabetes before the index date (Ontario definition) 15,574 43,034
5 Chronic kidney disease before the index date 6,664 8,910
6 On a public drug plan for all 365 days before the index date 6,521 143
7 No dialysis before the index date 6,224 297
Saved figures/day06_attrition.png

Each step has a reason a reviewer will ask for:
| Step | Why |
|---|---|
| Alive and registered on the index date | Follow-up needs a living, insured person |
| Registered 365 days before | A full look-back window (Day 5) |
| Aged 66+ | A full year of public drug history in Ontario (Day 5.5) |
| Diabetes, CKD before index | The study population, by validated definitions |
| Public plan all 365 days | Drug history observable for everyone (this also removes Quebecers who kept a private plan after 65) |
| No dialysis | Renavex's (fictional) indication excludes kidney failure on dialysis |
6.2 Baseline characteristics (40 min)
Characteristics come from the 365 days before index, never after. The window is one parameter of baseline_sql():
def baseline_sql(index_table, lookback_days=365, window_end=None):
"""Baseline covariates measured in the `lookback_days` before each index date.
window_end=None ends the window the day before the index date, as it should.
Passing a later date makes the look-back peek into the future (Day 6 bug).
"""
end = "i.index_date - INTERVAL 1 DAY" if window_end is None else f"DATE '{window_end}'"
start = f"i.index_date - INTERVAL {lookback_days} DAY"
return f"""
WITH i AS (SELECT person_id, index_date FROM {index_table}),
claims AS (
SELECT c.person_id, c.dx_code, c.specialty, c.fee_code
FROM fct_physician_claims c JOIN i USING (person_id)
WHERE c.service_date BETWEEN {start} AND {end}),
dx AS (
SELECT d.person_id, d.code
FROM fct_hospital_diagnoses d JOIN i USING (person_id)
WHERE d.admit_date BETWEEN {start} AND {end}),
stays AS (
SELECT s.person_id, count(*) AS n
FROM fct_hospital_stays s JOIN i USING (person_id)
WHERE s.admit_date BETWEEN {start} AND {end} GROUP BY 1),
rx AS (
SELECT r.person_id, r.atc
FROM fct_drug_dispensations r JOIN i USING (person_id)
WHERE r.dispense_date BETWEEN {start} AND {end})
SELECT i.person_id,
i.person_id IN (SELECT person_id FROM claims WHERE dx_code = '428')
OR i.person_id IN (SELECT person_id FROM dx WHERE code LIKE 'I50%') AS heart_failure,
i.person_id IN (SELECT person_id FROM claims WHERE dx_code = '401')
OR i.person_id IN (SELECT person_id FROM dx WHERE code = 'I10') AS hypertension,
i.person_id IN (SELECT person_id FROM claims WHERE dx_code = '496')
OR i.person_id IN (SELECT person_id FROM dx WHERE code LIKE 'J44%') AS copd,
coalesce((SELECT n FROM stays WHERE stays.person_id = i.person_id), 0) AS prior_stays,
(SELECT count(*) FROM claims WHERE claims.person_id = i.person_id
AND fee_code NOT IN ('CH103', 'Q0103')) AS physician_visits,
i.person_id IN (SELECT person_id FROM claims WHERE specialty = 'nephrology') AS nephrology_visit,
i.person_id IN (SELECT person_id FROM rx WHERE atc LIKE 'A10BA%') AS metformin,
i.person_id IN (SELECT person_id FROM rx WHERE atc LIKE 'A10BK%') AS sglt2,
i.person_id IN (SELECT person_id FROM rx WHERE atc LIKE 'A10A%') AS insulin,
i.person_id IN (SELECT person_id FROM rx WHERE atc LIKE 'C09%') AS ace_inhibitor,
i.person_id IN (SELECT person_id FROM rx WHERE atc LIKE 'C10%') AS statin,
(SELECT count(DISTINCT left(atc, 5)) FROM rx WHERE rx.person_id = i.person_id) AS drug_classes
FROM i"""
"""Day 6.2: baseline covariates from the 365 days before the index date."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import build_base_cohort # noqa: E402
from corridor.db import show, warehouse # noqa: E402
con = warehouse()
build_base_cohort(con)
print("--- Three people in the cohort")
show(con, "SELECT * FROM cohort ORDER BY person_id LIMIT 3")
print("\n--- How common is each characteristic? (share of the cohort, %)")
show(con, """
UNPIVOT (SELECT round(100 * avg(heart_failure::INT), 1) AS heart_failure,
round(100 * avg(hypertension::INT), 1) AS hypertension,
round(100 * avg(copd::INT), 1) AS copd,
round(100 * avg((prior_stays > 0)::INT), 1) AS any_hospital_stay,
round(100 * avg(nephrology_visit::INT), 1) AS nephrology_visit,
round(100 * avg(metformin::INT), 1) AS metformin,
round(100 * avg(sglt2::INT), 1) AS sglt2_inhibitor,
round(100 * avg(insulin::INT), 1) AS insulin,
round(100 * avg(ace_inhibitor::INT), 1) AS ace_inhibitor,
round(100 * avg(statin::INT), 1) AS statin
FROM cohort)
ON COLUMNS(*) INTO NAME characteristic VALUE pct""")
--- Three people in the cohort
person_id province region sex age income_quintile rural index_date heart_failure hypertension copd prior_stays physician_visits nephrology_visit metformin sglt2 insulin ace_inhibitor statin drug_classes
P0002F79A12 ON ON-EST M 79 4 True 2025-01-01 False True False 0 12 False True False False True True 4
P0007D6585F QC QC-03 F 69 1 False 2025-01-01 False True False 1 8 False True True False True True 5
P001D4B3D21 QC QC-OTH F 82 5 True 2025-01-01 False True False 0 16 True True False False True True 4
--- How common is each characteristic? (share of the cohort, %)
characteristic pct
heart_failure 15.3
hypertension 70.8
copd 6.3
any_hospital_stay 32.5
nephrology_visit 42.7
metformin 84.4
sglt2_inhibitor 40.4
insulin 26.3
ace_inhibitor 61.1
statin 78.0
A typical person in the cohort is 79, takes four drug classes, and saw a physician 11 times last year. 40% are already on an SGLT2 inhibitor, the class Renavex will be compared with in Module 3.
6.3 Table 1 and standardized differences (55 min)
Every cohort study's first table describes the people in each group. When groups are compared, it also needs a measure of balance that does not depend on sample size: the standardized mean difference (SMD).
A common rule of thumb treats |SMD| above 0.1 as a meaningful imbalance. Unlike a p-value, the SMD does not shrink or grow with the number of people. Module 3 uses it to check propensity-score weighting.
"""Day 6: Table 1 (baseline characteristics by group) with standardized differences."""
import math
import pandas as pd
from corridor.privacy import SMALL
def _smd_mean(a, b):
s = math.sqrt((a.var(ddof=1) + b.var(ddof=1)) / 2)
return (a.mean() - b.mean()) / s if s else 0.0
def _smd_prop(p1, p2):
s = math.sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / 2)
return (p1 - p2) / s if s else 0.0
def _count(n, total, small=SMALL):
if 0 < n < small:
return f"<{small}"
return f"{n:,} ({100 * n / total:.1f}%)"
def table_one(df, group, binary=(), continuous=(), labels=None, small=SMALL):
"""Rows = characteristics; columns = each group, overall, and the standardized difference
between the first two groups. Counts from 1 to small-1 are suppressed."""
labels = labels or {}
groups = sorted(df[group].unique())
a, b = (df[df[group] == g] for g in groups[:2])
rows = [("People", *[f"{(df[group] == g).sum():,}" for g in groups], f"{len(df):,}", "")]
for col in continuous:
cells = [f"{df[df[group] == g][col].mean():.1f} ({df[df[group] == g][col].std():.1f})" for g in groups]
rows.append((labels.get(col, col) + ", mean (SD)", *cells,
f"{df[col].mean():.1f} ({df[col].std():.1f})", f"{_smd_mean(a[col], b[col]):.2f}"))
for col in binary:
cells = [_count(int(df[df[group] == g][col].sum()), int((df[group] == g).sum()), small) for g in groups]
rows.append((labels.get(col, col) + ", n (%)", *cells, _count(int(df[col].sum()), len(df), small),
f"{_smd_prop(a[col].mean(), b[col].mean()):.2f}"))
return pd.DataFrame(rows, columns=["characteristic", *groups, "overall", "smd"])
"""Day 6.3: Table 1 - the cohort by province, with standardized differences and small cells hidden."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import build_base_cohort # noqa: E402
from corridor.db import warehouse # noqa: E402
from corridor.table_one import table_one # noqa: E402
con = warehouse()
build_base_cohort(con)
df = con.sql("SELECT *, sex = 'F' AS female, income_quintile = 1 AS lowest_income_quintile, "
"prior_stays > 0 AS any_hospital_stay, prior_stays >= 3 AS three_plus_stays FROM cohort").df()
labels = {"age": "Age (years)", "physician_visits": "Physician visits in the past year",
"drug_classes": "Drug classes dispensed", "female": "Female", "lowest_income_quintile": "Income quintile 1",
"rural": "Rural", "heart_failure": "Heart failure", "hypertension": "Hypertension", "copd": "COPD",
"any_hospital_stay": "Any hospital stay", "nephrology_visit": "Nephrology visit",
"metformin": "Metformin", "sglt2": "SGLT2 inhibitor", "insulin": "Insulin",
"ace_inhibitor": "ACE inhibitor", "statin": "Statin", "three_plus_stays": "3+ hospital stays"}
t = table_one(df, "province",
binary=["female", "lowest_income_quintile", "rural", "heart_failure", "hypertension", "copd",
"any_hospital_stay", "nephrology_visit", "metformin", "sglt2", "insulin", "ace_inhibitor",
"statin"],
continuous=["age", "physician_visits", "drug_classes"], labels=labels)
print(t.to_string(index=False))
print("\n--- The same, for one small region: Outaouais (QC-07) vs North (ON-NTH)")
small = df[df.region.isin(["QC-07", "ON-NTH"])]
print(table_one(small, "region", binary=["female", "heart_failure", "copd", "insulin", "three_plus_stays"],
continuous=["age"], labels=labels).to_string(index=False))
characteristic ON QC overall smd
People 3,956 2,268 6,224
Age (years), mean (SD) 79.3 (8.5) 79.1 (8.4) 79.2 (8.5) 0.02
Physician visits in the past year, mean (SD) 11.3 (4.3) 11.3 (4.3) 11.3 (4.3) -0.00
Drug classes dispensed, mean (SD) 4.0 (1.2) 3.9 (1.2) 3.9 (1.2) 0.05
Female, n (%) 1,908 (48.2%) 1,091 (48.1%) 2,999 (48.2%) 0.00
Income quintile 1, n (%) 928 (23.5%) 549 (24.2%) 1,477 (23.7%) -0.02
Rural, n (%) 468 (11.8%) 452 (19.9%) 920 (14.8%) -0.22
Heart failure, n (%) 605 (15.3%) 346 (15.3%) 951 (15.3%) 0.00
Hypertension, n (%) 2,789 (70.5%) 1,620 (71.4%) 4,409 (70.8%) -0.02
COPD, n (%) 238 (6.0%) 154 (6.8%) 392 (6.3%) -0.03
Any hospital stay, n (%) 1,279 (32.3%) 741 (32.7%) 2,020 (32.5%) -0.01
Nephrology visit, n (%) 1,693 (42.8%) 962 (42.4%) 2,655 (42.7%) 0.01
Metformin, n (%) 3,359 (84.9%) 1,893 (83.5%) 5,252 (84.4%) 0.04
SGLT2 inhibitor, n (%) 1,648 (41.7%) 865 (38.1%) 2,513 (40.4%) 0.07
Insulin, n (%) 1,067 (27.0%) 568 (25.0%) 1,635 (26.3%) 0.04
ACE inhibitor, n (%) 2,383 (60.2%) 1,417 (62.5%) 3,800 (61.1%) -0.05
Statin, n (%) 3,093 (78.2%) 1,761 (77.6%) 4,854 (78.0%) 0.01
--- The same, for one small region: Outaouais (QC-07) vs North (ON-NTH)
characteristic ON-NTH QC-07 overall smd
People 201 119 320
Age (years), mean (SD) 79.5 (8.4) 78.6 (8.3) 79.2 (8.4) 0.11
Female, n (%) 97 (48.3%) 61 (51.3%) 158 (49.4%) -0.06
Heart failure, n (%) 22 (10.9%) 14 (11.8%) 36 (11.2%) -0.03
COPD, n (%) 14 (7.0%) 8 (6.7%) 22 (6.9%) 0.01
Insulin, n (%) 61 (30.3%) 27 (22.7%) 88 (27.5%) 0.17
3+ hospital stays, n (%) <6 <6 6 (1.9%) 0.02
The provinces are well balanced on everything except rurality (SMD −0.22: 19.9% rural in Quebec against 11.8% in Ontario). Keep that in mind for Module 4: a difference between provinces could partly be a rural–urban difference.
The second table shows small-cell suppression at work. Two small regions, each with fewer than 6 people with three or more hospital stays, have those cells hidden. One caution: in real releases the SMD of a suppressed row can leak information, so suppress it too.
6.4 The data dictionary (30 min)
A cohort without a dictionary cannot be reviewed or reused. Write it from the data itself (types, missing values, ranges) plus one human-written line per column, and regenerate it whenever the cohort changes:
"""Day 6: a data dictionary written from the data itself, plus human descriptions."""
import pandas as pd
def describe(df, descriptions):
rows = []
for col in df.columns:
s = df[col]
kind = str(s.dtype)
if s.dtype == bool or kind == "boolean":
values = f"true {int(s.sum()):,} / false {int((~s.astype(bool)).sum()):,}"
elif pd.api.types.is_numeric_dtype(s):
values = f"{s.min():g} to {s.max():g}"
elif pd.api.types.is_datetime64_any_dtype(s):
values = f"{s.min().date()} to {s.max().date()}"
else:
levels = sorted(s.dropna().astype(str).unique())
values = ", ".join(levels) if len(levels) <= 6 else f"{len(levels):,} distinct values"
rows.append((col, kind, descriptions.get(col, "(no description)"), int(s.isna().sum()), values))
return pd.DataFrame(rows, columns=["column", "type", "description", "missing", "values"])
def to_markdown(table, title):
lines = [f"# {title}", "", "| " + " | ".join(table.columns) + " |",
"|" + "---|" * len(table.columns)]
for r in table.itertuples(index=False):
lines.append("| " + " | ".join(str(v).replace("|", "/") for v in r) + " |")
return "\n".join(lines) + "\n"
"""Day 6.4: write the cohort's data dictionary from the data."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import build_base_cohort # noqa: E402
from corridor.db import ROOT, warehouse # noqa: E402
from corridor.dictionary import describe, to_markdown # noqa: E402
DESCRIPTIONS = {
"person_id": "Encrypted person key (links to every warehouse table)",
"province": "Province of residence (registry)",
"region": "Health region (registry); see regions lookup",
"sex": "Sex recorded in the registry",
"age": "Age in whole years on the index date",
"income_quintile": "Neighbourhood income quintile, 1 = lowest",
"rural": "Lives in a rural area (registry)",
"index_date": "Cohort entry date (2025-01-01 for everyone in the base cohort)",
"heart_failure": "Claim 428 or hospital diagnosis I50* in the 365 days before index",
"hypertension": "Claim 401 or hospital diagnosis I10 in the 365 days before index",
"copd": "Claim 496 or hospital diagnosis J44* in the 365 days before index",
"prior_stays": "Hospital admissions in the 365 days before index",
"physician_visits": "Physician claims in the 365 days before index, excluding dialysis supervision",
"nephrology_visit": "Any nephrology claim in the 365 days before index",
"metformin": "Public drug claim for ATC A10BA* in the 365 days before index",
"sglt2": "Public drug claim for ATC A10BK* in the 365 days before index",
"insulin": "Public drug claim for ATC A10A* in the 365 days before index",
"ace_inhibitor": "Public drug claim for ATC C09* in the 365 days before index",
"statin": "Public drug claim for ATC C10* in the 365 days before index",
"drug_classes": "Distinct ATC level-4 classes dispensed in the 365 days before index",
}
con = warehouse()
build_base_cohort(con)
table = describe(con.sql("SELECT * FROM cohort").df(), DESCRIPTIONS)
print(table.to_string(index=False, max_colwidth=58))
path = os.path.join(ROOT, "docs", "data_dictionary_cohort_base.md")
with open(path, "w", encoding="utf-8") as f:
f.write(to_markdown(table, "Data dictionary: base cohort (index 2025-01-01)"))
print("\nWrote docs/data_dictionary_cohort_base.md")
column type description missing values
person_id str Encrypted person key (links to every warehouse table) 0 6,224 distinct values
province str Province of residence (registry) 0 ON, QC
region str Health region (registry); see regions lookup 0 11 distinct values
sex str Sex recorded in the registry 0 F, M
age int64 Age in whole years on the index date 0 66 to 100
income_quintile int64 Neighbourhood income quintile, 1 = lowest 0 1 to 5
rural bool Lives in a rural area (registry) 0 true 920 / false 5,304
index_date datetime64[us] Cohort entry date (2025-01-01 for everyone in the base ... 0 2025-01-01 to 2025-01-01
heart_failure bool Claim 428 or hospital diagnosis I50* in the 365 days be... 0 true 951 / false 5,273
hypertension bool Claim 401 or hospital diagnosis I10 in the 365 days bef... 0 true 4,409 / false 1,815
copd bool Claim 496 or hospital diagnosis J44* in the 365 days be... 0 true 392 / false 5,832
prior_stays int64 Hospital admissions in the 365 days before index 0 0 to 6
physician_visits int64 Physician claims in the 365 days before index, excludin... 0 0 to 33
nephrology_visit bool Any nephrology claim in the 365 days before index 0 true 2,655 / false 3,569
metformin bool Public drug claim for ATC A10BA* in the 365 days before... 0 true 5,252 / false 972
sglt2 bool Public drug claim for ATC A10BK* in the 365 days before... 0 true 2,513 / false 3,711
insulin bool Public drug claim for ATC A10A* in the 365 days before ... 0 true 1,635 / false 4,589
ace_inhibitor bool Public drug claim for ATC C09* in the 365 days before i... 0 true 3,800 / false 2,424
statin bool Public drug claim for ATC C10* in the 365 days before i... 0 true 4,854 / false 1,370
drug_classes int64 Distinct ATC level-4 classes dispensed in the 365 days ... 0 0 to 9
Wrote docs/data_dictionary_cohort_base.md
The Markdown version is written to docs/data_dictionary_cohort_base.md. It goes into the study's appendix, and on Day 10 into the capstone.
6.5 A baseline that looks into the future (25 min)
Bug of the day. A colleague measured baseline characteristics from 1 January 2024 to the end of the data "to catch more of them":
"""Day 6 bug of the day: a baseline window that runs past the index date.
A colleague measured baseline characteristics from 2024-01-01 to the end of the data
(2025-12-31) 'to catch more of them'.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import baseline_sql, build_base_cohort # noqa: E402
from corridor.db import show, warehouse # noqa: E402
con = warehouse()
build_base_cohort(con)
con.execute(f"CREATE TEMP TABLE right_window AS {baseline_sql('cohort')}")
con.execute(f"CREATE TEMP TABLE wrong_window AS {baseline_sql('cohort', window_end='2025-12-31')}")
show(con, """
SELECT 'baseline = 365 days before index' AS window,
round(100 * avg(heart_failure::INT), 1) AS heart_failure_pct,
round(100 * avg(sglt2::INT), 1) AS sglt2_pct,
round(avg(prior_stays), 3) AS stays_per_person
FROM right_window
UNION ALL
SELECT 'colleague: 2024-01-01 to 2025-12-31',
round(100 * avg(heart_failure::INT), 1), round(100 * avg(sglt2::INT), 1), round(avg(prior_stays), 3)
FROM wrong_window""")
print()
show(con, """
SELECT count_if(w.sglt2 AND NOT r.sglt2) AS sglt2_only_after_index,
count_if(w.prior_stays > r.prior_stays) AS stays_added_after_index
FROM right_window r JOIN wrong_window w USING (person_id)""")
window heart_failure_pct sglt2_pct stays_per_person
baseline = 365 days before index 15.3 40.4 0.405
colleague: 2024-01-01 to 2025-12-31 15.9 47.5 0.778
sglt2_only_after_index stays_added_after_index
444 1874
"Baseline" SGLT2 use rises from 40.4% to 47.5%, and hospital stays per person nearly double. 444 people are counted as SGLT2 users only because they started after the index date, and 1,874 people gain stays that happened during follow-up. In a comparative study, that is fatal. If you adjust for a "baseline" variable that partly records the outcome, you adjust away part of the effect you are trying to measure. Every covariate window ends the day before the index date. In baseline_sql() that is the default, and the only way to change it is a parameter whose name gives the change away.
6.6 Mini-project: save the cohort and check it (55 min)
Save the cohort as Parquet for Days 7–10 and Module 2. Check it against the truth. And release a table of hospital stays by region with small cells suppressed.
"""Day 6 mini-project: save the base cohort for later modules, and check it against the truth."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor import truth # noqa: E402
from corridor.cohort import build_base_cohort # noqa: E402
from corridor.db import ROOT, show, warehouse # noqa: E402
con = warehouse()
truth.register(con)
attrition = build_base_cohort(con)
path = os.path.join(ROOT, "warehouse", "cohort_base.parquet")
con.execute(f"COPY (SELECT * FROM cohort ORDER BY person_id) TO '{path}' (FORMAT parquet)")
print(f"Saved warehouse/cohort_base.parquet: {attrition.count():,} people, "
f"{len(con.sql('SELECT * FROM cohort').columns)} columns")
print("\n--- How many of them truly have diabetes and CKD before the index date?")
show(con, """
SELECT count(*) AS people,
count_if(t.diabetes_from < DATE '2025-01-01') AS true_diabetes,
count_if(t.ckd_from_year <= 2024) AS true_ckd,
count_if(t.diabetes_from < DATE '2025-01-01' AND t.ckd_from_year <= 2024) AS true_both,
round(100 * count_if(t.diabetes_from < DATE '2025-01-01' AND t.ckd_from_year <= 2024)
/ count(*), 1) AS pct_both
FROM cohort c JOIN truth_history t USING (person_id)""")
print("\n--- Hospital stays in the year before index, by region (counts under 6 hidden)")
from corridor.privacy import suppress # noqa: E402
counts = con.sql("""SELECT region, CASE WHEN prior_stays >= 3 THEN '3+' ELSE prior_stays::VARCHAR END AS stays
FROM cohort""").df().pivot_table(index="region", columns="stays", aggfunc="size", fill_value=0)
safe, hidden = suppress(counts)
print(safe.to_string())
print(f"{hidden} cells hidden")
Saved warehouse/cohort_base.parquet: 6,224 people, 20 columns
--- How many of them truly have diabetes and CKD before the index date?
people true_diabetes true_ckd true_both pct_both
6224 6201 6204 6181 99.3
--- Hospital stays in the year before index, by region (counts under 6 hidden)
stays 0 1 2 3+
region
ON-CEN 810 269 60 9
ON-EST 714 272 50 11
ON-NTH 142 49 <6 <6
ON-TOR 568 227 56 12
ON-WST 443 206 42 6
QC-03 136 58 <6 <6
QC-06 359 135 28 7
QC-07 79 31 <6 <6
QC-13 77 31 <6 <6
QC-16 288 108 <6 <6
QC-OTH 588 226 52 13
10 cells hidden
99.3% of the cohort truly has both diabetes and CKD before the index date. Requiring two claims or a hospital diagnosis, for both conditions, buys a very clean population. The price is the early CKD that Day 5 showed you miss. The suppressed table shows the usual pattern: the rare category (3+ stays) is hidden in the smaller regions, and secondary suppression hides one more cell in each of those rows.
Try it (10 min). Build the same cohort with the index date on Ontario's Renavex listing day, 1 October 2025. How does the attrition change?
Solution
"""Day 6 exercise: the same cohort with the index date on Ontario's Renavex listing day (2025-10-01)."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.cohort import build_base_cohort # noqa: E402
from corridor.db import warehouse # noqa: E402
con = warehouse()
for index in ("2025-01-01", "2025-10-01"):
a = build_base_cohort(con, index_date=index, table=f"cohort_{index[:4]}_{index[5:7]}")
print(f"--- index {index}")
a.show()
print()
--- index 2025-01-01
step criterion remaining excluded
0 Start 262,711 0
1 Alive and registered on the index date 247,521 15,190
2 Registered for at least 365 days before the index date 246,147 1,374
3 Aged 66 or older on the index date 58,608 187,539
4 Diabetes before the index date (Ontario definition) 15,574 43,034
5 Chronic kidney disease before the index date 6,664 8,910
6 On a public drug plan for all 365 days before the index date 6,521 143
7 No dialysis before the index date 6,224 297
--- index 2025-10-01
step criterion remaining excluded
0 Start 262,711 0
1 Alive and registered on the index date 245,623 17,088
2 Registered for at least 365 days before the index date 245,623 0
3 Aged 66 or older on the index date 60,333 185,290
4 Diabetes before the index date (Ontario definition) 16,775 43,558
5 Chronic kidney disease before the index date 7,164 9,611
6 On a public drug plan for all 365 days before the index date 7,006 158
7 No dialysis before the index date 6,705 301
The October cohort is larger: 6,705 against 6,224. Nine more months of claims mean more people meet the case definitions (Day 5.6), and more people have turned 66. No one is excluded for less than a year of registration, because the registry starts in 2019. Choosing the index date is a design decision, and it changes who is studied.
6.7 Save your work
python -m pytest -q
git add .
git commit -m "Day 6: base cohort, attrition, Table 1, data dictionary"
The tests for Days 4–6 check the attrition counter, covered days across a leap year, Table 1's SMD and suppression, and the built cohort:
"""Known-answer tests for Days 4-6 (toy tables, plus checks on the built warehouse)."""
import os
import duckdb
import pandas as pd
import pytest
from corridor.cohort import Attrition, validate
from corridor.db import WAREHOUSE
from corridor.dictionary import describe
from corridor.table_one import table_one
from corridor.windows import covered_days_sql
@pytest.fixture()
def toy():
con = duckdb.connect()
con.execute("""CREATE TABLE stg_drug_plan_eligibility AS SELECT * FROM (VALUES
('A', 'ODB-65', DATE '2023-06-01', NULL), -- covered the whole year
('B', 'ODB-SA', DATE '2024-01-01', DATE '2024-03-31'), -- window starts 2024-01-02: 90 days
('B', 'ODB-65', DATE '2024-10-01', NULL)) -- 92 more days
t(person_id, plan_id, start_date, end_date)""")
con.execute("""CREATE TABLE idx AS SELECT * FROM (VALUES
('A', DATE '2025-01-01'), ('B', DATE '2025-01-01'), ('C', DATE '2025-01-01'))
t(person_id, index_date)""")
return con
def test_covered_days(toy):
got = dict(toy.sql(covered_days_sql("idx")).fetchall())
assert got == {"A": 365, "B": 90 + 92, "C": 0} # 2024 is a leap year
def test_attrition_counts(toy):
toy.execute("CREATE TEMP TABLE pop AS SELECT * FROM range(10) t(x)")
a = Attrition(toy, "pop")
a.keep("even", "x % 2 = 0")
a.keep("big", "x >= 4")
assert [(label, n, removed) for _, label, n, removed in a.table_rows()] == [
("Start", 10, 0), ("even", 5, 5), ("big", 3, 2)]
def test_attrition_null_condition_is_excluded(toy):
toy.execute("CREATE TEMP TABLE pop2 AS SELECT * FROM (VALUES (1), (NULL)) t(x)")
a = Attrition(toy, "pop2")
assert a.keep("x is one", "x = 1") == 1
def test_validate_measures(toy):
pop = "SELECT * FROM (VALUES ('a'), ('b'), ('c'), ('d')) t(person_id)"
found = "SELECT * FROM (VALUES ('a'), ('b')) t(person_id)"
truth = "SELECT * FROM (VALUES ('a'), ('c')) t(person_id)"
r = validate(toy, found, truth, pop)
assert (r["sensitivity"], r["specificity"], r["ppv"], r["npv"]) == (0.5, 0.5, 0.5, 0.5)
def test_table_one_smd_and_suppression():
df = pd.DataFrame({"g": ["x"] * 10 + ["y"] * 10, "flag": [1] * 5 + [0] * 5 + [1] * 3 + [0] * 7,
"age": list(range(10)) * 2})
t = table_one(df, "g", binary=["flag"], continuous=["age"])
flag = t[t.characteristic == "flag, n (%)"].iloc[0]
assert flag["x"] == "<6" and flag["y"] == "<6" and flag["overall"] == "8 (40.0%)"
assert flag["smd"] == "0.42" # (0.5 - 0.3) / sqrt((0.25 + 0.21) / 2) = 0.417
assert t[t.characteristic == "age, mean (SD)"].iloc[0]["smd"] == "0.00"
def test_describe():
d = describe(pd.DataFrame({"a": [1, 3], "b": ["x", None]}), {"a": "a number"})
assert d.loc[0, "values"] == "1 to 3" and d.loc[1, "missing"] == 1 and d.loc[1, "description"] == "(no description)"
@pytest.mark.skipif(not os.path.exists(WAREHOUSE), reason="build the warehouse first (Day 4)")
def test_warehouse_and_cohort():
from corridor.cohort import build_base_cohort
from corridor.db import warehouse
con = warehouse()
years = con.sql("SELECT min(year), max(year), count(*) FROM fct_person_years").fetchall()[0]
assert years[:2] == (2019, 2025)
a = build_base_cohort(con)
assert a.count() > 1000
assert con.sql("SELECT min(age), count(*) - count(DISTINCT person_id) FROM cohort").fetchall()[0] == (66, 0)
Day 6 checklist
- My cohort is built one criterion at a time, and the attrition table and diagram match
- Every baseline window ends the day before the index date
- My Table 1 shows SMDs and hides small cells, and I can say why the SMD is better than a p-value here
- The data dictionary is generated from the data and saved with the cohort
-
warehouse/cohort_base.parquetholds 6,224 people with 20 columns
Bloc français (30 min)
Thème : la cohorte et le tableau 1.
On construit la cohorte en appliquant les critères d'inclusion et d'exclusion un à un, et on compte les personnes exclues à chaque étape. Le diagramme de flux qui en résulte ouvre tout rapport d'étude. Les caractéristiques initiales sont mesurées pendant l'année qui précède la date index, jamais après. Le tableau 1 compare les groupes à l'aide de la différence moyenne standardisée. Enfin, le dictionnaire de données décrit chaque variable : son type, sa définition et ses valeurs.
| Français | English |
|---|---|
| les critères d'inclusion et d'exclusion | inclusion and exclusion criteria |
| le diagramme de flux | the flow (attrition) diagram |
| une personne exclue | an excluded person |
| les caractéristiques initiales | baseline characteristics |
| le tableau 1 | Table 1 |
| la différence moyenne standardisée | the standardized mean difference |
| un déséquilibre | an imbalance |
| le dictionnaire de données | the data dictionary |
| une variable | a variable |
| la dialyse | dialysis |
| l'insuffisance rénale chronique | chronic kidney disease |
| le milieu rural | rural areas |
Exercices
- Translate: "Every baseline window ends the day before the index date."
- Translate: « Les deux provinces sont bien équilibrées, sauf pour la proportion de personnes vivant en milieu rural. »
- In three French sentences, describe the cohort: who is in it, how many people, and its average age.
Réponses
- Chaque période de mesure des caractéristiques initiales se termine la veille de la date index.
- "The two provinces are well balanced, except for the proportion of people living in rural areas."
- Example: La cohorte comprend des personnes de 66 ans et plus atteintes de diabète de type 2 et d'insuffisance rénale chronique. Elle compte 6 224 personnes, couvertes par un régime public et non dialysées au 1er janvier 2025. Leur âge moyen est de 79 ans.