File size: 5,380 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
"""Constraint / world feasibility checks for interventions (``docs/02`` §10).

CLEAN_DELETE_V1 (§10.3) and SUBSTITUTE_V1 on a geometry world (§10.4 "geometry:
constraint satisfiable") must reject a transformation that leaves the world
ill-formed — a dangling reference after a delete, or a contradictory stating
constraint after a substitute. Full theorem-proving satisfiability is the P13
reference executor's job; here "feasible" means **structurally well-formed and
free of direct contradictions** the executor would trip over: no dangling
entity references, no two stating constraints assigning different values to the
same entity, and the plot/table shape intact.

An infeasible world is reported via :class:`FeasibilityError` (a typed reject)
so an operator never emits a broken world silently (P5 gate: "invalid
geometry/plot mutation reject").
"""

from __future__ import annotations

from ..dsl.ast import Dsl, parse_number
from ..ingest.base import IngestError
from ..sources.base import World
from ..sources.world_ops import is_geometry, is_plot, is_table, looks_numeric


class FeasibilityError(IngestError):
    """A world is ill-formed / self-contradictory after a transformation."""


def is_feasible(world: World, *, dsl: Dsl) -> bool:
    """True iff ``world`` is structurally well-formed for ``dsl``.

    Raises :class:`FeasibilityError` (carrying the reason) when infeasible, so a
    caller can distinguish "reject" from "feasible". Returns ``True`` otherwise.
    """
    if is_plot(world):
        _check_plot(world)
    elif is_table(world):
        _check_table(world)
    elif is_geometry(world):
        _check_geometry(world)
    else:
        raise FeasibilityError(f"unknown world shape for dsl {dsl!r}")
    return True


def _check_plot(world: World) -> None:
    series = world.get("series", []) or []
    if not isinstance(series, list):
        raise FeasibilityError("plot world `series` is not a list")
    seen_points: set[str] = set()
    for s in series:
        if not isinstance(s, dict) or not s.get("id"):
            raise FeasibilityError("plot series missing an id")
        for p in s.get("points", []) or []:
            if not isinstance(p, dict) or not p.get("id"):
                raise FeasibilityError("plot point missing an id")
            if "x" not in p or "y" not in p:
                raise FeasibilityError(f"plot point {p.get('id')} missing x/y")
            if p["id"] in seen_points:
                raise FeasibilityError(f"duplicate plot point id {p['id']}")
            seen_points.add(p["id"])


def _check_table(world: World) -> None:
    rows = world.get("rows", []) or []
    if not isinstance(rows, list):
        raise FeasibilityError("table world `rows` is not a list")
    seen: set[str] = set()
    for r in rows:
        if not isinstance(r, dict) or not r.get("id"):
            raise FeasibilityError("table row missing an id")
        if r["id"] in seen:
            raise FeasibilityError(f"duplicate table row id {r['id']}")
        seen.add(r["id"])


def _check_geometry(world: World) -> None:
    entities = world.get("entities", []) or []
    entity_ids = {str(e.get("id")) for e in entities if isinstance(e, dict) and e.get("id")}
    constraints = world.get("constraints", []) or []
    if not isinstance(constraints, list):
        raise FeasibilityError("geometry world `constraints` is not a list")

    # 1. No dangling non-numeric reference: every string arg that is not a
    #    numeric literal must name a known entity.
    for c in constraints:
        if not isinstance(c, dict) or not c.get("predicate"):
            raise FeasibilityError("geometry constraint missing a predicate")
        for arg in c.get("args", []) or []:
            if isinstance(arg, str) and not looks_numeric(arg) and arg not in entity_ids:
                raise FeasibilityError(
                    f"constraint {c.get('predicate')} references unknown entity {arg!r}"
                )

    # 2. No conflicting stating constraints: at most one value per entity from
    #    MeasureOf / Equals (a substitute that creates a second, different value
    #    is a direct contradiction the executor cannot resolve).
    stated: dict[str, str] = {}
    for c in constraints:
        pred = c.get("predicate")
        args = c.get("args") or []
        if pred == "MeasureOf" and len(args) >= 2 and looks_numeric(args[1]):
            _record_stated(stated, str(args[0]), str(args[1]), pred)
        elif pred == "Equals" and len(args) == 2:
            if looks_numeric(args[1]) and not looks_numeric(args[0]):
                _record_stated(stated, str(args[0]), str(args[1]), pred)
            elif looks_numeric(args[0]) and not looks_numeric(args[1]):
                _record_stated(stated, str(args[1]), str(args[0]), pred)


def _record_stated(stated: dict[str, str], entity: str, value: str, pred: str) -> None:
    canonical = _num(value)
    if entity in stated and stated[entity] != canonical:
        raise FeasibilityError(
            f"entity {entity!r} is stated twice with conflicting values "
            f"({stated[entity]} vs {canonical}) via {pred}"
        )
    stated[entity] = canonical


def _num(text: str) -> str:
    try:
        return str(parse_number(text))
    except (ValueError, ZeroDivisionError):
        return text


__all__ = ["FeasibilityError", "is_feasible"]