omnidiag / scripts /v3_validation /population_run.py
yahyoha's picture
Space snapshot of af9d80f (binaries stripped)
ef838e0
Raw History Blame Contribute Delete
17.6 kB
#!/usr/bin/env python3
"""
V3-S1 validation, part B: run build_evidence_actions() over whole populations.
heart: every row of the training CSV named in configs/heart_disease.yaml
diabetes: the 26,904-row NHANES 2007-2018 screening cohort, rebuilt with the
exact construction of train_diabetes_nhanes_ebm_v2.py (lines 93-145)
from the raw NHANES files outside this repo (--nhanes-dir).
Every row goes to the builder directly (not over HTTP), NaN -> None. The rows
the API schema would refuse with a 422 are counted separately, by field: the
builder is meant for validated input, but the population run checks it does
not break on any real row.
Measures, per module and intervention: status distribution, share of patients
with >=1 indicated item / none, not_evaluable rate and the fields that caused
it, exceptions (count + first 5 tracebacks), the invariants on every row, R2 on
a 200-row sample, and 3 example patients per status.
Read-only: imports product code, changes none.
python scripts/v3_validation/population_run.py \
--nhanes-dir "/home/yahia/Desktop/Ψ¨ΩŠΨ§Ω†Ψ§Ψͺ Ψ³ΩƒΨ± جديدة " \
--out docs/v3/validation/population_run.json
"""
from __future__ import annotations
import argparse
import json
import math
import os
import random
import re
import sys
import traceback
from collections import Counter, defaultdict
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT))
from pydantic import ValidationError # noqa: E402
from backend.evidence.actions import build_evidence_actions # noqa: E402
from backend.evidence.registry import load_registry # noqa: E402
from backend.schemas import HeartDiseaseInput # noqa: E402
from backend.schemas_diabetes_nhanes import DiabetesNhanesInput # noqa: E402
STATUSES = ("indicated", "assess", "needs_measurement", "at_target", "not_evaluable")
FORBIDDEN = ("probability", "risk_reduction", "estimate")
CYCLES = ["2007-2008", "2009-2010", "2011-2012", "2013-2014", "2015-2016", "2017-2018"]
SCHEMAS = {"heart_disease": HeartDiseaseInput, "diabetes_nhanes": DiabetesNhanesInput}
IMMUTABLE_PERTURB = {
# R2: change ONLY age and sex; items must not move.
"heart_disease": lambda p: {**p, "Age": 30 if (p.get("Age") or 0) > 50 else 70,
"Sex": "F" if p.get("Sex") == "M" else "M"},
"diabetes_nhanes": lambda p: {**p, "RIDAGEYR": 25 if (p.get("RIDAGEYR") or 0) > 50 else 75,
"RIAGENDR": 0 if p.get("RIAGENDR") == 1 else 1},
}
# ── data ─────────────────────────────────────────────────────────────────────
def heart_rows() -> list[dict]:
config = yaml.safe_load(open(ROOT / "configs/heart_disease.yaml"))
path = ROOT / config["data"]["training_file"]
frame = pd.read_csv(path)
inputs = list(HeartDiseaseInput.model_fields)
return [_clean({k: r[k] for k in inputs if k in r}) for r in frame.to_dict("records")], str(path.relative_to(ROOT))
def nhanes_rows(nhanes_dir: Path) -> list[dict]:
"""The training cohort, built exactly as train_diabetes_nhanes_ebm_v2.py does."""
want = {
"demographics/demographics.csv": ["SEQN", "RIDSTATR", "RIAGENDR", "RIDAGEYR", "RIDEXPRG", "RIDRETH3", "WTMEC2YR"],
"examination/body_measures.csv": ["SEQN", "BMXBMI", "BMXWAIST", "BMXHT", "BMXWT"],
"examination/blood_pressure.csv": ["SEQN", "BPXPLS"] + [f"BPXSY{i}" for i in (1, 2, 3)] + [f"BPXDI{i}" for i in (1, 2, 3)],
"laboratory/glycohemoglobin.csv": ["SEQN", "LBXGH"],
"laboratory/standard_biochem_profile.csv": None,
"laboratory/cholestrol_hdl.csv": ["SEQN", "LBDHDD"],
"questionnaire/diabetes.csv": ["SEQN", "DIQ010", "DIQ050", "DIQ070"],
"questionnaire/medical_conditions.csv": ["SEQN", "MCQ300C", "MCQ160B", "MCQ160C", "MCQ160E", "MCQ160F"],
"questionnaire/physical_activity.csv": ["SEQN", "PAQ650", "PAQ665"],
}
def load(path, cols):
parts = []
for c in CYCLES:
fp = nhanes_dir / "nhanes_raw" / c / path
if not fp.exists():
continue
d = pd.read_csv(fp, encoding="latin1")
d = d if cols is None else d[[x for x in cols if x in d.columns]]
if path.startswith("demographics"):
d = d.assign(cycle=c)
parts.append(d)
return pd.concat(parts, ignore_index=True) if parts else None
df = load("demographics/demographics.csv", want["demographics/demographics.csv"])
for path, cols in list(want.items())[1:]:
d = load(path, cols)
if d is None:
continue
df = df.merge(d.loc[:, ~d.columns.duplicated()], on="SEQN", how="left", suffixes=("", "_dup"))
df = df.loc[:, ~df.columns.str.endswith("_dup")]
df = df[(df.RIDSTATR == 2) & (df.RIDAGEYR >= 20) & (df.RIDEXPRG.fillna(0) != 1) & df.LBXGH.notna()].copy()
for i in (1, 2, 3):
df.loc[df[f"BPXDI{i}"] == 0, f"BPXDI{i}"] = np.nan
df["SBP"] = df[[f"BPXSY{i}" for i in (1, 2, 3)]].mean(axis=1)
df["DBP"] = df[[f"BPXDI{i}" for i in (1, 2, 3)]].mean(axis=1)
df["CVD_ANY"] = df[["MCQ160B", "MCQ160C", "MCQ160E", "MCQ160F"]].eq(1).any(axis=1).astype(float)
for c in ["MCQ300C", "PAQ650", "PAQ665", "RIAGENDR"]:
df[c] = df[c].map({1: 1.0, 2: 0.0})
df["WHtR"] = df.BMXWAIST / df.BMXHT
df["ADIPOSITY_BAND"] = pd.cut(df.WHtR, [-np.inf, 0.50, 0.60, np.inf], labels=[0, 1, 2]).astype("float")
diag = df.DIQ010.eq(1)
meds = df.DIQ050.eq(1) | df.DIQ070.eq(1)
cohort = df[~(diag | meds)].copy()
assert len(cohort) == 26904, f"cohort drifted from the verified 26904: {len(cohort)}"
band = {0.0: "normal", 1.0: "increased", 2.0: "high"}
cohort["ADIPOSITY_BAND"] = cohort["ADIPOSITY_BAND"].map(band)
inputs = list(DiabetesNhanesInput.model_fields)
return [_clean({k: r.get(k) for k in inputs}) for r in cohort.to_dict("records")]
def _clean(row: dict) -> dict:
out = {}
for k, v in row.items():
if isinstance(v, float) and math.isnan(v):
v = None
elif isinstance(v, (np.floating,)):
v = None if np.isnan(v) else float(v)
elif isinstance(v, (np.integer,)):
v = int(v)
out[k] = v
return out
# ── invariants ───────────────────────────────────────────────────────────────
REGISTRY = load_registry()
def _leaves(node):
if isinstance(node, dict):
for v in node.values():
yield from _leaves(v)
elif isinstance(node, list):
for v in node:
yield from _leaves(v)
else:
yield node
def _keys(node, path=()):
if isinstance(node, dict):
for k, v in node.items():
yield path, k
yield from _keys(v, path + (k,))
elif isinstance(node, list):
for i, v in enumerate(node):
yield from _keys(v, path + (i,))
def _numbers(node, path=()):
if isinstance(node, dict):
for k, v in node.items():
yield from _numbers(v, path + (k,))
elif isinstance(node, list):
for i, v in enumerate(node):
yield from _numbers(v, path + (i,))
elif isinstance(node, (int, float)) and not isinstance(node, bool):
yield path, node
REGISTRY_NUMBERS = {v for v in _leaves(REGISTRY) if isinstance(v, (int, float)) and not isinstance(v, bool)}
REGISTRY_STRING_NUMBERS = {
t for v in _leaves(REGISTRY) if isinstance(v, str)
for t in re.findall(r"(?<![\w.])\d+(?:\.\d+)?(?![\w])", v)
}
def invariant_violations(response: dict, patient: dict) -> list[str]:
bad = []
for path, key in _keys(response):
if any(part in str(key).lower() for part in FORBIDDEN):
bad.append(f"forbidden key {key!r} at {path}")
for path, number in _numbers(response):
if "matched_clauses" in path and path[-1] == "value":
clause = response
for step in path[:-1]:
clause = clause[step]
if patient.get(clause["field"]) != number:
bad.append(f"clause value {number} != patient {clause['field']}={patient.get(clause['field'])}")
elif number not in REGISTRY_NUMBERS:
bad.append(f"number {number} at {path} not in registry")
# A patient value as given, or at a registry display precision (0-2 decimals).
patient_numbers = {
text for v in patient.values() if isinstance(v, (int, float)) and not isinstance(v, bool)
for text in [f"{v:g}" if isinstance(v, float) else str(v)] + [f"{v:.{d}f}" for d in range(3)]
}
for item in response["items"]:
for token in re.findall(r"(?<![\w.])\d+(?:\.\d+)?(?![\w])", item.get("matched_rule") or ""):
if token not in patient_numbers and token not in REGISTRY_STRING_NUMBERS:
bad.append(f"matched_rule number {token} neither patient nor registry: {item['matched_rule']}")
sources = [e["source"] for e in item.get("effects") or []]
sources += [item["rule_source"]] if item.get("rule_source") else []
sources += [r["source"] for r in item.get("reasons") or [] if r.get("source")]
for source in sources:
if not (source.get("doi") or source.get("pmid")):
bad.append(f"source {source.get('id')} without DOI/PMID")
return bad
# ── run ──────────────────────────────────────────────────────────────────────
def schema_rejections(disease: str, rows: list[dict]) -> dict:
"""Rows the API schema would refuse (422), per field: blank vs which bound,
with the offending values' range and the field's schema range."""
schema = SCHEMAS[disease]
by_field: Counter = Counter()
detail: dict = defaultdict(lambda: defaultdict(lambda: {"n": 0, "min": None, "max": None, "values": Counter()}))
rejected = 0
for row in rows:
try:
schema(**row)
except ValidationError as exc:
rejected += 1
for err in exc.errors():
field = ".".join(str(p) for p in err["loc"])
by_field[field] += 1
value = err.get("input")
ctx = err.get("ctx") or {}
if value is None:
kind = "blank (required, no default)"
elif "ge" in ctx:
kind = f"below minimum (ge={ctx['ge']})"
elif "le" in ctx:
kind = f"above maximum (le={ctx['le']})"
elif "expected" in ctx:
kind = f"not one of {ctx['expected']}"
else:
kind = err.get("type", "invalid")
d = detail[field][kind]
d["n"] += 1
if isinstance(value, (int, float)) and not isinstance(value, bool):
d["min"] = value if d["min"] is None else min(d["min"], value)
d["max"] = value if d["max"] is None else max(d["max"], value)
elif value is not None:
d["values"][str(value)] += 1
def schema_range(field):
info = schema.model_fields.get(field)
if info is None:
return None
ge = next((m.ge for m in info.metadata if getattr(m, "ge", None) is not None), None)
le = next((m.le for m in info.metadata if getattr(m, "le", None) is not None), None)
required = info.is_required()
return {"ge": ge, "le": le, "required": required, "annotation": str(info.annotation)}
return {
"rows": len(rows), "rejected": rejected, "rejected_pct": round(100 * rejected / len(rows), 2),
"by_field": dict(by_field.most_common()),
"detail": {
field: {"schema": schema_range(field),
"violations": {k: {**v, "values": dict(v["values"])} for k, v in kinds.items()}}
for field, kinds in detail.items()
},
}
def run_module(disease: str, rows: list[dict], seed: int = 42) -> dict:
per_intervention: dict = defaultdict(Counter)
not_evaluable_fields: dict = defaultdict(Counter)
examples: dict = defaultdict(lambda: defaultdict(list))
exceptions, tracebacks = 0, []
violations: Counter = Counter()
violation_examples: list = []
with_indicated = 0
responses = []
for idx, patient in enumerate(rows):
try:
response = build_evidence_actions(disease, patient)
except Exception: # noqa: BLE001 β€” counting is the point
exceptions += 1
if len(tracebacks) < 5:
tracebacks.append({"row": idx, "traceback": traceback.format_exc()})
responses.append(None)
continue
responses.append(response)
bad = invariant_violations(response, patient)
for b in bad:
violations[b.split(" ")[0] + " " + b.split(" ")[1]] += 1
if bad and len(violation_examples) < 5:
violation_examples.append({"row": idx, "violations": bad[:5]})
statuses = {i["intervention_id"]: i for i in response["items"]}
if any(i["status"] == "indicated" for i in response["items"]):
with_indicated += 1
for iid, item in statuses.items():
per_intervention[iid][item["status"]] += 1
if item["status"] == "not_evaluable":
for field in item.get("missing") or []:
not_evaluable_fields[iid][field] += 1
bucket = examples[iid][item["status"]]
if len(bucket) < 3:
bucket.append({"row": idx, "matched_rule": item.get("matched_rule"),
"headline": item.get("headline"), "missing": item.get("missing"),
"inputs": {f["feature"]: patient.get(f["feature"]) for f in item["features"]}})
n = len(rows)
# Interventions with a silent band (heart FastingBS = 0) produce no item.
distribution = {}
for iid, counts in per_intervention.items():
total = sum(counts.values())
distribution[iid] = {
"items": total,
"no_item_silent": n - total,
**{s: {"n": counts.get(s, 0), "pct": round(100 * counts.get(s, 0) / n, 2)} for s in STATUSES},
"not_evaluable_fields": dict(not_evaluable_fields[iid].most_common()),
}
# R2 on a 200-row sample: change only age and sex.
rng = random.Random(seed)
sample = rng.sample(range(n), min(200, n))
r2_failures = []
for idx in sample:
if responses[idx] is None:
continue
moved = build_evidence_actions(disease, IMMUTABLE_PERTURB[disease](rows[idx]))
if moved["items"] != responses[idx]["items"]:
r2_failures.append(idx)
return {
"rows": n,
"exceptions": exceptions,
"first_tracebacks": tracebacks,
"pct_with_indicated": round(100 * with_indicated / n, 2),
"pct_with_no_indicated": round(100 * (n - with_indicated - exceptions) / n, 2),
"status_by_intervention": distribution,
"invariant_violations": dict(violations),
"invariant_violation_examples": violation_examples,
"r2_sample": {"n": len(sample), "seed": seed, "items_changed": len(r2_failures),
"changed_rows": r2_failures[:10]},
"examples": {iid: dict(by_status) for iid, by_status in examples.items()},
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--nhanes-dir", required=True, type=Path)
ap.add_argument("--out", default=str(ROOT / "docs/v3/validation/population_run.json"))
args = ap.parse_args()
heart, heart_source = heart_rows()
nhanes = nhanes_rows(args.nhanes_dir)
result = {
"sources": {
"heart_disease": heart_source,
"diabetes_nhanes": "NHANES 2007-2018 cohort rebuilt from nhanes_raw/ "
"(construction of train_diabetes_nhanes_ebm_v2.py; n asserted = 26904)",
},
"schema_rejections": {
"heart_disease": schema_rejections("heart_disease", heart),
"diabetes_nhanes": schema_rejections("diabetes_nhanes", nhanes),
},
"heart_disease": run_module("heart_disease", heart),
"diabetes_nhanes": run_module("diabetes_nhanes", nhanes),
}
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2, default=str) + "\n", encoding="utf-8")
for disease in SCHEMAS:
r = result[disease]
print(f"== {disease}: rows={r['rows']} exceptions={r['exceptions']} "
f">=1 indicated={r['pct_with_indicated']}% none={r['pct_with_no_indicated']}% "
f"violations={r['invariant_violations']} r2_changed={r['r2_sample']['items_changed']}")
for iid, d in r["status_by_intervention"].items():
print(f" {iid:28s} " + " ".join(f"{s}={d[s]['n']}({d[s]['pct']}%)" for s in STATUSES)
+ f" silent={d['no_item_silent']} ne_fields={d['not_evaluable_fields']}")
print(" schema would reject:", result["schema_rejections"][disease])
print(f"wrote {out.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
sys.exit(main())