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