File size: 7,491 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
"""``CONTROL_MATCHED_V1`` — a matched non-dependency control node (§10.5).

A control view edits a node the program does **not** depend on, so the formal
answer is unchanged while the image changes in a region matched to the target.
The matched node shares the target's visual type, pixel-area quantile, and
center-position bin, and is edited with the same operator (§10.5).

Pixels do not exist until P6, so area/position are proxied from the semantic
world: *visual type* = :func:`~explicit_learning.sources.world_ops.node_kind`,
*area quantile* = the node's value-magnitude rank among same-kind nodes, and
*position bin* = its index rank in world order. P6/P9 replace these proxies
with real pixel audits; the selection contract is unchanged.

When no matched non-dependency node exists, the spec lets the caller either form
a control-less group or reject. :func:`find_control_match` returns ``None`` so
the group builder (P11) can choose; :meth:`ControlMatchedOperator.apply`
rejects via :class:`InterventionError` for callers that want a hard fail.
"""

from __future__ import annotations

import hashlib
from typing import Any

from ..dsl.ast import Dsl
from ..sources.base import World
from ..sources.world_ops import (
    find_point,
    find_row,
    find_series,
    is_geometry,
    is_plot,
    is_table,
    node_kind,
    world_sha256,
)
from .base import (
    InterventionError,
    OperatorName,
    TransformedWorld,
    transformed_hash,
)

_NAME: OperatorName = "CONTROL_MATCHED_V1"
_BINS = 4


class ControlMatchedOperator:
    """Apply the matched edit to a non-dependency control node."""

    name = _NAME

    def apply(
        self,
        world: World,
        target_node: str,
        *,
        seed: int,
        dsl: Dsl,
        dependency_node_ids: tuple[str, ...] | frozenset[str] = (),
        edit_operator: OperatorName = "REDACT_SOLID_V1",
        **kwargs: Any,
    ) -> TransformedWorld:
        control = find_control_match(
            world,
            target_node,
            frozenset(dependency_node_ids),
            edit_operator=edit_operator,
            seed=seed,
        )
        if control is None:
            raise InterventionError(
                f"CONTROL_MATCHED_V1: no matched non-dependency node for "
                f"{target_node!r} ({edit_operator})"
            )
        # Apply the matched edit to the control node. The transformation is
        # labelled CONTROL_MATCHED_V1; the underlying edit is in the description.
        from . import get_operator  # local: the registry is finalized at import

        inner = get_operator(edit_operator).apply(world, control, seed=seed, dsl=dsl, **kwargs)
        return TransformedWorld(
            world=inner.world,
            operator=_NAME,
            target_node=control,
            seed=seed,
            transformed_world_sha256=transformed_hash(
                operator=_NAME,
                target_node=control,
                seed=seed,
                source_world_sha256=world_sha256(world),
                transformed_world_sha256=world_sha256(inner.world),
                hidden_nodes=inner.hidden_nodes,
                substitute_value=inner.substitute_value,
            ),
            hidden_nodes=inner.hidden_nodes,
            substitute_value=inner.substitute_value,
            description=f"control-matched {edit_operator} on {control} (for {target_node})",
        )


def find_control_match(
    world: World,
    target_node: str,
    dependency_node_ids: frozenset[str],
    *,
    edit_operator: OperatorName,
    seed: int,
) -> str | None:
    """The best same-kind, non-dependency match for ``target_node`` (or ``None``).

    Ranks every same-kind node by area (value-magnitude) and position (world
    index) into ``_BINS`` quantile buckets and prefers a candidate sharing both
    of the target's buckets; ties break by seeded hash for determinism. The
    target itself and every dependency node are excluded.
    """
    target_kind = node_kind(world, target_node)
    if target_kind is None:
        return None
    same_kind = [nid for nid in _all_nodes(world) if node_kind(world, nid) == target_kind]
    if not same_kind:
        return None
    area_rank = _ranks(same_kind, lambda nid: _area_metric(world, nid, target_kind))
    pos_rank = _ranks(same_kind, lambda nid: float(same_kind.index(nid)))
    t_area = _bucket(area_rank[target_node])
    t_pos = _bucket(pos_rank[target_node])

    candidates = [nid for nid in same_kind if nid != target_node and nid not in dependency_node_ids]
    if not candidates:
        return None

    def _score(nid: str) -> tuple[int, int, int]:
        # (area-bucket match, position-bucket match, seeded tie-break) — lower is
        # better; the seeded hash keeps selection deterministic.
        a = 0 if _bucket(area_rank[nid]) == t_area else 1
        p = 0 if _bucket(pos_rank[nid]) == t_pos else 1
        h = int.from_bytes(hashlib.sha256(f"{seed}|control|{nid}".encode()).digest()[:4], "big")
        return (a, p, h)

    candidates.sort(key=_score)
    return candidates[0]


# --- node enumeration + metrics -------------------------------------------


def _all_nodes(world: World) -> list[str]:
    out: list[str] = []
    if is_plot(world):
        for s in world.get("series", []) or []:
            if s.get("id"):
                out.append(str(s["id"]))
            for p in s.get("points", []) or []:
                if p.get("id"):
                    out.append(str(p["id"]))
    if is_table(world):
        for r in world.get("rows", []) or []:
            if r.get("id"):
                out.append(str(r["id"]))
    if is_geometry(world):
        for e in world.get("entities", []) or []:
            if e.get("id"):
                out.append(str(e["id"]))
        for c in world.get("constraints", []) or []:
            for a in c.get("args") or []:
                if isinstance(a, str) and not _is_numeric(a):
                    out.append(str(a))
    # de-dup, preserve order
    seen: set[str] = set()
    uniq: list[str] = []
    for nid in out:
        if nid not in seen:
            seen.add(nid)
            uniq.append(nid)
    return uniq


def _area_metric(world: World, nid: str, kind: str) -> float:
    if kind == "point":
        point = find_point(world, nid)
        if point is not None:
            _s, _p, p = point
            try:
                return abs(float(p.get("y", 0)))
            except (TypeError, ValueError):
                return 0.0
    if kind == "series":
        series = find_series(world, nid)
        if series is not None:
            _i, s = series
            return float(len(s.get("points", []) or []))
    if kind == "row":
        row = find_row(world, nid)
        if row is not None:
            _i, r = row
            return float(len(r.get("cells", {}) or {}))
    return 0.0


def _ranks(items: list[str], metric: Any) -> dict[str, float]:
    """Normalized ``[0, 1]`` rank of each item by ``metric`` (ties average)."""
    if len(items) <= 1:
        return {items[0]: 0.0} if items else {}
    keyed = sorted(items, key=metric)
    return {nid: idx / (len(keyed) - 1) for idx, nid in enumerate(keyed)}


def _bucket(rank: float) -> int:
    return min(_BINS - 1, int(rank * _BINS))


def _is_numeric(text: str) -> bool:
    try:
        float(text)
    except (TypeError, ValueError):
        return False
    return True


__all__ = ["ControlMatchedOperator", "find_control_match"]