"""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 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 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.""" worlds = [full] + list(alternatives) answers = [evaluate(w.entities, w.edges, query) for w in worlds] if any(a is None for a in answers) or len(set(answers)) != 1: # the observation admits more than one truth: this is the real # "insufficient evidence" case, not an occlusion tag return Label(answer="unknown", change="unknown", evidence=[], sufficient=False) ans_after = answers[0] before = Query(kind=query.kind, a=query.a, b=query.b, edit=None) ans_before = evaluate(full.entities, full.edges, before) if query.edit is None: change = "same" elif ans_before is None: change = "unknown" else: change = "changed" if ans_before != ans_after else "same" return Label(answer="true" if ans_after else "false", change=change, evidence=evidence_for(full, query), sufficient=True)