File size: 2,391 Bytes
d6b762b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Evaluate a complete set of finite numeric predictions against rational references.

Copyright 2026 Calxo AI. MIT license; see LICENSE.
"""
import argparse
import json
import math
from fractions import Fraction
from pathlib import Path

def load_lines(path):
    return [json.loads(line) for line in Path(path).read_text(encoding="utf-8").splitlines() if line.strip()]

def evaluate(reference, predictions):
    expected_by_id = {row["case_id"]: row for row in reference}
    if len(expected_by_id) != len(reference):
        raise ValueError("Reference data contains duplicate IDs.")
    actual_by_id = {}
    for row in predictions:
        case_id, value = row["case_id"], row["prediction"]
        if case_id in actual_by_id:
            raise ValueError(f"Duplicate prediction: {case_id}")
        if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
            raise ValueError(f"Prediction must be a finite JSON number: {case_id}")
        actual_by_id[case_id] = value
    missing = set(expected_by_id) - set(actual_by_id)
    extra = set(actual_by_id) - set(expected_by_id)
    if missing or extra:
        raise ValueError(f"Prediction coverage mismatch: {len(missing)} missing, {len(extra)} unknown.")
    passed = 0
    failures = []
    for case_id, row in expected_by_id.items():
        expected = float(Fraction(int(row["expected_numerator"]), int(row["expected_denominator"])))
        tolerance = max(row["absolute_tolerance"], row["relative_tolerance"] * abs(expected))
        if abs(actual_by_id[case_id] - expected) <= tolerance:
            passed += 1
        else:
            failures.append(case_id)
    return {"total": len(reference), "predictions": len(predictions), "passed": passed, "failed": len(failures), "accuracy": passed / len(reference) if reference else None, "failed_case_ids": failures}

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("predictions", type=Path)
    parser.add_argument("--reference", type=Path, default=Path(__file__).with_name("conversion-reference.jsonl"))
    args = parser.parse_args()
    try:
        report = evaluate(load_lines(args.reference), load_lines(args.predictions))
    except (ValueError, KeyError, TypeError, OverflowError) as error:
        parser.error(str(error))
    print(json.dumps(report, indent=2))