Datasets:
File size: 7,970 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 | """``geometry_dsl_v1`` operator table + Geometry3K program compiler (``docs/02``
§6.2, ``docs/07`` §4 P2).
The compiler consumes the parsed ``geometry_world_v1`` from
:meth:`~explicit_learning.sources.geometry3k.Geometry3KAdapter.build_world` — it
does **not** re-parse the annotated logic forms. Each world constraint becomes a
typed boolean :class:`~explicit_learning.dsl.ast.AstNode`; the goal (``find_angle``
/ ``find_length``) becomes a goal op (``MEASURE`` / ``FIND``) over the single
target entity. Channel provenance (``text`` / ``visual`` / ``redundant``) is
preserved on the :class:`Program` via ``constraint_channels`` — a side table, not
part of the schema hash, so the P3 intervention layer can alter only ``visual``
constraints without changing the program fingerprint.
Goal extraction is conservative: the target entity must be the unique entity of
the goal's kind (one angle for ``find_angle``, one segment for ``find_length``).
When the target is ambiguous or the goal type is unrecognized, the program is
``compile_status="unsupported"`` with a ``reason_code`` — never a guess. The
6-check solver acceptance is P3; P2 produces the typed structure only.
"""
from __future__ import annotations
from dataclasses import replace
from fractions import Fraction
from typing import Any
from ..ingest.base import NormalizedItem
from ..sources.base import World
from .ast import AstNode, Dsl, Program, lit, ref
from .canonicalize import canonical_program_sha256
from .typecheck import OpSignature, typecheck
DSL: Dsl = "geometry_dsl_v1"
# --- operator signature table (§6.2) ---------------------------------------
#
# Constraint predicates are boolean assertions over entities; their operands are
# ``any`` because a single predicate (e.g. ``Equals``) may relate points, angles,
# or segments. Goal ops yield the sought value/boolean. ``SELECT_ENTITY`` is the
# scalar referent selector for the goal target. ``AND`` is the commutative
# conjunction of givens; ``SOLVE`` pairs a goal with its givens.
SIGNATURES: dict[str, OpSignature] = {
# Constraint predicates (boolean facts).
"MeasureOf": OpSignature(arg_types=("any", "any"), return_type="boolean"),
"Equals": OpSignature(arg_types=("any", "any"), return_type="boolean"),
"IsMidpointOf": OpSignature(arg_types=("any", "any"), return_type="boolean"),
"Parallel": OpSignature(arg_types=("any", "any"), return_type="boolean"),
"Perpendicular": OpSignature(arg_types=("any", "any"), return_type="boolean"),
# Goal ops.
"MEASURE": OpSignature(arg_types=("angle",), return_type="value", selector_kind="none"),
"FIND": OpSignature(arg_types=("any",), return_type="value", selector_kind="none"),
"PROVE": OpSignature(arg_types=("any",), return_type="boolean", selector_kind="none"),
# Structural ops.
"SELECT_ENTITY": OpSignature(arg_types=("any",), return_type="entity", selector_kind="scalar"),
"AND": OpSignature(
arg_types=("boolean",), return_type="boolean", commutative=True, variadic=True
),
"SOLVE": OpSignature(arg_types=("any", "any"), return_type="any", selector_kind="none"),
}
# Canonicalization profile (§7.2 steps 3–5). ``AND`` is commutative; geometry has
# no operator aliases or identity casts in P2.
COMMUTATIVE_OPS: frozenset[str] = frozenset({"AND"})
ALIASES: dict[str, str] = {}
IDENTITY_CASTS: frozenset[str] = frozenset()
_UNSUPPORTED_NODE = AstNode(op="UNSUPPORTED", args=(), return_type="")
# --- compile ---------------------------------------------------------------
def compile_geometry3k(item: NormalizedItem, world: World) -> Program:
"""Build the typed ``geometry_dsl_v1`` program for one normalized Geometry3K item.
Consumes ``build_world``'s entities/constraints/channels. Returns a compiled
:class:`Program` (goal op + constraint conjunction, channel provenance on the
envelope, canonical hash filled) or ``"unsupported"`` (with ``reason_code``)
when the goal target is ambiguous/unrecognized. Never guesses.
"""
entities = world.get("entities", []) or []
entity_kind = {
str(e["id"]): str(e["id"]).split(":", 1)[0]
for e in entities
if isinstance(e, dict) and e.get("id")
}
goal_type = world.get("goal")
target_id, goal_op = _goal_target(goal_type, entities)
if target_id is None or goal_op is None:
return _unsupported(item, f"goal_{goal_type}_unresolved")
target_kind = entity_kind.get(target_id, "entity")
goal_node = AstNode(
op=goal_op, args=(ref(target_id, return_type=target_kind),), return_type="value"
)
constraint_nodes, constraint_channels = _constraints(world)
given = (
AstNode(op="AND", args=tuple(constraint_nodes), return_type="boolean")
if constraint_nodes
else lit(True, return_type="boolean")
)
program_tree = AstNode(op="SOLVE", args=(goal_node, given), return_type="value")
referent = AstNode(
op="SELECT_ENTITY", args=(ref(target_id, return_type=target_kind),), return_type="entity"
)
program = typecheck(
Program(
dsl=DSL,
program=program_tree,
base_id=item.base_id,
question_sha256=item.question_sha256,
choices_sha256=item.choices_sha256,
compile_status="compiled",
referent_selector=referent,
required_referent_cardinality=1,
constraint_channels=tuple(constraint_channels),
),
world=world,
)
return replace(program, canonical_program_sha256=canonical_program_sha256(program, world=world))
# --- goal + constraint builders -------------------------------------------
def _goal_target(goal_type: Any, entities: list[dict[str, Any]]) -> tuple[str | None, str | None]:
"""Resolve the (target entity id, goal op) for a goal type; (None, None) if ambiguous."""
if goal_type == "find_angle":
return _unique_entity(entities, "angle"), "MEASURE"
if goal_type == "find_length":
return _unique_entity(entities, "segment"), "FIND"
return None, None
def _unique_entity(entities: list[dict[str, Any]], kind: str) -> str | None:
matches = [
str(e["id"])
for e in entities
if isinstance(e, dict) and e.get("id") and str(e["id"]).startswith(f"{kind}:")
]
return matches[0] if len(matches) == 1 else None
def _constraints(world: World) -> tuple[list[AstNode], list[tuple[str, str]]]:
"""Build typed boolean nodes for each world constraint + (key, channel) provenance."""
nodes: list[AstNode] = []
channels: list[tuple[str, str]] = []
for c in world.get("constraints", []) or []:
if not isinstance(c, dict) or not c.get("predicate"):
continue
args = tuple(_constraint_arg(a) for a in c.get("args", []))
nodes.append(AstNode(op=str(c["predicate"]), args=args, return_type="boolean"))
key = f"{c['predicate']}({','.join(str(a) for a in c.get('args', []))})"
channels.append((key, str(c.get("channel", "text"))))
return nodes, sorted(channels, key=lambda kc: kc[0])
def _constraint_arg(raw: Any) -> AstNode:
"""One constraint operand: an entity REF (``point:A``) or a literal (number/string)."""
text = str(raw)
if ":" in text:
return ref(text, return_type=text.split(":", 1)[0])
try:
Fraction(text)
except (ValueError, ZeroDivisionError):
return lit(text, return_type="string")
return lit(text, return_type="number")
def _unsupported(item: NormalizedItem, reason: str) -> Program:
return Program(
dsl=DSL,
program=_UNSUPPORTED_NODE,
base_id=item.base_id,
question_sha256=item.question_sha256,
choices_sha256=item.choices_sha256,
compile_status="unsupported",
reason_code=reason,
)
__all__ = [
"ALIASES",
"COMMUTATIVE_OPS",
"DSL",
"IDENTITY_CASTS",
"SIGNATURES",
"compile_geometry3k",
]
|