| """``SUBSTITUTE_V1`` — sample a new typed value for a node (§10.4). |
| |
| The substitute is drawn from the node's typed domain, deterministically seeded: |
| |
| * **numeric** (a plot point's ``y``, a table cell, a geometry measure) — a |
| value within the source range and at the source precision, distinct from the |
| current value. |
| * **category** (a series / entity label) — a label that does not collide with |
| any existing label. |
| * **geometry** — after the substitute, the constraint graph must stay feasible |
| (no contradiction); :mod:`feasibility` guards this. |
| * **multiple choice** — when the problem is multiple-choice, the *new* answer |
| the executor computes on the substituted world must match **exactly one** of |
| the unchanged choices. A substitute that drives the answer out of the choice |
| set (zero or >1 matches) is rejected (P5 gate: "objective choice outside |
| unchanged choices reject"). |
| |
| The operator never labels the resulting state — it only validates that the |
| substitute is *admissible*; P7 derives ``A_SAME`` / ``A_CHANGED`` by execution. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import hashlib |
| import math |
| from collections.abc import Iterator, Sequence |
| from fractions import Fraction |
| from typing import Any |
|
|
| from ..dsl.ast import Dsl, Program, canonical_number_str, parse_number |
| from ..executors.base import Executor, match_choice |
| from ..ingest.base import Choice |
| from ..sources.base import World |
| from ..sources.world_ops import ( |
| clone_world, |
| find_point, |
| find_row, |
| find_series, |
| find_stating_constraint, |
| is_geometry, |
| looks_numeric, |
| node_kind, |
| world_sha256, |
| ) |
| from .base import ( |
| InterventionError, |
| OperatorName, |
| TransformedWorld, |
| _set_value, |
| transformed_hash, |
| ) |
| from .feasibility import FeasibilityError, is_feasible |
|
|
| _NAME: OperatorName = "SUBSTITUTE_V1" |
|
|
|
|
| class SubstituteOperator: |
| """Substitute a seeded, typed, admissible new value onto ``target_node``.""" |
|
|
| name = _NAME |
|
|
| def apply( |
| self, |
| world: World, |
| target_node: str, |
| *, |
| seed: int, |
| dsl: Dsl, |
| executor: Executor | None = None, |
| program: Program | None = None, |
| choices: Sequence[Choice] = (), |
| answer_type: str = "", |
| **_kwargs: Any, |
| ) -> TransformedWorld: |
| kind = node_kind(world, target_node) |
| if kind is None: |
| raise InterventionError(f"SUBSTITUTE_V1: target {target_node!r} is not a world node") |
| value, desc = _sample_value(world, target_node, kind, seed) |
| new = clone_world(world) |
| if not _set_value(new, target_node, value): |
| raise InterventionError( |
| f"SUBSTITUTE_V1: target {target_node!r} has no mutable value site" |
| ) |
| if is_geometry(new): |
| try: |
| is_feasible(new, dsl=dsl) |
| except FeasibilityError as exc: |
| raise InterventionError( |
| f"SUBSTITUTE_V1: infeasible substitute on {target_node!r}: {exc}" |
| ) from exc |
| |
| |
| |
| if answer_type == "multiple_choice": |
| _assert_choice_admissible(new, executor, program, choices, target_node) |
| return TransformedWorld( |
| world=new, |
| operator=_NAME, |
| target_node=target_node, |
| seed=seed, |
| transformed_world_sha256=transformed_hash( |
| operator=_NAME, |
| target_node=target_node, |
| seed=seed, |
| source_world_sha256=world_sha256(world), |
| transformed_world_sha256=world_sha256(new), |
| hidden_nodes=frozenset(), |
| substitute_value=value, |
| ), |
| hidden_nodes=frozenset(), |
| substitute_value=value, |
| description=desc, |
| ) |
|
|
|
|
| |
|
|
|
|
| def _assert_choice_admissible( |
| world: World, |
| executor: Executor | None, |
| program: Program | None, |
| choices: Sequence[Choice], |
| target_node: str, |
| ) -> None: |
| if executor is None or program is None: |
| raise InterventionError( |
| "SUBSTITUTE_V1: multiple-choice admissibility requires an executor and program" |
| ) |
| result = executor.execute(program, world=world) |
| if result.status != "UNIQUE": |
| raise InterventionError( |
| f"SUBSTITUTE_V1: {target_node!r} substitute made the answer " |
| f"non-unique ({result.status}); rejected" |
| ) |
| keys = match_choice(result.answer_value, choices, "multiple_choice") |
| if len(keys) != 1: |
| raise InterventionError( |
| f"SUBSTITUTE_V1: new answer {result.answer_canonical!r} matches " |
| f"{len(keys)} unchanged choices (must be exactly one); rejected" |
| ) |
|
|
|
|
| |
|
|
|
|
| def _sample_value(world: World, node_id: str, kind: str, seed: int) -> tuple[str, str]: |
| if kind == "point": |
| return _sample_point_y(world, node_id, seed) |
| if kind == "series": |
| return _sample_series_label(world, node_id, seed) |
| if kind == "row": |
| return _sample_row_cell(world, node_id, seed) |
| if kind == "constraint": |
| return _sample_geometry_measure(world, node_id, seed) |
| if kind == "entity": |
| return _sample_entity_label(world, node_id, seed) |
| raise InterventionError(f"SUBSTITUTE_V1: no sampler for kind {kind!r}") |
|
|
|
|
| def _sample_point_y(world: World, pid: str, seed: int) -> tuple[str, str]: |
| point = find_point(world, pid) |
| if point is None: |
| raise InterventionError(f"point {pid!r} not found") |
| sidx, _pidx, p = point |
| siblings = world["series"][sidx].get("points", []) or [] |
| values = [_frac(q.get("y", "0")) for q in siblings] |
| cur = _frac(p.get("y", "0")) |
| lo = min(values) if values else cur |
| hi = max(values) if values else cur |
| new = _seeded_in_range(seed, pid, "point_y", lo, hi, {cur}) |
| return canonical_number_str(new), f"substitute point {pid} y → {new}" |
|
|
|
|
| def _sample_row_cell(world: World, rid: str, seed: int) -> tuple[str, str]: |
| row = find_row(world, rid) |
| if row is None: |
| raise InterventionError(f"row {rid!r} not found") |
| _ridx, r = row |
| cells = r.get("cells", {}) or {} |
| if not cells: |
| raise InterventionError(f"row {rid!r} has no cells") |
| key = next(iter(cells)) |
| cur = _frac(cells[key]) |
| |
| col_vals = [ |
| _frac(row_.get("cells", {}).get(key, cells[key])) |
| for row_ in (world.get("rows", []) or []) |
| if key in (row_.get("cells", {}) or {}) |
| ] |
| lo = min(col_vals) if col_vals else cur |
| hi = max(col_vals) if col_vals else cur |
| new = _seeded_in_range(seed, rid, f"cell:{key}", lo, hi, {cur}) |
| return canonical_number_str(new), f"substitute row {rid} cell {key} → {new}" |
|
|
|
|
| def _sample_series_label(world: World, sid: str, seed: int) -> tuple[str, str]: |
| series = find_series(world, sid) |
| if series is None: |
| raise InterventionError(f"series {sid!r} not found") |
| _sidx, s = series |
| existing = {str(t.get("label", "")) for t in world.get("series", []) or []} |
| cur = str(s.get("label", sid)) |
| prefix = _label_prefix(cur) |
| for n in _seeded_offsets(seed, sid, "label", span=1000): |
| cand = f"{prefix}_{n}" |
| if cand not in existing: |
| return cand, f"substitute series {sid} label → {cand}" |
| raise InterventionError(f"series {sid!r}: no non-colliding label found") |
|
|
|
|
| def _sample_geometry_measure(world: World, entity: str, seed: int) -> tuple[str, str]: |
| found = find_stating_constraint(world, entity) |
| if found is None: |
| raise InterventionError(f"no stating constraint for {entity!r}") |
| _cidx, c = found |
| args = list(c.get("args") or []) |
| pred = c.get("predicate") |
| if pred == "MeasureOf" and len(args) >= 2: |
| cur = _frac(args[1]) |
| elif pred == "Equals" and len(args) == 2: |
| cur = _frac(args[1]) if looks_numeric(args[1]) else _frac(args[0]) |
| else: |
| raise InterventionError(f"stating constraint for {entity!r} is not numeric") |
| |
| |
| new = cur + Fraction(next(_seeded_offsets(seed, entity, "measure", span=200)) - 100) |
| return canonical_number_str(new), f"substitute measure {entity} → {new}" |
|
|
|
|
| def _sample_entity_label(world: World, eid: str, seed: int) -> tuple[str, str]: |
| entity = next((e for e in world.get("entities", []) or [] if e.get("id") == eid), None) |
| if entity is None: |
| raise InterventionError(f"entity {eid!r} not found") |
| cur = str(entity.get("label", entity.get("id", eid))) |
| existing = {str(e.get("label", e.get("id", ""))) for e in world.get("entities", []) or []} |
| prefix = _label_prefix(cur) |
| for n in _seeded_offsets(seed, eid, "elabel", span=1000): |
| cand = f"{prefix}_{n}" |
| if cand not in existing: |
| return cand, f"substitute entity {eid} label → {cand}" |
| raise InterventionError(f"entity {eid!r}: no non-colliding label found") |
|
|
|
|
| |
|
|
|
|
| def _seeded_in_range( |
| seed: int, tag: str, kind: str, lo: Fraction, hi: Fraction, exclude: set[Fraction] |
| ) -> Fraction: |
| """A deterministic integer in ``[lo, hi]`` (extended by ±1 when degenerate), |
| not in ``exclude``, at source integer precision.""" |
| lo_i = int(lo) |
| hi_i = int(hi) |
| if hi_i < lo_i: |
| lo_i, hi_i = hi_i, lo_i |
| if hi_i - lo_i < 1: |
| lo_i -= 1 |
| hi_i += 1 |
| span = hi_i - lo_i + 1 |
| |
| |
| |
| for probe, n in enumerate(_seeded_offsets(seed, tag, kind, span=span)): |
| if probe > len(exclude): |
| break |
| cand = Fraction(lo_i + (n % (hi_i - lo_i + 1))) |
| if cand not in exclude: |
| return cand |
| raise InterventionError(f"no in-range substitute for {tag!r} ({kind})") |
|
|
|
|
| def _seeded_offsets(seed: int, tag: str, kind: str, *, span: int) -> Iterator[int]: |
| """Yield a deterministic O(1)-memory permutation of ``[0, span)``.""" |
|
|
| span = max(span, 1) |
| digest = hashlib.sha256(f"{seed}|{tag}|{kind}|affine-v1".encode()).digest() |
| start = int.from_bytes(digest[:16], "big") % span |
| step = int.from_bytes(digest[16:], "big") % span |
| if step == 0: |
| step = 1 |
| while math.gcd(step, span) != 1: |
| step = (step + 1) % span |
| if step == 0: |
| step = 1 |
| for index in range(span): |
| yield (start + index * step) % span |
|
|
|
|
| def _frac(value: Any) -> Fraction: |
| return parse_number(value) |
|
|
|
|
| def _label_prefix(label: str) -> str: |
| return label.rstrip("0123456789_") or label or "node" |
|
|
|
|
| __all__ = ["SubstituteOperator"] |
|
|