File size: 7,176 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
"""``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  # canonical string form of the alternative value
    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,
        )


# --- value samplers (distinct, seeded) ------------------------------------


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"]