"""Rebuild trust-level recorded overheating comparisons from NHS England ERIC CSVs.
Use Python 3.10+ with the four inputs in INPUTS beside this script.
Writes trusts.csv beside the script and prints the coverage and sensitivity checks.
"""
import csv
import hashlib
from dataclasses import dataclass
from pathlib import Path
HERE = Path(__file__).resolve().parent
METRIC = "Overheating occurrences triggering a risk assessment (No.)"
INPUTS = {
"site24.csv": "a9b6798fd6bc57aaf810164f575d4ac914ee313834cdfa87cabbe05f23dfe84f",
"trust24.csv": "56cea2dc7238e207dd35e4010f971f8d590624e1078634512b9a7f45d4e0e300",
"site25.csv": "b77cf6956854a08f96f9669e9d8d78c245873f7e643b9ca7fc99dafa233844fd",
"trust25.csv": "576e6dbe1b7568ac83332e7e3f7c0307fed0403ed934ef67ca3c09db28a8f49d",
}
def rows(filename):
path = HERE / filename
if hashlib.sha256(path.read_bytes()).hexdigest() != INPUTS[filename]:
raise ValueError(f"Input has changed: {filename}. Check the release version.")
with path.open(encoding="cp1252", newline="") as stream:
reader = csv.reader(stream)
header = next(row for row in reader if row[0] == "Trust Code")
for row in reader:
yield dict(zip(header, row, strict=True))
@dataclass
class Trust:
name: str
sites: int = 0
numeric: int = 0
zeros: int = 0
total: int = 0
def cells(self):
return self.sites, self.numeric, self.zeros, self.total if self.numeric else None
def release(year):
roster = {}
for row in rows(f"trust{year}.csv"):
code = row["Trust Code"]
assert code and code not in roster
roster[code] = Trust(row["Trust Name"])
sites = {}
for row in rows(f"site{year}.csv"):
code, site = row["Trust Code"], row["Site Code"]
trust = roster[code]
assert site and site not in sites and row["Trust Name"] == trust.name
value = row[METRIC].strip()
count = None if value == "Not Applicable" else int(value)
assert count is None or count >= 0
sites[site] = (code, count, row["Site Type"], row["Site Name"])
trust.sites += 1
if count is not None:
trust.numeric += 1
trust.zeros += count == 0
trust.total += count
assert all(t.sites for t in roster.values())
return roster, sites
def compare(label, old, new, keys):
left = sum(old[k] for k in keys)
right = sum(new[k] for k in keys)
print(label, "units", len(keys), "totals", left, right, "difference", right - left)
return right - left
def main():
a, sa = release("24")
b, sb = release("25")
old = {k: t.total for k, t in a.items() if t.numeric}
new = {k: t.total for k, t in b.items() if t.numeric}
matched = old.keys() & new.keys()
delta = compare("Same numeric trust codes", old, new, matched)
for tag, roster, counts in [("2024/25", a, old), ("2025/26", b, new)]:
print(tag, "trusts / numeric / zero / national total",
len(roster), len(counts), sum(v == 0 for v in counts.values()), sum(counts.values()))
print(tag, "site rows / numeric / zero",
sum(t.sites for t in roster.values()), sum(t.numeric for t in roster.values()),
sum(t.zeros for t in roster.values()))
with (HERE / "trusts.csv").open("w", newline="", encoding="utf-8") as stream:
writer = csv.writer(stream, lineterminator="\n")
columns = ["rows", "numeric", "zeros", "occurrences"]
writer.writerow(["code", "name"] + [f"{c}_{y}" for y in ["24", "25"] for c in columns]
+ ["status", "change", "matched_change_without_trust"])
for k in sorted(a.keys() | b.keys()):
eligible = k in matched
change = new[k] - old[k] if eligible else None
if eligible:
status = "matched"
elif k not in b:
status = "2024_only"
elif k not in a:
status = "2025_only"
else:
assert not a[k].numeric and not b[k].numeric
status = "all_NA"
writer.writerow([k, (b.get(k) or a[k]).name]
+ list(a[k].cells() if k in a else (None,) * 4)
+ list(b[k].cells() if k in b else (None,) * 4)
+ [status, change, delta - change if eligible else None])
changes = {k: new[k] - old[k] for k in matched}
print("Trust increases / decreases / unchanged",
sum(x > 0 for x in changes.values()), sum(x < 0 for x in changes.values()),
sum(x == 0 for x in changes.values()))
for k in [max(changes, key=changes.get), min(changes, key=changes.get)]:
print("Influence extreme", k, changes[k], "remaining", delta - changes[k])
for old_positive in (False, True):
for new_positive in (False, True):
group = {k for k in matched if (old[k] > 0) == old_positive
and (new[k] > 0) == new_positive}
compare(f"Positive before={old_positive}, after={new_positive}", old, new, group)
both_positive = {k for k in matched if old[k] > 0 and new[k] > 0}
compare("Positive in both, excluding Sandwell and West Birmingham",
old, new, both_positive - {"RXK"})
for group in [{"RAL", "RAP"}, {"RAX", "RY9", "RKL"}]:
print("Reorganisation group", sorted(group),
sum(old[k] for k in group & old.keys()), sum(new[k] for k in group & new.keys()))
london = {"RAL", "RAX", "RKL"}
compare("Outside both London groups", old, new, matched - london)
affected = london | {"RW1", "R1F", "G6V2S", "RNA", "TAJ"}
compare("Outside selected first-year transactions", old, new, matched - affected)
compare("Omitting two largest rises", old, new,
matched - set(sorted(changes, key=changes.get, reverse=True)[:2]))
same = sa.keys() & sb.keys()
assert all(sa[s][0] == sb[s][0] for s in same)
va = {s: v[1] for s, v in sa.items() if v[1] is not None}
vb = {s: v[1] for s, v in sb.items() if v[1] is not None}
paired = va.keys() & vb.keys()
compare("Same numeric trust/site codes", va, vb, paired)
individual = {s for s in paired if all(row[s][2] != "Other Reportable Site" for row in (sa, sb))}
compare("Same numeric site codes excluding aggregate rows", va, vb, individual)
for label, values, other, other_sites in [("2024/25", va, vb, sb), ("2025/26", vb, va, sa)]:
outside = values.keys() - other.keys()
for state, keys in [("absent", outside - other_sites.keys()),
("inapplicable", outside & other_sites.keys())]:
print(label, "numeric here and", state, "in other year", len(keys), sum(values[s] for s in keys))
if __name__ == "__main__":
main()