| """``U_MISSING`` completion-candidate enumeration (``docs/02`` §11.2). |
| |
| For a hidden node, the state-proof builder (P7) needs a set of *completion* |
| worlds — the same world with the hidden node set to each of several valid |
| alternative values — so it can search for a pair that renders identically (same |
| observed hash) yet yields different unique answers (the ``U_MISSING`` criterion). |
| This module provides the deterministic enumeration and the |
| :func:`~explicit_learning.interventions.base.with_value` re-builder; P7 owns the |
| pair search itself. |
| |
| Enumeration is seed-determined and yields ``≥8`` distinct admissible values |
| (mirroring the §7.3 mutation suite's per-leaf count), each producing a fresh |
| world via :func:`with_value` so the source world stays immutable. |
| """ |
|
|
| from __future__ import annotations |
|
|
| from collections.abc import Iterator |
| from dataclasses import dataclass |
| from fractions import Fraction |
| from typing import Any |
|
|
| from ..dsl.ast import canonical_number_str, parse_number |
| from ..sources.base import World |
| from ..sources.world_ops import ( |
| find_point, |
| find_row, |
| find_stating_constraint, |
| looks_numeric, |
| node_kind, |
| ) |
| from .base import InterventionError, with_value |
| from .substitute import _seeded_offsets |
|
|
| _DEFAULT_COUNT = 8 |
|
|
|
|
| @dataclass(frozen=True) |
| class Completion: |
| """One alternative completion of a hidden node.""" |
|
|
| world: World |
| node_id: str |
| value: str |
| index: int |
|
|
|
|
| def valid_values( |
| world: World, |
| hidden_node: str, |
| *, |
| seed: int, |
| count: int = _DEFAULT_COUNT, |
| ) -> list[str]: |
| """Enumerate ``count`` distinct admissible values for ``hidden_node``. |
| |
| Numeric sites (a point's ``y``, a row cell, a geometry measure) yield seeded |
| distinct rationals near the source range; category sites (a label) yield |
| non-colliding labels. The values are deterministic in ``(seed, node, count)``. |
| """ |
| kind = node_kind(world, hidden_node) |
| if kind is None: |
| raise InterventionError(f"completion: {hidden_node!r} is not a world node") |
| if kind == "point": |
| return _point_values(world, hidden_node, seed, count) |
| if kind == "row": |
| return _row_values(world, hidden_node, seed, count) |
| if kind == "constraint": |
| return _measure_values(world, hidden_node, seed, count) |
| if kind in ("series", "entity"): |
| return _label_values(world, hidden_node, kind, seed, count) |
| raise InterventionError(f"completion: no sampler for kind {kind!r}") |
|
|
|
|
| def completion_candidates( |
| world: World, |
| hidden_node: str, |
| *, |
| seed: int, |
| count: int = _DEFAULT_COUNT, |
| ) -> list[Completion]: |
| """``count`` completion worlds for ``hidden_node`` (source world immutable). |
| |
| Each completion is :func:`with_value` applied to a distinct enumerated value; |
| the source world is never mutated. Raises :class:`InterventionError` if the |
| node has no mutable value site. |
| """ |
| out: list[Completion] = [] |
| for i, value in enumerate(valid_values(world, hidden_node, seed=seed, count=count)): |
| out.append( |
| Completion( |
| world=with_value(world, hidden_node, value), |
| node_id=hidden_node, |
| value=value, |
| index=i, |
| ) |
| ) |
| return out |
|
|
|
|
| def iter_completions( |
| world: World, hidden_node: str, *, seed: int, count: int = _DEFAULT_COUNT |
| ) -> Iterator[Completion]: |
| """Lazy stream of completions (memory-bounded for large enumerations).""" |
| for i, value in enumerate(valid_values(world, hidden_node, seed=seed, count=count)): |
| yield Completion( |
| world=with_value(world, hidden_node, value), |
| node_id=hidden_node, |
| value=value, |
| index=i, |
| ) |
|
|
|
|
| |
|
|
|
|
| def _point_values(world: World, pid: str, seed: int, count: int) -> list[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 [] |
| used = {_frac(q.get("y", "0")) for q in siblings} |
| cur = _frac(p.get("y", "0")) |
| return _distinct_near(seed, pid, "comp_point", cur, used, count) |
|
|
|
|
| def _row_values(world: World, rid: str, seed: int, count: int) -> list[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)) |
| used = { |
| _frac(row_.get("cells", {}).get(key)) |
| for row_ in (world.get("rows", []) or []) |
| if key in (row_.get("cells", {}) or {}) and looks_numeric(row_.get("cells", {}).get(key)) |
| } |
| cur = _frac(cells[key]) |
| return _distinct_near(seed, f"{rid}:{key}", "comp_cell", cur, used, count) |
|
|
|
|
| def _measure_values(world: World, entity: str, seed: int, count: int) -> list[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 []) |
| if c.get("predicate") == "MeasureOf" and len(args) >= 2 or looks_numeric(args[1]): |
| cur = _frac(args[1]) |
| elif looks_numeric(args[0]): |
| cur = _frac(args[0]) |
| else: |
| raise InterventionError(f"stating constraint for {entity!r} is not numeric") |
| return _distinct_near(seed, entity, "comp_measure", cur, set(), count) |
|
|
|
|
| def _label_values(world: World, nid: str, kind: str, seed: int, count: int) -> list[str]: |
| if kind == "series": |
| existing = {str(t.get("label", "")) for t in world.get("series", []) or []} |
| else: |
| existing = {str(e.get("label", e.get("id", ""))) for e in world.get("entities", []) or []} |
| out: list[str] = [] |
| for n in _seeded_offsets(seed, nid, "comp_label", span=10_000): |
| cand = f"node_{n}" |
| if cand not in existing and cand not in out: |
| out.append(cand) |
| if len(out) >= count: |
| break |
| if len(out) < count: |
| raise InterventionError(f"could not enumerate {count} labels for {nid!r}") |
| return out |
|
|
|
|
| def _distinct_near( |
| seed: int, tag: str, kind: str, cur: Fraction, used: set[Fraction], count: int |
| ) -> list[str]: |
| """``count`` distinct rationals near ``cur`` not in ``used`` (seeded).""" |
| out: list[str] = [] |
| seen: set[Fraction] = {cur, *used} |
| base = int(cur) |
| for off in _seeded_offsets(seed, tag, kind, span=2 * count * 20 + 10): |
| cand = Fraction(base + (off % (4 * count + 20)) - (2 * count + 10)) |
| if cand in seen: |
| continue |
| seen.add(cand) |
| out.append(canonical_number_str(cand)) |
| if len(out) >= count: |
| break |
| if len(out) < count: |
| raise InterventionError(f"could not enumerate {count} distinct values for {tag!r}") |
| return out |
|
|
|
|
| def _frac(value: Any) -> Fraction: |
| return parse_number(value) |
|
|
|
|
| __all__ = ["Completion", "completion_candidates", "iter_completions", "valid_values"] |
|
|