diff --git a/spatial/checker.py b/spatial/checker.py index 9f047d6..5ec21fb 100644 --- a/spatial/checker.py +++ b/spatial/checker.py @@ -239,8 +239,15 @@ def _contact_is_real(ents: dict, e: Edge) -> bool: 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.""" +def validate_evidence(full: FullState, query: Query, evidence, + conflicts=()) -> bool: + """Independent re-check of a claimed certificate. + + A certificate may not cite a relation two sources disagree on: the whole + point of the dispute is that nobody has established that relation, so it + cannot carry a proof. Same principle as ``_contact_is_real`` refusing a + contact the geometry does not show. + """ evidence = list(evidence or []) if not evidence or _removed_edge(query) in evidence: return False @@ -248,6 +255,10 @@ def validate_evidence(full: FullState, query: Query, evidence) -> bool: if any(eid not in by_id for eid in evidence): return False edges = [by_id[eid] for eid in evidence] + if conflicts: + named = {(c.get("kind"), frozenset((c.get("a"), c.get("b")))) for c in conflicts} + if any((e.kind, frozenset((e.a, e.b))) in named for e in edges): + return False if query.kind == "connection": return conduct_path(edges, query.a, query.b) is not None if query.kind == "freedom": @@ -279,6 +290,13 @@ def validate_evidence(full: FullState, query: Query, evidence) -> bool: # label +def hostile(obs, edge) -> bool: + """Is this relation disputed between two sources.""" + key = frozenset((edge.a, edge.b)) + return any(c.get("kind") == edge.kind and frozenset((c.get("a"), c.get("b"))) == key + for c in (obs.conflicts or [])) + + def withheld_flag(obs) -> bool: """Is the inventory bigger than what was handed over. @@ -302,6 +320,8 @@ def withheld_flag(obs) -> bool: rel_r = scope.get("rendered_relations") or {} if any(rel.get(k, 0) > rel_r.get(k, 0) for k in rel): return True + if scope.get("conflicts"): + return True return bool(set(scope.get("layers") or []) - set(scope.get("rendered_layers") or [])) @@ -331,11 +351,32 @@ def label(obs: Observation, full: FullState, query: Query, ans_vis = evaluate(alt[0].entities, alt[0].edges, query) if alt else ans_full withheld = withheld_flag(obs) - if withheld: - if ans_vis is True: - # the observation proves it on its own; nothing withheld can break it + conflicts = list(obs.conflicts or []) + if conflicts or withheld: + # Two sources naming the same relation and disagreeing is not the same + # kind of ignorance as "nobody told me". A disputed relation can be + # present or absent, both consistent with everything we were told, so the + # honest answer is whatever holds in *both* worlds -- and nothing else. + # + # That is sharper than the withheld rule, which cannot enumerate the + # missing content and so must answer "unknown" as soon as the visible + # structure fails to prove. Here the disputed item is named, so "false in + # both worlds" is a legitimate false rather than an abstention. + sure = alt[0] if alt else full + if conflicts: + disputed = {(c.get("kind"), frozenset((c.get("a"), c.get("b")))) + for c in conflicts} + kept = [e for e in sure.edges if (e.kind, frozenset((e.a, e.b))) not in disputed] + sure = FullState(entities=list(sure.entities), edges=kept) + ans_sure = evaluate(sure.entities, sure.edges, query) + if ans_sure is True: + # this proof never touches a disputed relation, so it stands return Label(answer="true", change=_change(full, query, True), - evidence=evidence_for(alt[0], query) if alt else [], sufficient=True) + evidence=evidence_for(sure, query), sufficient=True) + if not withheld and ans_vis is False: + # the answer is false whether the disputed relation exists or not + return Label(answer="false", change=_change(full, query, False), + evidence=[], 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: diff --git a/spatial/cli.py b/spatial/cli.py index 312aac0..c928c0f 100644 --- a/spatial/cli.py +++ b/spatial/cli.py @@ -97,8 +97,14 @@ def check_insufficient() -> bool: sc = generator.make(fam, seed=5, index=i) if sc.label.answer != "unknown": continue - restricted = FullState(entities=list(sc.obs.entities), edges=list(sc.obs.edges)) - a_vis = checker.evaluate(restricted.entities, restricted.edges, sc.query) + # "visible proves it" must mean *undisputed* visible structure: a + # relation two sources disagree on cannot carry a proof, so it is + # excluded here exactly as the label rule excludes it. + disputed = {(c.get("kind"), frozenset((c.get("a"), c.get("b")))) + for c in (sc.obs.conflicts or [])} + kept = [e for e in sc.obs.edges + if (e.kind, frozenset((e.a, e.b))) not in disputed] + a_vis = checker.evaluate(list(sc.obs.entities), kept, sc.query) withheld = checker.withheld_flag(sc.obs) if withheld and a_vis is not True: found += 1 @@ -107,7 +113,8 @@ def check_insufficient() -> bool: f"visible proof; label is not justified") if found == 0: return _fail("no insufficient-evidence sample was produced") - print(f"ok {found} unknown samples are undecided by the observation") + print(f"ok {found} unknown samples are undecided by the observation " + f"(undisputed part)") return True @@ -210,15 +217,25 @@ def check_scope_agrees(n: int = 24) -> bool: old = bool(sc.obs.dangling) or bool((sc.obs.hidden or {}).get("entity")) or bool((sc.obs.hidden or {}).get("edge")) new = checker.withheld_flag(sc.obs) rows += 1 - if old != new: + # conflicts are a second, independent reason to suspend: they are + # declared by the sources, not derived from the full state, so they + # have no diagnostic analogue. Two ways to be wrong, both checked: + # a withheld fact the scope cannot express, or a declared conflict + # the scope forgot to count. + # scope must equal the diagnostic *plus* the declared conflicts: the + # full state has no way to know that two sources disagree, so the + # union is what "something is not settled" should mean. + declared = bool(sc.obs.conflicts) + forgot = declared and not (sc.obs.scope or {}).get("conflicts") + if new != (old or declared) or forgot: bad.append((fam, i, old, new)) if bad: fams = sorted({f for f, _, _, _ in bad}) print(f" {len(bad)}/{rows} samples disagree, families {fams}") for f, i, o, nn in bad[:4]: print(f" {f}[{i}] diagnostic={o} scope={nn}") - return _fail("scope cannot express what was withheld; the label path still " - "needs full-state data") + return _fail("scope cannot express what was withheld, or a conflict went " + "undeclared") print(f"ok {rows} samples: declared inventory agrees with the diagnostic one") return True diff --git a/spatial/configs/smoke.json b/spatial/configs/smoke.json index 7272ba2..e00ae6c 100644 --- a/spatial/configs/smoke.json +++ b/spatial/configs/smoke.json @@ -23,7 +23,8 @@ "cond.p1h", "cond.p3h", "area.sup2h", - "dof.c6h" + "dof.c6h", + "src.scope" ], "availability": "declared" }, diff --git a/spatial/configs/sources.json b/spatial/configs/sources.json new file mode 100644 index 0000000..bc92a9b --- /dev/null +++ b/spatial/configs/sources.json @@ -0,0 +1,52 @@ +{ + "seed": 0, + "model": { + "d": 192, + "n_layer": 4, + "n_head": 6, + "dropout": 0.1, + "max_entities": 32, + "rounds": 2, + "n_evidence": 4 + }, + "data": { + "train_families": [ + "cond.p1", + "cond.p3", + "cond.p3h", + "cond.p1h", + "area.sup2", + "area.sup3", + "area.sup3h", + "area.sup2d", + "area.free", + "dof.c6", + "dof.c6r", + "dof.c6d", + "dof.set", + "area.near", + "src.scope", + "src.clean" + ], + "val_families": [ + "src.scope4" + ], + "test_families": [ + "area.sup2h", + "dof.c6h" + ], + "availability": "declared" + }, + "optim": { + "lr": 0.003, + "weight_decay": 0.01, + "steps": 12000, + "batch": 32, + "log_every": 400, + "warmup": 300 + }, + "eval": { + "n": 192 + }, + "out_dir": "out_spatial/sources" +} diff --git a/spatial/data.py b/spatial/data.py index 6b17706..f02daea 100644 --- a/spatial/data.py +++ b/spatial/data.py @@ -121,9 +121,18 @@ def edge_features(sc: Scenario, ed, removed: bool, dangling: bool = False) -> li f[N_EDGE + N_AXIS + 2] = geom[0] f[N_EDGE + N_AXIS + 3] = 1.0 if dangling else 0.0 f[N_EDGE + N_AXIS + 4:N_EDGE + N_AXIS + 7] = list(geom[1:]) + f[N_EDGE + N_AXIS + 7] = 1.0 if _disputed(sc, ed) else 0.0 return f +def _disputed(sc: Scenario, ed) -> bool: + """Named by two sources and disagreed on. Carries no vote: which source wins + is the one thing the system must not decide by itself.""" + pair = {ed.a, ed.b} + return any(c.get("kind") == ed.kind and {c.get("a"), c.get("b")} == pair + for c in (sc.obs.conflicts or [])) + + def scene_features(sc: Scenario, availability: str = "leaked") -> list: """The observation's own admission of what it is missing. diff --git a/spatial/generator.py b/spatial/generator.py index 631256b..dfada9a 100644 --- a/spatial/generator.py +++ b/spatial/generator.py @@ -26,6 +26,17 @@ FAMILIES = { "cond.p3": {"domain": "connection", "n_paths": 3, "hidden": 0}, "cond.p1h": {"domain": "connection", "n_paths": 2, "hidden": 1}, "cond.p3h": {"domain": "connection", "n_paths": 4, "hidden": 1}, + # source conflicts. The dispute is drawn *within* the family and its + # position is the causal variable: a branch is redundant once a second one + # exists, the trunk never is. So the same scene shape yields true when the + # dispute sits on a branch and unknown when it sits on the trunk -- which is + # the rule the contract has to teach, and no constant answer fits it. + "src.scope": {"domain": "connection", "n_paths_pick": (2, 3), + "conflict_pick": (1, 3), "hidden": 0, "no_edit": 1}, + "src.clean": {"domain": "connection", "n_paths_pick": (0, 1, 2), + "conflict": 0, "hidden": 0, "no_edit": 1}, + "src.scope4": {"domain": "connection", "n_paths": 4, + "conflict_pick": (1, 3), "hidden": 0, "no_edit": 1}, "area.sup2": {"domain": "stability", "n_blocks": 2, "hidden": 0}, "area.sup3": {"domain": "stability", "n_blocks": 3, "hidden": 0}, "area.sup2h": {"domain": "stability", "n_blocks": 2, "hidden": 1}, @@ -49,7 +60,8 @@ FAMILIES = { DOMAIN_OF = {f: spec["domain"] for f, spec in FAMILIES.items()} -def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, cameras, units): +def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, cameras, + units, conflicts=()): vis_e = [e for e in edges if e.eid in visible_edges] keep = set(visible_ents) | {e.a for e in vis_e} | {e.b for e in vis_e} # derived, not hand-written: the gap between the full state and this view is @@ -87,6 +99,7 @@ def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, camera "rendered_relations": dict(Counter(e.kind for e in vis_e)), "layers": _layers(entities), "rendered_layers": _layers([e for e in entities if e.eid in keep]), + "conflicts": dict(Counter(c["kind"] for c in conflicts)), } return Observation( entities=[e for e in entities if e.eid in keep], @@ -96,6 +109,7 @@ def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, camera hidden_layers=sorted(hidden_layers), hidden=hidden, dangling=dangling, + conflicts=list(conflicts), scope=scope, ) @@ -110,7 +124,8 @@ def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, camera # cannot tell those apart. -def _build_connection(rng, n_paths: int, hidden: int): +def _build_connection(rng, n_paths: int, hidden: int, conflict: int = 0, + no_edit: int = 0): ents = [Entity("A", "pad", attrs={"x": 0, "y": 0, "z": 0, "layer": 0}), Entity("B", "pad", attrs={"x": 100, "y": 0, "z": 0, "layer": 0}), Entity("M", "via", attrs={"x": 50, "y": 0, "z": 0, "layer": 0})] @@ -134,16 +149,36 @@ def _build_connection(rng, n_paths: int, hidden: int): visible.add(trunk.eid) query = Query(kind="connection", a="A", b="B") - r = rng.random() - if r < 0.4 and branch_edges: - query.edit = {"op": "remove_edge", "edge": branch_edges[0]} - elif r < 0.7: - query.edit = {"op": "remove_edge", "edge": "trunk"} + # The source-conflict families stay edit-free on purpose: the query is about + # what two observers disagree on, and an intervention would be a third + # variable changing the answer at the same time. + if not (conflict or no_edit): + r = rng.random() + if r < 0.4 and branch_edges: + query.edit = {"op": "remove_edge", "edge": branch_edges[0]} + elif r < 0.7: + query.edit = {"op": "remove_edge", "edge": "trunk"} # a hidden branch must not appear as an isolated node either: the mere # presence of a via on layer 1 is already a leak of the hidden detour vis_ents = {"A", "B", "M"} | {f"V{i}" for i in range(n_paths - hidden)} - return ents, edges, query, visible, vis_ents, layers, ["top"], {"length": "mm", "per_unit": 1} + # A dispute is about one relation, named by its endpoints: the netlist says + # A connects to V0, the board says there is no copper. Both edges of the + # branch can be disputed at once, in which case neither world decides. + conflicts = [] + if conflict: + # 1 = one branch edge, 2 = both branch edges, 3 = the trunk. A disputed + # branch is survivable while another branch exists; a disputed trunk is + # not, because every path uses it. + disputed = {1: ["c0a"], 2: ["c0a", "c0b"], 3: ["trunk"]}[int(conflict)] + by_id = {e.eid: e for e in edges} + for eid in disputed: + e = by_id.get(eid) + if e is not None: + conflicts.append({"kind": e.kind, "a": e.a, "b": e.b, + "against": "board", "with": "netlist"}) + return (ents, edges, query, visible, vis_ents, layers, ["top"], + {"length": "mm", "per_unit": 1}, conflicts) # -------------------------------------------------------------------------- @@ -304,7 +339,9 @@ def _build_freedom(rng, n_cons: int, hidden: int, no_edit: int = 0, notch: int = _BUILDERS = { - "connection": lambda rng, spec: _build_connection(rng, spec["n_paths"], spec["hidden"]), + "connection": lambda rng, spec: _build_connection(rng, spec["n_paths"], spec["hidden"], + spec.get("conflict", 0), + spec.get("no_edit", 0)), "stability": lambda rng, spec: _build_stability(rng, spec["n_blocks"], spec["hidden"], spec.get("free", 0), spec.get("notch", 0), spec.get("clearance", 0), @@ -315,13 +352,20 @@ _BUILDERS = { def make(family: str, seed: int, index: int = 0) -> Scenario: - spec = FAMILIES[family] rng = random.Random(f"{family}:{seed}:{index}") - ents, edges, query, vis_edges, vis_ents, layers, cameras, units = \ - _BUILDERS[spec["domain"]](rng, spec) + spec = dict(FAMILIES[family]) + # a spec may say "draw this instead of fixing it": the draw happens per + # sample, which is what makes the family two-label rather than one. + for key in ("n_paths", "conflict"): + pick = spec.pop(key + "_pick", None) + if pick: + spec[key] = rng.choice(list(pick)) + built = _BUILDERS[spec["domain"]](rng, spec) + ents, edges, query, vis_edges, vis_ents, layers, cameras, units = built[:8] + conflicts = built[8] if len(built) > 8 else [] full = FullState(entities=ents, edges=edges) - obs = _observe(ents, edges, vis_edges, vis_ents, layers, cameras, units) + obs = _observe(ents, edges, vis_edges, vis_ents, layers, cameras, units, conflicts) # the world the observation alone describes: anything not visible is gone restricted = FullState(entities=list(obs.entities), edges=list(obs.edges)) diff --git a/spatial/model.py b/spatial/model.py index ee8604b..c696fc3 100644 --- a/spatial/model.py +++ b/spatial/model.py @@ -48,7 +48,10 @@ FEAT_DIM = N_KIND + 2 + 3 + 7 # kind, source, unit, (x,y,z,layer,w,h,d) # do the faces meet in z, is the upper block's centroid inside the overlap, and # how much of the upper footprint is covered. They are measurements, not # answers -- the same numbers a caliper and a straight edge would give. -EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4 + 3 +# The last slot is the disputed flag: two sources name this relation and +# disagree. Without it a disputed edge and an agreed edge are the same input, and +# "the proof goes through the disputed wire" is unlearnable. +EDGE_FEAT_DIM = N_EDGE + N_AXIS + 4 + 3 + 1 QUERY_KINDS = ("connection", "stability", "freedom") HOP_MAX = 4 # longer paths collapse into one bucket diff --git a/spatial/report.py b/spatial/report.py index 3abaf2d..d84df7c 100644 --- a/spatial/report.py +++ b/spatial/report.py @@ -27,6 +27,7 @@ from .model import N_AXIS, N_EDGE, SCENE_HIDDEN from .train import load DANGLING_BIT = N_EDGE + N_AXIS + 3 +DISPUTED_BIT = N_EDGE + N_AXIS + 7 ANSWERS = ("true", "false", "unknown") diff --git a/spatial/schema.py b/spatial/schema.py index d366175..723b125 100644 --- a/spatial/schema.py +++ b/spatial/schema.py @@ -123,10 +123,17 @@ class Observation: # leaking the answer -- a BOM knows how many parts exist, a netlist knows # how many conductors exist and on which layers, and neither of them knows # which part ends up holding the load. + # Relations one source asserts and another denies. Not "missing" -- both + # sources are talking about the same pair and disagree, which is a different + # epistemic state from "nobody told me". Carries no vote and no priority: + # deciding which source wins is exactly the thing the system must not do on + # its own, so a disputed relation can only ever suspend an answer. + conflicts: list = field(default_factory=list) scope: dict = field(default_factory=lambda: { "parts": {}, "rendered": {}, "relations": {}, "rendered_relations": {}, "layers": [], "rendered_layers": [], + "conflicts": {}, }) def entity_ids(self) -> set: @@ -142,6 +149,10 @@ class Observation: "hidden_faces": sorted(self.hidden_faces), "hidden": {k: dict(sorted(v.items())) for k, v in sorted(self.hidden.items())}, "dangling": [e.to_dict() for e in sorted(self.dangling, key=lambda x: x.eid)], + "conflicts": [dict(sorted(c.items())) for c in + sorted(self.conflicts, key=lambda c: (c.get("kind", ""), + c.get("a", ""), + c.get("b", "")))], "scope": _canonical_scope(self.scope), }