import csv import json from collections import Counter VALID_LABELS = {"coherent", "tradeoff", "collapse_risk"} EXPOSURE_MAP = {"low": 0, "moderate": 1, "high": 2} CLEARANCE_MAP = {"low": 0, "normal": 1, "high": 2} COMED_MAP = {"low": 0, "moderate": 1, "high": 2} TOX_MAP = {"stable": 0, "rising": 1, "escalating": 2} REQUIRED_GOLD_COLS = [ "trial_id", "exposure_level", "metabolic_clearance", "co_medication_load", "toxicity_signal", "label", ] def _norm(x) -> str: return str(x).strip().lower() def _map_val(x, m, name: str) -> int: s = _norm(x) if s not in m: raise ValueError(f"Bad {name} value: {x}") return m[s] def _validate_gold_row(r: dict): for c in REQUIRED_GOLD_COLS: if c not in r: raise ValueError(f"Missing column: {c}") lab = str(r["label"]).strip() if lab not in VALID_LABELS: raise ValueError(f"Bad label: {r['label']}") _map_val(r["exposure_level"], EXPOSURE_MAP, "exposure_level") _map_val(r["metabolic_clearance"], CLEARANCE_MAP, "metabolic_clearance") _map_val(r["co_medication_load"], COMED_MAP, "co_medication_load") _map_val(r["toxicity_signal"], TOX_MAP, "toxicity_signal") def _extract_pred_label(pred_row: dict) -> str: v = pred_row.get("label") or pred_row.get("prediction") or pred_row.get("output") or "" s = str(v).strip() if s in VALID_LABELS: return s if s.startswith("{") and s.endswith("}"): try: obj = json.loads(s) if isinstance(obj, dict) and "label" in obj: lab = str(obj["label"]).strip() if lab in VALID_LABELS: return lab except Exception: pass return "invalid" def rule_pred(g: dict) -> str: exp = _map_val(g["exposure_level"], EXPOSURE_MAP, "exposure_level") clr = _map_val(g["metabolic_clearance"], CLEARANCE_MAP, "metabolic_clearance") com = _map_val(g["co_medication_load"], COMED_MAP, "co_medication_load") tox = _map_val(g["toxicity_signal"], TOX_MAP, "toxicity_signal") mismatch = (exp >= 1 and clr == 0) or (exp == 2 and clr <= 1) if tox == 2 and com == 2 and clr == 0 and exp >= 1: return "collapse_risk" if tox == 0 and exp <= 1 and clr >= 1 and com <= 1: return "coherent" return "tradeoff" def risk_score(g: dict) -> float: exp = _map_val(g["exposure_level"], EXPOSURE_MAP, "exposure_level") clr = _map_val(g["metabolic_clearance"], CLEARANCE_MAP, "metabolic_clearance") com = _map_val(g["co_medication_load"], COMED_MAP, "co_medication_load") tox = _map_val(g["toxicity_signal"], TOX_MAP, "toxicity_signal") clearance_penalty = 2 - clr raw = exp + com + tox + clearance_penalty # max raw = 2+2+2+2 = 8 return raw / 8.0 def run_scorer(preds_csv_path: str, gold_csv_path: str): with open(gold_csv_path, newline="", encoding="utf-8") as gf: gold_rows = list(csv.DictReader(gf)) for r in gold_rows: _validate_gold_row(r) with open(preds_csv_path, newline="", encoding="utf-8") as pf: pred_rows = list(csv.DictReader(pf)) pred_by_id = {} for r in pred_rows: pid = r.get("trial_id") or r.get("id") if pid is None: continue pred_by_id[str(pid).strip()] = r total = 0 correct = 0 confusion = Counter() errors = [] missing_ids = [] for g in gold_rows: gid = str(g["trial_id"]).strip() gold = str(g["label"]).strip() pr = pred_by_id.get(gid) if pr is None: pred = "missing" missing_ids.append(gid) else: pred = _extract_pred_label(pr) confusion[(gold, pred)] += 1 if pred == gold: correct += 1 else: errors.append({ "trial_id": gid, "gold": gold, "pred": pred, "rule_pred": rule_pred(g), "risk_score": round(risk_score(g), 4), }) total += 1 report = { "n": total, "accuracy": (correct / total) if total else 0.0, "confusion": {f"{k[0]}->{k[1]}": v for k, v in confusion.items()}, "avg_risk_score": round(sum(risk_score(r) for r in gold_rows) / max(1, len(gold_rows)), 4), "errors_sample": errors[:25], "missing_ids": missing_ids[:50], } return report if __name__ == "__main__": import argparse p = argparse.ArgumentParser() p.add_argument("--preds_csv", required=True) p.add_argument("--gold_csv", required=True) args = p.parse_args() print(json.dumps(run_scorer(args.preds_csv, args.gold_csv), indent=2))