File size: 5,795 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
"""Shared, pure helpers for locating and inspecting structured-world nodes.

A *world* (``docs/02`` §6) is a plain JSON-serializable mapping —
``plot_world_v1`` / ``geometry_world_v1`` / ``table_world_v1``. Both the C2
mutation suite (``docs/02`` §7.3) and the P5 intervention operators
(``docs/02`` §10) need to find a node by stable id, tell the world kinds apart,
and hash a world deterministically. Those helpers live here once so the two
layers stay consistent and neither reaches into the other's privates.

Everything here is **read-only** over the passed world and never mutates it; the
caller is responsible for ``copy.deepcopy`` when it wants a mutable copy (see
:func:`clone_world`).
"""

from __future__ import annotations

import copy
from typing import Any

from ..hashing import canonical_json_hash
from .base import World

# The reserved top-level marker a transformed world carries to record which
# semantic nodes a renderer must hide (``docs/02`` §10.1 REDACT_SOLID_V1). It is
# intentionally namespaced so executors — which read only ``series`` /
# ``constraints`` / ``rows`` — ignore it, while the renderer (P6) reads it.
NODE_VISIBILITY_KEY = "_node_visibility"


def clone_world(world: World) -> World:
    """A deep, independent copy of ``world`` (the source stays immutable)."""
    return copy.deepcopy(world)


def hidden_nodes(world: World) -> frozenset[str]:
    """The node ids a world marks hidden (``frozenset()`` when none).

    A pure read of the reserved :data:`NODE_VISIBILITY_KEY` map; executors
    ignore it, the renderer (P6) consumes it for REDACT_SOLID_V1 (§10.1).
    """
    vis = world.get(NODE_VISIBILITY_KEY, {}) or {}
    return frozenset(nid for nid, state in vis.items() if state == "hidden")


def world_sha256(world: World) -> str:
    """Content-addressed hash of a world (canonical-JSON, deterministic).

    The same world bytes always reproduce the same hash, so a transformed
    world's identity is byte-stable across runs (``docs/07`` §7 P5 gate:
    "seed/operation → same transformed world hash").
    """
    return canonical_json_hash(world)


def world_kind(world: World) -> str:
    """The world family: ``"plot"`` / ``"table"`` / ``"geometry"`` / ``"unknown"``."""
    if is_plot(world):
        return "plot"
    if is_table(world):
        return "table"
    if is_geometry(world):
        return "geometry"
    return "unknown"


def is_plot(world: World) -> bool:
    return "series" in world


def is_table(world: World) -> bool:
    return "rows" in world


def is_geometry(world: World) -> bool:
    return "constraints" in world or "entities" in world


def looks_numeric(text: Any) -> bool:
    """True if ``text`` parses as an exact number (``Fraction``-compatible)."""
    from ..dsl.ast import parse_number  # local: avoids a dsl import cycle at load

    try:
        parse_number(str(text))
    except (ValueError, ZeroDivisionError):
        return False
    return True


# --- node locators ---------------------------------------------------------


def find_point(world: World, pid: str) -> tuple[int, int, dict[str, Any]] | None:
    """Locate a plot point by id → ``(series_idx, point_idx, point_dict)``."""
    for sidx, s in enumerate(world.get("series", []) or []):
        for pidx, p in enumerate(s.get("points", []) or []):
            if isinstance(p, dict) and p.get("id") == pid:
                return sidx, pidx, p
    return None


def find_series(world: World, sid: str) -> tuple[int, dict[str, Any]] | None:
    for sidx, s in enumerate(world.get("series", []) or []):
        if isinstance(s, dict) and s.get("id") == sid:
            return sidx, s
    return None


def find_row(world: World, rid: str) -> tuple[int, dict[str, Any]] | None:
    for ridx, r in enumerate(world.get("rows", []) or []):
        if isinstance(r, dict) and r.get("id") == rid:
            return ridx, r
    return None


def find_stating_constraint(world: World, entity: str) -> tuple[int, dict[str, Any]] | None:
    """The constraint that states ``entity``'s value (``MeasureOf``/``Equals``)."""
    for cidx, c in enumerate(world.get("constraints", []) or []):
        if not isinstance(c, dict):
            continue
        pred = c.get("predicate")
        args = c.get("args") or []
        if pred == "MeasureOf" and len(args) >= 2 and str(args[0]) == entity:
            return cidx, c
        if pred == "Equals" and len(args) == 2:
            a, b = str(args[0]), str(args[1])
            if a == entity and looks_numeric(b):
                return cidx, c
            if b == entity and looks_numeric(a):
                return cidx, c
    return None


def node_kind(world: World, node_id: str) -> str | None:
    """The semantic kind of a node id: ``point``/``series``/``row``/``entity``/``constraint``.

    ``None`` when the id is not present. Used by CONTROL_MATCHED_V1 to match on
    visual type (``docs/02`` §10.5) via a semantic proxy (no pixels until P6).
    """
    if is_plot(world):
        if find_point(world, node_id) is not None:
            return "point"
        if find_series(world, node_id) is not None:
            return "series"
    if is_table(world) and find_row(world, node_id) is not None:
        return "row"
    if is_geometry(world):
        if find_stating_constraint(world, node_id) is not None:
            return "constraint"
        if any(e.get("id") == node_id for e in world.get("entities", []) or []):
            return "entity"
    return None


__all__ = [
    "NODE_VISIBILITY_KEY",
    "clone_world",
    "find_point",
    "find_row",
    "find_series",
    "find_stating_constraint",
    "hidden_nodes",
    "is_geometry",
    "is_plot",
    "is_table",
    "looks_numeric",
    "node_kind",
    "world_kind",
    "world_sha256",
]