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
import sys
def _die(msg: str) -> None:
print(f"ERROR {msg}")
print(" 这个模块需要 pcbnew(KiCad 的 Python 绑定),只能在装了 KiCad 的机器上跑。")
def _pcbnew():
try:
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):
for pad in board.GetPads():
yield pad
return list(board.GetPads())
def _ref(pad) -> str:
"""Footprint reference. ``GetParent()`` returns a container, not a footprint
(measured on KiCad 10.0.6), so the accessor is ``GetParentFootprint``."""
try:
return pad.GetParentFootprint().GetReference()
except Exception:
return "?"
return pad.GetParentFootprint().GetReference()
def _ratsnest(board, code: int) -> int:
"""How many connections inside this net are not yet realised in copper."""
try:
return len(board.GetConnectivity().GetRatsnestForNet(code))
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 _missing(board) -> int:
"""Copper connections the board still owes. No swallowing: if this raises,
the measurement failed and must not be printed as zero."""
return int(board.GetConnectivity().GetUnconnectedCount(False))
def report(paths) -> None:
try:
import pcbnew
except Exception:
_die("pcbnew 不可用")
return
print(f"{'board':24s} {'焊盘':>5s} {'有网':>5s} {'无网':>5s} {'网数':>4s} "
f"{'未布通':>6s} {'未布网':>6s} {'悬空对':>6s}")
print("-" * 66)
pcbnew = _pcbnew()
print(f"{'board':26s} {'焊盘':>5s} {'有网':>5s} {'无网':>5s} {'网数':>4s} {'缺连接':>6s}")
print("-" * 56)
for path in paths:
board = pcbnew.LoadBoard(path)
try:
board.BuildConnectivity()
except Exception:
pass
pads = list(_pads(board))
board.BuildConnectivity()
pads = _pads(board)
with_net = [p for p in pads if p.GetNetCode() != 0]
codes = sorted({p.GetNetCode() for p in with_net})
unrouted, dangling = 0, 0
for code in codes:
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}")
codes = {p.GetNetCode() for p in with_net}
print(f"{path.rsplit('/', 1)[-1]:26s} {len(pads):5d} {len(with_net):5d} "
f"{len(pads) - len(with_net):5d} {len(codes):4d} {_missing(board):6d}")
print()
print("焊盘 = 板上所有封装焊盘;有网 = 归属某条网的;无网 = netcode 0(机械脚/未标注)")
print("未布通 = 网内还有未连通的连接(老鼠线)的网数;悬空对 = 这些网里缺的连接数")
print()
print("'未布网' 与 '未布通' 同列是笔误吗——不是:前者是网表里根本不存在这条网,")
print("后者是网存在但铜没连完。两种都由 ratsnest 读出,这里按网数统一计数。")
print("焊盘 = 板上所有封装焊盘;有网 = 归属某条网的;无网 = netcode 0(无编号机械焊盘)")
print("缺连接 = 铜箔还没连上的连接数。0 表示这份板子与网表在连通性上没有冲突。")
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
mechanical pads never appear in a net. So "the netlist described everything"
is false by construction, and the size of the lie is exactly this count.
Measured, not assumed. The first guess was "a netlist never mentions NC pins
or mechanical pads". Half wrong: KiCad gives every no-connect pin its own
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:
import pcbnew
from . import kicad_netlist
except Exception:
_die("pcbnew 不可用")
return
pcbnew = _pcbnew()
from . import kicad_netlist
nl = kicad_netlist.load(netlist_path)
named = {(r, p) for r, p in nl.nodes()}
board = pcbnew.LoadBoard(board_path)
pads = list(_pads(board))
pads = _pads(board)
pad_keys = {(_ref(p), p.GetNumber()) for p in pads}
missing = pad_keys - named
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, "
f"{len(nl.comps)} parts")
print(f"板上有、网表没提:{len(missing)} ({len(missing) / max(1, len(pad_keys)):.1%} 的焊盘)")
print(f"网表提了、板上没有:{len(extra)} (网表与板子版本不一致时会非零)")
print(f"板上有、网表没提:{len(missing)} "
f"({len(missing) / max(1, len(pad_keys)):.1%} of pads)")
print(f"网表提了、板上没有:{len(extra)} (非零 = 网表与板子版本不一致)")
if missing:
sample = sorted(missing)[:8]
print(f" 举例:{sample}")
print(f" 举例:{sorted(missing)[:8]}")
print()
print("这个数是 netlist provider 的盲区大小,而且**只能**由知道封装的那一侧算出。")
print("它正好是 scope 契约里'清单比交付多'的实物版本:网表交出的东西比板子少。")
print("这就是 netlist provider 的盲区,而且只能由知道封装的一侧算出来。")
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
metric that always returns zero has not been tested. This removes the tracks
of one small net and shows the count go up. If it does not, the detector is
reading the wrong thing and every "0" above is meaningless.
metric that only ever returns zero has not been tested. This removes the
tracks of one small net and demands the count go up.
"""
try:
import pcbnew
except Exception:
_die("pcbnew 不可用")
return
pcbnew = _pcbnew()
board = pcbnew.LoadBoard(board_path)
try:
board.BuildConnectivity()
except Exception:
pass
before = _unrouted(board)
board.BuildConnectivity()
before = _missing(board)
per_net = {}
for t in board.GetTracks():
code = t.GetNetCode()
if code:
per_net.setdefault(code, []).append(t)
for track in board.GetTracks():
if track.GetNetCode():
per_net.setdefault(track.GetNetCode(), []).append(track)
if not per_net:
print("no tracks on this board")
return
@@ -159,16 +129,17 @@ def control(board_path: str) -> None:
net = board.FindNet(code)
name = net.GetNetname() if net else str(code)
cut = len(per_net[code])
for t in per_net[code]:
board.Remove(t)
for track in per_net[code]:
board.Remove(track)
board.BuildConnectivity()
after = _unrouted(board)
after = _missing(board)
print(f"control on {board_path.rsplit('/', 1)[-1]}")
print(f" cut net {name!r}: removed {cut} track(s)")
print(f" before: {before[0]} nets broken, {before[1]} missing connections")
print(f" after : {after[0]} nets broken, {after[1]} missing connections")
ok = after[1] > before[1]
print(f" cut net {name!r}: removed {cut} track(s), "
f"{len([p for p in _pads(board) if p.GetNetCode() == code])} pads on it")
print(f" missing before: {before}")
print(f" missing after : {after}")
ok = after > before
print(f" {'PASS' if ok else 'FAIL'} the detector "
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:
argv = list(sys.argv[1:] if argv is None else argv)
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:
coverage(argv[0], argv[1])
elif argv:
report(argv)
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>")
return 2
return 0