#!/usr/bin/env python3 """Evaluation script for LLM4Mat-Bench XRD Max-Peak HKL Identification. Computes set-based metrics (Jaccard, Precision, Recall, F1) by comparing model predictions against ground truth HKL sets. Prediction format (JSONL, one line per sample): {"sample_id": "mp-1024962", "predicted_hkls": [[2,2,1],[2,1,0],[1,1,-1]]} Usage: python evaluate.py --predictions predictions.jsonl python evaluate.py --predictions predictions.jsonl --ground_truth metadata.jsonl python evaluate.py --predictions predictions.jsonl --by_dataset """ from __future__ import annotations import argparse import json import sys from collections import defaultdict from pathlib import Path from typing import Any SCRIPT_DIR = Path(__file__).resolve().parent DEFAULT_GT = SCRIPT_DIR / "metadata.jsonl" # --------------------------------------------------------------------------- # Metric computation # --------------------------------------------------------------------------- def normalize_hkl_set(hkls: list[list[int]]) -> set[tuple[int, ...]]: """Convert list of HKL lists to a set of tuples, filtering out [0,0,0].""" result = set() for hkl in hkls: t = tuple(int(x) for x in hkl) # Skip zero vectors if all(x == 0 for x in t): continue result.add(t) return result def compute_metrics( pred_set: set[tuple[int, ...]], gt_set: set[tuple[int, ...]], ) -> dict[str, float]: """Compute Jaccard, Precision, Recall, F1 for a single sample.""" if not gt_set and not pred_set: return {"jaccard": 1.0, "precision": 1.0, "recall": 1.0, "f1": 1.0} if not gt_set: return {"jaccard": 0.0, "precision": 0.0, "recall": 1.0, "f1": 0.0} if not pred_set: return {"jaccard": 0.0, "precision": 1.0, "recall": 0.0, "f1": 0.0} intersection = pred_set & gt_set union = pred_set | gt_set jaccard = len(intersection) / len(union) precision = len(intersection) / len(pred_set) recall = len(intersection) / len(gt_set) if precision + recall > 0: f1 = 2 * precision * recall / (precision + recall) else: f1 = 0.0 return { "jaccard": jaccard, "precision": precision, "recall": recall, "f1": f1, } # --------------------------------------------------------------------------- # Data loading # --------------------------------------------------------------------------- def load_ground_truth(path: Path) -> dict[str, dict[str, Any]]: """Load ground truth from metadata.jsonl. Returns {sample_id: {"gt_hkls": [...], "dataset": ..., ...}}. """ gt_map = {} with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue rec = json.loads(line) sample_id = rec.get("sample_id", "") gt_hkls_raw = rec.get("gt_hkls", "[]") if isinstance(gt_hkls_raw, str): gt_hkls = json.loads(gt_hkls_raw) else: gt_hkls = gt_hkls_raw gt_map[sample_id] = { "gt_hkls": gt_hkls, "dataset": rec.get("dataset", ""), "material_type": rec.get("material_type", ""), "gt_union_size": rec.get("gt_union_size", len(gt_hkls)), } return gt_map def load_predictions(path: Path) -> dict[str, list[list[int]]]: """Load predictions from JSONL. Expected format: {"sample_id": "...", "predicted_hkls": [[h,k,l], ...]} Also supports: {"sample_id": "...", "max_peak_hkls": [[h,k,l], ...]} """ pred_map = {} with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue rec = json.loads(line) sample_id = rec.get("sample_id", "") # Support multiple field names hkls = ( rec.get("predicted_hkls") or rec.get("max_peak_hkls") or rec.get("hkls") or [] ) pred_map[sample_id] = hkls return pred_map # --------------------------------------------------------------------------- # Evaluation # --------------------------------------------------------------------------- def evaluate( predictions: dict[str, list[list[int]]], ground_truth: dict[str, dict[str, Any]], by_dataset: bool = False, ) -> dict[str, Any]: """Run evaluation and return results. Returns dict with overall metrics and optionally per-dataset breakdown. """ all_metrics = [] dataset_metrics: dict[str, list[dict[str, float]]] = defaultdict(list) matched = 0 missing_gt = 0 missing_pred = 0 for sample_id, gt_info in ground_truth.items(): gt_hkls = gt_info["gt_hkls"] gt_set = normalize_hkl_set(gt_hkls) dataset = gt_info.get("dataset", "unknown") if sample_id not in predictions: missing_pred += 1 # Treat missing prediction as empty set pred_set: set[tuple[int, ...]] = set() else: matched += 1 pred_set = normalize_hkl_set(predictions[sample_id]) metrics = compute_metrics(pred_set, gt_set) all_metrics.append(metrics) dataset_metrics[dataset].append(metrics) # Check for predictions without ground truth for sample_id in predictions: if sample_id not in ground_truth: missing_gt += 1 # Compute averages def avg_metrics(metrics_list: list[dict[str, float]]) -> dict[str, float]: if not metrics_list: return {"jaccard": 0.0, "precision": 0.0, "recall": 0.0, "f1": 0.0, "n": 0} n = len(metrics_list) return { "jaccard": sum(m["jaccard"] for m in metrics_list) / n, "precision": sum(m["precision"] for m in metrics_list) / n, "recall": sum(m["recall"] for m in metrics_list) / n, "f1": sum(m["f1"] for m in metrics_list) / n, "n": n, } results: dict[str, Any] = { "overall": avg_metrics(all_metrics), "coverage": { "total_gt_samples": len(ground_truth), "matched_predictions": matched, "missing_predictions": missing_pred, "extra_predictions": missing_gt, }, } if by_dataset: results["per_dataset"] = { ds: avg_metrics(m) for ds, m in sorted(dataset_metrics.items()) } return results def print_results(results: dict[str, Any]) -> None: """Pretty-print evaluation results.""" print("\n" + "=" * 70) print(" LLM4Mat-Bench Evaluation Results") print("=" * 70) # Coverage cov = results["coverage"] print(f"\n Coverage:") print(f" Ground truth samples: {cov['total_gt_samples']}") print(f" Matched predictions: {cov['matched_predictions']}") print(f" Missing predictions: {cov['missing_predictions']}") if cov["extra_predictions"] > 0: print(f" Extra predictions (no GT): {cov['extra_predictions']}") # Overall metrics overall = results["overall"] print(f"\n Overall Metrics (n={overall['n']}):") print(f" Jaccard Similarity: {overall['jaccard']:.4f}") print(f" Precision: {overall['precision']:.4f}") print(f" Recall: {overall['recall']:.4f}") print(f" F1 Score: {overall['f1']:.4f}") # Per-dataset breakdown if "per_dataset" in results: print(f"\n Per-Dataset Breakdown:") print(f" {'Dataset':<15} {'N':>5} {'Jaccard':>9} {'Prec':>7} {'Recall':>7} {'F1':>7}") print(f" {'-'*15} {'-'*5} {'-'*9} {'-'*7} {'-'*7} {'-'*7}") for ds, m in results["per_dataset"].items(): print( f" {ds:<15} {m['n']:>5} " f"{m['jaccard']:>9.4f} {m['precision']:>7.4f} " f"{m['recall']:>7.4f} {m['f1']:>7.4f}" ) print("\n" + "=" * 70) # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- def main() -> None: parser = argparse.ArgumentParser( description="Evaluate predictions for LLM4Mat-Bench XRD benchmark", ) parser.add_argument( "--predictions", type=str, required=True, help="Path to predictions JSONL file", ) parser.add_argument( "--ground_truth", type=str, default=str(DEFAULT_GT), help=f"Path to ground truth metadata.jsonl (default: {DEFAULT_GT})", ) parser.add_argument( "--by_dataset", action="store_true", help="Show per-dataset metric breakdown", ) parser.add_argument( "--output", type=str, default=None, help="Save results to JSON file (optional)", ) args = parser.parse_args() pred_path = Path(args.predictions).resolve() gt_path = Path(args.ground_truth).resolve() if not pred_path.exists(): print(f"ERROR: Predictions file not found: {pred_path}") sys.exit(1) if not gt_path.exists(): print(f"ERROR: Ground truth file not found: {gt_path}") sys.exit(1) # Load data print(f"Loading ground truth from: {gt_path}") ground_truth = load_ground_truth(gt_path) print(f" {len(ground_truth)} samples loaded") print(f"Loading predictions from: {pred_path}") predictions = load_predictions(pred_path) print(f" {len(predictions)} predictions loaded") # Evaluate results = evaluate(predictions, ground_truth, by_dataset=args.by_dataset) # Print results print_results(results) # Save if requested if args.output: output_path = Path(args.output).resolve() with open(output_path, "w", encoding="utf-8") as f: json.dump(results, f, indent=2, ensure_ascii=False) print(f"\nResults saved to: {output_path}") if __name__ == "__main__": main()