sungguk's picture
Release visual answerability benchmark v1.0.0
e1ced61 verified
Raw
History Blame Contribute Delete
10.8 kB
"""``geometry_dsl_v1`` executor — direct-lookup solver over the supported subset (P3).
Evaluates ``SOLVE(goal, AND(constraints))`` programs built by
:mod:`~explicit_learning.dsl.geometrydsl` against a ``geometry_world_v1``. The P3
supported predicate subset is the *direct-lookup* case: the goal target's value
is stated outright by a ``MeasureOf(target, v)`` or ``Equals(target, v)``
constraint. A full theorem-proving solver (the 6-check Inter-GPS/FormalGeo
acceptance of ``docs/02`` §6.3) is the **reference executor** (P13); this
executor covers the subset where the answer is explicitly given and reports
``MISSING_INFORMATION`` (never a guess) when it cannot derive the goal.
Channel provenance (``text``/``visual``/``redundant``) lives on the program
envelope; the executor reads the formal constraint graph from the **world**
(``world["constraints"]`` dicts, not the program's ``AND`` mirror) so that
re-executing the fixed program against a *mutated* world (§14 replay) reflects
the mutation. ``U_INVALID`` arises when the scalar ``SELECT_ENTITY`` referent
(the goal target) is deleted from the world.
"""
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,
serialize_answer,
)
NAME = "geometry_executor"
VERSION = "geometry_dsl_v1/1"
class GeometryExecutor:
"""Deterministic direct-lookup executor for ``geometry_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)
answer = self._solve(program.program, world, trace)
_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 _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 _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 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, ...]:
if selector.op == "SELECT_ENTITY":
eid = _ref_id(selector.args[0])
return (eid,) if _entity(world, eid) is not None else ()
if selector.op == "SELECT_SERIES": # parity; geometry worlds carry no series
return ()
return ()
# --- referent precondition --------------------------------------------
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:
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
# --- solving ------------------------------------------------------------
def _solve(self, node: AstNode, world: World, trace: _Trace) -> AnswerValue:
if node.op != "SOLVE":
raise ExecutorError(f"expected SOLVE root, got {node.op!r}")
goal = node.args[0]
constraints = self._world_constraints(world)
return self._solve_goal(goal, constraints, world, trace)
def _world_constraints(self, world: World) -> tuple[Mapping[str, Any], ...]:
"""The formal constraint facts (``world["constraints"]`` dicts).
Read from the world — not the program's ``AND`` mirror — so a mutated
world (a deleted stating-constraint, §14 replay) changes the result.
"""
out: list[Mapping[str, Any]] = []
for c in world.get("constraints", []) or []:
if isinstance(c, Mapping) and c.get("predicate"):
out.append(c)
return tuple(out)
def _solve_goal(
self, goal: Arg, constraints: tuple[Mapping[str, Any], ...], world: World, trace: _Trace
) -> AnswerValue:
if not isinstance(goal, AstNode):
raise ExecutorError(f"expected a goal AST node, got {type(goal).__name__}")
if goal.op == "MEASURE":
target = _ref_id(goal.args[0])
return self._measure(target, constraints, trace)
if goal.op == "FIND":
target = _ref_id(goal.args[0])
return self._find(target, constraints, trace)
if goal.op == "PROVE":
return self._prove(goal, constraints, trace)
raise ExecutorError(f"unsupported goal op {goal.op!r}")
def _measure(
self, target: str, constraints: tuple[Mapping[str, Any], ...], trace: _Trace
) -> Fraction:
for c in constraints:
if c.get("predicate") == "MeasureOf" and _arg0(c) == target:
value = _as_number(_arg1(c))
trace.record("MEASURE", (target,), value)
return value
raise _MissingInformation(f"no MeasureOf constraint states {target!r}")
def _find(
self, target: str, constraints: tuple[Mapping[str, Any], ...], trace: _Trace
) -> Fraction:
for c in constraints:
if c.get("predicate") == "MeasureOf" and _arg0(c) == target:
value = _as_number(_arg1(c))
trace.record("FIND", (target,), value)
return value
if c.get("predicate") == "Equals" and _equals_target_value(c, target) is not None:
value = _as_number(_equals_target_value(c, target))
trace.record("FIND", (target,), value)
return value
raise _MissingInformation(f"no constraint states the value of {target!r}")
def _prove(
self, goal: AstNode, constraints: tuple[Mapping[str, Any], ...], trace: _Trace
) -> bool:
# PROVE asserts a predicate; true iff an identical constraint is given.
target_pred = goal.args[0]
if not isinstance(target_pred, AstNode):
raise ExecutorError("PROVE expects a predicate argument")
for c in constraints:
if _constraint_matches(c, target_pred):
trace.record("PROVE", (), True)
return True
raise _MissingInformation("PROVE: asserted predicate not found among givens")
# --- helpers ---------------------------------------------------------------
def _entity(world: World, eid: str) -> Mapping[str, Any] | None:
for entity in world.get("entities", []) or []:
if isinstance(entity, Mapping) and entity.get("id") == eid:
return entity
return None
def _ref_id(arg: Any) -> str:
if isinstance(arg, AstNode):
return arg.ref_id()
return str(arg)
def _arg0(c: Mapping[str, Any]) -> str:
args = c.get("args") or []
return str(args[0]) if args else ""
def _arg1(c: Mapping[str, Any]) -> str:
args = c.get("args") or []
return str(args[1]) if len(args) > 1 else ""
def _equals_target_value(c: Mapping[str, Any], target: str) -> str | None:
"""If ``Equals(target, v)`` or ``Equals(v, target)``, return the other side's value."""
args = c.get("args") or []
if len(args) != 2:
return None
a, b = str(args[0]), str(args[1])
if a == target and _looks_numeric(b):
return b
if b == target and _looks_numeric(a):
return a
return None
def _looks_numeric(text: str) -> bool:
try:
Fraction(text)
except (ValueError, ZeroDivisionError):
return False
return True
def _as_number(value: Any) -> Fraction:
if isinstance(value, bool): # noqa: FBT001
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 _constraint_matches(c: Mapping[str, Any], pred_node: AstNode) -> bool:
if pred_node.op not in ("MeasureOf", "Equals", "IsMidpointOf", "Parallel", "Perpendicular"):
return False
if c.get("predicate") != pred_node.op:
return False
cargs = [str(a) for a in (c.get("args") or [])]
pargs = [str(a.ref_id()) if isinstance(a, AstNode) else str(a) for a in pred_node.args]
return cargs == pargs
__all__ = ["GeometryExecutor"]