"""``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"]