From 2ddba5843c016e76ddc47ce7387ec67eabcab5cf Mon Sep 17 00:00:00 2001 From: lhj <403133128@qq.com> Date: Thu, 3 Dec 2026 22:29:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(spatial):=20=E6=8E=A5=E8=A7=A6=E5=88=A4?= =?UTF-8?q?=E5=AE=9A=E6=94=B9=E6=88=90=E5=85=B1=E9=9D=A2=E7=B2=BE=E7=A1=AE?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=EF=BC=8C=E5=AE=B9=E5=B7=AE=E4=BB=8E=E5=86=B3?= =?UTF-8?q?=E5=AE=9A=E7=AD=94=E6=A1=88=E9=99=8D=E7=BA=A7=E6=88=90=E5=90=83?= =?UTF-8?q?=E6=B5=AE=E7=82=B9=E5=99=AA=E5=A3=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spatial/extract.py | 177 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 146 insertions(+), 31 deletions(-) diff --git a/spatial/extract.py b/spatial/extract.py index 9ebcab6..ec53dd8 100644 --- a/spatial/extract.py +++ b/spatial/extract.py @@ -4,13 +4,20 @@ M2 的第一件事不是加结构,而是查一个从没查过的前提:``Obs 实体+关系图,在真实场景里由谁给出。 这里不接 CAD、不引第三方几何库,只做最小可判定的实验:把夹具的盒子表面变成 -三角形,再从**三角形之间的距离**推接触关系(不看 schema 里的答案),然后问 -两个问题: +三角形,再从**几何本身**推接触关系(不看 schema 里的答案),然后问两个问题: 1. 从几何提取的图,能不能复现检查器给出的凭证? 2. 连通和自由度这两类关系,能不能从几何里提出来? 第 2 问的答案决定了 M2 的输入从哪来,比任何模型改动都重要。 + +接触的判定方式换过一次,这件事本身是个结论。第一版按**表面距离 <= 容差**判, +于是容差变成了决定答案的参数:真实装配的余隙是 0.2mm 级,容差一旦跨过余隙, +两个根本没碰上的零件就被焊在一起,而且这种假接触还能通过凭证校验 +(``area.gap1`` 在容差 1 格时 8/8 全错)。第二版按**共面精确匹配**判:B-rep 里 +贴合的两个面本来就是同一张面,平面坐标相等、法向相反、矩形投影有正面积重叠, +不需要容差。``eps`` 从"决定答案的参数"降级成"吃掉浮点噪声的兜底"。 +两版都留着,``report_tolerance`` 把它们并排跑——旧版是这一节的控制组。 """ from __future__ import annotations @@ -72,6 +79,56 @@ def _aabb_gap(a, b) -> float: 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. @@ -92,10 +149,44 @@ def surface_gap(box_a, box_b) -> float: return best -def extract_edges(entities, tol: float = 0.5) -> list: - """Contacts implied by geometry alone: touching within ``tol`` and sharing a - footprint. Everything else -- conduct, constraint -- has no geometric - signature and is simply not produced.""" +def extract_edges(entities, eps: float = 0.0) -> list: + """Contacts implied by geometry alone: coincident faces. + + ``eps`` is a numerical epsilon, not a design tolerance. It should be zero + for exact coordinates and a few ulps when boxes come out of a transform. + Everything else -- conduct, constraint -- has no geometric signature and is + simply not produced. + """ + boxes = {e.eid: tuple(float(v) for v in e.attrs["box"]) + for e in entities if e.attrs.get("box")} + planes = {e.eid: float(e.attrs.get("plane", 0)) for e in entities + if e.kind == "ground"} + ids = sorted(boxes) + edges = [] + n = 0 + for i in range(len(ids)): + for j in range(i + 1, len(ids)): + if box_contact_area(boxes[ids[i]], boxes[ids[j]], eps) > 0: + edges.append(Edge(f"x{n}", CONTACT, ids[i], ids[j])) + n += 1 + for eid in ids: + b = boxes[eid] + for gid, z in planes.items(): + if abs(b[2] - z) <= eps: + edges.append(Edge(f"x{n}", CONTACT, eid, gid)) + n += 1 + return edges + + +def extract_edges_by_distance(entities, tol: float = 0.5) -> list: + """The first version, kept as the control group. + + Touching = surfaces within ``tol`` and a shared footprint. It looks + reasonable and it is the reason ``tol`` was a live parameter: whether a + contact exists depends on how big ``tol`` is, so a part 0.25mm away can be + welded to its neighbour by choosing ``tol = 0.5``. Used by + ``report_tolerance`` only; production paths use :func:`extract_edges`. + """ boxes = {e.eid: tuple(float(v) for v in e.attrs["box"]) for e in entities if e.attrs.get("box")} planes = {e.eid: float(e.attrs.get("plane", 0)) for e in entities @@ -145,7 +236,7 @@ def report(n: int = 32) -> None: sc = generator.make(fam, seed=3, index=i) if sc.query.edit is not None: continue - edges = extract_edges(sc.obs.entities, tol=0.5) + edges = extract_edges(sc.obs.entities) boxes = [e.attrs["box"] for e in sc.obs.entities if e.attrs.get("box")] for p in range(len(boxes)): for q in range(p + 1, len(boxes)): @@ -171,35 +262,32 @@ def report(n: int = 32) -> None: print(f"{fam:11s} {truth / max(1, total):5.1f} {got / max(1, total):5.1f} " f"{rec} {neg} {cert} {g:>5s}") print() - print("真边 = 观测里的关系数;提取 = 只看几何能得到的边数(容差 0.5,单位 0.25mm)") + print("真边 = 观测里的关系数;提取 = 只看几何能得到的关系数(共面精确匹配)") print("真阳率 = 真值为真的样本里几何图也判真的比例,即几何能不能自己证明") print("真阴率 = 真值为假的样本里几何图也判假的比例,零关系的图靠这一列刷分") print("凭证 = 真值为真的样本里,几何图给出的凭证能通过检查的比例") - print("余隙 = 互不接触的零件表面之间的最小距离,说明容差有没有被真正考验") + print("余隙 = 互不接触的零件表面之间的最小距离,说明有没有零件是悬空的") GAP_FAMILIES = (("area.sup2", 0), ("area.gap1", 1), ("area.gap2", 2), ("area.gap4", 4)) +# grid units. The last two entries are the abuse case: an eps of a quarter +# millimetre is not a numerical epsilon any more, it is a design tolerance +# wearing a numerical epsilon's name -- and the old failure comes straight back. +DIST_TOLS = (0.0, 0.5, 1.0, 2.0, 4.0) +NUM_EPS = (0.0, 1e-12, 1e-9, 1e-6, 1e-3, 0.25) -def report_tolerance(n: int = 8) -> None: - """Does the distance tolerance decide anything, and what does it cost. - - For every clearance the upper block sits at, sweep the tolerance and ask two - questions: does an edge between the block and its (absent) pedestal appear, - and if so does the checker accept that edge as a certificate. A tolerance - that fuses two parts 0.25mm apart does not merely add noise -- it forges a - support that validates. - """ - tols = (0.0, 0.5, 1.0, 2.0, 4.0) - print(f"{'family':10s} {'间隙':>4s} " + " ".join(f"{t:>9.1f}" for t in tols)) - print("-" * 68) - for fam, gap in GAP_FAMILIES: +def _panel(title: str, families, cols, extract, marks: bool, n: int) -> None: + """One sweep of the same four clearances under one extraction rule.""" + print(title) + print(f" {'family':10s} {'间隙':>4s} " + " ".join(f"{c:>9s}" for c in cols)) + for fam, gap in families: cells = [] - for tol in tols: + for col in cols: got = forged = total = 0 for i in range(n): sc = generator.make(fam, seed=7, index=i) - edges = extract_edges(sc.obs.entities, tol=tol) + edges = extract(sc.obs.entities, col) world = FullState(entities=list(sc.obs.entities), edges=edges) tp = [e for e in edges if {e.a, e.b} == {"T", "P"}] total += 1 @@ -207,15 +295,42 @@ def report_tolerance(n: int = 8) -> None: got += 1 forged += int(checker.validate_evidence( world, Query(kind="stability", a="T"), [tp[0].eid])) - mark = "ok" if gap == 0 else ("x" if not forged else "!") - cells.append(f"{got:2d}/{total} {mark:2s}") - print(f"{fam:10s} {gap:4d} " + " ".join(f"{c:>9s}" for c in cells)) + if not marks: + cells.append(f"{got:2d}/{total}") + elif gap == 0: + cells.append(f"{got:2d}/{total} {'ok' if got else 'miss'}") + elif not got: + cells.append(f"{got:2d}/{total} -") + else: + cells.append(f"{got:2d}/{total} {'?' if not forged else '!'}") + print(f" {fam:10s} {gap:4d} " + " ".join(f"{c:>9s}" for c in cells)) print() + + +def report_tolerance(n: int = 8) -> None: + """Does the contact rule decide anything by accident, and what does it cost. + + Same four clearances, two extraction rules. For each cell: does an edge + between the block and its (absent) pedestal appear, and does the checker + accept that edge as a certificate. A rule that fuses two parts 0.25mm apart + does not merely add noise -- it forges a support that validates, i.e. it + turns a wrong graph into a wrong *proof*. + """ + _panel("距离阈值(第一版,tol 以格为单位扫)", GAP_FAMILIES, + [f"{t:.1f}" for t in DIST_TOLS], + lambda ents, t: extract_edges_by_distance(ents, tol=t), True, n) + _panel("共面精确匹配(第二版,eps 以 mm 为单位扫)", GAP_FAMILIES, + ["0", "1e-12", "1e-9", "1e-6", "1e-3", "0.25"], + lambda ents, e: extract_edges(ents, eps=e), True, n) print("单元格 = 提取到 T-P 边的样本数 / 总数") - print("ok = 该边合法(间隙为 0,零件本来就贴着)") - print("x = 提取到了一条不存在的接触,但凭证校验按几何拒绝了它(正确行为)") - print("! = 假边通过了凭证校验 —— 校验器有洞(修复前每一格都是这个)") - print("间隙单位 0.25mm;真实装配的余隙是 0.2mm 级,即 1 格") + print("ok = 间隙为 0,零件本来就贴着,提取到了") + print("miss = 间隙为 0 却没提取到(该报的没报)") + print("- = 间隙 > 0,没有提取到边(正确)") + print("? = 间隙 > 0 却提取到边,但凭证校验按几何拒了它(图错了,校验器救了)") + print("! = 假边通过了凭证校验 —— 图错,而且这个错还能当证明用") + print("间隙单位 0.25mm;真实装配的余隙是 0.2mm 级,即约 1 格") + print("距离法在这一格上分辨不了;共面法只需要 eps 盖住浮点噪声,0.25 那列是把") + print("eps 当容差用的滥用,旧坑原样回来 —— 这也是为什么它只是数值兜底。") def main(argv=None) -> int: