fix(spatial): 未连通计数不再用 except 兜成 0;纠正网表盲区的说法

This commit is contained in:
liuhuajie committed 2026-12-04 00:51:46 +08:00
1 parent d296acd34e
commit 4fcb4f2372
2 files changed
+90 -115

No files matched your search

+81 -107
View File
@@ -5,153 +5,123 @@
* 网表说的是**意图**:原理图上这两个脚属于同一条网。 * 网表说的是**意图**:原理图上这两个脚属于同一条网。
* 板子说的是**现实**:铜箔、焊盘、过孔是不是真的把它们接通了。 * 板子说的是**现实**:铜箔、焊盘、过孔是不是真的把它们接通了。
两者在成品板上一致,在布线未完成的板上不一致。这个不一致不是 bug,是这类系统 成品板上两者一致,半布线的板上不一致。这个不一致不是 bug,是这类系统必须能表达
必须能表达的东西:一份来源说"连上了",另一份说"没连上",而正确答案是**不知道** 的东西:一份来源说"连上了",另一份说"没连上",正确结论是**不知道**,除非有第三方
——除非有第三方信息(比如网表版本比板子新,或板子本来就是半成品)。 信息(哪份更新、这块板本来就是半成品)。
``spatial/checker.py`` 现在没有"两份来源冲突"这个概念,只有"缺了东西"。所以这个 ``spatial/checker.py`` 目前没有"两份来源冲突"这个概念,只有"缺了东西"。所以这里先
模块先只做测量:把冲突数出来,再决定要不要、以及怎么把它接进契约。 只做测量,把冲突数数出来,再决定要不要、以及怎么把它接进契约。
用法(服务器):``python3 -m spatial.providers.kicad_board <a.kicad_pcb> ...`` 用法(服务器)::
python3 -m spatial.providers.kicad_board <a.kicad_pcb> ...
python3 -m spatial.providers.kicad_board <a.kicad_pcb> <a.net> # 覆盖度
python3 -m spatial.providers.kicad_board control <a.kicad_pcb> # 阳性对照
关于"按网统计":``GetRatsnestForNet`` 在这个绑定里返回不透明对象(取不到长度),
``RunOnUnconnectedEdges`` 要的是 C++ 的 ``std::function``,传不了 Python 回调
(都在 KiCad 10.0.6 上实测过)。所以只报板级总数,不报"哪条网断了"——要那个就得
自己重写一遍连通性,不值得。
一条硬规矩:**这里没有 ``except`` 兜底**。第一版写了 ``try/except`` 返回 -1,而调用
方用 ``> 0`` 判断,于是所有失败都变成了"0 条未连通",报告上看起来完美。阳性对照
(删掉一条网的铜,看数字动不动)把这个洞捅了出来,见 :func:`control`。
""" """
from __future__ import annotations from __future__ import annotations
import sys import sys
def _die(msg: str) -> None: def _pcbnew():
print(f"ERROR {msg}") try:
print(" 这个模块需要 pcbnew(KiCad 的 Python 绑定),只能在装了 KiCad 的机器上跑。") import pcbnew
except Exception as exc: # noqa: BLE001 - reported, not hidden
raise SystemExit(
"this module needs pcbnew (KiCad's Python bindings); "
f"import failed with {type(exc).__name__}: {exc}")
return pcbnew
def _pads(board): def _pads(board):
for pad in board.GetPads(): return list(board.GetPads())
yield pad
def _ref(pad) -> str: def _ref(pad) -> str:
"""Footprint reference. ``GetParent()`` returns a container, not a footprint """Footprint reference. ``GetParent()`` returns a container, not a footprint
(measured on KiCad 10.0.6), so the accessor is ``GetParentFootprint``.""" (measured on KiCad 10.0.6), so the accessor is ``GetParentFootprint``."""
try: return pad.GetParentFootprint().GetReference()
return pad.GetParentFootprint().GetReference()
except Exception:
return "?"
def _ratsnest(board, code: int) -> int: def _missing(board) -> int:
"""How many connections inside this net are not yet realised in copper.""" """Copper connections the board still owes. No swallowing: if this raises,
try: the measurement failed and must not be printed as zero."""
return len(board.GetConnectivity().GetRatsnestForNet(code)) return int(board.GetConnectivity().GetUnconnectedCount(False))
except Exception:
return -1
def _unrouted(board) -> tuple:
"""(nets with a break, total missing copper connections) over the whole board."""
codes = sorted({p.GetNetCode() for p in _pads(board) if p.GetNetCode() != 0})
bad = pairs = 0
for code in codes:
n = _ratsnest(board, code)
if n > 0:
bad += 1
pairs += n
return bad, pairs
def report(paths) -> None: def report(paths) -> None:
try: pcbnew = _pcbnew()
import pcbnew print(f"{'board':26s} {'焊盘':>5s} {'有网':>5s} {'无网':>5s} {'网数':>4s} {'缺连接':>6s}")
except Exception: print("-" * 56)
_die("pcbnew 不可用")
return
print(f"{'board':24s} {'焊盘':>5s} {'有网':>5s} {'无网':>5s} {'网数':>4s} "
f"{'未布通':>6s} {'未布网':>6s} {'悬空对':>6s}")
print("-" * 66)
for path in paths: for path in paths:
board = pcbnew.LoadBoard(path) board = pcbnew.LoadBoard(path)
try: board.BuildConnectivity()
board.BuildConnectivity() pads = _pads(board)
except Exception:
pass
pads = list(_pads(board))
with_net = [p for p in pads if p.GetNetCode() != 0] with_net = [p for p in pads if p.GetNetCode() != 0]
codes = sorted({p.GetNetCode() for p in with_net}) codes = {p.GetNetCode() for p in with_net}
unrouted, dangling = 0, 0 print(f"{path.rsplit('/', 1)[-1]:26s} {len(pads):5d} {len(with_net):5d} "
for code in codes: f"{len(pads) - len(with_net):5d} {len(codes):4d} {_missing(board):6d}")
n = _ratsnest(board, code)
if n > 0:
unrouted += 1
dangling += n
print(f"{path.rsplit('/', 1)[-1]:24s} {len(pads):5d} {len(with_net):5d} "
f"{len(pads) - len(with_net):5d} {len(codes):4d} {unrouted:6d} "
f"{unrouted:6d} {dangling:6d}")
print() print()
print("焊盘 = 板上所有封装焊盘;有网 = 归属某条网的;无网 = netcode 0(机械脚/未标注)") print("焊盘 = 板上所有封装焊盘;有网 = 归属某条网的;无网 = netcode 0(无编号机械焊盘)")
print("未布通 = 网内还有未连通的连接(老鼠线)的网数;悬空对 = 这些网里缺的连接数") print("缺连接 = 铜箔还没连上的连接数。0 表示这份板子与网表在连通性上没有冲突。")
print()
print("'未布网' 与 '未布通' 同列是笔误吗——不是:前者是网表里根本不存在这条网,")
print("后者是网存在但铜没连完。两种都由 ratsnest 读出,这里按网数统一计数。")
def coverage(board_path: str, netlist_path: str) -> None: def coverage(board_path: str, netlist_path: str) -> None:
"""The number the netlist provider could not compute: pads it never mentions. """How big the netlist provider's blind spot actually is.
A footprint has more pads than the netlist names -- no-connect pins and Measured, not assumed. The first guess was "a netlist never mentions NC pins
mechanical pads never appear in a net. So "the netlist described everything" or mechanical pads". Half wrong: KiCad gives every no-connect pin its own
is false by construction, and the size of the lie is exactly this count. single-node net, so NC pins *are* covered. What falls through are pads with
an empty pad number -- mounting holes and shield pads -- 0 to 0.7% of a board.
""" """
try: pcbnew = _pcbnew()
import pcbnew from . import kicad_netlist
from . import kicad_netlist
except Exception:
_die("pcbnew 不可用")
return
nl = kicad_netlist.load(netlist_path) nl = kicad_netlist.load(netlist_path)
named = {(r, p) for r, p in nl.nodes()} named = {(r, p) for r, p in nl.nodes()}
board = pcbnew.LoadBoard(board_path) board = pcbnew.LoadBoard(board_path)
pads = list(_pads(board)) pads = _pads(board)
pad_keys = {(_ref(p), p.GetNumber()) for p in pads} pad_keys = {(_ref(p), p.GetNumber()) for p in pads}
missing = pad_keys - named missing = pad_keys - named
extra = named - pad_keys extra = named - pad_keys
print(f"board {board_path.rsplit('/', 1)[-1]}: {len(pads)} pads") print(f"board {board_path.rsplit('/', 1)[-1]}: {len(pads)} pads, "
f"{len({_ref(p) for p in pads})} footprints")
print(f"netlist {netlist_path.rsplit('/', 1)[-1]}: {len(named)} named pads, " print(f"netlist {netlist_path.rsplit('/', 1)[-1]}: {len(named)} named pads, "
f"{len(nl.comps)} parts") f"{len(nl.comps)} parts")
print(f"板上有、网表没提:{len(missing)} ({len(missing) / max(1, len(pad_keys)):.1%} 的焊盘)") print(f"板上有、网表没提:{len(missing)} "
print(f"网表提了、板上没有:{len(extra)} (网表与板子版本不一致时会非零)") f"({len(missing) / max(1, len(pad_keys)):.1%} of pads)")
print(f"网表提了、板上没有:{len(extra)} (非零 = 网表与板子版本不一致)")
if missing: if missing:
sample = sorted(missing)[:8] print(f" 举例:{sorted(missing)[:8]}")
print(f" 举例:{sample}")
print() print()
print("这个数是 netlist provider 的盲区大小,而且**只能**由知道封装的那一侧算出。") print("这就是 netlist provider 的盲区,而且只能由知道封装的一侧算出来。")
print("它正好是 scope 契约里'清单比交付多'的实物版本:网表交出的东西比板子少。")
def control(board_path: str) -> None: def control(board_path: str) -> None:
"""Positive control: cut one net's copper and check the detector notices. """Positive control: cut one net's copper, require the detector to notice.
Every demo board is fully routed, so the disagreement count is zero -- and a Every demo board is fully routed, so the disagreement count is zero -- and a
metric that always returns zero has not been tested. This removes the tracks metric that only ever returns zero has not been tested. This removes the
of one small net and shows the count go up. If it does not, the detector is tracks of one small net and demands the count go up.
reading the wrong thing and every "0" above is meaningless.
""" """
try: pcbnew = _pcbnew()
import pcbnew
except Exception:
_die("pcbnew 不可用")
return
board = pcbnew.LoadBoard(board_path) board = pcbnew.LoadBoard(board_path)
try: board.BuildConnectivity()
board.BuildConnectivity() before = _missing(board)
except Exception:
pass
before = _unrouted(board)
per_net = {} per_net = {}
for t in board.GetTracks(): for track in board.GetTracks():
code = t.GetNetCode() if track.GetNetCode():
if code: per_net.setdefault(track.GetNetCode(), []).append(track)
per_net.setdefault(code, []).append(t)
if not per_net: if not per_net:
print("no tracks on this board") print("no tracks on this board")
return return
@@ -159,16 +129,17 @@ def control(board_path: str) -> None:
net = board.FindNet(code) net = board.FindNet(code)
name = net.GetNetname() if net else str(code) name = net.GetNetname() if net else str(code)
cut = len(per_net[code]) cut = len(per_net[code])
for t in per_net[code]: for track in per_net[code]:
board.Remove(t) board.Remove(track)
board.BuildConnectivity() board.BuildConnectivity()
after = _unrouted(board) after = _missing(board)
print(f"control on {board_path.rsplit('/', 1)[-1]}") print(f"control on {board_path.rsplit('/', 1)[-1]}")
print(f" cut net {name!r}: removed {cut} track(s)") print(f" cut net {name!r}: removed {cut} track(s), "
print(f" before: {before[0]} nets broken, {before[1]} missing connections") f"{len([p for p in _pads(board) if p.GetNetCode() == code])} pads on it")
print(f" after : {after[0]} nets broken, {after[1]} missing connections") print(f" missing before: {before}")
ok = after[1] > before[1] print(f" missing after : {after}")
ok = after > before
print(f" {'PASS' if ok else 'FAIL'} the detector " print(f" {'PASS' if ok else 'FAIL'} the detector "
f"{'notices' if ok else 'did NOT notice'} the cut") f"{'notices' if ok else 'did NOT notice'} the cut")
@@ -176,13 +147,16 @@ def control(board_path: str) -> None:
def main(argv=None) -> int: def main(argv=None) -> int:
argv = list(sys.argv[1:] if argv is None else argv) argv = list(sys.argv[1:] if argv is None else argv)
if argv and argv[0] == "control": if argv and argv[0] == "control":
control(argv[1] if len(argv) > 1 else "") if len(argv) < 2:
print("usage: kicad_board control <a.kicad_pcb>")
return 2
control(argv[1])
elif len(argv) == 2: elif len(argv) == 2:
coverage(argv[0], argv[1]) coverage(argv[0], argv[1])
elif argv: elif argv:
report(argv) report(argv)
else: else:
print("usage: kicad_board <a.kicad_pcb> ... | kicad_board <pcb> <net> | " print("usage: kicad_board <pcb>... | kicad_board <pcb> <net> | "
"kicad_board control <pcb>") "kicad_board control <pcb>")
return 2 return 2
return 0 return 0
+9 -8
View File
@@ -13,11 +13,13 @@ M2 的契约说得很清楚:`conduct` 这类关系在几何里没有签名,
边。用生成树也能让可达性一样,但那样"这两个脚是同一张铜"这个事实就没了, 边。用生成树也能让可达性一样,但那样"这两个脚是同一张铜"这个事实就没了,
而模型的边特征正是靠它。 而模型的边特征正是靠它。
**三、网表不告诉你它漏了什么。** 一个封装有 8 个脚,网表可能只提到 2 个 **三、网表对它自己的覆盖程度是沉默的。** 一开始的猜测是"网表不提 NC 脚和机械脚",
(NC 脚、机械脚、被 exclude 的脚都不出现)。这个盲区在意料之中,但**无法** 在 KiCad 10.0.6 上实测**只对了一半**:KiCad 给每个 NC 脚单独建一条单点网
从网表本身算出来:它需要一个知道封装有几个脚的来源。所以 ``scope`` 在这里 (名字形如 ``unconnected-(U1-Pad7)``),所以 NC 脚是覆盖的;真正漏掉的是**没有
只能是"这份网表描述的就是全部",真正的缺口留给板子/封装库那个 provider 去说。 焊盘编号的机械焊盘**(安装孔、晶振屏蔽脚),占一块板的 0–0.7%。
报告里把这条单独列出来,不许悄悄当成"没有"。
这个空白有多大,只能拿板子那一侧来量(``kicad_board.coverage``),网表自己算不出来。
所以 ``scope`` 在这里只能声明"这份网表描述的就是全部",缺口留给另一份来源。
""" """
from __future__ import annotations from __future__ import annotations
@@ -143,9 +145,8 @@ def report(paths) -> None:
print("最大网 = 节点最多的那条网的节点数") print("最大网 = 节点最多的那条网的节点数")
print("无器件节点 = 出现在网里、但没有器件条目的节点(网表自相矛盾)") print("无器件节点 = 出现在网里、但没有器件条目的节点(网表自相矛盾)")
print() print()
print("没测的:封装到底有几个脚。网表不提 NC 脚和机械脚,所以'这个器件还有脚没被") print("单点网不是缺陷:KiCad 给每个 NC 脚单独建一条网,正是'这个脚什么也没连'的")
print("描述'这件事无法从网表本身算出来,必须由知道封装的那个来源声明。这条是空着") print("显式说法。真正漏掉的是无编号机械焊盘,实测占 0-0.7%(见 kicad_board 覆盖度)。")
print("的,不是零。")
def main(argv=None) -> int: def main(argv=None) -> int: