232 lines
10 KiB
Python
232 lines
10 KiB
Python
"""几何 → 关系图:提取器,以及它证明不出来的东西。
|
||
|
||
M2 的第一件事不是加结构,而是查一个从没查过的前提:``Observation`` 里那张
|
||
实体+关系图,在真实场景里由谁给出。
|
||
|
||
这里不接 CAD、不引第三方几何库,只做最小可判定的实验:把夹具的盒子表面变成
|
||
三角形,再从**三角形之间的距离**推接触关系(不看 schema 里的答案),然后问
|
||
两个问题:
|
||
|
||
1. 从几何提取的图,能不能复现检查器给出的凭证?
|
||
2. 连通和自由度这两类关系,能不能从几何里提出来?
|
||
|
||
第 2 问的答案决定了 M2 的输入从哪来,比任何模型改动都重要。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
|
||
import numpy as np
|
||
|
||
from . import checker, generator
|
||
from .schema import Edge, FullState, Query
|
||
|
||
CONTACT = "contact"
|
||
TOLERANCES = (0.0, 0.5, 1.0, 2.0, 4.0)
|
||
|
||
|
||
def box_triangles(box) -> np.ndarray:
|
||
"""(12,3,3) triangles for an axis-aligned box. Surface only, no interior."""
|
||
x0, y0, z0, x1, y1, z1 = (float(v) for v in box)
|
||
c = np.array([(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 np.array([[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 = b - a, c - a, p - a
|
||
d1, d2 = ab @ ap, ac @ ap
|
||
if d1 <= 0 and d2 <= 0:
|
||
return float(np.linalg.norm(ap))
|
||
bp = p - b
|
||
d3, d4 = ab @ bp, ac @ bp
|
||
if d3 >= 0 and d4 <= d3:
|
||
return float(np.linalg.norm(bp))
|
||
vc = d1 * d4 - d3 * d2
|
||
if vc <= 0 <= d1 and d3 <= 0:
|
||
return float(np.linalg.norm(p - (a + ab * (d1 / (d1 - d3)))))
|
||
cp = p - c
|
||
d5, d6 = ab @ cp, ac @ cp
|
||
if d6 >= 0 and d5 <= d6:
|
||
return float(np.linalg.norm(cp))
|
||
vb = d5 * d2 - d1 * d6
|
||
if vb <= 0 <= d2 and d6 <= 0:
|
||
return float(np.linalg.norm(p - (a + 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 float(np.linalg.norm(p - (b + (c - b) * w)))
|
||
denom = 1.0 / (va + vb + vc)
|
||
return float(np.linalg.norm(p - (a + ab * (vb * denom) + 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 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.
|
||
"""
|
||
ta, tb = box_triangles(box_a), box_triangles(box_b)
|
||
va, vb = np.unique(ta.reshape(-1, 3), axis=0), np.unique(tb.reshape(-1, 3), axis=0)
|
||
best = np.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 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."""
|
||
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)):
|
||
a, b = boxes[ids[i]], boxes[ids[j]]
|
||
if _aabb_gap(a, b) > tol:
|
||
continue
|
||
if min(a[3], b[3]) <= max(a[0], b[0]) or min(a[4], b[4]) <= max(a[1], b[1]):
|
||
continue # no shared footprint: no contact
|
||
if surface_gap(a, b) <= tol:
|
||
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) <= tol:
|
||
edges.append(Edge(f"x{n}", CONTACT, eid, gid))
|
||
n += 1
|
||
return edges
|
||
|
||
|
||
def _answer(sc, edges) -> bool:
|
||
return checker.evaluate(sc.obs.entities, edges, Query(kind=sc.query.kind,
|
||
a=sc.query.a, b=sc.query.b))
|
||
|
||
|
||
def report(n: int = 32) -> None:
|
||
"""Positive and negative recall are reported apart on purpose.
|
||
|
||
A graph with no relations answers "false" to every query, so a single
|
||
"agreement" number would hand it the whole negative class for free. What M2
|
||
needs to know is whether geometry alone can ever establish the positive.
|
||
"""
|
||
print(f"{'family':11s} {'真边':>5s} {'提取':>5s} {'真阳率':>6s} {'真阴率':>6s} "
|
||
f"{'凭证':>5s} {'余隙':>5s}")
|
||
print("-" * 54)
|
||
for fam in generator.FAMILIES:
|
||
n_true = n_false = hit_true = hit_false = cert_ok = 0
|
||
got = truth = total = 0
|
||
gap = np.inf
|
||
for i in range(n):
|
||
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)
|
||
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)):
|
||
g = surface_gap(boxes[p], boxes[q])
|
||
if g > 0:
|
||
gap = min(gap, g) # clearance, not the touching pairs
|
||
total += 1
|
||
truth += len(sc.obs.edges)
|
||
got += len(edges)
|
||
world = FullState(entities=list(sc.obs.entities), edges=edges)
|
||
if _answer(sc, sc.obs.edges):
|
||
n_true += 1
|
||
hit_true += int(bool(_answer(sc, edges)))
|
||
ev = checker.evidence_for(world, sc.query)
|
||
cert_ok += int(bool(ev) and checker.validate_evidence(world, sc.query, ev))
|
||
else:
|
||
n_false += 1
|
||
hit_false += int(not _answer(sc, edges))
|
||
rec = f"{hit_true / n_true:6.2f}" if n_true else " —"
|
||
neg = f"{hit_false / n_false:6.2f}" if n_false else " —"
|
||
cert = f"{cert_ok / n_true:5.2f}" if n_true else " —"
|
||
g = "—" if not np.isfinite(gap) else f"{gap:.0f}"
|
||
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("余隙 = 互不接触的零件表面之间的最小距离,说明容差有没有被真正考验")
|
||
|
||
|
||
GAP_FAMILIES = (("area.sup2", 0), ("area.gap1", 1), ("area.gap2", 2), ("area.gap4", 4))
|
||
|
||
|
||
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:
|
||
cells = []
|
||
for tol in tols:
|
||
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)
|
||
world = FullState(entities=list(sc.obs.entities), edges=edges)
|
||
tp = [e for e in edges if {e.a, e.b} == {"T", "P"}]
|
||
total += 1
|
||
if tp:
|
||
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))
|
||
print()
|
||
print("单元格 = 提取到 T-P 边的样本数 / 总数")
|
||
print("ok = 该边合法(间隙为 0,零件本来就贴着)")
|
||
print("x = 提取到了一条不存在的接触,但凭证校验按几何拒绝了它(正确行为)")
|
||
print("! = 假边通过了凭证校验 —— 校验器有洞(修复前每一格都是这个)")
|
||
print("间隙单位 0.25mm;真实装配的余隙是 0.2mm 级,即 1 格")
|
||
|
||
|
||
def main(argv=None) -> int:
|
||
argv = list(sys.argv[1:] if argv is None else argv)
|
||
if argv and argv[0] == "tol":
|
||
report_tolerance(int(argv[1]) if len(argv) > 1 else 8)
|
||
else:
|
||
report(int(argv[0]) if argv else 32)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|