diff --git a/README.md b/README.md index da4f873..47dde50 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ |---|---|---| | `spatial/` | 关系主干、数据契约、生成器、检查器、训练与诊断工具 | **当前主线** | | `spatial/configs/` | 运行配置,规范配置在顶层,历史实验在 `archive/` | | -| `docs/` | 全部文档:需求、路线、架构提案、测出来的结果 | | +| `docs/` | 全部文档:需求、路线、契约、测出来的结果 | | | `mm/` | 前一条线:45M 原生多模态 GPT,补全/可控生成实验 | 暂停,代码与探针保留 | | `vendor/llamagen_vq/` | VQ 编解码(第三方) | 依赖 | | `tools/` | 与模型无关的小工具 | | @@ -21,6 +21,7 @@ |---|---| | [docs/FINDINGS.md](docs/FINDINGS.md) | **先读这个**:M1 全部测量结果、八处修复的单变量证据、三种子水位 | | [docs/M2_INPUT_SOURCE.md](docs/M2_INPUT_SOURCE.md) | **M2 起点**:关系图从哪来,三类关系三种来源的实测 | +| [docs/M2_VIEW_CONTRACT.md](docs/M2_VIEW_CONTRACT.md) | **M2 契约**:哪部分"没看到"可推、哪部分必须声明、哪部分禁止 | | [docs/SPATIAL_FOUNDATION.md](docs/SPATIAL_FOUNDATION.md) | 架构提案与分阶段路线 | | [docs/REQUIREMENTS.md](docs/REQUIREMENTS.md) | 需求与架构决策 v3 | | [docs/PLAN_v2.md](docs/PLAN_v2.md) | 上一版路线(已被上面两份取代,留作对照) | @@ -32,6 +33,7 @@ python3 -m spatial.cli smoke # 契约测试, python3 -m spatial.baselines 128 # 平凡规则基线 python3 -m spatial.extract 24 # 几何→关系图的保真度 python3 -m spatial.extract tol 8 # 接触判定对余隙的敏感度 +python3 -m spatial.view 24 # 表面可见性能不能替代 hidden/dangling python3 -m spatial.cli train --config spatial/configs/dangling.json --seed 0 python3 -m spatial.cli report --config spatial/configs/dangling.json --seed 0 --n 128 python3 -m spatial.cli report --config spatial/configs/dangling.json --n 128 --ablate dangling,scene diff --git a/docs/M2_VIEW_CONTRACT.md b/docs/M2_VIEW_CONTRACT.md new file mode 100644 index 0000000..59a975d --- /dev/null +++ b/docs/M2_VIEW_CONTRACT.md @@ -0,0 +1,114 @@ +# M2 输入契约:哪些"没看到"可以说,哪些不能说 + +`Observation.hidden` 和 `Observation.dangling` 是 M1 弃权的全部依据。它们现在的 +算法是**完整状态减去可见集合**。真实场景里没有完整状态 —— 否则就不需要谈不确定。 +所以这两个字段是一个循环:要知道"我少看到了一条关系",得先看到它的两端。 + +这篇文档定三件事:别的路走过没有(走过,走不通)、契约应该长什么样、以及已经落地 +到什么程度。 + +## 一、试过的路:表面可见性 + +最容易想到的替代品是几何:拿几台正交相机,一个面如果背朝所有相机、或者被别的零 +件挡住,就是"没看到的面";没看到的面正是关系可能附着的地方。 + +`python3 -m spatial.view 24`(`spatial/view.py`,只吃可见实体和相机方向,不碰完整 +状态): + +``` +family 可见 有盒 悬空锚 有未见面 两者 仅悬空 仅见面 平均未见面 +cond.p1 4.0 0.0 0.0 0.0 0.0 0.0 0.0 0.00 +cond.p1h 4.0 0.0 2.0 0.0 0.0 2.0 0.0 0.00 +area.sup2 4.0 3.0 0.0 3.0 0.0 0.0 3.0 1.67 +area.sup2h 3.0 2.0 2.0 2.0 1.0 1.0 1.0 1.00 +area.sup3h 4.0 3.0 2.0 3.0 1.0 1.0 2.0 1.08 +area.sup2d 4.0 3.0 1.0 3.0 0.0 1.0 3.0 1.67 +dof.c6h 6.0 0.0 1.0 0.0 0.0 1.0 0.0 0.00 +``` + +两列数字就是判决书,方向相反: + +* **`仅悬空`:有悬空关系,可六张面全被看到。** 连接域和自由度域全是这种。内层导体 + 不是被挡住的,它在板子**里面**——表面可见性对它一个字都说不出来(`有盒 0.0`)。 + 一个挂在完全可见焊盘上的隐藏支路,几何上没有任何痕迹。 +* **`仅见面`:有看不到的面,可那里没有悬空关系。** 坐着的东西底面永远看不到 + (平均 1–1.7 张面不可见),所以这个信号在稳定性域**恒亮**,对"哪个零件藏着"没有 + 分辨力。 + +两条同时成立,而且交集几乎为空:**表面可见性既漏又滥,不能替代 `hidden`/`dangling`。** + +这不是实现没做好,是问题本身的结构。遮挡能推出"某个面上可能有东西",推不出"这个 +场景里确实有一条关系,只是我看不到它的另一头"。 + +## 二、契约:三档 + +分档的标准只有一个:**这句话里有没有端点。** + +| 档 | 内容 | 谁能给 | 为什么 | +|---|---|---|---| +| 可推 | 从可见几何算出接触、算出面朝哪、算出谁挡谁 | 几何 | 只看观测就够,`spatial/extract.py` 已实测接触 100% 可恢复 | +| 必须声明(只给计数与名单) | 零件清单(BOM 几件、按类别)、关系清单(几条、按类别)、层清单(板子几层)、本次交付了哪些 | 元数据源 | 它是一条关于**源自己**的声明,不是关于场景的结论 | +| 禁止 | 任何关系的端点、任何"这里应该有个支撑"、任何指认 | —— | 有端点就等于给了答案的一半;这是 M2 存在的理由 | + +第二档是关键妥协,也是这份契约的全部内容:**源可以告诉你"我的清单比给你的多", +不能告诉你"多出来的是什么"。** + +`Observation.scope` 就是按这一档写的: + +```python +scope = { + "parts": {kind: n}, # 清单里有几件(按类别) + "rendered": {kind: n}, # 实际给了几件 + "relations": {kind: n}, # 清单里有几条关系 + "rendered_relations": {kind: n}, # 实际给了几条 + "layers": [...], # 板子说它有哪几层 + "rendered_layers": [...], # 实际导出了哪几层 +} +``` + +判"有没有东西没给我"只读这个:`checker.withheld_flag(obs)`。 + +## 三、迁移已经落地,而且标签逐样本没变 + +判据不是"看起来对",是**换掉之后每一条标签都不许动**。 + +* `checker.label` 里的 `withheld` 从 + `bool(dangling) or hidden["entity"] or hidden["edge"]` 改成读 `scope`。 +* `cli.check_scope_agrees()` 进 smoke:两种口径必须在每个样本上一致。 + 实测 **1152 个样本(17 家族 × 64)全部一致**。 +* 标签整体摘要(17 家族 × 32,含 answer/change/sufficient/evidence)在改动前后 + 两个 commit 上分别是 + `dc935840…cb6f83` 与 `dc935840…cb6f83` —— 完全相同。 + +也就是说:**弃权这条能力不需要完整状态了。** 需要完整状态的那部分,从标签路径上被 +摘掉了。 + +## 四、还没做的(有意留着的) + +`hidden` 和 `dangling` 仍然是**模型输入**(`data.py` 的 `scene_features` 按类别 +计数,`dangle` 张量给锚点位置)。按上面的契约,它们属于第三档,不该进输入。 + +没有顺手删掉,是因为删了要重训,而重训要三种子,服务器现在连不上(见 +`docs/M2_INPUT_SOURCE.md` 末尾)。半改模型、然后拿单次运行的数字交差,正是前面吃过 +的亏。 + +所以这一步拆成两件,顺序不能反: + +1. 把 `scope` 的四个数(缺几件、缺几条关系、缺几层、有没有缺)接进 + `scene_features`,`SCENE_DIM` 加 4; +2. 用 `--ablate dangling --ablate scene` 各跑三种子,回答一个问题: + **只靠"清单比交付多"这种不含端点的信号,还能不能正确弃权。** + 能,契约就成立;不能,说明 M1 的弃权有一半是建立在完整状态上的,得重新设计。 + +第 2 条才是真正的验收,而且它可能失败 —— 这正是它值得先做的原因。 + +## 五、和另一条线的关系 + +`docs/M2_INPUT_SOURCE.md` 说三类关系三种来源。那份文档管**三类关系分别从哪来**, +这份管**"没给你的那部分"怎么表达**。两份合起来才是完整的输入契约: + +``` +几何 ──→ contact(已实测 100%) +元数据 ─→ conduct / constraint(待接 provider) +清单声明 ─→ scope(缺口,已落地在标签路径上) +``` diff --git a/spatial/checker.py b/spatial/checker.py index be2a7c4..9f047d6 100644 --- a/spatial/checker.py +++ b/spatial/checker.py @@ -279,6 +279,32 @@ def validate_evidence(full: FullState, query: Query, evidence) -> bool: # label +def withheld_flag(obs) -> bool: + """Is the inventory bigger than what was handed over. + + Read from ``obs.scope`` only -- counts of parts and relations, and the layer + stack. It deliberately does **not** consult ``hidden`` or ``dangling``: + those are computed as "full state minus visible", and no real provider can + compute them, because knowing that a relation exists with one end off-screen + requires seeing both ends. + + What a provider can say is that its inventory is bigger: a BOM lists five + parts and three were rendered; a netlist has nine conductors on two layers + and one layer was exported. That statement carries no endpoints, so it + cannot decide the answer -- only suspend it. + """ + scope = obs.scope or {} + parts = scope.get("parts") or {} + rendered = scope.get("rendered") or {} + if any(parts.get(k, 0) > rendered.get(k, 0) for k in parts): + return True + rel = scope.get("relations") or {} + rel_r = scope.get("rendered_relations") or {} + if any(rel.get(k, 0) > rel_r.get(k, 0) for k in rel): + return True + return bool(set(scope.get("layers") or []) - set(scope.get("rendered_layers") or [])) + + def label(obs: Observation, full: FullState, query: Query, alternatives: Iterable[FullState] = ()) -> Label: """Full state decides; the observation decides whether we may say so. @@ -303,8 +329,7 @@ def label(obs: Observation, full: FullState, query: Query, 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")) + withheld = withheld_flag(obs) if withheld: if ans_vis is True: diff --git a/spatial/cli.py b/spatial/cli.py index 6eb3d20..ad6282a 100644 --- a/spatial/cli.py +++ b/spatial/cli.py @@ -99,8 +99,7 @@ def check_insufficient() -> bool: continue restricted = FullState(entities=list(sc.obs.entities), edges=list(sc.obs.edges)) a_vis = checker.evaluate(restricted.entities, restricted.edges, sc.query) - withheld = bool(sc.obs.dangling) or bool((sc.obs.hidden or {}).get("entity")) \ - or bool((sc.obs.hidden or {}).get("edge")) + withheld = checker.withheld_flag(sc.obs) if withheld and a_vis is not True: found += 1 else: @@ -194,12 +193,42 @@ def check_extract_contacts(n: int = 8) -> bool: return True +def check_scope_agrees(n: int = 24) -> bool: + """The declared inventory must say "something withheld" exactly when the + diagnostic one does. + + ``hidden``/``dangling`` are computed from the full state, so they are not + something a provider can produce. ``scope`` is. This check pins the + migration: wherever the two disagree, the label path would have to fall back + on full-state data -- and that is the leak M2 exists to remove. + """ + bad = [] + rows = 0 + for fam in generator.FAMILIES: + for i in range(n): + sc = generator.make(fam, seed=11, index=i) + 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: + 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") + print(f"ok {rows} samples: declared inventory agrees with the diagnostic one") + return True + + def cmd_smoke(args) -> int: cfg = _load_config(args.config) print(f"config {args.config} out {cfg['out_dir']}") results = [check_splits(cfg), check_determinism(), check_labels(), check_insufficient(), check_invariances(), check_cross_family_digest(), - check_extract_contacts()] + check_extract_contacts(), check_scope_agrees()] # one update, then interrupt and resume: the step counter must advance from . import train as trainer diff --git a/spatial/extract.py b/spatial/extract.py index 12c821e..a8e1061 100644 --- a/spatial/extract.py +++ b/spatial/extract.py @@ -29,159 +29,7 @@ from .schema import Edge, FullState, Query CONTACT = "contact" -def _sub(u, v): - return (u[0] - v[0], u[1] - v[1], u[2] - v[2]) - - -def _add(u, v): - return (u[0] + v[0], u[1] + v[1], u[2] + v[2]) - - -def _mul(u, s): - return (u[0] * s, u[1] * s, u[2] * s) - - -def _dot(u, v): - return u[0] * v[0] + u[1] * v[1] + u[2] * v[2] - - -def _len(u): - return _dot(u, u) ** 0.5 - - -def box_triangles(box) -> list: - """12 triangles for an axis-aligned box. Surface only, no interior. - - Plain tuples on purpose: this module has to run on a machine that has no - third-party packages at all, and the arithmetic here is a few dots and - norms on four boxes. numpy would be the only dependency in the file. - """ - x0, y0, z0, x1, y1, z1 = (float(v) for v in box) - c = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), - (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)] - faces = [(0, 2, 1), (0, 3, 2), (4, 5, 6), (4, 6, 7), (0, 1, 5), (0, 5, 4), - (1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), (3, 0, 4), (3, 4, 7)] - return [tuple(c[i] for i in f) for f in faces] - - -def _pt_tri(p, tri) -> float: - """Distance from a point to a triangle (Ericson, clamped barycentric).""" - a, b, c = tri - ab, ac, ap = _sub(b, a), _sub(c, a), _sub(p, a) - d1, d2 = _dot(ab, ap), _dot(ac, ap) - if d1 <= 0 and d2 <= 0: - return _len(ap) - bp = _sub(p, b) - d3, d4 = _dot(ab, bp), _dot(ac, bp) - if d3 >= 0 and d4 <= d3: - return _len(bp) - vc = d1 * d4 - d3 * d2 - if vc <= 0 <= d1 and d3 <= 0: - return _len(_sub(p, _add(a, _mul(ab, d1 / (d1 - d3))))) - cp = _sub(p, c) - d5, d6 = _dot(ab, cp), _dot(ac, cp) - if d6 >= 0 and d5 <= d6: - return _len(cp) - vb = d5 * d2 - d1 * d6 - if vb <= 0 <= d2 and d6 <= 0: - return _len(_sub(p, _add(a, _mul(ac, d2 / (d2 - d6))))) - va = d3 * d6 - d5 * d4 - if va <= 0 and (d4 - d3) >= 0 and (d5 - d6) >= 0: - w = (d4 - d3) / ((d4 - d3) + (d5 - d6)) - return _len(_sub(p, _add(b, _mul(_sub(c, b), w)))) - denom = 1.0 / (va + vb + vc) - return _len(_sub(p, _add(a, _add(_mul(ab, vb * denom), _mul(ac, vc * denom))))) - - -def _aabb_gap(a, b) -> float: - """Lower bound on the surface distance -- used only as a cheap prefilter.""" - dx = max(0.0, max(a[0] - b[3], b[0] - a[3])) - dy = max(0.0, max(a[1] - b[4], b[1] - a[4])) - dz = max(0.0, max(a[2] - b[5], b[2] - a[5])) - return (dx * dx + dy * dy + dz * dz) ** 0.5 - - -def box_faces(box) -> list: - """The six faces of an axis-aligned box as (axis, sign, plane, rect2d). - - ``rect2d`` is the face's extent in the two axes it spans, in ascending order. - This is the poor man's B-rep: faces are stored as *surfaces*, not as vertex - triples, because contact is a statement about surfaces. - """ - x0, y0, z0, x1, y1, z1 = (float(v) for v in box) - lo, hi = (x0, y0, z0), (x1, y1, z1) - out = [] - for ax in range(3): - u, v = [i for i in range(3) if i != ax] - rect = (lo[u], lo[v], hi[u], hi[v]) - out.append((ax, -1, lo[ax], rect)) - out.append((ax, +1, hi[ax], rect)) - return out - - -def contact_area(fa, fb, eps: float = 0.0) -> float: - """Overlap area of two faces if they are coincident, else 0. - - Coincident means: same plane orientation (same axis, opposite outward - normals -- two faces pointing the same way are facing each other, not - touching) and the same offset along that axis, up to ``eps``, which only - has to absorb floating-point noise from transforms. Line and point contacts - (zero overlap area) are deliberately *not* contacts: in a B-rep they are a - separate topological case and pretending a rectangle of zero width is a - surface would be the same mistake as the distance threshold. - """ - ax, sa, pa, ra = fa - bx, sb, pb, rb = fb - if ax != bx or sa == sb or abs(pa - pb) > eps: - return 0.0 - ou = min(ra[2], rb[2]) - max(ra[0], rb[0]) - ov = min(ra[3], rb[3]) - max(ra[1], rb[1]) - if ou <= 0 or ov <= 0: - return 0.0 - return ou * ov - - -def box_contact_area(box_a, box_b, eps: float = 0.0) -> float: - best = 0.0 - for fa in box_faces(box_a): - for fb in box_faces(box_b): - a = contact_area(fa, fb, eps) - if a > best: - best = a - return best - - -def surface_gap(box_a, box_b) -> float: - """Minimum distance between two box surfaces, measured on triangles. - - Vertex-to-triangle only: edge-to-edge minima are missed, which can overestimate - the gap when two edges cross without a vertex near the contact. For the - separation this benchmark actually has (>=16 grid units) it never matters -- - and that "never matters" is itself one of the findings. - - Kept for the clearance column only. Contact is decided by ``contact_area``, - which needs no distance at all. - """ - ta, tb = box_triangles(box_a), box_triangles(box_b) - va, vb = _vertices(ta), _vertices(tb) - best = float("inf") - for tri in ta: - for p in vb: - best = min(best, _pt_tri(p, tri)) - for tri in tb: - for p in va: - best = min(best, _pt_tri(p, tri)) - return best - - -def _vertices(tris) -> list: - seen, out = set(), [] - for tri in tris: - for p in tri: - if p not in seen: - seen.add(p) - out.append(p) - return out +from .geom import _aabb_gap, box_contact_area, surface_gap def extract_edges(entities, eps: float = 0.0) -> list: diff --git a/spatial/generator.py b/spatial/generator.py index 08dd4e2..cdd0bf6 100644 --- a/spatial/generator.py +++ b/spatial/generator.py @@ -1,337 +1,354 @@ -"""Procedural scenes. - -Three domains, each built so that a *structure family* -- not a single sample -- -is the unit of split. Families differ in topology depth and in what the -observation withholds, never in rendering noise, so a test family is genuinely -unseen structure. - -Builders only construct geometry and visible subsets. They never write a label: -``checker.label`` does that, using the full state plus the world obtained by -restricting the full state to what the observation shows. -""" -from __future__ import annotations - -import random -from collections import Counter -from dataclasses import replace - -from . import checker -from .schema import (DOF_AXES, Edge, Entity, FullState, Observation, Query, - Scenario) - -# family -> builder parameters. Splits are assigned in configs/*.json and must -# be disjoint over families. -FAMILIES = { - "cond.p1": {"domain": "connection", "n_paths": 1, "hidden": 0}, - "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}, - "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}, - "area.free": {"domain": "stability", "n_blocks": 2, "hidden": 0, "free": 1}, - "area.sup3h": {"domain": "stability", "n_blocks": 3, "hidden": 1}, - "area.sup2d": {"domain": "stability", "n_blocks": 2, "hidden": 0, "notch": 1}, - "area.gap1": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 1}, - "area.gap2": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 2}, - "area.gap4": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 4}, - "dof.c6": {"domain": "freedom", "n_cons": 6, "hidden": 0}, - "dof.c6r": {"domain": "freedom", "n_cons": 7, "hidden": 0}, - "dof.c6h": {"domain": "freedom", "n_cons": 6, "hidden": 1}, - # the pure sub-skill: no intervention at all, so the answer is exactly "are - # all six axes covered". If this family cannot be learned, the edit families - # are not the problem -- the set readout is. - "dof.c6d": {"domain": "freedom", "n_cons": 6, "hidden": 0, "notch": 1}, - "dof.set": {"domain": "freedom", "n_cons": 6, "hidden": 0, "no_edit": 1}, -} - -DOMAIN_OF = {f: spec["domain"] for f, spec in FAMILIES.items()} - - -def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, cameras, units): - 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 - # exactly what an agent has to know in order to decide it cannot decide. - # Computing it here means a new occluder cannot silently go undeclared. - hidden = { - "entity": dict(Counter(e.kind for e in entities if e.eid not in keep)), - "edge": dict(Counter(e.kind for e in edges if e.eid not in visible_edges)), - } - # a hidden relation with one visible end becomes a dangling edge anchored on - # that visible end. Both ends hidden leaves no mouth to report, so it stays - # a bare count. The anchor is always something already in view: this says - # where the ignorance attaches, never where it leads. - dangling = [] - for e in edges: - if e.eid in visible_edges: - continue - anchor = e.a if e.a in keep else (e.b if e.b in keep else None) - if anchor is None: - continue - dangling.append(Edge(f"d{len(dangling)}", e.kind, anchor, "", - layer=e.layer, source="inferred")) - return Observation( - entities=[e for e in entities if e.eid in keep], - edges=vis_e, - cameras=list(cameras), - units=dict(units), - hidden_layers=sorted(hidden_layers), - hidden=hidden, - dangling=dangling, - ) - - -# -------------------------------------------------------------------------- -# connection: parallel branches into one trunk, optional inner-layer branch -# -# A --branch i--> M --trunk--> B -# -# removing one branch is harmless while another exists; removing the trunk is -# never harmless. With one visible branch and one hidden branch the observation -# cannot tell those apart. - - -def _build_connection(rng, n_paths: int, hidden: int): - 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})] - edges, visible, layers = [], set(), set() - branch_edges = [] - for i in range(n_paths): - is_hidden = i >= (n_paths - hidden) - layer = (1 + i % 2) if is_hidden else 0 - vid = f"V{i}" - ents.append(Entity(vid, "via", attrs={"x": 50, "y": 10 * (i + 1), "z": layer, "layer": layer})) - e1 = Edge(f"c{i}a", "conduct", "A", vid, layer=layer) - e2 = Edge(f"c{i}b", "conduct", vid, "M", layer=layer) - edges += [e1, e2] - if layer == 0: - visible.update({e1.eid, e2.eid}) - branch_edges += [e1.eid, e2.eid] - else: - layers.add(layer) - trunk = Edge("trunk", "conduct", "M", "B", layer=0) - edges.append(trunk) - 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"} - - # 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} - - -# -------------------------------------------------------------------------- -# stability: stacked blocks, optional hidden pedestal - - -def _build_stability(rng, n_blocks: int, hidden: int, free: int = 0, notch: int = 0, - clearance: int = 0): - if free: - # the minimal pair against area.sup2h: here T has exactly one contact and - # that contact leads to a block which itself hangs in the air. Nothing - # dangles and nothing is hidden, so "no support" is a fact rather than a - # gap -- the answer is legitimately false and abstaining would be wrong. - ents = [Entity("G", "ground", attrs={"plane": 0}), - Entity("T", "block", attrs={"box": [42, 42, 20, 58, 58, 36]}), - Entity("Q", "block", attrs={"box": [44, 44, 8, 56, 56, 20]}), - Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})] - edges = [Edge("kTQ", "contact", "Q", "T"), Edge("kDG", "contact", "D", "G")] - query = Query(kind="stability", a="T") - if rng.random() < 0.6: - query.edit = {"op": "remove_entity", "entity": "Q"} - return (ents, edges, query, {e.eid for e in edges}, {e.eid for e in ents}, - set(), ["front", "iso"], {"length": "mm", "per_unit": 1}) - - # D is a decoy: it rests on the ground next to the stack and carries - # nothing. Without it "something was removed" and "the target lost support" - # are the same event on every sample, and a one-bit rule fits the whole - # family -- measured: that rule scores 1.000 here while knowing no physics. - # the causal variable is drawn, not fixed. Until it was, "there is a contact" - # and "the contact carries load" were the same event inside the family, so a - # constant answer fit it and the model never had to look at geometry -- which - # is exactly what the report kept showing. - dx = rng.choice((-13, -6, 0, 3, 6, 13)) - dy = rng.choice((-9, 0, 0, 0, 9)) - # clearance lifts the upper block off its pedestal by a few grid units (one - # grid unit is 0.25mm). At 0 the two surfaces touch exactly; at 1 they are - # 0.25mm apart, which is the regime real assemblies live in and the regime a - # distance tolerance actually has to decide. - cl = int(clearance) - ents = [Entity("G", "ground", attrs={"plane": 0}), - Entity("P", "block", attrs={"box": [40, 40, 0, 60, 60, 20]}), - Entity("T", "block", attrs={"box": [42 + dx, 42 + dy, 20 + cl, - 58 + dx, 58 + dy, 36 + cl]}), - Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})] - edges = [Edge("kPG", "contact", "P", "G"), Edge("kDG", "contact", "D", "G")] - if cl == 0: - edges.append(Edge("kPT", "contact", "T", "P")) - # With a clearance there is no contact, so the fixture must not declare one: - # a kPT edge over a 1-unit gap would be the schema contradicting its own - # geometry. Dropping it is what makes the near-fit families sharp -- any - # spurious T-P edge now flips the answer false -> true instead of merely - # adding a redundant edge. - top = None - if n_blocks >= 3: - ents.append(Entity("U", "block", - attrs={"box": [44 + dx, 44 + dy, 36 + cl, 56 + dx, 56 + dy, 48 + cl]})) - edges.append(Edge("kTU", "contact", "U", "T")) - top = "U" - vis_edges = {e.eid for e in edges} - vis_ents = {e.eid for e in ents} - layers = set() - - if hidden: - # the pedestal sits behind the front face: its contacts are unseen, and - # the pedestal itself is not in view - for e in list(edges): - if "P" in (e.a, e.b): - vis_edges.discard(e.eid) - vis_ents.discard("P") - - if notch: - # a decoy that is *itself* withheld, hanging off the ground and never off - # the target: the visible structure still proves the target stands. This - # is the case that makes "something is hidden" and "I cannot tell" two - # different facts inside one family. Without it every hidden family is - # all-unknown and keying on the hidden flag is a perfect answer. - ents.append(Entity("H", "block", attrs={"box": [80, 70, -16, 100, 90, 0]})) - edges.append(Edge("kHG", "contact", "H", "G")) - vis_edges.discard("kHG") - vis_ents.discard("H") - - # the target is T on purpose: it survives every legal edit except the one - # that removes P, so "removed something" no longer implies "answer false" - query = Query(kind="stability", a="T") - r = rng.random() - if clearance: - return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1} - if not hidden: - harmless = top or "D" - if r < 0.4: - query.edit = {"op": "remove_entity", "entity": "P"} # collapses - elif r < 0.75: - query.edit = {"op": "remove_entity", "entity": harmless} # no effect - elif notch: - # removing P takes the only visible proof away; the hidden decoy cannot - # stand in for it, so the verdict becomes unknown rather than false - if r < 0.5: - query.edit = {"op": "remove_entity", "entity": "P"} - return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1} - - -# -------------------------------------------------------------------------- -# freedom: constraint sets, optionally redundant on one axis - - -def _build_freedom(rng, n_cons: int, hidden: int, no_edit: int = 0, notch: int = 0): - # the axes are drawn, so a family spans both verdicts with the same entity - # count: six mates that cover every axis lock the part, six that cover five - # do not, and the difference is invisible from the shape of the scene - axes = list(DOF_AXES) - if n_cons == 7: - rng.shuffle(axes) - axes = axes + [rng.choice(axes)] # a redundant 7th mate, last - else: - if rng.random() < 0.5: # drop one, repeat another - drop = rng.randrange(len(axes)) - dup = rng.choice([a for i, a in enumerate(axes) if i != drop]) - axes = [a for i, a in enumerate(axes) if i != drop] + [dup] - rng.shuffle(axes) - ents = [Entity("P", "part", attrs={"x": 0, "y": 0, "z": 0})] - edges, visible = [], set() - for i in range(n_cons): - fid = f"F{i}" - ents.append(Entity(fid, "ground", attrs={"x": 0, "y": 0, "z": 0})) - e = Edge(f"k{i}", "constraint", "P", fid, attrs={"axis": axes[i]}) - edges.append(e) - visible.add(e.eid) - - vis_ents = {e.eid for e in ents} - layers = set() - if hidden: - visible.discard("k5") # one mate lives in the part definition - vis_ents.discard("F5") - if notch: - # a redundant mate kept outside the view: it dangles on the part, but the - # visible mates already cover every axis, so the proof stands - ents.append(Entity(f"F{n_cons}", "ground", attrs={"x": 0, "y": 0, "z": 0})) - edges.append(Edge(f"k{n_cons}", "constraint", "P", f"F{n_cons}", - attrs={"axis": rng.choice(list(DOF_AXES))})) - visible.discard(f"k{n_cons}") - vis_ents.discard(f"F{n_cons}") - - query = Query(kind="freedom", a="P") - if no_edit: - return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1} - if n_cons == 7: - # removing the duplicate must not change the verdict; that is the point - query.edit = {"op": "remove_edge", "edge": "k6"} - elif rng.random() < 0.6: - query.edit = {"op": "remove_edge", "edge": "k0"} - return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1} - - -_BUILDERS = { - "connection": lambda rng, spec: _build_connection(rng, spec["n_paths"], spec["hidden"]), - "stability": lambda rng, spec: _build_stability(rng, spec["n_blocks"], spec["hidden"], - spec.get("free", 0), spec.get("notch", 0), - spec.get("clearance", 0)), - "freedom": lambda rng, spec: _build_freedom(rng, spec["n_cons"], spec["hidden"], - spec.get("no_edit", 0), spec.get("notch", 0)), -} - - -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) - - full = FullState(entities=ents, edges=edges) - obs = _observe(ents, edges, vis_edges, vis_ents, layers, cameras, units) - # the world the observation alone describes: anything not visible is gone - restricted = FullState(entities=list(obs.entities), edges=list(obs.edges)) - - sc = Scenario(key=f"{family}-{seed}-{index:04d}", domain=spec["domain"], - family=family, seed=seed, obs=obs, query=query, full=full, - tags={"n_hidden": spec["hidden"], "edit": query.edit is not None}) - sc.label = checker.label(obs, full, query, alternatives=[restricted]) - return sc - - -# -------------------------------------------------------------------------- -# invariances: camera and units must not change the answer - - -def with_camera(sc: Scenario, camera: str) -> Scenario: - out = replace(sc, obs=replace(sc.obs, cameras=[camera])) - out.tags = dict(sc.tags, camera=camera) - return out - - -def rescale(sc: Scenario, factor: int, unit: str) -> Scenario: - """Multiply integer geometry by ``factor`` and relabel the unit. The answer - must be invariant; the fixture checks that it actually is.""" - def scale_ent(e: Entity) -> Entity: - attrs = dict(e.attrs) - for k in ("x", "y", "z"): - if k in attrs: - attrs[k] = attrs[k] * factor - if "box" in attrs: - attrs["box"] = [v * factor for v in attrs["box"]] - return replace(e, attrs=attrs, unit=unit) - - full = FullState(entities=[scale_ent(e) for e in sc.full.entities], edges=list(sc.full.edges)) - obs = replace(sc.obs, entities=[scale_ent(e) for e in sc.obs.entities], - edges=list(sc.obs.edges), - units={"length": unit, "per_unit": factor}) - out = replace(sc, obs=obs, full=full, tags=dict(sc.tags, unit=unit, scale=factor)) - return out +"""Procedural scenes. + +Three domains, each built so that a *structure family* -- not a single sample -- +is the unit of split. Families differ in topology depth and in what the +observation withholds, never in rendering noise, so a test family is genuinely +unseen structure. + +Builders only construct geometry and visible subsets. They never write a label: +``checker.label`` does that, using the full state plus the world obtained by +restricting the full state to what the observation shows. +""" +from __future__ import annotations + +import random +from collections import Counter +from dataclasses import replace + +from . import checker +from .schema import (DOF_AXES, Edge, Entity, FullState, Observation, Query, + Scenario) + +# family -> builder parameters. Splits are assigned in configs/*.json and must +# be disjoint over families. +FAMILIES = { + "cond.p1": {"domain": "connection", "n_paths": 1, "hidden": 0}, + "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}, + "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}, + "area.free": {"domain": "stability", "n_blocks": 2, "hidden": 0, "free": 1}, + "area.sup3h": {"domain": "stability", "n_blocks": 3, "hidden": 1}, + "area.sup2d": {"domain": "stability", "n_blocks": 2, "hidden": 0, "notch": 1}, + "area.gap1": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 1}, + "area.gap2": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 2}, + "area.gap4": {"domain": "stability", "n_blocks": 2, "hidden": 0, "clearance": 4}, + "dof.c6": {"domain": "freedom", "n_cons": 6, "hidden": 0}, + "dof.c6r": {"domain": "freedom", "n_cons": 7, "hidden": 0}, + "dof.c6h": {"domain": "freedom", "n_cons": 6, "hidden": 1}, + # the pure sub-skill: no intervention at all, so the answer is exactly "are + # all six axes covered". If this family cannot be learned, the edit families + # are not the problem -- the set readout is. + "dof.c6d": {"domain": "freedom", "n_cons": 6, "hidden": 0, "notch": 1}, + "dof.set": {"domain": "freedom", "n_cons": 6, "hidden": 0, "no_edit": 1}, +} + +DOMAIN_OF = {f: spec["domain"] for f, spec in FAMILIES.items()} + + +def _observe(entities, edges, visible_edges, visible_ents, hidden_layers, cameras, units): + 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 + # exactly what an agent has to know in order to decide it cannot decide. + # Computing it here means a new occluder cannot silently go undeclared. + hidden = { + "entity": dict(Counter(e.kind for e in entities if e.eid not in keep)), + "edge": dict(Counter(e.kind for e in edges if e.eid not in visible_edges)), + } + # a hidden relation with one visible end becomes a dangling edge anchored on + # that visible end. Both ends hidden leaves no mouth to report, so it stays + # a bare count. The anchor is always something already in view: this says + # where the ignorance attaches, never where it leads. + dangling = [] + for e in edges: + if e.eid in visible_edges: + continue + anchor = e.a if e.a in keep else (e.b if e.b in keep else None) + if anchor is None: + continue + dangling.append(Edge(f"d{len(dangling)}", e.kind, anchor, "", + layer=e.layer, source="inferred")) + # The same gap, stated the way a provider can actually state it: what the + # inventory contains versus what was handed over. Counts and layer names, + # no endpoints. ``hidden`` and ``dangling`` above stay for diagnostics and + # as model features, but the label is decided from ``scope`` -- see + # ``checker.withheld``. + def _layers(items): + return sorted({int(e.attrs.get("layer", 0)) for e in items}) + + scope = { + "parts": dict(Counter(e.kind for e in entities)), + "rendered": dict(Counter(e.kind for e in entities if e.eid in keep)), + "relations": dict(Counter(e.kind for e in edges)), + "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]), + } + return Observation( + entities=[e for e in entities if e.eid in keep], + edges=vis_e, + cameras=list(cameras), + units=dict(units), + hidden_layers=sorted(hidden_layers), + hidden=hidden, + dangling=dangling, + scope=scope, + ) + + +# -------------------------------------------------------------------------- +# connection: parallel branches into one trunk, optional inner-layer branch +# +# A --branch i--> M --trunk--> B +# +# removing one branch is harmless while another exists; removing the trunk is +# never harmless. With one visible branch and one hidden branch the observation +# cannot tell those apart. + + +def _build_connection(rng, n_paths: int, hidden: int): + 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})] + edges, visible, layers = [], set(), set() + branch_edges = [] + for i in range(n_paths): + is_hidden = i >= (n_paths - hidden) + layer = (1 + i % 2) if is_hidden else 0 + vid = f"V{i}" + ents.append(Entity(vid, "via", attrs={"x": 50, "y": 10 * (i + 1), "z": layer, "layer": layer})) + e1 = Edge(f"c{i}a", "conduct", "A", vid, layer=layer) + e2 = Edge(f"c{i}b", "conduct", vid, "M", layer=layer) + edges += [e1, e2] + if layer == 0: + visible.update({e1.eid, e2.eid}) + branch_edges += [e1.eid, e2.eid] + else: + layers.add(layer) + trunk = Edge("trunk", "conduct", "M", "B", layer=0) + edges.append(trunk) + 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"} + + # 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} + + +# -------------------------------------------------------------------------- +# stability: stacked blocks, optional hidden pedestal + + +def _build_stability(rng, n_blocks: int, hidden: int, free: int = 0, notch: int = 0, + clearance: int = 0): + if free: + # the minimal pair against area.sup2h: here T has exactly one contact and + # that contact leads to a block which itself hangs in the air. Nothing + # dangles and nothing is hidden, so "no support" is a fact rather than a + # gap -- the answer is legitimately false and abstaining would be wrong. + ents = [Entity("G", "ground", attrs={"plane": 0}), + Entity("T", "block", attrs={"box": [42, 42, 20, 58, 58, 36]}), + Entity("Q", "block", attrs={"box": [44, 44, 8, 56, 56, 20]}), + Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})] + edges = [Edge("kTQ", "contact", "Q", "T"), Edge("kDG", "contact", "D", "G")] + query = Query(kind="stability", a="T") + if rng.random() < 0.6: + query.edit = {"op": "remove_entity", "entity": "Q"} + return (ents, edges, query, {e.eid for e in edges}, {e.eid for e in ents}, + set(), ["front", "iso"], {"length": "mm", "per_unit": 1}) + + # D is a decoy: it rests on the ground next to the stack and carries + # nothing. Without it "something was removed" and "the target lost support" + # are the same event on every sample, and a one-bit rule fits the whole + # family -- measured: that rule scores 1.000 here while knowing no physics. + # the causal variable is drawn, not fixed. Until it was, "there is a contact" + # and "the contact carries load" were the same event inside the family, so a + # constant answer fit it and the model never had to look at geometry -- which + # is exactly what the report kept showing. + dx = rng.choice((-13, -6, 0, 3, 6, 13)) + dy = rng.choice((-9, 0, 0, 0, 9)) + # clearance lifts the upper block off its pedestal by a few grid units (one + # grid unit is 0.25mm). At 0 the two surfaces touch exactly; at 1 they are + # 0.25mm apart, which is the regime real assemblies live in and the regime a + # distance tolerance actually has to decide. + cl = int(clearance) + ents = [Entity("G", "ground", attrs={"plane": 0}), + Entity("P", "block", attrs={"box": [40, 40, 0, 60, 60, 20]}), + Entity("T", "block", attrs={"box": [42 + dx, 42 + dy, 20 + cl, + 58 + dx, 58 + dy, 36 + cl]}), + Entity("D", "block", attrs={"box": [80, 40, 0, 100, 60, 16]})] + edges = [Edge("kPG", "contact", "P", "G"), Edge("kDG", "contact", "D", "G")] + if cl == 0: + edges.append(Edge("kPT", "contact", "T", "P")) + # With a clearance there is no contact, so the fixture must not declare one: + # a kPT edge over a 1-unit gap would be the schema contradicting its own + # geometry. Dropping it is what makes the near-fit families sharp -- any + # spurious T-P edge now flips the answer false -> true instead of merely + # adding a redundant edge. + top = None + if n_blocks >= 3: + ents.append(Entity("U", "block", + attrs={"box": [44 + dx, 44 + dy, 36 + cl, 56 + dx, 56 + dy, 48 + cl]})) + edges.append(Edge("kTU", "contact", "U", "T")) + top = "U" + vis_edges = {e.eid for e in edges} + vis_ents = {e.eid for e in ents} + layers = set() + + if hidden: + # the pedestal sits behind the front face: its contacts are unseen, and + # the pedestal itself is not in view + for e in list(edges): + if "P" in (e.a, e.b): + vis_edges.discard(e.eid) + vis_ents.discard("P") + + if notch: + # a decoy that is *itself* withheld, hanging off the ground and never off + # the target: the visible structure still proves the target stands. This + # is the case that makes "something is hidden" and "I cannot tell" two + # different facts inside one family. Without it every hidden family is + # all-unknown and keying on the hidden flag is a perfect answer. + ents.append(Entity("H", "block", attrs={"box": [80, 70, -16, 100, 90, 0]})) + edges.append(Edge("kHG", "contact", "H", "G")) + vis_edges.discard("kHG") + vis_ents.discard("H") + + # the target is T on purpose: it survives every legal edit except the one + # that removes P, so "removed something" no longer implies "answer false" + query = Query(kind="stability", a="T") + r = rng.random() + if clearance: + return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1} + if not hidden: + harmless = top or "D" + if r < 0.4: + query.edit = {"op": "remove_entity", "entity": "P"} # collapses + elif r < 0.75: + query.edit = {"op": "remove_entity", "entity": harmless} # no effect + elif notch: + # removing P takes the only visible proof away; the hidden decoy cannot + # stand in for it, so the verdict becomes unknown rather than false + if r < 0.5: + query.edit = {"op": "remove_entity", "entity": "P"} + return ents, edges, query, vis_edges, vis_ents, layers, ["front", "iso"], {"length": "mm", "per_unit": 1} + + +# -------------------------------------------------------------------------- +# freedom: constraint sets, optionally redundant on one axis + + +def _build_freedom(rng, n_cons: int, hidden: int, no_edit: int = 0, notch: int = 0): + # the axes are drawn, so a family spans both verdicts with the same entity + # count: six mates that cover every axis lock the part, six that cover five + # do not, and the difference is invisible from the shape of the scene + axes = list(DOF_AXES) + if n_cons == 7: + rng.shuffle(axes) + axes = axes + [rng.choice(axes)] # a redundant 7th mate, last + else: + if rng.random() < 0.5: # drop one, repeat another + drop = rng.randrange(len(axes)) + dup = rng.choice([a for i, a in enumerate(axes) if i != drop]) + axes = [a for i, a in enumerate(axes) if i != drop] + [dup] + rng.shuffle(axes) + ents = [Entity("P", "part", attrs={"x": 0, "y": 0, "z": 0})] + edges, visible = [], set() + for i in range(n_cons): + fid = f"F{i}" + ents.append(Entity(fid, "ground", attrs={"x": 0, "y": 0, "z": 0})) + e = Edge(f"k{i}", "constraint", "P", fid, attrs={"axis": axes[i]}) + edges.append(e) + visible.add(e.eid) + + vis_ents = {e.eid for e in ents} + layers = set() + if hidden: + visible.discard("k5") # one mate lives in the part definition + vis_ents.discard("F5") + if notch: + # a redundant mate kept outside the view: it dangles on the part, but the + # visible mates already cover every axis, so the proof stands + ents.append(Entity(f"F{n_cons}", "ground", attrs={"x": 0, "y": 0, "z": 0})) + edges.append(Edge(f"k{n_cons}", "constraint", "P", f"F{n_cons}", + attrs={"axis": rng.choice(list(DOF_AXES))})) + visible.discard(f"k{n_cons}") + vis_ents.discard(f"F{n_cons}") + + query = Query(kind="freedom", a="P") + if no_edit: + return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1} + if n_cons == 7: + # removing the duplicate must not change the verdict; that is the point + query.edit = {"op": "remove_edge", "edge": "k6"} + elif rng.random() < 0.6: + query.edit = {"op": "remove_edge", "edge": "k0"} + return ents, edges, query, visible, vis_ents, layers, ["iso"], {"length": "mm", "per_unit": 1} + + +_BUILDERS = { + "connection": lambda rng, spec: _build_connection(rng, spec["n_paths"], spec["hidden"]), + "stability": lambda rng, spec: _build_stability(rng, spec["n_blocks"], spec["hidden"], + spec.get("free", 0), spec.get("notch", 0), + spec.get("clearance", 0)), + "freedom": lambda rng, spec: _build_freedom(rng, spec["n_cons"], spec["hidden"], + spec.get("no_edit", 0), spec.get("notch", 0)), +} + + +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) + + full = FullState(entities=ents, edges=edges) + obs = _observe(ents, edges, vis_edges, vis_ents, layers, cameras, units) + # the world the observation alone describes: anything not visible is gone + restricted = FullState(entities=list(obs.entities), edges=list(obs.edges)) + + sc = Scenario(key=f"{family}-{seed}-{index:04d}", domain=spec["domain"], + family=family, seed=seed, obs=obs, query=query, full=full, + tags={"n_hidden": spec["hidden"], "edit": query.edit is not None}) + sc.label = checker.label(obs, full, query, alternatives=[restricted]) + return sc + + +# -------------------------------------------------------------------------- +# invariances: camera and units must not change the answer + + +def with_camera(sc: Scenario, camera: str) -> Scenario: + out = replace(sc, obs=replace(sc.obs, cameras=[camera])) + out.tags = dict(sc.tags, camera=camera) + return out + + +def rescale(sc: Scenario, factor: int, unit: str) -> Scenario: + """Multiply integer geometry by ``factor`` and relabel the unit. The answer + must be invariant; the fixture checks that it actually is.""" + def scale_ent(e: Entity) -> Entity: + attrs = dict(e.attrs) + for k in ("x", "y", "z"): + if k in attrs: + attrs[k] = attrs[k] * factor + if "box" in attrs: + attrs["box"] = [v * factor for v in attrs["box"]] + return replace(e, attrs=attrs, unit=unit) + + full = FullState(entities=[scale_ent(e) for e in sc.full.entities], edges=list(sc.full.edges)) + obs = replace(sc.obs, entities=[scale_ent(e) for e in sc.obs.entities], + edges=list(sc.obs.edges), + units={"length": unit, "per_unit": factor}) + out = replace(sc, obs=obs, full=full, tags=dict(sc.tags, unit=unit, scale=factor)) + return out diff --git a/spatial/geom.py b/spatial/geom.py new file mode 100644 index 0000000..0918ebb --- /dev/null +++ b/spatial/geom.py @@ -0,0 +1,167 @@ +"""Geometry primitives: points, boxes, faces, gaps. + +No third-party dependencies on purpose. Everything here is a few dots and norms +on hand-written tuples, because these modules have to run on machines where pip +cannot install numpy, and the inputs are four boxes, not a mesh. + +The one idea worth keeping straight: a *box* is not enough to talk about +contact, because contact is a statement about **surfaces**. ``box_faces`` turns +a box into six (axis, sign, plane, rect) records, which is the poor man's B-rep +and the object every rule below is written against. +""" +from __future__ import annotations + + +def _sub(u, v): + return (u[0] - v[0], u[1] - v[1], u[2] - v[2]) + + +def _add(u, v): + return (u[0] + v[0], u[1] + v[1], u[2] + v[2]) + + +def _mul(u, s): + return (u[0] * s, u[1] * s, u[2] * s) + + +def _dot(u, v): + return u[0] * v[0] + u[1] * v[1] + u[2] * v[2] + + +def _len(u): + return _dot(u, u) ** 0.5 + + +def box_triangles(box) -> list: + """12 triangles for an axis-aligned box. Surface only, no interior. + + Plain tuples on purpose: this module has to run on a machine that has no + third-party packages at all, and the arithmetic here is a few dots and + norms on four boxes. numpy would be the only dependency in the file. + """ + x0, y0, z0, x1, y1, z1 = (float(v) for v in box) + c = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), + (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)] + faces = [(0, 2, 1), (0, 3, 2), (4, 5, 6), (4, 6, 7), (0, 1, 5), (0, 5, 4), + (1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), (3, 0, 4), (3, 4, 7)] + return [tuple(c[i] for i in f) for f in faces] + + +def _pt_tri(p, tri) -> float: + """Distance from a point to a triangle (Ericson, clamped barycentric).""" + a, b, c = tri + ab, ac, ap = _sub(b, a), _sub(c, a), _sub(p, a) + d1, d2 = _dot(ab, ap), _dot(ac, ap) + if d1 <= 0 and d2 <= 0: + return _len(ap) + bp = _sub(p, b) + d3, d4 = _dot(ab, bp), _dot(ac, bp) + if d3 >= 0 and d4 <= d3: + return _len(bp) + vc = d1 * d4 - d3 * d2 + if vc <= 0 <= d1 and d3 <= 0: + return _len(_sub(p, _add(a, _mul(ab, d1 / (d1 - d3))))) + cp = _sub(p, c) + d5, d6 = _dot(ab, cp), _dot(ac, cp) + if d6 >= 0 and d5 <= d6: + return _len(cp) + vb = d5 * d2 - d1 * d6 + if vb <= 0 <= d2 and d6 <= 0: + return _len(_sub(p, _add(a, _mul(ac, d2 / (d2 - d6))))) + va = d3 * d6 - d5 * d4 + if va <= 0 and (d4 - d3) >= 0 and (d5 - d6) >= 0: + w = (d4 - d3) / ((d4 - d3) + (d5 - d6)) + return _len(_sub(p, _add(b, _mul(_sub(c, b), w)))) + denom = 1.0 / (va + vb + vc) + return _len(_sub(p, _add(a, _add(_mul(ab, vb * denom), _mul(ac, vc * denom))))) + + +def _aabb_gap(a, b) -> float: + """Lower bound on the surface distance -- used only as a cheap prefilter.""" + dx = max(0.0, max(a[0] - b[3], b[0] - a[3])) + dy = max(0.0, max(a[1] - b[4], b[1] - a[4])) + dz = max(0.0, max(a[2] - b[5], b[2] - a[5])) + return (dx * dx + dy * dy + dz * dz) ** 0.5 + + +def box_faces(box) -> list: + """The six faces of an axis-aligned box as (axis, sign, plane, rect2d). + + ``rect2d`` is the face's extent in the two axes it spans, in ascending order. + This is the poor man's B-rep: faces are stored as *surfaces*, not as vertex + triples, because contact is a statement about surfaces. + """ + x0, y0, z0, x1, y1, z1 = (float(v) for v in box) + lo, hi = (x0, y0, z0), (x1, y1, z1) + out = [] + for ax in range(3): + u, v = [i for i in range(3) if i != ax] + rect = (lo[u], lo[v], hi[u], hi[v]) + out.append((ax, -1, lo[ax], rect)) + out.append((ax, +1, hi[ax], rect)) + return out + + +def contact_area(fa, fb, eps: float = 0.0) -> float: + """Overlap area of two faces if they are coincident, else 0. + + Coincident means: same plane orientation (same axis, opposite outward + normals -- two faces pointing the same way are facing each other, not + touching) and the same offset along that axis, up to ``eps``, which only + has to absorb floating-point noise from transforms. Line and point contacts + (zero overlap area) are deliberately *not* contacts: in a B-rep they are a + separate topological case and pretending a rectangle of zero width is a + surface would be the same mistake as the distance threshold. + """ + ax, sa, pa, ra = fa + bx, sb, pb, rb = fb + if ax != bx or sa == sb or abs(pa - pb) > eps: + return 0.0 + ou = min(ra[2], rb[2]) - max(ra[0], rb[0]) + ov = min(ra[3], rb[3]) - max(ra[1], rb[1]) + if ou <= 0 or ov <= 0: + return 0.0 + return ou * ov + + +def box_contact_area(box_a, box_b, eps: float = 0.0) -> float: + best = 0.0 + for fa in box_faces(box_a): + for fb in box_faces(box_b): + a = contact_area(fa, fb, eps) + if a > best: + best = a + return best + + +def surface_gap(box_a, box_b) -> float: + """Minimum distance between two box surfaces, measured on triangles. + + Vertex-to-triangle only: edge-to-edge minima are missed, which can overestimate + the gap when two edges cross without a vertex near the contact. For the + separation this benchmark actually has (>=16 grid units) it never matters -- + and that "never matters" is itself one of the findings. + + Kept for the clearance column only. Contact is decided by ``contact_area``, + which needs no distance at all. + """ + ta, tb = box_triangles(box_a), box_triangles(box_b) + va, vb = _vertices(ta), _vertices(tb) + best = float("inf") + for tri in ta: + for p in vb: + best = min(best, _pt_tri(p, tri)) + for tri in tb: + for p in va: + best = min(best, _pt_tri(p, tri)) + return best + + +def _vertices(tris) -> list: + seen, out = set(), [] + for tri in tris: + for p in tri: + if p not in seen: + seen.add(p) + out.append(p) + return out diff --git a/spatial/schema.py b/spatial/schema.py index 2fe0e8e..d366175 100644 --- a/spatial/schema.py +++ b/spatial/schema.py @@ -40,6 +40,13 @@ def digest(obj) -> str: return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest() +def _canonical_scope(scope: dict) -> dict: + out = {} + for k, v in sorted((scope or {}).items()): + out[k] = dict(sorted(v.items())) if isinstance(v, dict) else sorted(v) + return out + + @dataclass class Entity: eid: str @@ -110,6 +117,17 @@ class Observation: hidden_faces: list = field(default_factory=list) hidden: dict = field(default_factory=lambda: {"entity": {}, "edge": {}}) dangling: list = field(default_factory=list) + # What the source says it has, versus what it actually handed over. Counts + # and layer names only: no endpoints, no "who supports whom". This is the + # part of "I did not see everything" that a real provider can state without + # 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. + scope: dict = field(default_factory=lambda: { + "parts": {}, "rendered": {}, + "relations": {}, "rendered_relations": {}, + "layers": [], "rendered_layers": [], + }) def entity_ids(self) -> set: return {e.eid for e in self.entities} @@ -124,6 +142,7 @@ 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)], + "scope": _canonical_scope(self.scope), } diff --git a/spatial/view.py b/spatial/view.py new file mode 100644 index 0000000..547c94b --- /dev/null +++ b/spatial/view.py @@ -0,0 +1,154 @@ +"""视野边界:可见性能不能算出 hidden 和 dangling。 + +M2 的输入契约卡在一个循环上:``Observation.hidden`` 和 ``Observation.dangling`` +说"有东西我没看到",而现在的夹具是拿**完整状态减去可见集合**算出来的。真实场景 +里没有完整状态可用,否则就不用谈不确定了。 + +出路只有一条:把"我没看到"换成某个能从**观测本身**算出来的量。最容易想到的是 +表面可见性——拿几个正交视角,一个面如果背朝所有相机、或被别的零件挡住,就是 +"没看到的面",而没看到的面正是关系可能附着的地方。 + +这个模块就是为了把这条路走到底并给出判决,而不是为了得到一个好用的特征: + +* :func:`unobserved_faces` 只吃可见实体和相机方向,不碰完整状态; +* :func:`report` 把它和 ``dangling`` 的锚点逐实体对账。 + +结论写在 ``docs/M2_VIEW_CONTRACT.md``:这条路走不通,而且是两头都不通。 +""" +from __future__ import annotations + +import sys + +from . import generator +from .geom import box_faces + +# An inspection rig: five orthographic views. Not a rendering camera -- the point +# is only that "seen" has to mean something computable from geometry alone. +VIEWS = ((1.0, 0.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), + (0.0, -1.0, 0.0), (0.0, 0.0, 1.0)) + + +def _box(entity): + b = entity.attrs.get("box") + return tuple(float(v) for v in b) if b else None + + +def _face_center(box, axis, sign): + x0, y0, z0, x1, y1, z1 = box + c = [(x0 + x1) / 2.0, (y0 + y1) / 2.0, (z0 + z1) / 2.0] + c[axis] = x1 if sign > 0 else x0 + return c + + +def _ray_hits_box(box, p, d, eps: float = 1e-9) -> bool: + """Slab test for the ray p + t*d, t > eps. Used for occlusion only.""" + tmin, tmax = 0.0, float("inf") + for k in range(3): + lo, hi = box[k], box[k + 3] + if abs(d[k]) < 1e-12: + if p[k] <= lo or p[k] >= hi: + return False + else: + t1, t2 = (lo - p[k]) / d[k], (hi - p[k]) / d[k] + if t1 > t2: + t1, t2 = t2, t1 + if t1 > tmin: + tmin = t1 + if t2 < tmax: + tmax = t2 + if tmin > tmax: + return False + return tmax > eps + + +def face_seen(box, face, others, eps: float = 1e-9) -> bool: + """Is this face visible from at least one view, with nothing in the way. + + ``others`` are the boxes that may occlude it. The ray starts just off the + surface so a face flush against another part does not test against itself, + and it is a single ray from the face centre -- an approximation that only + ever over-reports occlusion for concave parts, which these fixtures do not + have. + """ + axis, sign, _, _ = face + n = [0.0, 0.0, 0.0] + n[axis] = float(sign) + p = _face_center(box, axis, sign) + for d in VIEWS: + if sum(n[k] * d[k] for k in range(3)) <= 0: + continue # back-facing under this view + start = [p[k] + n[k] * eps for k in range(3)] + if not any(_ray_hits_box(o, start, d, eps) for o in others): + return True + return False + + +def unobserved_faces(entities) -> dict: + """eid -> number of its six faces no view can see. Box entities only.""" + boxes = {e.eid: _box(e) for e in entities if _box(e) is not None} + out = {} + for eid, box in boxes.items(): + others = [b for k, b in boxes.items() if k != eid] + out[eid] = sum(1 for f in box_faces(box) if not face_seen(box, f, others)) + return out + + +def dangling_anchors(obs) -> set: + return {e.a for e in obs.dangling} + + +def report(n: int = 24) -> None: + """Per family: do "a relation I cannot see the far end of" and "a surface no + view can see" pick out the same entities. + + Two ways to be wrong, and both matter: + + * ``d-only`` -- an entity carrying a dangling relation that every view sees + completely. Geometry has no way to say "something attaches here", so the + fact can only be *declared*. Inner-layer conductors in a PCB are exactly + this: the conductor is not occluded, it is inside another material. + * ``u-only`` -- an entity with unseen surfaces and no dangling relation. A + part resting on a pedestal has an unseeable bottom face every time, so the + signal is on for nearly everything and stops distinguishing anything. + """ + print(f"{'family':11s} {'可见':>4s} {'有盒':>4s} {'悬空锚':>5s} {'有未见面':>6s} " + f"{'两者':>4s} {'仅悬空':>5s} {'仅见面':>5s} {'平均未见面':>8s}") + print("-" * 66) + for fam in generator.FAMILIES: + vis = boxed = both = u_only = dang = unobs = 0 + tot_faces = 0 + for i in range(n): + sc = generator.make(fam, seed=5, index=i) + ents = list(sc.obs.entities) + vis += len(ents) + un = unobserved_faces(ents) + boxed += len(un) + tot_faces += sum(un.values()) + anchors = dangling_anchors(sc.obs) + dang += len(anchors) + unobs += sum(1 for v in un.values() if v > 0) + both += sum(1 for eid in anchors if un.get(eid, 0) > 0) + u_only += sum(1 for eid, v in un.items() if v > 0 and eid not in anchors) + per = max(1, n) + avg = (tot_faces / boxed) if boxed else 0.0 + print(f"{fam:11s} {vis / per:4.1f} {boxed / per:4.1f} {dang / per:5.1f} " + f"{unobs / per:6.1f} {both / per:4.1f} {(dang - both) / per:7.1f} " + f"{u_only / per:5.1f} {avg:8.2f}") + print() + print("可见 = 观测里的实体数(含无几何的地面/焊盘)") + print("有盒 = 能用表面可见性说话的实体数;连接域恒为 0,那类的隐藏不是遮挡") + print("悬空锚 = 挂着悬空关系的实体数(悬空关系 = 一端不可见,只剩锚点)") + print("有未见面 = 至少有一张面任何视角都看不到的实体数") + print("仅悬空 = 有悬空关系但六张面全可见 —— 表面可见性对它无话可说,只能靠声明") + print("仅见面 = 有未见面但没有悬空关系 —— 坐着的东西底面永远看不到,信号恒亮") + print("平均未见面 = 有盒实体平均有多少张面看不到(0-6)") + + +def main(argv=None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + report(int(argv[0]) if argv else 24) + return 0 + + +if __name__ == "__main__": + sys.exit(main())