"""Reference checker. The generator only builds structure; every label is produced here from the full state, then downgraded to ``unknown`` whenever the observation admits a different answer. That downgrade rule is what makes "evidence insufficient" a real label instead of a random occlusion tag: answers = {answer(full), answer(full restricted to the observation)} if len(answers) != 1 -> unknown Restricting the full state to what is visible is the cheapest way to build the "same observation, opposite truth" pair that the plan asks for, and it needs no special case per domain. Nothing here imports the model, so a disagreement between the two is real. """ from __future__ import annotations from collections import defaultdict, deque from typing import Iterable, Optional from .schema import (DOF_AXES, Edge, Entity, FullState, Label, Observation, Query) # -------------------------------------------------------------------------- # query edits def _removed_edge(query: Query) -> Optional[str]: if query.edit and query.edit.get("op") == "remove_edge": return query.edit.get("edge") return None def _removed_entity(query: Query) -> Optional[str]: if query.edit and query.edit.get("op") == "remove_entity": return query.edit.get("entity") return None def _alive_edges(edges: Iterable[Edge], query: Query) -> list: drop = _removed_edge(query) return [e for e in edges if e.eid != drop] def _alive_entities(entities: Iterable[Entity], query: Query) -> list: drop = _removed_entity(query) return [e for e in entities if e.eid != drop] def _index(entities: Iterable[Entity]) -> dict: return {e.eid: e for e in entities} # -------------------------------------------------------------------------- # connection def conduct_path(edges: Iterable[Edge], src: str, dst: str) -> Optional[list]: adj = defaultdict(list) for e in edges: if e.kind != "conduct": continue adj[e.a].append((e.b, e.eid)) adj[e.b].append((e.a, e.eid)) if src == dst: return [] prev = {src: (None, None)} q = deque([src]) while q: u = q.popleft() for v, eid in adj[u]: if v in prev: continue prev[v] = (u, eid) if v == dst: path = [] while v != src: v, pe = prev[v] path.append(pe) return list(reversed(path)) q.append(v) return None def _connection_answer(entities, edges, query: Query) -> Optional[bool]: idx = _index(_alive_entities(entities, query)) if query.a not in idx or query.b not in idx: return None return conduct_path(_alive_edges(edges, query), query.a, query.b) is not None # -------------------------------------------------------------------------- # stability def _box(e: Entity): b = e.attrs.get("box") return tuple(b) if b else None def _overlap(a, b): ox0, oy0 = max(a[0], b[0]), max(a[1], b[1]) ox1, oy1 = min(a[3], b[3]), min(a[4], b[4]) if ox0 >= ox1 or oy0 >= oy1: return None return (ox0, oy0, ox1, oy1) def stable_blocks(entities) -> dict: """{block eid: supporter eid or "ground"} for blocks that stand.""" blocks = [e for e in entities if e.kind == "block" and _box(e)] support, stable = {}, set() changed = True while changed: changed = False for b in blocks: if b.eid in stable: continue x0, y0, z0, x1, y1, _ = _box(b) if z0 == 0: stable.add(b.eid) support[b.eid] = "ground" changed = True continue cx2, cy2 = x0 + x1, y0 + y1 # twice the centroid: stays integer for s in blocks: if s.eid == b.eid or s.eid not in stable: continue sx0, sy0, _, sx1, sy1, sz1 = _box(s) if sz1 != z0: continue ov = _overlap(_box(b), _box(s)) if ov is None: continue if 2 * ov[0] <= cx2 <= 2 * ov[2] and 2 * ov[1] <= cy2 <= 2 * ov[3]: stable.add(b.eid) support[b.eid] = s.eid changed = True break return support def _stability_answer(entities, edges, query: Query) -> Optional[bool]: alive = _alive_entities(entities, query) part = _index(alive).get(query.a) if part is None or part.kind != "block": return None return query.a in stable_blocks(alive) # -------------------------------------------------------------------------- # freedom def _freedom_answer(entities, edges, query: Query) -> Optional[bool]: idx = _index(_alive_entities(entities, query)) part = idx.get(query.a) if part is None or part.kind != "part": return None covered = {e.attrs.get("axis") for e in _alive_edges(edges, query) if e.kind == "constraint"} return len(covered & set(DOF_AXES)) == len(DOF_AXES) _ANSWER_FN = { "connection": _connection_answer, "stability": _stability_answer, "freedom": _freedom_answer, } def evaluate(entities, edges, query: Query) -> Optional[bool]: fn = _ANSWER_FN.get(query.kind) if fn is None: raise ValueError(f"unknown query kind {query.kind!r}") return fn(list(entities), list(edges), query) # -------------------------------------------------------------------------- # certificates def evidence_for(full: FullState, query: Query) -> list: """One certificate, as edge ids. Several may be valid; the checker accepts any that validates.""" edges = _alive_edges(full.edges, query) ents = _alive_entities(full.entities, query) if query.kind == "connection": return conduct_path(edges, query.a, query.b) or [] if query.kind == "freedom": picked, seen = [], set() for e in edges: if e.kind != "constraint": continue ax = e.attrs.get("axis") if ax in DOF_AXES and ax not in seen: seen.add(ax) picked.append(e.eid) return picked if len(seen) == len(DOF_AXES) else [] if query.kind == "stability": support = stable_blocks(ents) if query.a not in support: return [] chain, cur = [], query.a while support.get(cur) not in (None, "ground"): nxt = support[cur] edge = next((e for e in edges if e.kind == "contact" and {e.a, e.b} == {cur, nxt}), None) if edge is None: break chain.append(edge.eid) cur = nxt return chain return [] def _contact_is_real(ents: dict, e: Edge) -> bool: """Re-derive a contact from the boxes instead of trusting the edge label. A certificate is only worth something if the thing it cites can be checked independently. Until this existed, `validate_evidence` walked the claimed chain and stopped as soon as it reached anything sitting on the ground -- so a provider that emitted one bogus contact edge could forge support that validated. Measured: with a distance tolerance of one grid unit (0.25mm) every part pair separated by 0.25mm produced an edge that passed. """ a, b = ents.get(e.a), ents.get(e.b) if a is None or b is None: return False ba, bb = _box(a), _box(b) if ba and bb: if not (ba[5] == bb[2] or bb[5] == ba[2]): return False # faces do not meet: no load path return _overlap(ba, bb) is not None # and they must share a footprint box, other = (ba, b) if ba else (bb, a) if box is None or other.kind != "ground": return False return box[2] == float(other.attrs.get("plane", 0)) def validate_evidence(full: FullState, query: Query, evidence) -> bool: """Independent re-check of a claimed certificate.""" evidence = list(evidence or []) if not evidence or _removed_edge(query) in evidence: return False by_id = {e.eid: e for e in full.edges} if any(eid not in by_id for eid in evidence): return False edges = [by_id[eid] for eid in evidence] if query.kind == "connection": return conduct_path(edges, query.a, query.b) is not None if query.kind == "freedom": covered = {e.attrs.get("axis") for e in edges if e.kind == "constraint"} return len(covered & set(DOF_AXES)) == len(DOF_AXES) if query.kind == "stability": if any(e.kind != "contact" for e in edges): return False ents = _index(full.entities) if query.a not in ents: return False # every cited step has to be a contact that the geometry actually shows if not all(_contact_is_real(ents, e) for e in edges): return False reached = {query.a} for _ in range(len(edges) + 1): for e in edges: if e.a in reached: reached.add(e.b) elif e.b in reached: reached.add(e.a) return any(eid in ents and ents[eid].kind == "ground" for eid in reached) or \ any(eid in ents and _box(ents[eid]) is not None and _box(ents[eid])[2] == 0 for eid in reached) return False # -------------------------------------------------------------------------- # label def label(obs: Observation, full: FullState, query: Query, alternatives: Iterable[FullState] = ()) -> Label: """Full state decides; the observation decides whether we may say so. When something is withheld the rule is *monotone*: a hidden conduct edge can only connect, a hidden contact can only support, a hidden mate can only lock an axis. None of them can undo a proof the observation already contains. So * the visible structure already proves the answer -> decidable "true"; * it does not -> the withheld item could be exactly the missing piece, and the answer is unknown, however the one full state we happen to hold resolves it. The cheaper rule -- compare the full state against the observation's own world -- marks "the pedestal is behind the part and in this particular scene it would not have helped" as decidable false. That is not a fact the agent can know: another equally consistent world puts the pedestal under the centroid and the answer flips. Measured: area.sup2h came out 36 decidable / 92 not, and the model swung between answering all of them and abstaining from all of them, because the split is not in the observation. """ ans_full = evaluate(full.entities, full.edges, query) alt = list(alternatives) ans_vis = evaluate(alt[0].entities, alt[0].edges, query) if alt else ans_full withheld = bool(obs.dangling) or bool((obs.hidden or {}).get("entity")) \ or bool((obs.hidden or {}).get("edge")) if withheld: if ans_vis is True: # the observation proves it on its own; nothing withheld can break it return Label(answer="true", change=_change(full, query, True), evidence=evidence_for(alt[0], query) if alt else [], sufficient=True) return Label(answer="unknown", change="unknown", evidence=[], sufficient=False) if ans_full is None or ans_vis is None or ans_full != ans_vis: return Label(answer="unknown", change="unknown", evidence=[], sufficient=False) return Label(answer="true" if ans_full else "false", change=_change(full, query, ans_full), evidence=evidence_for(full, query), sufficient=True) def _change(full: FullState, query: Query, ans_after) -> str: if query.edit is None: return "same" before = Query(kind=query.kind, a=query.a, b=query.b, edit=None) ans_before = evaluate(full.entities, full.edges, before) if ans_before is None: return "unknown" return "changed" if ans_before != ans_after else "same"