File size: 4,101 Bytes
e1ced61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""Small independent PlotQA reference executor used for certified evaluation.

This implementation intentionally does not call :class:`PlotExecutor`.  It
supports the v1 certified-release contract (a scalar series/x ``LOOKUP``) using
a separate iterative code path and trace representation.
"""

from __future__ import annotations

from fractions import Fraction
from typing import Any

from ..dsl.ast import AstNode, Program, canonical_number_str
from ..hashing import canonical_json_hash
from ..sources.base import World
from .base import ExecutionResult

NAME = "reference_plot_lookup_executor"
VERSION = "plotqa_reference_lookup_v1/1"


class ReferencePlotExecutor:
    """Independent evaluator for the certified PlotQA lookup subset."""

    name = NAME
    version = VERSION

    def execute(self, program: Program, *, world: World) -> ExecutionResult:
        steps: list[dict[str, Any]] = []
        try:
            series_id, x_label = _decode_lookup(program.program)
        except ValueError as exc:
            return _result("ERROR", None, (), None, [{"error": str(exc)}])

        series_matches = [
            s
            for s in world.get("series", [])
            if isinstance(s, dict) and str(s.get("id")) == series_id
        ]
        steps.append({"op": "series_cardinality", "id": series_id, "count": len(series_matches)})
        if len(series_matches) != 1:
            return _result("INVALID_REFERENT", None, (), len(series_matches), steps)

        points = [
            p
            for p in series_matches[0].get("points", [])
            if isinstance(p, dict) and str(p.get("x")) == x_label
        ]
        steps.append(
            {
                "op": "x_cardinality",
                "x": x_label,
                "ids": sorted(str(p.get("id")) for p in points),
            }
        )
        if len(points) != 1 or points[0].get("y") in (None, "", "nan"):
            deps = (series_id, *(str(p.get("id")) for p in points if p.get("id")))
            return _result("MISSING_INFORMATION", None, deps, 1, steps)
        try:
            value = Fraction(str(points[0]["y"]))
        except (ValueError, ZeroDivisionError):
            return _result("ERROR", None, (series_id, str(points[0].get("id"))), 1, steps)
        steps.append({"op": "value", "value": canonical_number_str(value)})
        return _result(
            "UNIQUE",
            canonical_number_str(value),
            (series_id, str(points[0].get("id"))),
            1,
            steps,
        )


def _decode_lookup(node: AstNode) -> tuple[str, str]:
    if node.op != "LOOKUP" or len(node.args) != 2:
        raise ValueError("reference executor only supports LOOKUP")
    series_selector, x_selector = node.args
    if not isinstance(series_selector, AstNode) or series_selector.op != "SELECT_SERIES":
        raise ValueError("LOOKUP series operand is not SELECT_SERIES")
    if not isinstance(x_selector, AstNode) or x_selector.op != "SELECT_X":
        raise ValueError("LOOKUP x operand is not SELECT_X")
    series_ref = series_selector.args[0]
    x_literal = x_selector.args[0]
    if not isinstance(series_ref, AstNode) or not series_ref.is_ref():
        raise ValueError("SELECT_SERIES does not contain a REF")
    if not isinstance(x_literal, AstNode) or not x_literal.is_literal() or not x_literal.args:
        raise ValueError("SELECT_X does not contain a literal")
    return series_ref.ref_id(), str(x_literal.args[0])


def _result(
    status: str,
    answer: str | None,
    dependencies: tuple[str, ...],
    cardinality: int | None,
    steps: list[dict[str, Any]],
) -> ExecutionResult:
    return ExecutionResult(
        status=status,  # type: ignore[arg-type]
        answer_value=Fraction(answer) if status == "UNIQUE" and answer is not None else None,
        answer_canonical=answer,
        dependency_node_ids=tuple(sorted(set(dependencies))),
        referent_cardinality=cardinality,
        trace_sha256=canonical_json_hash(steps),
        executor_name=NAME,
        executor_version=VERSION,
    )


__all__ = ["ReferencePlotExecutor"]