Files
tiny-gpt/spatial/extract.py
T

242 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""几何 → 关系图:提取器,以及它证明不出来的东西。
M2 的第一件事不是加结构,而是查一个从没查过的前提:``Observation`` 里那张
实体+关系图,在真实场景里由谁给出。
这里不接 CAD、不引第三方几何库,只做最小可判定的实验:把夹具的盒子表面变成
三角形,再从**几何本身**推接触关系(不看 schema 里的答案),然后问两个问题:
1. 从几何提取的图,能不能复现检查器给出的凭证?
2. 连通和自由度这两类关系,能不能从几何里提出来?
第 2 问的答案决定了 M2 的输入从哪来,比任何模型改动都重要。
接触的判定方式换过一次,这件事本身是个结论。第一版按**表面距离 <= 容差**判,
于是容差变成了决定答案的参数:真实装配的余隙是 0.2mm 级,容差一旦跨过余隙,
两个根本没碰上的零件就被焊在一起,而且这种假接触还能通过凭证校验
(``area.gap1`` 在容差 1 格时 8/8 全错)。第二版按**共面精确匹配**判:B-rep 里
贴合的两个面本来就是同一张面,平面坐标相等、法向相反、矩形投影有正面积重叠,
不需要容差。``eps`` 从"决定答案的参数"降级成"吃掉浮点噪声的兜底"。
两版都留着,``report_tolerance`` 把它们并排跑——旧版是这一节的控制组。
"""
from __future__ import annotations
import sys
from . import checker, generator
from .schema import Edge, FullState, Query
CONTACT = "contact"
from .geom import _aabb_gap, box_contact_area, surface_gap
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
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 = float("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)
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 gap == float("inf") 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("真边 = 观测里的关系数;提取 = 只看几何能得到的关系数(共面精确匹配)")
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 _panel(title: str, families, cols, extract, n: int) -> None:
"""One sweep of the same four clearances under one extraction rule.
``cols`` is a list of (label, value): the label is what the header shows, the
value is what the rule is actually called with.
"""
print(title)
print(f" {'family':10s} {'间隙':>4s} " + " ".join(f"{c[0]:>9s}" for c in cols))
for fam, gap in families:
cells = []
for _, val in cols:
got = forged = total = 0
for i in range(n):
sc = generator.make(fam, seed=7, index=i)
edges = extract(sc.obs.entities, val)
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]))
if 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} {'x' 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}", t) for t in DIST_TOLS],
lambda ents, t: extract_edges_by_distance(ents, tol=t), n)
_panel("共面精确匹配(第二版,eps 以坐标单位扫)", GAP_FAMILIES,
[("0", 0.0), ("1e-12", 1e-12), ("1e-9", 1e-9), ("1e-6", 1e-6),
("1e-3", 1e-3), ("1.0", 1.0)],
lambda ents, e: extract_edges(ents, eps=e), n)
print("单元格 = 提取到 T-P 边的样本数 / 总数")
print("ok = 间隙为 0,零件本来就贴着,提取到了")
print("miss = 间隙为 0 却没提取到(该报的没报)")
print("- = 间隙 > 0,没有提取到边(正确)")
print("x = 间隙 > 0 却焊出一条接触(这一步就把答案 false 翻成了 true),但凭证")
print(" 校验自己复核几何后拒了它 —— 校验器只挡住了「错还能当证明用」")
print("! = 假边连凭证校验都过了。现在不该出现,出现就是校验器回退了")
print("间隙 = 上面那块被抬高的坐标单位数(夹具 per_unit=1,1 格即 1 单位)")
print()
print("两版差别就一条:距离法在 tol >= 间隙时必然焊出一个接触,容差因此是决定")
print("答案的参数;共面法只看两张面是不是同一张面,eps 只盖浮点噪声,扫描从 1e-12")
print("到 1e-3 一格都不动。最后一列 1.0 是把 eps 当容差用的滥用——旧坑原样回来,")
print("这正说明它只能是数值兜底,不能是设计容差。")
print()
print("顺带修掉夹具自己的矛盾:近贴合家族原先一边把上面那块抬高 1/2/4 格,一边")
print("还在 schema 里声明 T 和 P 接触。几何上没碰上就不存在这条边,所以现在只剩")
print("真边 2 条、答案 false。也正因为少了那条边,任何跨越间隙的假接触都会让答案")
print("从 false 变成 true —— 假边才第一次真的骗到了结论,而不只是画错了一条线。")
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())