"""Build the Living Proof No. 2 edition file from the raw NTPF open-data CSVs. Usage: python -I build_edition.py Reads every CSV listed in /manifest.csv and writes: /ntpf_edition_2026-11.csv one tidy row per report/date/cut /ntpf_edition_2026-11.csv.sha256 /parse_log.json quirks counted while parsing Two source formats exist on https://www.ntpf.ie/waiting-list-data/open-data/ : legacy (2014 to March 2021): long format, one row per hospital x specialty x case type x age band x 3-month time band. opendata (April 2021 onward): wide format per report (OPNational01/02, IPDCNational01-04), four time bands. Legacy rows are aggregated to the four open-data bands (0-6, 6-12, 12-18, 18+ months), summing age profiles. """ import csv import hashlib import io import json import re import sys from collections import defaultdict from pathlib import Path LIST = {"OP": "Outpatient", "IPDC": "Inpatient/Day Case", "GI": "GI Endoscopy"} OPENDATA = {"OPNational01": ("OP", "by hospital"), "OPNational02": ("OP", "by specialty"), "IPDCNational01": ("IPDC", "by hospital"), "IPDCNational02": ("IPDC", "by specialty"), "IPDCNational03": ("IPDC", "by hospital and case type"), "IPDCNational04": ("GI", "by hospital")} FINE_TO_BAND = {"0-3 months": "w0_6", "3-6 months": "w0_6", "6-9 months": "w6_12", "9-12 months": "w6_12", "12-15 months": "w12_18", "15-18 months": "w12_18", "18+ months": "w18_plus", "18 months +": "w18_plus", "": "w_band_unknown"} BANDS = ["w0_6", "w6_12", "w12_18", "w18_plus", "w_band_unknown"] FIELDS = ["snapshot_date", "month", "list_type", "report", "report_cut", "source_format", "source_file", "adult_child", "hospital_group", "hospital", "specialty", "case_type"] + BANDS + ["total", "total_published", "w0_3_legacy_only"] def norm(c): return re.sub(r"[\s_/]+", " ", c.strip().lstrip("")).lower() def iso(d): d = d.strip() m = re.fullmatch(r"(\d{2})/(\d{2})/(\d{4})", d) if m: return f"{m.group(3)}-{m.group(2)}-{m.group(1)}" if re.fullmatch(r"\d{4}-\d{2}-\d{2}", d): return d raise ValueError(f"unexpected date {d!r}") def num(s): s = s.strip().replace(",", "") if not re.fullmatch(r"-?\d+", s): raise ValueError(f"not a whole number {s!r}") return int(s) def pick(row, *names): for n in names: if n in row: return row[n].strip() return "" def main(raw_dir, ed_dir): raw, ed = Path(raw_dir), Path(ed_dir) ed.mkdir(parents=True, exist_ok=True) files = [r["file"] for r in csv.DictReader(open(raw / "manifest.csv", encoding="utf-8")) if r["file"].endswith(".csv") and not r["file"].startswith("CSO_")] log = {"files": {}, "quirks": defaultdict(int), "examples": defaultdict(list)} agg = {} agg03 = defaultdict(int) def add(key, counts, published, quirk_dupe): if key in agg: if quirk_dupe: log["quirks"]["opendata_repeated_rows_summed"] += 1 if len(log["examples"]["opendata_repeated_rows_summed"]) < 5: log["examples"]["opendata_repeated_rows_summed"].append(list(key)) a = agg[key] for b in BANDS: a[b] += counts[b] a["total_published"] += published else: agg[key] = dict(counts, total_published=published) for fname in sorted(files): b = (raw / fname).read_bytes() try: text = b.decode("utf-8-sig") except UnicodeDecodeError: text = b.decode("cp1252") log["quirks"]["files_decoded_as_cp1252"] += 1 rdr = csv.DictReader(io.StringIO(text)) rdr.fieldnames = [norm(c) for c in rdr.fieldnames] m = re.match(r"OpenData_([A-Za-z]+\d\d)_", fname) n = 0 if m: report = m.group(1) lt, cut = OPENDATA[report] for r in rdr: if not pick(r, "archivedate"): log["quirks"]["blank_trailing_rows_skipped"] += 1 continue c = {"w0_6": num(r["0-6 months"]), "w6_12": num(r["6-12 months"]), "w12_18": num(r["12-18 months"]), "w18_plus": num(r["18 months +"]), "w_band_unknown": 0} pub = num(r["total"]) if sum(c.values()) != pub: log["quirks"]["opendata_total_ne_sum_of_bands"] += 1 if len(log["examples"]["opendata_total_ne_sum_of_bands"]) < 8: log["examples"]["opendata_total_ne_sum_of_bands"].append([fname, dict(r)]) key = (iso(r["archivedate"]), LIST[lt], report, cut, "opendata", fname, pick(r, "adult child"), "", pick(r, "hospitalname", "hospital name"), pick(r, "speciality"), pick(r, "case type")) add(key, c, pub, True) n += 1 else: lt = "GI" if "GI-Endoscopy" in fname else ("OP" if fname.startswith("OP-") else "IPDC") report = f"Legacy_{lt}" cut = "by hospital, specialty, case type and time band" for r in rdr: d = pick(r, "archive date") if not d: log["quirks"]["blank_trailing_rows_skipped"] += 1 continue band_raw = re.sub(r"\s+", " ", pick(r, "time bands", "time band")).lower() band = FINE_TO_BAND[band_raw] if band == "w_band_unknown": log["quirks"]["legacy_blank_time_band_rows"] += 1 cnt = num(pick(r, "count", "total")) c = {b: 0 for b in BANDS} c[band] = cnt key = (iso(d), LIST[lt], report, cut, "legacy", fname, pick(r, "adult child"), pick(r, "group", "hospital group"), pick(r, "hospital", "hospital name"), pick(r, "specialty", "speciality", "specialty name"), pick(r, "case type")) add(key, c, cnt, False) if band_raw == "0-3 months": agg03[key] += cnt else: agg03[key] += 0 n += 1 log["files"][fname] = n # CSO PEA01: population of Ireland in April, all ages, both sexes (published in thousands, stored as persons). pea = raw / "CSO_PEA01.csv" for r in csv.DictReader(io.StringIO(pea.read_bytes().decode("utf-8-sig"))): if r["Age Group"] == "All ages" and r["Sex"] == "Both sexes" and int(r["Year"]) >= 2014: persons = round(float(r["VALUE"]) * 1000) key = (f"{r['Year']}-04-15", "Population", "CSO_PEA01", "persons in April, all ages, both sexes", "cso", pea.name, "", "", "", "", "") agg[key] = {"w0_6": 0, "w6_12": 0, "w12_18": 0, "w18_plus": 0, "w_band_unknown": 0, "total_published": persons} log["files"][pea.name] = "population rows: band columns 0, total = persons" out = ed / "ntpf_edition_2026-11.csv" with open(out, "w", newline="", encoding="utf-8") as fh: w = csv.writer(fh, lineterminator="\n") w.writerow(FIELDS) for key in sorted(agg): a = agg[key] tot = a["total_published"] if key[2] == "CSO_PEA01" else sum(a[b] for b in BANDS) w.writerow([key[0], key[0][:7]] + list(key[1:]) + [a[b] for b in BANDS] + [tot, a["total_published"], agg03[key] if key in agg03 else ""]) h = hashlib.sha256(out.read_bytes()).hexdigest() (ed / "ntpf_edition_2026-11.csv.sha256").write_text(f"{h} ntpf_edition_2026-11.csv\n", encoding="utf-8") log["rows_out"] = len(agg) log["sha256"] = h log["quirks"] = dict(log["quirks"]) log["examples"] = dict(log["examples"]) (ed / "parse_log.json").write_text(json.dumps(log, indent=1), encoding="utf-8") print(len(agg), h, json.dumps(log["quirks"])) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])