#!/usr/bin/env python3 """AcuBench evaluation harness (self-contained). Ports the metric definitions from the research repo's `acubench/src/metrics.py` with NO external import beyond numpy/scikit-learn. Scores a predictions file against a gold file over the fixed 361-point WHO label space. METRIC SUITE ------------ * jaccard_mean -- mean per-sample Jaccard(pred_set, gold_set) * f1_macro -- mean per-sample (example-based) F1 * f1_micro -- pooled TP/FP/FN across all samples, one global F1 * precision_at_k / recall_at_k / ndcg_at_k for k in --ks (default 5,10,20) * prauc_mean -- mean per-sample average precision (needs scores) * invalid_combination_rate -- structural meridian-scatter PROXY (needs --who) INPUT FORMATS ------------- predictions file (JSONL, one object per line). Each object needs an "id" and at least one of: {"id": 12, "acupoints": ["LU1","LU7"]} # a predicted set {"id": 12, "scores": {"LU1": 0.9, "LU7": 0.8, ...}} # per-point scores {"id": 12, "acupoints": [...], "scores": {...}} # both (recommended) - "acupoints" drives the SET metrics (Jaccard / F1-micro / F1-macro) and the meridian-validity proxy. - "scores" drives the RANKING metrics (P@k / R@k / NDCG@k / PRAUC). If a row has no "scores", ranking falls back to its "acupoints" ranked alphabetically (a weak but deterministic proxy -- provide real scores for meaningful ranking metrics). PRAUC is only reported when at least one row supplies "scores". - If a row has "scores" but no "acupoints", the predicted set is taken as every point with score > --score-threshold (default 0.5). gold file (JSONL). Each object needs "id" and "acupoints". The AcuBench `acubench.jsonl` produced by build_acubench.py works directly as the gold file (it also carries "split", so pass --split test to score only the test rows). The shipped sample_labels.jsonl uses "symptoms" instead of an "id"; pass --gold-key symptoms to key rows by their symptom string, and key your predictions the same way (use the symptom string as "id"). USAGE ----- python3 eval.py --pred preds.jsonl --gold acubench.jsonl --who who_acupoints.csv python3 eval.py --pred preds.jsonl --gold acubench.jsonl --split test --who who_acupoints.csv python3 eval.py --pred preds.jsonl --gold sample_labels.jsonl --gold-key symptoms Prints a JSON metric dict to stdout (use --out to also write it to a file). TINY EXAMPLE (predictions JSONL) {"id": 0, "acupoints": ["CV15"], "scores": {"CV15": 0.9, "LU1": 0.1}} {"id": 1, "acupoints": ["LU1", "LU2"], "scores": {"LU1": 0.8, "LU2": 0.7}} """ import argparse import csv import json import math from collections import defaultdict from typing import Dict, Iterable, List, Optional, Sequence, Tuple import numpy as np from sklearn.metrics import average_precision_score # -------------------------------------------------------------------------- # Set metrics (ported verbatim from src/metrics.py). # -------------------------------------------------------------------------- def jaccard(pred: Iterable[str], gold: Iterable[str]) -> float: pred, gold = set(pred), set(gold) if not pred and not gold: return 1.0 union = pred | gold if not union: return 1.0 return len(pred & gold) / len(union) def precision_recall_f1(pred: Iterable[str], gold: Iterable[str]) -> Tuple[float, float, float]: pred, gold = set(pred), set(gold) tp = len(pred & gold) precision = tp / len(pred) if pred else (1.0 if not gold else 0.0) recall = tp / len(gold) if gold else (1.0 if not pred else 0.0) f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0 return precision, recall, f1 def f1_macro(pred_sets: Sequence[Iterable[str]], gold_sets: Sequence[Iterable[str]]) -> float: if not pred_sets: return 0.0 scores = [precision_recall_f1(p, g)[2] for p, g in zip(pred_sets, gold_sets)] return sum(scores) / len(scores) def f1_micro(pred_sets: Sequence[Iterable[str]], gold_sets: Sequence[Iterable[str]]) -> float: tp = fp = fn = 0 for pred, gold in zip(pred_sets, gold_sets): pred, gold = set(pred), set(gold) tp += len(pred & gold) fp += len(pred - gold) fn += len(gold - pred) precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0 recall = tp / (tp + fn) if (tp + fn) > 0 else 0.0 return 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0.0 # -------------------------------------------------------------------------- # Ranking metrics. # -------------------------------------------------------------------------- def precision_at_k(ranked_points: Sequence[str], gold: Iterable[str], k: int) -> float: gold = set(gold) top_k = ranked_points[:k] if not top_k: return 0.0 hits = sum(1 for p in top_k if p in gold) return hits / len(top_k) def recall_at_k(ranked_points: Sequence[str], gold: Iterable[str], k: int) -> float: gold = set(gold) if not gold: return 1.0 top_k = ranked_points[:k] hits = sum(1 for p in top_k if p in gold) return hits / len(gold) def ndcg_at_k(ranked_points: Sequence[str], gold: Iterable[str], k: int) -> float: gold = set(gold) top_k = ranked_points[:k] dcg = sum((1.0 if p in gold else 0.0) / math.log2(i + 2) for i, p in enumerate(top_k)) ideal_hits = min(len(gold), k) idcg = sum(1.0 / math.log2(i + 2) for i in range(ideal_hits)) return dcg / idcg if idcg > 0 else 0.0 def average_precision(scores: Dict[str, float], gold: Iterable[str]) -> float: gold = set(gold) if not scores: return 0.0 points = list(scores.keys()) y_true = [1 if p in gold else 0 for p in points] if sum(y_true) == 0: return 0.0 y_score = [scores[p] for p in points] return float(average_precision_score(y_true, y_score)) def _ranked_from_scores(scores: Dict[str, float]) -> List[str]: """Rank points by score descending; deterministic alphabetical tie-break.""" return [p for p, _ in sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))] # -------------------------------------------------------------------------- # Meridian-validity heuristic (structural PROXY, NOT a clinical judgment). # -------------------------------------------------------------------------- def is_valid_combination( pred: Iterable[str], point_meridian_map: Dict[str, str], max_distinct_meridian_ratio: float = 0.8, min_size_for_check: int = 3, ) -> bool: """Documented, rule-based PROXY for prescription plausibility -- NOT a clinical validity check. Flags a set of size >= min_size_for_check as 'implausible' (structurally scattered) when distinct_meridians / n_points exceeds max_distinct_meridian_ratio. See src/metrics.py for full rationale. """ pred = list(pred) n = len(pred) if n < min_size_for_check: return True meridians = [point_meridian_map[p] for p in pred if p in point_meridian_map] if not meridians: return True distinct = len(set(meridians)) ratio = distinct / n return ratio <= max_distinct_meridian_ratio def invalid_combination_rate( pred_sets: Sequence[Iterable[str]], point_meridian_map: Dict[str, str], max_distinct_meridian_ratio: float = 0.8, min_size_for_check: int = 3, ) -> float: if not pred_sets: return 0.0 flags = [ not is_valid_combination(p, point_meridian_map, max_distinct_meridian_ratio, min_size_for_check) for p in pred_sets ] return sum(flags) / len(flags) # -------------------------------------------------------------------------- # Batch summary. # -------------------------------------------------------------------------- def summarize( pred_sets: Sequence[Iterable[str]], gold_sets: Sequence[Iterable[str]], scores: Optional[Sequence[Optional[Dict[str, float]]]] = None, point_meridian_map: Optional[Dict[str, str]] = None, ks: Sequence[int] = (5, 10, 20), ) -> Dict[str, float]: pred_sets = [set(p) for p in pred_sets] gold_sets = [set(g) for g in gold_sets] n = len(pred_sets) result: Dict[str, float] = {"n_samples": n} if n == 0: return result result["jaccard_mean"] = sum(jaccard(p, g) for p, g in zip(pred_sets, gold_sets)) / n result["f1_macro"] = f1_macro(pred_sets, gold_sets) result["f1_micro"] = f1_micro(pred_sets, gold_sets) # Ranked list per sample: real scores where given, else alphabetical # fallback over the predicted set (documented weak proxy). any_scores = scores is not None and any(s for s in scores) if scores is not None: ranked_lists = [ _ranked_from_scores(s) if s else sorted(pred_sets[i]) for i, s in enumerate(scores) ] else: ranked_lists = [sorted(p) for p in pred_sets] for k in ks: result[f"precision_at_{k}"] = sum( precision_at_k(r, g, k) for r, g in zip(ranked_lists, gold_sets) ) / n result[f"recall_at_{k}"] = sum( recall_at_k(r, g, k) for r, g in zip(ranked_lists, gold_sets) ) / n result[f"ndcg_at_{k}"] = sum( ndcg_at_k(r, g, k) for r, g in zip(ranked_lists, gold_sets) ) / n if any_scores: result["prauc_mean"] = sum( average_precision(s, g) for s, g in zip(scores, gold_sets) if s ) / sum(1 for s in scores if s) if point_meridian_map is not None: result["invalid_combination_rate"] = invalid_combination_rate(pred_sets, point_meridian_map) return result # -------------------------------------------------------------------------- # I/O helpers. # -------------------------------------------------------------------------- def load_jsonl(path: str) -> List[dict]: rows = [] with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if line: rows.append(json.loads(line)) return rows def load_point_meridian_map(who_csv: str) -> Dict[str, str]: mapping = {} with open(who_csv, newline="") as f: for row in csv.DictReader(f): mapping[row["point_code"]] = row["meridian"] return mapping def _row_key(row: dict, key: str): """Key a row: by 'id' (default), or by the join column (e.g. 'symptoms'). 'symptoms' may be a list -> use its single element / joined string.""" if key == "id": return row["id"] val = row.get(key) if isinstance(val, list): return val[0] if len(val) == 1 else "|".join(map(str, val)) return val def align( preds: List[dict], golds: List[dict], gold_key: str, score_threshold: float, ) -> Tuple[List[List[str]], List[List[str]], List[Optional[Dict[str, float]]]]: """Join predictions to gold rows on the key column. Returns aligned (pred_sets, gold_sets, scores_per_row) over the intersection of keys.""" pred_by_key = {} for r in preds: # Predictions key on "id" by default; when gold is keyed by another # column, predictions should carry that value in "id". k = r.get("id") if k is None and gold_key != "id": k = _row_key(r, gold_key) pred_by_key[k] = r pred_sets: List[List[str]] = [] gold_sets: List[List[str]] = [] scores: List[Optional[Dict[str, float]]] = [] matched = 0 for g in golds: gk = _row_key(g, gold_key) if gk not in pred_by_key: # Missing prediction = empty predicted set (penalized, not skipped). pred_sets.append([]) gold_sets.append(list(g["acupoints"])) scores.append(None) continue matched += 1 pr = pred_by_key[gk] sc = pr.get("scores") if pr.get("acupoints") is not None: pset = list(pr["acupoints"]) elif sc: pset = [p for p, v in sc.items() if v > score_threshold] else: pset = [] pred_sets.append(pset) gold_sets.append(list(g["acupoints"])) scores.append(sc if sc else None) print(f"Matched {matched}/{len(golds)} gold rows to predictions " f"({len(golds) - matched} gold rows had no prediction -> scored as empty set).") return pred_sets, gold_sets, scores def main() -> None: ap = argparse.ArgumentParser(description="Evaluate AcuBench predictions against gold labels.") ap.add_argument("--pred", required=True, help="Predictions JSONL file.") ap.add_argument("--gold", required=True, help="Gold JSONL file (e.g. acubench.jsonl).") ap.add_argument("--who", default=None, help="who_acupoints.csv (enables invalid_combination_rate).") ap.add_argument("--split", default=None, help="Only score gold rows whose 'split' == this value.") ap.add_argument("--gold-key", default="id", help="Join column (default 'id'; use 'symptoms' for sample_labels.jsonl).") ap.add_argument("--score-threshold", type=float, default=0.5, help="Threshold to derive a set from scores when 'acupoints' absent.") ap.add_argument("--ks", default="5,10,20", help="Comma-separated k values for @k metrics.") ap.add_argument("--out", default=None, help="Optional path to also write the metric dict as JSON.") args = ap.parse_args() preds = load_jsonl(args.pred) golds = load_jsonl(args.gold) if args.split is not None: golds = [g for g in golds if g.get("split") == args.split] print(f"Filtered gold to split={args.split!r}: {len(golds)} rows.") ks = tuple(int(x) for x in args.ks.split(",") if x.strip()) pmm = load_point_meridian_map(args.who) if args.who else None pred_sets, gold_sets, scores = align(preds, golds, args.gold_key, args.score_threshold) result = summarize(pred_sets, gold_sets, scores=scores, point_meridian_map=pmm, ks=ks) print(json.dumps(result, indent=2)) if args.out: with open(args.out, "w") as f: json.dump(result, f, indent=2) print(f"Wrote {args.out}") if __name__ == "__main__": main()