fix(spatial): 近贴合家族不该声明那条接触边,假边才第一次真能骗到结论
This commit is contained in:
1 parent
2ddba5843c
commit
9d449f2108
6 files changed
+797
-674
No files matched your search
+290
-261
@@ -1,261 +1,290 @@
|
||||
"""Unified entry point: smoke / train / resume / eval.
|
||||
|
||||
``smoke`` is the M0 gate. It does not care about accuracy; it cares that the
|
||||
contract holds -- labels provably right, same seed rebuilds the same scene, the
|
||||
insufficient-evidence pair really is indistinguishable, units and camera do not
|
||||
move the answer, and a checkpoint survives an interruption.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from . import checker, generator
|
||||
from .schema import FullState
|
||||
|
||||
|
||||
def _load_config(path: str) -> dict:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
# configs live in spatial/configs, so the run root is the package's parent
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
cfg["out_dir"] = os.path.join(root, cfg.get("out_dir", "out_spatial/smoke"))
|
||||
return cfg
|
||||
|
||||
|
||||
def _fail(msg: str):
|
||||
print(f"FAIL {msg}")
|
||||
return False
|
||||
|
||||
|
||||
def check_splits(cfg) -> bool:
|
||||
d = cfg["data"]
|
||||
tr, va, te = set(d["train_families"]), set(d["val_families"]), set(d["test_families"])
|
||||
known = set(generator.FAMILIES)
|
||||
if not (tr | va | te) <= known:
|
||||
return _fail(f"unknown families: {(tr | va | te) - known}")
|
||||
if tr & va or tr & te or va & te:
|
||||
return _fail(f"split families overlap: {sorted(tr & va)} {sorted(tr & te)} {sorted(va & te)}")
|
||||
if tr | va | te != known:
|
||||
missing = known - (tr | va | te)
|
||||
print(f"note families not used by any split: {sorted(missing)}")
|
||||
print(f"ok splits disjoint over families: {len(tr)}/{len(va)}/{len(te)}")
|
||||
return True
|
||||
|
||||
|
||||
def check_determinism() -> bool:
|
||||
ok = True
|
||||
for fam in generator.FAMILIES:
|
||||
a = generator.make(fam, seed=11, index=3)
|
||||
b = generator.make(fam, seed=11, index=3)
|
||||
if a.full_digest() != b.full_digest():
|
||||
ok = _fail(f"{fam} not reproducible from the same seed")
|
||||
if ok:
|
||||
print("ok same seed rebuilds an identical scene (10 families)")
|
||||
return ok
|
||||
|
||||
|
||||
def check_labels() -> bool:
|
||||
"""Every sufficient positive label must carry a certificate the checker
|
||||
accepts, and every sufficient label must agree with a rerun on the full
|
||||
state alone."""
|
||||
bad = 0
|
||||
n = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(6):
|
||||
sc = generator.make(fam, seed=23, index=i)
|
||||
n += 1
|
||||
if sc.label.sufficient:
|
||||
ans = checker.evaluate(sc.full.entities, sc.full.edges, sc.query)
|
||||
if (ans is True) != (sc.label.answer == "true"):
|
||||
bad += 1
|
||||
print(f" {fam}[{i}] label {sc.label.answer} vs checker {ans}")
|
||||
if sc.label.answer == "true" and not checker.validate_evidence(
|
||||
sc.full, sc.query, sc.label.evidence):
|
||||
bad += 1
|
||||
print(f" {fam}[{i}] certificate rejected: {sc.label.evidence}")
|
||||
if bad:
|
||||
return _fail(f"{bad} label/certificate mismatches over {n} samples")
|
||||
print(f"ok {n} labels agree with the full-state checker, certificates validate")
|
||||
return True
|
||||
|
||||
|
||||
def check_insufficient() -> bool:
|
||||
"""The point of the unknown label: the observation does not settle it.
|
||||
|
||||
Under the monotone rule an unknown label no longer implies that *the one full
|
||||
state we hold* answers differently from the observation's own world -- it
|
||||
implies that the withheld content could be the missing piece. So the check is
|
||||
that something is withheld and the visible structure does not already prove
|
||||
the answer, which is exactly the condition the label promises.
|
||||
"""
|
||||
found = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(8):
|
||||
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)
|
||||
withheld = bool(sc.obs.dangling) or bool((sc.obs.hidden or {}).get("entity")) \
|
||||
or bool((sc.obs.hidden or {}).get("edge"))
|
||||
if withheld and a_vis is not True:
|
||||
found += 1
|
||||
else:
|
||||
return _fail(f"{fam}[{i}] unknown without withheld content or with a "
|
||||
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")
|
||||
return True
|
||||
|
||||
|
||||
def check_invariances() -> bool:
|
||||
bad = 0
|
||||
for fam in generator.FAMILIES:
|
||||
sc = generator.make(fam, seed=31, index=1)
|
||||
scaled = generator.rescale(sc, 10, "0.1mm")
|
||||
if scaled.label.answer != sc.label.answer:
|
||||
bad += 1
|
||||
print(f" {fam} unit change moved the answer")
|
||||
cam = generator.with_camera(sc, "iso")
|
||||
if cam.label.answer != sc.label.answer:
|
||||
bad += 1
|
||||
print(f" {fam} camera change moved the answer")
|
||||
if bad:
|
||||
return _fail(f"{bad} invariance violations")
|
||||
print("ok answer invariant to unit scaling and camera relabel")
|
||||
return True
|
||||
|
||||
|
||||
def check_cross_family_digest() -> bool:
|
||||
"""Two samples with the same ``input_digest`` must carry the same label.
|
||||
|
||||
This is the whole contract, and it has to hold *across* families, not only
|
||||
inside one: "no hidden branch exists" and "a hidden branch exists but is not
|
||||
visible" produce the same observation, so a label that says "decidable" in
|
||||
the first case and "unknown" in the second is a label the model can never
|
||||
reproduce -- absence of evidence is not evidence of absence. Samples whose
|
||||
scores differ are still a bug, just a quieter one.
|
||||
"""
|
||||
seen = {}
|
||||
bad = []
|
||||
n = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(40):
|
||||
sc = generator.make(fam, seed=71, index=i)
|
||||
n += 1
|
||||
d = sc.input_digest()
|
||||
prev = seen.get(d)
|
||||
if prev is None:
|
||||
seen[d] = (fam, sc.label.answer, sc.label.change)
|
||||
elif (prev[1], prev[2]) != (sc.label.answer, sc.label.change):
|
||||
bad.append((prev, (fam, sc.label.answer, sc.label.change)))
|
||||
if bad:
|
||||
# collapse to the distinct family pairs, the list itself is long
|
||||
pairs = sorted({(a[0], b[0]) for a, b in bad})
|
||||
print(f" {len(bad)} samples share an input digest with a different label")
|
||||
for a, b in pairs[:6]:
|
||||
print(f" {a:11s} vs {b:11s}")
|
||||
return _fail("same input, different label -- the observation does not "
|
||||
"determine the answer, so both cannot be decidable")
|
||||
print(f"ok {n} samples: no two families assign different labels to "
|
||||
f"the same observation ({len(seen)} distinct inputs)")
|
||||
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()]
|
||||
|
||||
# one update, then interrupt and resume: the step counter must advance
|
||||
from . import train as trainer
|
||||
short = json.loads(json.dumps(cfg))
|
||||
short["optim"]["steps"] = 2
|
||||
short["optim"]["log_every"] = 1
|
||||
short["eval"]["n"] = 12
|
||||
m1 = trainer.run(short, verbose=False)
|
||||
ckpt = os.path.join(short["out_dir"], "ckpt.pt")
|
||||
if not os.path.exists(ckpt):
|
||||
results.append(_fail("checkpoint not written"))
|
||||
elif os.path.exists(ckpt + ".tmp"):
|
||||
results.append(_fail("temporary checkpoint left behind"))
|
||||
else:
|
||||
print(f"ok checkpoint written atomically, val answer_acc {m1['answer_acc']:.2f}")
|
||||
|
||||
from . import train as trainer2
|
||||
m2 = trainer2.run(short, resume=True, steps=1, verbose=False)
|
||||
_, _, step, _ = trainer2.load(ckpt)
|
||||
if step != 3:
|
||||
results.append(_fail(f"resume advanced to step {step}, expected 3"))
|
||||
else:
|
||||
print(f"ok resume continued at step {step} (2 + 1)")
|
||||
|
||||
print("---")
|
||||
if all(results):
|
||||
print("smoke PASS")
|
||||
return 0
|
||||
print("smoke FAIL")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_train(args) -> int:
|
||||
from . import train as trainer
|
||||
cfg = _load_config(args.config)
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}"
|
||||
trainer.run(cfg, resume=args.resume, steps=args.steps)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_eval(args) -> int:
|
||||
from . import train as trainer
|
||||
cfg = _load_config(args.config)
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}"
|
||||
model, _, step, cfg = trainer.load(os.path.join(cfg["out_dir"], "ckpt.pt"))
|
||||
for split in ("train", "val", "test"):
|
||||
fams = cfg["data"][f"{split}_families"]
|
||||
m = trainer.evaluate(model, fams, cfg["seed"], cfg["eval"]["n"])
|
||||
print(f"{split:5s} " + json.dumps({k: (round(v, 3) if isinstance(v, float) else v)
|
||||
for k, v in m.items() if k != "loss"}))
|
||||
print(f"step {step}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_report(args) -> int:
|
||||
from . import report
|
||||
report.report(args.config, n=args.n, ablate=args.ablate, seed=args.seed)
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
p = argparse.ArgumentParser(prog="spatial")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
for name, fn in (("smoke", cmd_smoke), ("train", cmd_train), ("eval", cmd_eval),
|
||||
("report", cmd_report)):
|
||||
sp = sub.add_parser(name)
|
||||
sp.add_argument("--config", default=os.path.join(os.path.dirname(__file__), "configs", "smoke.json"))
|
||||
sp.add_argument("--seed", type=int, default=None,
|
||||
help="override config seed (data and init both follow it)")
|
||||
if name != "eval":
|
||||
sp.add_argument("--steps", type=int, default=None)
|
||||
if name == "train":
|
||||
sp.add_argument("--resume", action="store_true")
|
||||
if name == "report":
|
||||
sp.add_argument("--n", type=int, default=128)
|
||||
sp.add_argument("--ablate", default=None,
|
||||
choices=[None, "dangling", "scene", "edge_feat", "dangling,scene"])
|
||||
sp.set_defaults(fn=fn)
|
||||
args = p.parse_args(argv)
|
||||
return args.fn(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
"""Unified entry point: smoke / train / resume / eval.
|
||||
|
||||
``smoke`` is the M0 gate. It does not care about accuracy; it cares that the
|
||||
contract holds -- labels provably right, same seed rebuilds the same scene, the
|
||||
insufficient-evidence pair really is indistinguishable, units and camera do not
|
||||
move the answer, and a checkpoint survives an interruption.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from . import checker, generator
|
||||
from .schema import FullState
|
||||
|
||||
|
||||
def _load_config(path: str) -> dict:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
cfg = json.load(f)
|
||||
# configs live in spatial/configs, so the run root is the package's parent
|
||||
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
cfg["out_dir"] = os.path.join(root, cfg.get("out_dir", "out_spatial/smoke"))
|
||||
return cfg
|
||||
|
||||
|
||||
def _fail(msg: str):
|
||||
print(f"FAIL {msg}")
|
||||
return False
|
||||
|
||||
|
||||
def check_splits(cfg) -> bool:
|
||||
d = cfg["data"]
|
||||
tr, va, te = set(d["train_families"]), set(d["val_families"]), set(d["test_families"])
|
||||
known = set(generator.FAMILIES)
|
||||
if not (tr | va | te) <= known:
|
||||
return _fail(f"unknown families: {(tr | va | te) - known}")
|
||||
if tr & va or tr & te or va & te:
|
||||
return _fail(f"split families overlap: {sorted(tr & va)} {sorted(tr & te)} {sorted(va & te)}")
|
||||
if tr | va | te != known:
|
||||
missing = known - (tr | va | te)
|
||||
print(f"note families not used by any split: {sorted(missing)}")
|
||||
print(f"ok splits disjoint over families: {len(tr)}/{len(va)}/{len(te)}")
|
||||
return True
|
||||
|
||||
|
||||
def check_determinism() -> bool:
|
||||
ok = True
|
||||
for fam in generator.FAMILIES:
|
||||
a = generator.make(fam, seed=11, index=3)
|
||||
b = generator.make(fam, seed=11, index=3)
|
||||
if a.full_digest() != b.full_digest():
|
||||
ok = _fail(f"{fam} not reproducible from the same seed")
|
||||
if ok:
|
||||
print("ok same seed rebuilds an identical scene (10 families)")
|
||||
return ok
|
||||
|
||||
|
||||
def check_labels() -> bool:
|
||||
"""Every sufficient positive label must carry a certificate the checker
|
||||
accepts, and every sufficient label must agree with a rerun on the full
|
||||
state alone."""
|
||||
bad = 0
|
||||
n = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(6):
|
||||
sc = generator.make(fam, seed=23, index=i)
|
||||
n += 1
|
||||
if sc.label.sufficient:
|
||||
ans = checker.evaluate(sc.full.entities, sc.full.edges, sc.query)
|
||||
if (ans is True) != (sc.label.answer == "true"):
|
||||
bad += 1
|
||||
print(f" {fam}[{i}] label {sc.label.answer} vs checker {ans}")
|
||||
if sc.label.answer == "true" and not checker.validate_evidence(
|
||||
sc.full, sc.query, sc.label.evidence):
|
||||
bad += 1
|
||||
print(f" {fam}[{i}] certificate rejected: {sc.label.evidence}")
|
||||
if bad:
|
||||
return _fail(f"{bad} label/certificate mismatches over {n} samples")
|
||||
print(f"ok {n} labels agree with the full-state checker, certificates validate")
|
||||
return True
|
||||
|
||||
|
||||
def check_insufficient() -> bool:
|
||||
"""The point of the unknown label: the observation does not settle it.
|
||||
|
||||
Under the monotone rule an unknown label no longer implies that *the one full
|
||||
state we hold* answers differently from the observation's own world -- it
|
||||
implies that the withheld content could be the missing piece. So the check is
|
||||
that something is withheld and the visible structure does not already prove
|
||||
the answer, which is exactly the condition the label promises.
|
||||
"""
|
||||
found = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(8):
|
||||
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)
|
||||
withheld = bool(sc.obs.dangling) or bool((sc.obs.hidden or {}).get("entity")) \
|
||||
or bool((sc.obs.hidden or {}).get("edge"))
|
||||
if withheld and a_vis is not True:
|
||||
found += 1
|
||||
else:
|
||||
return _fail(f"{fam}[{i}] unknown without withheld content or with a "
|
||||
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")
|
||||
return True
|
||||
|
||||
|
||||
def check_invariances() -> bool:
|
||||
bad = 0
|
||||
for fam in generator.FAMILIES:
|
||||
sc = generator.make(fam, seed=31, index=1)
|
||||
scaled = generator.rescale(sc, 10, "0.1mm")
|
||||
if scaled.label.answer != sc.label.answer:
|
||||
bad += 1
|
||||
print(f" {fam} unit change moved the answer")
|
||||
cam = generator.with_camera(sc, "iso")
|
||||
if cam.label.answer != sc.label.answer:
|
||||
bad += 1
|
||||
print(f" {fam} camera change moved the answer")
|
||||
if bad:
|
||||
return _fail(f"{bad} invariance violations")
|
||||
print("ok answer invariant to unit scaling and camera relabel")
|
||||
return True
|
||||
|
||||
|
||||
def check_cross_family_digest() -> bool:
|
||||
"""Two samples with the same ``input_digest`` must carry the same label.
|
||||
|
||||
This is the whole contract, and it has to hold *across* families, not only
|
||||
inside one: "no hidden branch exists" and "a hidden branch exists but is not
|
||||
visible" produce the same observation, so a label that says "decidable" in
|
||||
the first case and "unknown" in the second is a label the model can never
|
||||
reproduce -- absence of evidence is not evidence of absence. Samples whose
|
||||
scores differ are still a bug, just a quieter one.
|
||||
"""
|
||||
seen = {}
|
||||
bad = []
|
||||
n = 0
|
||||
for fam in generator.FAMILIES:
|
||||
for i in range(40):
|
||||
sc = generator.make(fam, seed=71, index=i)
|
||||
n += 1
|
||||
d = sc.input_digest()
|
||||
prev = seen.get(d)
|
||||
if prev is None:
|
||||
seen[d] = (fam, sc.label.answer, sc.label.change)
|
||||
elif (prev[1], prev[2]) != (sc.label.answer, sc.label.change):
|
||||
bad.append((prev, (fam, sc.label.answer, sc.label.change)))
|
||||
if bad:
|
||||
# collapse to the distinct family pairs, the list itself is long
|
||||
pairs = sorted({(a[0], b[0]) for a, b in bad})
|
||||
print(f" {len(bad)} samples share an input digest with a different label")
|
||||
for a, b in pairs[:6]:
|
||||
print(f" {a:11s} vs {b:11s}")
|
||||
return _fail("same input, different label -- the observation does not "
|
||||
"determine the answer, so both cannot be decidable")
|
||||
print(f"ok {n} samples: no two families assign different labels to "
|
||||
f"the same observation ({len(seen)} distinct inputs)")
|
||||
return True
|
||||
|
||||
|
||||
def check_extract_contacts(n: int = 8) -> bool:
|
||||
"""The geometry provider must not invent a contact across a clearance.
|
||||
|
||||
``area.gap1/2/4`` place the same block 1, 2 and 4 units above its pedestal.
|
||||
Contact is decided by coincident faces, not by distance, so at a numerical
|
||||
epsilon the extractor has to report no T-P edge there -- and still report
|
||||
the two contacts that are real. This is the regression gate for the
|
||||
parameter that used to decide the answer by itself.
|
||||
"""
|
||||
from . import extract
|
||||
bad = set()
|
||||
for fam in ("area.gap1", "area.gap2", "area.gap4"):
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=0, index=i)
|
||||
if any({e.a, e.b} == {"T", "P"}
|
||||
for e in extract.extract_edges(sc.obs.entities, eps=1e-9)):
|
||||
bad.add(fam)
|
||||
break
|
||||
if bad:
|
||||
return _fail(f"extractor welded T to P across a clearance: {sorted(bad)}")
|
||||
got = len(extract.extract_edges(
|
||||
generator.make("area.sup2", seed=0, index=0).obs.entities, eps=1e-9))
|
||||
if got != 3:
|
||||
return _fail(f"area.sup2: extractor found {got} contacts, expected 3")
|
||||
print("ok extractor: nothing welded across a clearance, 3/3 real contacts kept")
|
||||
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()]
|
||||
|
||||
# one update, then interrupt and resume: the step counter must advance
|
||||
from . import train as trainer
|
||||
short = json.loads(json.dumps(cfg))
|
||||
short["optim"]["steps"] = 2
|
||||
short["optim"]["log_every"] = 1
|
||||
short["eval"]["n"] = 12
|
||||
m1 = trainer.run(short, verbose=False)
|
||||
ckpt = os.path.join(short["out_dir"], "ckpt.pt")
|
||||
if not os.path.exists(ckpt):
|
||||
results.append(_fail("checkpoint not written"))
|
||||
elif os.path.exists(ckpt + ".tmp"):
|
||||
results.append(_fail("temporary checkpoint left behind"))
|
||||
else:
|
||||
print(f"ok checkpoint written atomically, val answer_acc {m1['answer_acc']:.2f}")
|
||||
|
||||
from . import train as trainer2
|
||||
m2 = trainer2.run(short, resume=True, steps=1, verbose=False)
|
||||
_, _, step, _ = trainer2.load(ckpt)
|
||||
if step != 3:
|
||||
results.append(_fail(f"resume advanced to step {step}, expected 3"))
|
||||
else:
|
||||
print(f"ok resume continued at step {step} (2 + 1)")
|
||||
|
||||
print("---")
|
||||
if all(results):
|
||||
print("smoke PASS")
|
||||
return 0
|
||||
print("smoke FAIL")
|
||||
return 1
|
||||
|
||||
|
||||
def cmd_train(args) -> int:
|
||||
from . import train as trainer
|
||||
cfg = _load_config(args.config)
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}"
|
||||
trainer.run(cfg, resume=args.resume, steps=args.steps)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_eval(args) -> int:
|
||||
from . import train as trainer
|
||||
cfg = _load_config(args.config)
|
||||
if args.seed is not None:
|
||||
cfg["seed"] = args.seed
|
||||
cfg["out_dir"] = f"{cfg['out_dir']}_s{args.seed}"
|
||||
model, _, step, cfg = trainer.load(os.path.join(cfg["out_dir"], "ckpt.pt"))
|
||||
for split in ("train", "val", "test"):
|
||||
fams = cfg["data"][f"{split}_families"]
|
||||
m = trainer.evaluate(model, fams, cfg["seed"], cfg["eval"]["n"])
|
||||
print(f"{split:5s} " + json.dumps({k: (round(v, 3) if isinstance(v, float) else v)
|
||||
for k, v in m.items() if k != "loss"}))
|
||||
print(f"step {step}")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_report(args) -> int:
|
||||
from . import report
|
||||
report.report(args.config, n=args.n, ablate=args.ablate, seed=args.seed)
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
p = argparse.ArgumentParser(prog="spatial")
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
for name, fn in (("smoke", cmd_smoke), ("train", cmd_train), ("eval", cmd_eval),
|
||||
("report", cmd_report)):
|
||||
sp = sub.add_parser(name)
|
||||
sp.add_argument("--config", default=os.path.join(os.path.dirname(__file__), "configs", "smoke.json"))
|
||||
sp.add_argument("--seed", type=int, default=None,
|
||||
help="override config seed (data and init both follow it)")
|
||||
if name != "eval":
|
||||
sp.add_argument("--steps", type=int, default=None)
|
||||
if name == "train":
|
||||
sp.add_argument("--resume", action="store_true")
|
||||
if name == "report":
|
||||
sp.add_argument("--n", type=int, default=128)
|
||||
sp.add_argument("--ablate", default=None,
|
||||
choices=[None, "dangling", "scene", "edge_feat", "dangling,scene"])
|
||||
sp.set_defaults(fn=fn)
|
||||
args = p.parse_args(argv)
|
||||
return args.fn(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -11,6 +11,13 @@
|
||||
| `setonly.json` | 只训 `dof.set`,隔离"六个轴是否全覆盖"这个子技能 | 1.000(用于定位读出缺陷) |
|
||||
| `cross_oneshot.json` | 对照:第一版混合集,被一位规则完全可分 | 6 族与平凡规则逐位相同 |
|
||||
|
||||
## 不进 split 的家族
|
||||
|
||||
`area.gap1/gap2/gap4` 是**单答案家族**(恒 false),常量规则就能拿 1.000,加进任何
|
||||
split 都会造出一个假满分。它们只做 `spatial.extract` 的回归测试:把上块抬离底座
|
||||
1/2/4 格,问提取器会不会焊出一条不存在的接触。同理 `smoke` 每次都会打印"哪些家族
|
||||
没被任何 split 使用",加家族时先看那行。
|
||||
|
||||
## 归档(`archive/`)
|
||||
|
||||
| 文件 | 当时的用途 | 留下它的理由 |
|
||||
|
||||
+393
-346
@@ -1,346 +1,393 @@
|
||||
"""几何 → 关系图:提取器,以及它证明不出来的东西。
|
||||
|
||||
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
|
||||
|
||||
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 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.
|
||||
"""
|
||||
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, 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 = 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)
|
||||
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("真边 = 观测里的关系数;提取 = 只看几何能得到的关系数(共面精确匹配)")
|
||||
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, 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 col in cols:
|
||||
got = forged = total = 0
|
||||
for i in range(n):
|
||||
sc = generator.make(fam, seed=7, index=i)
|
||||
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
|
||||
if tp:
|
||||
got += 1
|
||||
forged += int(checker.validate_evidence(
|
||||
world, Query(kind="stability", a="T"), [tp[0].eid]))
|
||||
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("miss = 间隙为 0 却没提取到(该报的没报)")
|
||||
print("- = 间隙 > 0,没有提取到边(正确)")
|
||||
print("? = 间隙 > 0 却提取到边,但凭证校验按几何拒了它(图错了,校验器救了)")
|
||||
print("! = 假边通过了凭证校验 —— 图错,而且这个错还能当证明用")
|
||||
print("间隙单位 0.25mm;真实装配的余隙是 0.2mm 级,即约 1 格")
|
||||
print("距离法在这一格上分辨不了;共面法只需要 eps 盖住浮点噪声,0.25 那列是把")
|
||||
print("eps 当容差用的滥用,旧坑原样回来 —— 这也是为什么它只是数值兜底。")
|
||||
|
||||
|
||||
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())
|
||||
"""几何 → 关系图:提取器,以及它证明不出来的东西。
|
||||
|
||||
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"
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
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())
|
||||
@@ -170,8 +170,14 @@ def _build_stability(rng, n_blocks: int, hidden: int, free: int = 0, notch: int
|
||||
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("kPT", "contact", "T", "P"),
|
||||
Edge("kDG", "contact", "D", "G")]
|
||||
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",
|
||||
|
||||
Reference in new issue
Block a user