Datasets:
File size: 10,822 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 | """``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"]
|