"""Living Proof No. 2: compute every number from the edition file only. Usage: python -I compute.py edition/ntpf_edition_2026-11.csv results.json Deterministic: no clock, no network, sorted iteration. Every number is stored in results.json under an id with its value, a plain formula and its inputs (filters on the edition file, or other result ids), so a browser engine can reproduce it. Indicator definitions and the stress tests are fixed in PREREG.md. """ import csv import hashlib import json import sys from collections import defaultdict # Which report gives the national total for each list (legacy files before April 2021, open data after). TOTAL_REPORTS = {"OP": ("Legacy_OP", "OPNational01"), "IPDC": ("Legacy_IPDC", "IPDCNational01"), "GI": ("Legacy_GI", "IPDCNational04")} LIST_NAME = {"OP": "Outpatient", "IPDC": "Inpatient/Day Case", "GI": "GI Endoscopy"} SPEC_REPORTS = {"OP": "OPNational02", "IPDC": "IPDCNational02"} MEASURES = { "total": ("total_published", "sum of the published Total column"), "bandsum": ("total", "sum of the four time-band columns (plus unknown band)"), "l12": (("w12_18", "w18_plus"), "sum of the 12-18 and 18+ month bands"), "l18": (("w18_plus",), "the 18+ month band"), } FLAT = 1.0 # verdict threshold, percent (PREREG) R = {} def put(rid, value, formula, inputs, note=None): if rid in R: raise KeyError(f"duplicate result id {rid}") R[rid] = {"value": value, "formula": formula, "inputs": inputs} if note: R[rid]["note"] = note return value def pct(new, old): return None if old in (None, 0) or new is None else round((new - old) / old * 100, 2) def verdict(p): if p is None: return None return "falling" if p < -FLAT else ("rising" if p > FLAT else "flat") def shift(month, years=0, months=0): y, m = int(month[:4]), int(month[5:7]) t = y * 12 + (m - 1) + years * 12 + months return f"{t // 12:04d}-{t % 12 + 1:02d}" def load(path): rows = list(csv.DictReader(open(path, encoding="utf-8", newline=""))) for r in rows: for c in ("w0_6", "w6_12", "w12_18", "w18_plus", "w_band_unknown", "total", "total_published"): r[c] = int(r[c]) return rows def value(r, measure): col = MEASURES[measure][0] return r[col] if isinstance(col, str) else sum(r[c] for c in col) def series(rows, lst, measure="total", where=None): """month -> national value for the list, from the by-hospital report.""" reps = TOTAL_REPORTS[lst] out = defaultdict(int) for r in rows: if r["report"] in reps and (where is None or where(r)): out[r["month"]] += value(r, measure) return dict(sorted(out.items())) def combined(rows, measure="total", where=None): out = defaultdict(int) parts = [series(rows, l, measure, where) for l in TOTAL_REPORTS] common = set(parts[0]) & set(parts[1]) & set(parts[2]) for p in parts: for m, v in p.items(): if m in common: out[m] += v return dict(sorted(out.items())) def main(edition, out_path): raw = open(edition, "rb").read() sha = hashlib.sha256(raw).hexdigest() rows = load(edition) pop = {r["month"][:4]: r["total_published"] for r in rows if r["report"] == "CSO_PEA01"} ntpf = [r for r in rows if r["report"] != "CSO_PEA01"] S = {} for lst in TOTAL_REPORTS: for ms in MEASURES: S[(lst, ms)] = series(ntpf, lst, ms) for ms in MEASURES: S[("ALL", ms)] = combined(ntpf, ms) latest = max(S[("ALL", "total")]) put("meta.latest_month", latest, "most recent month present in all three lists", {"edition_sha256": sha}) put("meta.first_month", {l: min(S[(l, "total")]) for l in ["OP", "IPDC", "GI"]}, "earliest month per list", {}) put("meta.months", {l: len(S[(l, "total")]) for l in ["OP", "IPDC", "GI", "ALL"]}, "count of monthly snapshots", {}) lists = ["OP", "IPDC", "GI", "ALL"] labels = dict(LIST_NAME, ALL="All three lists combined (entries)") def src(lst, ms): reps = list(TOTAL_REPORTS.values()) if lst == "ALL" else [TOTAL_REPORTS[lst]] return {"reports": reps, "measure": MEASURES[ms][1], "group_by": "month"} # ---- full monthly series (for charts and the browser engine) for lst in lists: for ms in MEASURES: put(f"series.{lst}.{ms}", S[(lst, ms)], f"{MEASURES[ms][1]}, national, per month", src(lst, ms)) # ---- data-quality: month-on-month jumps over 10%, and the legacy/open-data join (Mar to Apr 2021) for lst in ["OP", "IPDC", "GI"]: s = S[(lst, "total")] ms_ = list(s) jumps = {m: pct(s[m], s[p]) for p, m in zip(ms_, ms_[1:]) if abs(pct(s[m], s[p])) > 10} put(f"quality.jumps_over_10pct.{lst}", jumps, "months whose total changed by more than 10% from the month before", {"series": f"series.{lst}.total"}) put(f"quality.join_2021.{lst}", {"2021-03": s.get("2021-03"), "2021-04": s.get("2021-04"), "pct": pct(s.get("2021-04"), s.get("2021-03"))}, "last legacy month vs first open-data month", {"series": f"series.{lst}.total"}) # published total vs band-sum gap, latest month for lst in lists: put(f"quality.total_minus_bandsum.{lst}", S[(lst, "total")][latest] - S[(lst, "bandsum")][latest], "published Total minus sum of bands, latest month", {"series": [f"series.{lst}.total", f"series.{lst}.bandsum"]}) # ---- headline: latest vs a year earlier, vs 2021 and 2019 same month yoy_base = shift(latest, -1) base21 = latest.replace(latest[:4], "2021") if latest[5:] not in ("01", "02", "03", "04", "05") else None base19 = latest.replace(latest[:4], "2019") for lst in lists: for ms in ["total", "l12", "l18"]: s = S[(lst, ms)] for tag, base in [("yoy", yoy_base), ("vs2021", base21), ("vs2019", base19)]: if base is None or base not in s: put(f"head.{lst}.{ms}.{tag}", None, "not computable: base month missing", {"base": base}) continue p = pct(s[latest], s[base]) put(f"head.{lst}.{ms}.{tag}", {"latest": s[latest], "base": s[base], "base_month": base, "change": s[latest] - s[base], "pct": p, "verdict": verdict(p)}, f"({ms} at {latest} - {ms} at {base}) / {ms} at {base} x 100; verdict falling if < -{FLAT}%, rising if > {FLAT}%", {"series": f"series.{lst}.{ms}"}) # share over 12 months, latest and year earlier for lst in lists: a, b = S[(lst, "l12")], S[(lst, "bandsum")] put(f"head.{lst}.share12", {m: round(a[m] / b[m] * 100, 2) for m in (yoy_base, latest) if m in a}, "l12 / band-sum total x 100", {"series": [f"series.{lst}.l12", f"series.{lst}.bandsum"]}) # ---- peaks and lows over the full history for lst in lists: for ms in ["total", "l18"]: s = S[(lst, ms)] pk = max(s, key=lambda m: (s[m], m)) lo = min(s, key=lambda m: (s[m], m)) put(f"history.{lst}.{ms}", {"peak_month": pk, "peak": s[pk], "low_month": lo, "low": s[lo], "latest_is_peak": pk == latest}, "maximum and minimum of the monthly series", {"series": f"series.{lst}.{ms}"}) # ---- ST1 per capita (per 1,000 people; April estimate of the snapshot's year, latest estimate carried forward) last_pop_year = max(pop) def popof(m): return pop.get(m[:4], pop[last_pop_year]) put("st1.population", pop, "CSO PEA01 persons in April, all ages, both sexes", {"report": "CSO_PEA01"}) for lst in lists: for ms in ["total", "l18"]: s = S[(lst, ms)] if yoy_base in s: a, b = s[latest] / popof(latest) * 1000, s[yoy_base] / popof(yoy_base) * 1000 p = pct(a, b) put(f"st1.{lst}.{ms}.per1000.yoy", {"latest": round(a, 3), "base": round(b, 3), "pct": p, "verdict": verdict(p)}, "(value / population of that year x 1000), latest vs a year earlier", {"series": f"series.{lst}.{ms}", "population": "st1.population"}) for base in [base21, base19]: if base and base in s: a, b = s[latest] / popof(latest) * 1000, s[base] / popof(base) * 1000 p = pct(a, b) put(f"st1.{lst}.{ms}.per1000.vs{base[:4]}", {"latest": round(a, 3), "base": round(b, 3), "pct": p, "verdict": verdict(p)}, "per 1,000 population, latest vs same month of base year", {"series": f"series.{lst}.{ms}"}) # ---- ST2 month-on-month mom = shift(latest, 0, -1) for lst in lists: for ms in ["total", "l18"]: s = S[(lst, ms)] p = pct(s[latest], s[mom]) put(f"st2.{lst}.{ms}.mom", {"latest": s[latest], "base": s[mom], "base_month": mom, "pct": p, "verdict": verdict(p)}, "latest vs the month before", {"series": f"series.{lst}.{ms}"}) # ---- ST3 three-month average vs same three months a year earlier for lst in lists: for ms in ["total", "l18"]: s = S[(lst, ms)] now = [shift(latest, 0, -k) for k in range(3)] then = [shift(m, -1) for m in now] if all(m in s for m in now + then): a, b = sum(s[m] for m in now) / 3, sum(s[m] for m in then) / 3 p = pct(a, b) put(f"st3.{lst}.{ms}.avg3.yoy", {"months": now, "latest_avg": round(a, 1), "base_avg": round(b, 1), "pct": p, "verdict": verdict(p)}, "mean of latest 3 snapshots vs mean of same 3 months a year earlier", {"series": f"series.{lst}.{ms}"}) # ---- ST4 validation / removals put("st4.validation", None, "not computable", {}, note="The NTPF files hold counts of people waiting on each census date only. Additions, removals after " "treatment and removals after validation are not in the source, so their effect cannot be separated.") # ---- ST5 long waiters: carried in head.*.l12 / head.*.l18 # ---- ST6 start-date and end-date sensitivity for lst in lists: for ms in ["total", "l18"]: s = S[(lst, ms)] starts = [m for m in s if "2021-04" <= m < latest] lower = [m for m in starts if s[latest] < s[m]] put(f"st6.{lst}.{ms}.start_months_lower_now", {"n_start_months": len(starts), "n_lower_now": len(lower), "share_pct": round(len(lower) / len(starts) * 100, 1)}, "share of start months (Apr 2021 to the month before latest) whose value is above the latest value", {"series": f"series.{lst}.{ms}"}) ends = [shift(latest, 0, -k) for k in range(12)] vs = {} for e in ends: b = shift(e, -1) if e in s and b in s: vs[e] = verdict(pct(s[e], s[b])) put(f"st6.{lst}.{ms}.yoy_last12_ends", {"verdicts": dict(sorted(vs.items())), "n_falling": sum(v == "falling" for v in vs.values()), "n_rising": sum(v == "rising" for v in vs.values()), "n_flat": sum(v == "flat" for v in vs.values())}, "year-on-year verdict for each of the last 12 end months", {"series": f"series.{lst}.{ms}"}) # ---- ST8 hospital group (fixed mapping from the last legacy month) last_legacy = max(r["month"] for r in ntpf if r["source_format"] == "legacy") gmap = {} for r in ntpf: if r["source_format"] == "legacy" and r["month"] == last_legacy and r["hospital_group"]: gmap.setdefault(r["hospital"].strip().lower(), set()).add(r["hospital_group"]) gmap = {h: sorted(g)[0] for h, g in gmap.items()} put("st8.group_map_source_month", last_legacy, "hospital to group mapping taken from legacy files of this month", {}) for lst in ["OP", "IPDC", "GI"]: rep = TOTAL_REPORTS[lst][1] g = defaultdict(lambda: defaultdict(int)) unmatched = defaultdict(int) for r in ntpf: if r["report"] == rep and r["month"] in (latest, yoy_base): grp = gmap.get(r["hospital"].strip().lower()) if grp is None: unmatched[r["hospital"]] += r["total_published"] if r["month"] == latest else 0 grp = "Unmatched" g[grp][r["month"]] += r["total_published"] res = {} for grp in sorted(g): a, b = g[grp].get(latest, 0), g[grp].get(yoy_base, 0) res[grp] = {"latest": a, "base": b, "pct": pct(a, b), "verdict": verdict(pct(a, b))} put(f"st8.{lst}.by_group.yoy", res, "total by 2021 hospital group, latest vs a year earlier", {"report": rep, "map": "st8.group_map_source_month"}) put(f"st8.{lst}.unmatched_hospitals_latest", dict(sorted(unmatched.items())), "hospitals in latest month with no legacy group (people waiting)", {"report": rep}) # ---- ST9 adult vs child (open data only) for lst in ["OP", "IPDC", "GI"]: for ac in ["Adult", "Child"]: for ms in ["total", "l18"]: s = series(ntpf, lst, ms, where=lambda r, ac=ac: r["adult_child"] == ac and r["source_format"] == "opendata") if latest in s and yoy_base in s: p = pct(s[latest], s[yoy_base]) put(f"st9.{lst}.{ac}.{ms}.yoy", {"latest": s[latest], "base": s[yoy_base], "pct": p, "verdict": verdict(p)}, "adult_child filter, latest vs a year earlier", {"report": TOTAL_REPORTS[lst][1], "adult_child": ac}) # ---- ST10 by specialty (sum of adult and child rows with the same specialty name) for lst, rep in SPEC_REPORTS.items(): sp = defaultdict(lambda: defaultdict(int)) for r in ntpf: if r["report"] == rep and r["month"] in (latest, yoy_base): sp[r["specialty"]][r["month"]] += r["total_published"] sp[r["specialty"]][r["month"] + ".l18"] += r["w18_plus"] big = {k: v for k, v in sp.items() if v.get(yoy_base, 0) >= 1000} table = {k: {"latest": v.get(latest, 0), "base": v.get(yoy_base, 0), "pct": pct(v.get(latest, 0), v.get(yoy_base, 0)), "verdict": verdict(pct(v.get(latest, 0), v.get(yoy_base, 0))), "l18_latest": v.get(latest + ".l18", 0), "l18_base": v.get(yoy_base + ".l18", 0)} for k, v in sorted(big.items())} nat = sum(v.get(latest, 0) for v in sp.values()) - sum(v.get(yoy_base, 0) for v in sp.values()) put(f"st10.{lst}.specialties", table, "specialties with >= 1,000 waiting a year earlier, latest vs a year earlier", {"report": rep}) put(f"st10.{lst}.summary", {"n": len(table), "n_falling": sum(t["verdict"] == "falling" for t in table.values()), "n_rising": sum(t["verdict"] == "rising" for t in table.values()), "n_flat": sum(t["verdict"] == "flat" for t in table.values()), "national_change": nat}, "count of specialty verdicts", {"from": f"st10.{lst}.specialties"}) ch = sorted(((v.get(latest, 0) - v.get(yoy_base, 0), k) for k, v in sp.items()), reverse=True) top = ch[0] put(f"st10.{lst}.top_contributor", {"specialty": top[1], "change": top[0], "share_of_national_change_pct": round(top[0] / nat * 100, 1) if nat else None, "top5": [[k, c] for c, k in ch[:5]]}, "specialty with the largest increase, and its share of the national change", {"report": rep}) # concentration by hospital (rule in PREREG: more than half of the national change from one hospital) for lst in ["OP", "IPDC", "GI"]: rep = TOTAL_REPORTS[lst][1] h = defaultdict(int) for r in ntpf: if r["report"] == rep and r["month"] == latest: h[r["hospital"]] += r["total_published"] elif r["report"] == rep and r["month"] == yoy_base: h[r["hospital"]] -= r["total_published"] nat = sum(h.values()) ch = sorted(((c, k) for k, c in h.items()), reverse=True) n_up = sum(1 for c, _ in ch if c > 0) put(f"conc.{lst}.by_hospital", {"national_change": nat, "top_hospital": ch[0][1], "top_change": ch[0][0], "top_share_pct": round(ch[0][0] / nat * 100, 1) if nat else None, "n_hospitals_up": n_up, "n_hospitals_down": sum(1 for c, _ in ch if c < 0), "n_hospitals": len(ch), "top5": [[k, c] for c, k in ch[:5]]}, "change by hospital (adult and child rows summed by hospital name), latest vs a year earlier", {"report": rep}) # ---- ST11 band-sum instead of published Total for lst in lists: s = S[(lst, "bandsum")] p = pct(s[latest], s[yoy_base]) put(f"st11.{lst}.bandsum.yoy", {"latest": s[latest], "base": s[yoy_base], "pct": p, "verdict": verdict(p)}, "band-sum total, latest vs a year earlier", {"series": f"series.{lst}.bandsum"}) # ---- ST12 long run: latest vs same month of every earlier year for lst in lists: for ms in ["total", "l18"]: s = S[(lst, ms)] out = {} y = int(latest[:4]) - 1 while f"{y:04d}{latest[4:]}" in s: b = f"{y:04d}{latest[4:]}" out[b] = {"base": s[b], "pct": pct(s[latest], s[b]), "verdict": verdict(pct(s[latest], s[b]))} y -= 1 put(f"st12.{lst}.{ms}.vs_same_month", out, "latest vs the same calendar month of each earlier year", {"series": f"series.{lst}.{ms}"}) # ---- legacy-only Slaintecare-style share: under 3 months (0-3 band), last legacy month, IPDC and OP for lst in ["OP", "IPDC", "GI"]: rep = TOTAL_REPORTS[lst][0] a = sum(int(r["w0_3_legacy_only"]) for r in ntpf if r["report"] == rep and r["month"] == last_legacy) b = sum(r["total_published"] for r in ntpf if r["report"] == rep and r["month"] == last_legacy) put(f"legacy.{lst}.share_under_3_months.{last_legacy}", round(a / b * 100, 2), "0-3 month band / total x 100 (legacy files only; open-data bands start at 0-6 months)", {"report": rep}) # ---- descriptive: distance from the peak and from the low, to the latest month for lst in lists: for ms in ["total", "l12", "l18"]: s = S[(lst, ms)] od = {m: v for m, v in s.items() if m >= "2021-04"} pk = max(od, key=lambda m: (od[m], m)) lo = min(od, key=lambda m: (od[m], m)) put(f"desc.{lst}.{ms}.since_2021_04", {"peak_month": pk, "peak": od[pk], "low_month": lo, "low": od[lo], "latest": s[latest], "pct_vs_peak": pct(s[latest], od[pk]), "pct_vs_low": pct(s[latest], od[lo])}, "open-data period (Apr 2021 on): peak, low, and latest compared with each", {"series": f"series.{lst}.{ms}"}) # ---- POST-HOC (added after reading WTAP 2026; not in PREREG): checks against official statements and targets for lst in lists: u12 = {m: round((S[(lst, "bandsum")][m] - S[(lst, "l12")][m]) / S[(lst, "bandsum")][m] * 100, 2) for m in S[(lst, "bandsum")] if m >= "2021-04"} put(f"posthoc.{lst}.share_under_12_months", u12, "(band-sum total - l12) / band-sum total x 100, open-data months", {"series": [f"series.{lst}.bandsum", f"series.{lst}.l12"]}, note="Post-hoc. WTAP 2026 target: 90% of OPD patients waiting under 12 months (Dec 2025 position stated as 83.6%).") s = S[("ALL", "l12")] for a, b in [("2021-09", "2025-12"), ("2021-09", latest)]: put(f"posthoc.ALL.l12.{a}_to_{b}", {"from": s[a], "to": s[b], "change": s[b] - s[a], "pct": pct(s[b], s[a])}, "combined over-12-month waiters, change between two months", {"series": "series.ALL.l12"}, note="Post-hoc. Compare with WTAP 2026: 'c. 58% reduction ... over 164,000 less patients' Sep 2021 to Dec 2025.") s = S[("ALL", "total")] for a, b in [("2024-12", "2025-12"), ("2025-09", "2025-12")]: put(f"posthoc.ALL.total.{a}_to_{b}", {"from": s[a], "to": s[b], "change": s[b] - s[a], "pct": pct(s[b], s[a])}, "combined total, change between two months", {"series": "series.ALL.total"}, note="Post-hoc. Context for WTAP 2026 statement on reductions in total volumes October to December 2025.") out = {"edition_file": edition.replace("\\", "/").split("/")[-1], "edition_sha256": sha, "flat_threshold_pct": FLAT, "results": R} with open(out_path, "w", encoding="utf-8", newline="\n") as fh: json.dump(out, fh, indent=1, sort_keys=True, ensure_ascii=False) print("results:", len(R), "latest:", latest, "sha:", sha[:12]) if __name__ == "__main__": main(sys.argv[1], sys.argv[2])