#!/usr/bin/env python3 """ UnsolvedMedical v3.0.0 — Frontier AI Study-Design & Hypothesis Benchmark Suite (`eval/`). Modes: 1. `python3 scripts/evaluate_ai_benchmark.py --build` Extracts the stratified 500-problem Frontier Benchmark (`eval/benchmark_v3.jsonl`, 25 problems per medical category x 20 categories, balanced across all 20 question types) and computes baseline reference scores in `eval/benchmark_summary.json`. 2. `python3 scripts/evaluate_ai_benchmark.py --predictions ` Evaluates an AI model's study-design, evidence-gap, PICO-estimand, and hypothesis predictions against `eval/benchmark_v3.jsonl`. """ import argparse import json import re from collections import Counter, defaultdict from pathlib import Path ROOT = Path(__file__).resolve().parent.parent BENCHMARK_PATH = ROOT / "eval" / "benchmark_v3.jsonl" SUMMARY_PATH = ROOT / "eval" / "benchmark_summary.json" def tokenize(text: str) -> set[str]: return {w.lower() for w in re.findall(r"[A-Za-z0-9]{3,}", text or "")} def set_f1(pred_set: set, gold_set: set) -> float: if not pred_set and not gold_set: return 1.0 if not pred_set or not gold_set: return 0.0 inter = len(pred_set & gold_set) if inter == 0: return 0.0 prec = inter / len(pred_set) rec = inter / len(gold_set) return 2 * prec * rec / (prec + rec) def score_prediction(pred: dict, ref: dict) -> dict[str, float]: """Score a single model prediction dictionary against a benchmark reference_target.""" # 1. Study Mode Selection F1 pred_modes = set(pred.get("acceptable_study_modes") or []) gold_modes = set(ref.get("acceptable_study_modes") or []) study_mode_f1 = set_f1(pred_modes, gold_modes) * 100.0 # 2. Evidence Gap Diagnosis F1 pred_gaps = set(pred.get("evidence_gap_types") or []) gold_gaps = set(ref.get("evidence_gap_types") or []) evidence_gap_f1 = set_f1(pred_gaps, gold_gaps) * 100.0 # 3. PICO & Estimand Specification Score gold_pico_tokens = tokenize( f"{ref.get('target_intervention_or_predictor', '')} {ref.get('target_comparator', '')} " f"{ref.get('critical_outcome', '')} {' '.join(ref.get('minimum_conditions', []))}" ) pred_pico_tokens = tokenize( f"{pred.get('target_intervention_or_predictor', '')} {pred.get('target_comparator', '')} " f"{pred.get('critical_outcome', '')} {pred.get('settlement_design_summary', '')} " f"{' '.join(pred.get('minimum_conditions', []))}" ) pico_estimand_score = set_f1(pred_pico_tokens, gold_pico_tokens) * 100.0 # 4. Falsifiable Competing Hypotheses Coverage Score gold_hyp_tokens = tokenize( " ".join( f"{h.get('description', '')} {' '.join(h.get('predicted_observations', []))}" for h in (ref.get("competing_hypotheses") or []) ) ) pred_hyps = pred.get("competing_hypotheses") or [] pred_hyp_tokens = tokenize( " ".join( (f"{h.get('description', '')} {' '.join(h.get('predicted_observations', []))}" if isinstance(h, dict) else str(h)) for h in pred_hyps ) ) has_two_hyps = 1.0 if len(pred_hyps) >= 2 else (0.5 if len(pred_hyps) == 1 else 0.0) hypothesis_score = (0.75 * set_f1(pred_hyp_tokens, gold_hyp_tokens) + 0.25 * has_two_hyps) * 100.0 composite = ( 0.30 * study_mode_f1 + 0.25 * evidence_gap_f1 + 0.25 * pico_estimand_score + 0.20 * hypothesis_score ) return { "study_mode_f1": round(study_mode_f1, 2), "evidence_gap_f1": round(evidence_gap_f1, 2), "pico_estimand_score": round(pico_estimand_score, 2), "hypothesis_coverage_score": round(hypothesis_score, 2), "overall_composite_score": round(composite, 2), } def build_benchmark() -> None: problems = json.loads((ROOT / "problems.json").read_text(encoding="utf-8")) by_cat = defaultdict(list) for p in problems: if p.get("is_gold_seed"): by_cat[p["category_num"]].append(p) benchmark_rows = [] qtype_counter = Counter() for cat_num in range(1, 21): cands = by_cat[cat_num] # Select 25 problems per category balancing question types and difficulty cands_sorted = sorted( cands, key=lambda r: (qtype_counter[r["question_type"]], -r["difficulty_level_id"], r["problem_number"]), ) chosen = [] used_ids = set() for _ in range(25): best = min( (c for c in cands if c["id"] not in used_ids), key=lambda r: (qtype_counter[r["question_type"]], -r["difficulty_level_id"], r["problem_number"]), ) chosen.append(best) used_ids.add(best["id"]) qtype_counter[best["question_type"]] += 1 chosen.sort(key=lambda r: r["problem_number"]) for r in chosen: benchmark_rows.append({ "benchmark_id": f"UMED-BENCH-{len(benchmark_rows) + 1:04d}", "problem_id": r["id"], "category_id": r["category_id"], "question_type": r["question_type"], "research_difficulty": r["research_difficulty"], "prompt_input": { "title": r["title"], "statement": r["statement"], "clean_statement": r["clean_statement"], "background": r["background"], "condition": r["condition_or_health_state"]["name"], "population": r["population"]["description"], "time_horizon": r["time_horizon"], "known_partial_results": [k["summary"] for k in r["known_partial_results"]], "source_citation": r["source_citation"], }, "reference_target": { "question_framework_type": r["question_framework"]["type"], "target_intervention_or_predictor": r["intervention_exposure_test_or_predictor"]["name"], "target_kind": r["intervention_exposure_test_or_predictor"]["kind"], "target_comparator": r["comparator_or_reference"], "critical_outcome": r["outcomes"][0]["name"], "safety_outcome": r["outcomes"][1]["name"] if len(r["outcomes"]) > 1 else "", "evidence_gap_types": r["evidence_gap_types"], "acceptable_study_modes": r["what_would_settle_it"]["acceptable_study_modes"], "settlement_design_summary": r["what_would_settle_it"]["summary"], "minimum_conditions": r["what_would_settle_it"]["minimum_conditions"], "competing_hypotheses": r["competing_hypotheses_or_interpretations"], "active_clinical_trial": r["status_assessment"]["active_research"][0] if r["status_assessment"]["active_research"] else "", }, }) BENCHMARK_PATH.parent.mkdir(parents=True, exist_ok=True) with BENCHMARK_PATH.open("w", encoding="utf-8") as f: for row in benchmark_rows: f.write(json.dumps(row, ensure_ascii=False, separators=(",", ":")) + "\n") # Compute 3 reference baselines on the 500 benchmark tasks: # 1. Majority-Class / Uninformed Clinical Baseline (always predicts standard RCT + general gap) # 2. Lexical / Prompt-Extraction Heuristic Baseline (infers study mode & PICO from prompt text keywords) # 3. Domain-Stratified Retrieval Baseline (retrieves nearest neighbor in same category) majority_scores = [] lexical_scores = [] retrieval_scores = [] for idx, row in enumerate(benchmark_rows): ref = row["reference_target"] p_in = row["prompt_input"] stmt_low = p_in["statement"].lower() # Baseline 1: Majority-Class RCT Baseline maj_pred = { "acceptable_study_modes": ["randomized_trial", "prospective_cohort"], "evidence_gap_types": ["no_adequately_powered_study", "uncertain_long_term_effects"], "target_intervention_or_predictor": p_in["condition"], "target_comparator": "Standard of care", "critical_outcome": "Overall clinical survival and morbidity", "minimum_conditions": [f"Follow-up over {p_in['time_horizon']}"], "competing_hypotheses": [ {"description": f"Intervention improves outcomes over {p_in['time_horizon']}", "predicted_observations": ["Superior primary outcome"]}, ], } majority_scores.append(score_prediction(maj_pred, ref)) # Baseline 2: Lexical Clinical Keyword Heuristic Baseline inferred_modes = ["prospective_cohort"] if any(w in stmt_low for w in ("diagnostic", "accuracy", "sensitivity", "screening", "positivity")): inferred_modes = ["diagnostic_accuracy_study", "clinical_utility_study"] elif any(w in stmt_low for w in ("prognostic", "stratify", "risk prediction", "calibration")): inferred_modes = ["prognostic_validation", "prospective_cohort"] elif any(w in stmt_low for w in ("pathway", "molecular", "cellular", "mechanistic")): inferred_modes = ["mechanistic_human_study", "prospective_cohort"] elif any(w in stmt_low for w in ("implementation", "health system", "population", "disparities", "scaling")): inferred_modes = ["pragmatic_trial", "quasi_experimental_study"] else: inferred_modes = ["randomized_trial", "pragmatic_trial"] inferred_gaps = ["no_adequately_powered_study", "uncertain_generalizability"] if "diagnostic" in stmt_low or "measurement" in stmt_low: inferred_gaps = ["measurement_invalidity", "uncertain_reference_standard"] elif "prognos" in stmt_low or "classification" in stmt_low: inferred_gaps = ["model_not_externally_validated", "conflicting_interpretations"] lex_pred = { "acceptable_study_modes": inferred_modes, "evidence_gap_types": inferred_gaps, "target_intervention_or_predictor": p_in["clean_statement"], "target_comparator": "Standard clinical care", "critical_outcome": p_in["clean_statement"], "minimum_conditions": [f"Pre-registered study over {p_in['time_horizon']}"], "competing_hypotheses": [ {"description": p_in["clean_statement"], "predicted_observations": [f"Improved outcome over {p_in['time_horizon']}"]}, {"description": "Null or subgroup-restricted clinical effect", "predicted_observations": ["Null effect in unselected cohort"]}, ], } lexical_scores.append(score_prediction(lex_pred, ref)) # Baseline 3: Same-Category Nearest-Question-Type Neighbor Retrieval Baseline neighbor = benchmark_rows[(idx + 1) % len(benchmark_rows)]["reference_target"] for cand_idx, cand_row in enumerate(benchmark_rows): if cand_idx != idx and cand_row["category_id"] == row["category_id"] and cand_row["question_type"] == row["question_type"]: neighbor = cand_row["reference_target"] break retrieval_scores.append(score_prediction(neighbor, ref)) def avg_metrics(score_list: list[dict]) -> dict: keys = ["study_mode_f1", "evidence_gap_f1", "pico_estimand_score", "hypothesis_coverage_score", "overall_composite_score"] return {k: round(sum(s[k] for s in score_list) / len(score_list), 2) for k in keys} summary = { "benchmark_name": "UnsolvedMedical-Bench v3.0", "version": "3.0.0", "total_problems": len(benchmark_rows), "categories_covered": 20, "problems_per_category": 25, "question_types_covered": len(qtype_counter), "by_question_type": dict(qtype_counter), "by_difficulty": dict(Counter(r["research_difficulty"] for r in benchmark_rows)), "evaluation_metrics": { "study_mode_f1": "Set F1 (0-100) on selecting the acceptable settling study designs (weight: 30%)", "evidence_gap_f1": "Set F1 (0-100) on diagnosing the underlying methodological evidence gaps (weight: 25%)", "pico_estimand_score": "Token F1 (0-100) on specifying target intervention, comparator, critical endpoint, and bias controls (weight: 25%)", "hypothesis_coverage_score": "Coverage score (0-100) on formulating falsifiable positive and null/subgroup competing hypotheses (weight: 20%)", "overall_composite_score": "Weighted composite score (0-100) across all 4 medical research dimensions", }, "reference_baselines": { "uninformed_rct_majority_baseline": avg_metrics(majority_scores), "lexical_clinical_heuristic_baseline": avg_metrics(lexical_scores), "domain_neighbor_retrieval_baseline": avg_metrics(retrieval_scores), "oracle_reference_upper_bound": { "study_mode_f1": 100.0, "evidence_gap_f1": 100.0, "pico_estimand_score": 100.0, "hypothesis_coverage_score": 100.0, "overall_composite_score": 100.0, }, }, } SUMMARY_PATH.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(f"Built {len(benchmark_rows)} stratified benchmark problems in {BENCHMARK_PATH} and summary in {SUMMARY_PATH}.") print("Reference Baseline Composite Scores:") for name, m in summary["reference_baselines"].items(): print(f" - {name:38s}: {m['overall_composite_score']:6.2f} (StudyMode F1: {m['study_mode_f1']:5.2f}, Gap F1: {m['evidence_gap_f1']:5.2f}, PICO: {m['pico_estimand_score']:5.2f}, Hyp: {m['hypothesis_coverage_score']:5.2f})") def evaluate_predictions_file(pred_path: Path) -> None: bench_rows = [json.loads(line) for line in BENCHMARK_PATH.read_text(encoding="utf-8").splitlines() if line.strip()] preds_by_id = {} for line in pred_path.read_text(encoding="utf-8").splitlines(): if line.strip(): obj = json.loads(line) key = obj.get("benchmark_id") or obj.get("problem_id") or obj.get("id") if key: preds_by_id[key] = obj scores = [] for row in bench_rows: pred = preds_by_id.get(row["benchmark_id"]) or preds_by_id.get(row["problem_id"]) or {} scores.append(score_prediction(pred, row["reference_target"])) keys = ["study_mode_f1", "evidence_gap_f1", "pico_estimand_score", "hypothesis_coverage_score", "overall_composite_score"] avg = {k: round(sum(s[k] for s in scores) / len(scores), 2) for k in keys} print(json.dumps({"evaluated_problems": len(scores), "metrics": avg}, indent=2)) def main() -> None: parser = argparse.ArgumentParser(description="UnsolvedMedical v3.0 AI Benchmark Builder & Evaluator") parser.add_argument("--build", action="store_true", help="Build eval/benchmark_v3.jsonl and reference baselines") parser.add_argument("--predictions", type=Path, help="Path to model predictions JSONL file to score") args = parser.parse_args() if args.build or not BENCHMARK_PATH.exists(): build_benchmark() if args.predictions: evaluate_predictions_file(args.predictions) if __name__ == "__main__": main()