| import csv |
| import json |
| from collections import Counter |
|
|
| VALID_LABELS = {"0", "1", "2"} |
|
|
| POP_MAP = {"none": 0, "minor": 1, "major": 2} |
| DEV_MAP = {"low": 0, "medium": 1, "high": 2} |
| SITE_MAP = {"low": 0, "medium": 1, "high": 2} |
| FRAG_MAP = {"low": 0, "medium": 1, "high": 2} |
|
|
| REQUIRED_GOLD_COLS = [ |
| "id", |
| "population_shift", |
| "protocol_deviation_rate", |
| "site_variance_level", |
| "endpoint_fragility", |
| "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["population_shift"], POP_MAP, "population_shift") |
| _map_val(r["protocol_deviation_rate"], DEV_MAP, "protocol_deviation_rate") |
| _map_val(r["site_variance_level"], SITE_MAP, "site_variance_level") |
| _map_val(r["endpoint_fragility"], FRAG_MAP, "endpoint_fragility") |
|
|
| 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: |
| pop = _map_val(g["population_shift"], POP_MAP, "population_shift") |
| dev = _map_val(g["protocol_deviation_rate"], DEV_MAP, "protocol_deviation_rate") |
| site = _map_val(g["site_variance_level"], SITE_MAP, "site_variance_level") |
| frag = _map_val(g["endpoint_fragility"], FRAG_MAP, "endpoint_fragility") |
|
|
| |
| if frag == 2 and (pop == 2 or dev == 2 or site == 2): |
| return "2" |
|
|
| |
| highish = sum([ |
| 1 if pop >= 1 else 0, |
| 1 if dev >= 1 else 0, |
| 1 if site >= 1 else 0, |
| 1 if frag >= 1 else 0, |
| ]) |
| if highish >= 4 and (dev == 2 or site == 2): |
| return "2" |
|
|
| |
| if pop == 0 and dev == 0 and site == 0 and frag == 0: |
| return "0" |
|
|
| return "1" |
|
|
| def _risk_score(g: dict) -> float: |
| pop = _map_val(g["population_shift"], POP_MAP, "population_shift") |
| dev = _map_val(g["protocol_deviation_rate"], DEV_MAP, "protocol_deviation_rate") |
| site = _map_val(g["site_variance_level"], SITE_MAP, "site_variance_level") |
| frag = _map_val(g["endpoint_fragility"], FRAG_MAP, "endpoint_fragility") |
|
|
| |
| raw = pop + dev + site + (2 * frag) |
| |
| return raw / 10.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 = {str(r.get("id")).strip(): r for r in pred_rows if r.get("id") is not None} |
|
|
| total = 0 |
| correct = 0 |
| confusion = Counter() |
| errors = [] |
| missing_ids = [] |
|
|
| for g in gold_rows: |
| gid = str(g["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({ |
| "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)) |