File size: 12,523 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""``plotqa_dsl_v1`` executor — exact-rational PlotQA program execution (P3).

Evaluates the typed programs built by :mod:`~explicit_learning.dsl.plotdsl`
(``LOOKUP``/``SUBTRACT``/``ARGMAX``/``ARGMIN``/``SUM``/``COUNT``/``EXIST`` over a
``plot_world_v1``) with exact ``fractions.Fraction`` arithmetic, records the
dependency closure ``D(P,W)``, and enforces the scalar-referent cardinality
precondition. A ``MISSING_INFORMATION`` arises when a needed point/x is absent; a
zero-cardinality *set* selector (``COUNT``/``EXIST``) runs to ``0``/``No`` and
stays ``UNIQUE`` (``docs/02`` §11.3).
"""

from __future__ import annotations

from collections.abc import Mapping
from fractions import Fraction
from typing import Any

from ..dsl.ast import Arg, AstNode, Program
from ..sources.base import World
from .base import (
    AnswerValue,
    ExecutionResult,
    ExecutorError,
    _InvalidReferent,
    _MissingInformation,
    _Trace,
    literal_value,
    serialize_answer,
)

NAME = "plot_executor"
VERSION = "plotqa_dsl_v1/1"


class PlotExecutor:
    """Deterministic executor for ``plotqa_dsl_v1``."""

    name = NAME
    version = VERSION

    def execute(self, program: Program, *, world: World) -> ExecutionResult:
        trace = _Trace()
        try:
            referent_card = self._check_referent(program, world, trace)
            value = self._eval(program.program, world, trace)
            answer = self._project_answer(program.program, value)
            _steps, deps, tsha = trace.finish()
            return ExecutionResult(
                status="UNIQUE",
                answer_value=answer,
                answer_canonical=serialize_answer(answer, return_type=program.program.return_type),
                dependency_node_ids=deps,
                referent_cardinality=referent_card,
                trace_sha256=tsha,
                executor_name=self.name,
                executor_version=self.version,
            )
        except _MissingInformation:
            _steps, deps, tsha = trace.finish()
            return ExecutionResult(
                status="MISSING_INFORMATION",
                answer_value=None,
                answer_canonical=None,
                dependency_node_ids=deps,
                referent_cardinality=self._safe_referent_card(program, world),
                trace_sha256=tsha,
                executor_name=self.name,
                executor_version=self.version,
            )
        except _InvalidReferent:
            _steps, deps, tsha = trace.finish()
            return ExecutionResult(
                status="INVALID_REFERENT",
                answer_value=None,
                answer_canonical=None,
                dependency_node_ids=deps,
                referent_cardinality=self._safe_referent_card(program, world),
                trace_sha256=tsha,
                executor_name=self.name,
                executor_version=self.version,
            )
        except ExecutorError:
            _steps, deps, tsha = trace.finish()
            return ExecutionResult(
                status="ERROR",
                answer_value=None,
                answer_canonical=None,
                dependency_node_ids=deps,
                referent_cardinality=self._safe_referent_card(program, world),
                trace_sha256=tsha,
                executor_name=self.name,
                executor_version=self.version,
            )

    def execute_selector(self, selector: AstNode, *, world: World) -> tuple[str, ...]:
        """Resolve a referent selector to its world node ids (``SELECT_SERIES``/``POINTS``)."""
        if selector.op == "SELECT_SERIES":
            sid = _ref_id(selector.args[0])
            return (sid,) if _series(world, sid) is not None else ()
        if selector.op == "POINTS":
            sid = _ref_id(selector.args[0])
            series = _series(world, sid)
            if series is None:
                return ()
            return tuple(str(p["id"]) for p in series.get("points", []) if isinstance(p, Mapping))
        if selector.op == "SELECT_ENTITY":  # parity; plot worlds carry no entities
            return ()
        return ()

    # --- referent precondition (§11.3) ------------------------------------

    def _check_referent(self, program: Program, world: World, trace: _Trace) -> int | None:
        selector = program.referent_selector
        required = program.required_referent_cardinality
        if selector is None or required is None:
            # Set selector (COUNT/EXIST) or no selector: no scalar precondition.
            return None if selector is None else len(self.execute_selector(selector, world=world))
        refs = self.execute_selector(selector, world=world)
        trace.record("REFERENT", refs, len(refs))
        if len(refs) != required:
            raise _InvalidReferent(
                f"scalar referent cardinality {len(refs)} != required {required}"
            )
        return len(refs)

    def _safe_referent_card(self, program: Program, world: World) -> int | None:
        if program.referent_selector is None:
            return None
        try:
            return len(self.execute_selector(program.referent_selector, world=world))
        except ExecutorError:
            return None

    # --- evaluation --------------------------------------------------------

    def _eval(self, node: Arg, world: World, trace: _Trace) -> Any:
        if not isinstance(node, AstNode):
            raise ExecutorError(f"expected an AST node, got {type(node).__name__}")
        op = node.op
        if op == "REF":
            return self._eval_ref(node, world, trace)
        if op == "LITERAL":
            return literal_value(node)
        if op == "SELECT_SERIES":
            sid = _ref_id(node.args[0])
            series = _series(world, sid)
            if series is None:
                raise _MissingInformation(f"series {sid!r} not in world")
            trace.record("SELECT_SERIES", series, sid)
            return series
        if op == "SELECT_X":
            return str(
                literal_value(node.args[0]) if isinstance(node.args[0], AstNode) else node.args[0]
            )
        if op == "LOOKUP":
            return self._eval_lookup(node, world, trace)
        if op == "POINTS":
            series = self._eval(node.args[0], world, trace)
            points = tuple(p for p in series.get("points", []) if isinstance(p, Mapping))
            trace.record("POINTS", points, len(points))
            return points
        if op in ("ARGMAX", "ARGMIN"):
            return self._eval_argextreme(op, node, world, trace)
        if op == "SUBTRACT":
            a = _as_number(self._eval(node.args[0], world, trace))
            b = _as_number(self._eval(node.args[1], world, trace))
            result = a - b
            trace.record("SUBTRACT", (), result)
            return result
        if op == "SUM":
            return self._eval_sum(node, world, trace)
        if op == "COUNT":
            points = self._eval(node.args[0], world, trace)
            count = len(points)
            trace.record("COUNT", points, count)
            return count
        if op == "EXIST":
            points = self._eval(node.args[0], world, trace)
            exists = bool(points)
            trace.record("EXIST", points, exists)
            return exists
        raise ExecutorError(f"unsupported plot op {op!r}")

    def _eval_ref(self, node: AstNode, world: World, trace: _Trace) -> Any:
        sid = _ref_id(node)
        series = _series(world, sid)
        if series is not None:
            trace.record("REF", series, sid)
            return series
        # A direct point/entity reference.
        point = _point(world, sid)
        if point is not None:
            trace.record("REF", point, sid)
            return point
        raise _MissingInformation(f"entity {sid!r} not in world")

    def _eval_lookup(self, node: AstNode, world: World, trace: _Trace) -> Fraction:
        series = self._eval(node.args[0], world, trace)
        x = self._eval(node.args[1], world, trace)
        for point in series.get("points", []):
            if isinstance(point, Mapping) and str(point.get("x", "")) == str(x):
                if point.get("y") in (None, "", "nan"):
                    raise _MissingInformation(f"point {point.get('id')} value hidden")
                value = _as_number(point["y"])
                trace.record("LOOKUP", point, value)
                return value
        raise _MissingInformation(f"x={x!r} not found in series {series.get('id')}")

    def _eval_argextreme(
        self, op: str, node: AstNode, world: World, trace: _Trace
    ) -> Mapping[str, Any]:
        points = self._eval(node.args[0], world, trace)
        if not points:
            raise _MissingInformation("argmax/argmin over empty point set")
        keyed: list[tuple[Fraction, Mapping[str, Any]]] = []
        for p in points:
            if p.get("y") in (None, "", "nan"):
                raise _MissingInformation(f"point {p.get('id')} value hidden")
            keyed.append((_as_number(p["y"]), p))
        # Deterministic: sort by (value, point id); ARGMAX → last, ARGMIN → first.
        keyed.sort(key=lambda kv: (kv[0], str(kv[1].get("id", ""))))
        chosen = keyed[-1] if op == "ARGMAX" else keyed[0]
        trace.record(op, chosen[1], chosen[1].get("id"))
        return chosen[1]

    def _eval_sum(self, node: AstNode, world: World, trace: _Trace) -> Fraction:
        total = Fraction(0)
        touched: list[Mapping[str, Any]] = []
        for arg in node.args:
            val = self._eval(arg, world, trace)
            for v in _flatten_values(val):
                total += v
            if isinstance(val, tuple):
                touched.extend(p for p in val if isinstance(p, Mapping))
        trace.record("SUM", touched, total)
        return total

    # --- answer projection -------------------------------------------------

    def _project_answer(self, root: AstNode, value: Any) -> AnswerValue:
        rt = root.return_type
        if rt == "integer":
            return int(value)
        if rt == "boolean":
            return bool(value)
        if rt == "point":
            # ARGMAX/ARGMIN answer is the extremum point's x (the year/label).
            return str(value.get("x", "")) if isinstance(value, Mapping) else str(value)
        if rt in ("value", "number"):
            return _as_number(value)
        return str(value)


# --- world helpers ---------------------------------------------------------


def _series(world: World, sid: str) -> Mapping[str, Any] | None:
    for series in world.get("series", []) or []:
        if isinstance(series, Mapping) and series.get("id") == sid:
            return series
    return None


def _point(world: World, pid: str) -> Mapping[str, Any] | None:
    for series in world.get("series", []) or []:
        for point in series.get("points", []) if isinstance(series, Mapping) else []:
            if isinstance(point, Mapping) and point.get("id") == pid:
                return point
    return None


def _ref_id(arg: Any) -> str:
    if isinstance(arg, AstNode):
        return arg.ref_id()
    return str(arg)


def _as_number(value: Any) -> Fraction:
    if isinstance(value, bool):  # noqa: FBT001 - guard before int
        raise ExecutorError("boolean where a number was expected")
    if isinstance(value, Fraction):
        return value
    if isinstance(value, int):
        return Fraction(value)
    try:
        return Fraction(str(value))
    except (ValueError, ZeroDivisionError) as exc:  # unparseable → ERROR, never a crash/U
        raise ExecutorError(f"unparseable numeric value {value!r}") from exc


def _flatten_values(val: Any) -> list[Fraction]:
    """Expand a SUM operand: a point-set → its y-values; a scalar → itself."""
    if isinstance(val, tuple):
        out: list[Fraction] = []
        for p in val:
            if isinstance(p, Mapping):
                if p.get("y") in (None, "", "nan"):
                    raise _MissingInformation(f"point {p.get('id')} value hidden")
                out.append(_as_number(p["y"]))
            else:
                out.append(_as_number(p))
        return out
    if isinstance(val, Mapping):  # a single point
        if val.get("y") in (None, "", "nan"):
            raise _MissingInformation(f"point {val.get('id')} value hidden")
        return [_as_number(val["y"])]
    return [_as_number(val)]


__all__ = ["PlotExecutor"]