Datasets:
Download src/explicit_learning/sources/world_ops.py from sungguk/visual-answerability: direct link, hf CLI and curl.
- Browser
- Download file 5.8 kB
-
https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/sources/world_ops.py
- Command line
-
hf download hf://datasets/sungguk/visual-answerability/src/explicit_learning/sources/world_ops.py
-
curl -L -o world_ops.py https://huggingface.co/datasets/sungguk/visual-answerability/resolve/main/src/explicit_learning/sources/world_ops.py
5.8 kB
| """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", | |
| ] | |