From 4fcb4f23727ab7ee5410a355d808d38228314223 Mon Sep 17 00:00:00 2001 From: lhj <403133128@qq.com> Date: Fri, 4 Dec 2026 00:51:46 +0800 Subject: [PATCH] =?UTF-8?q?fix(spatial):=20=E6=9C=AA=E8=BF=9E=E9=80=9A?= =?UTF-8?q?=E8=AE=A1=E6=95=B0=E4=B8=8D=E5=86=8D=E7=94=A8=20except=20?= =?UTF-8?q?=E5=85=9C=E6=88=90=200=EF=BC=9B=E7=BA=A0=E6=AD=A3=E7=BD=91?= =?UTF-8?q?=E8=A1=A8=E7=9B=B2=E5=8C=BA=E7=9A=84=E8=AF=B4=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spatial/providers/kicad_board.py | 188 +++++++++++++---------------- spatial/providers/kicad_netlist.py | 17 +-- 2 files changed, 90 insertions(+), 115 deletions(-) diff --git a/spatial/providers/kicad_board.py b/spatial/providers/kicad_board.py index a99453c..11ef830 100644 --- a/spatial/providers/kicad_board.py +++ b/spatial/providers/kicad_board.py @@ -5,153 +5,123 @@ * 网表说的是**意图**:原理图上这两个脚属于同一条网。 * 板子说的是**现实**:铜箔、焊盘、过孔是不是真的把它们接通了。 -两者在成品板上一致,在布线未完成的板上不一致。这个不一致不是 bug,是这类系统 -必须能表达的东西:一份来源说"连上了",另一份说"没连上",而正确答案是**不知道** -——除非有第三方信息(比如网表版本比板子新,或板子本来就是半成品)。 +成品板上两者一致,半布线的板上不一致。这个不一致不是 bug,是这类系统必须能表达 +的东西:一份来源说"连上了",另一份说"没连上",正确结论是**不知道**,除非有第三方 +信息(哪份更新、这块板本来就是半成品)。 -``spatial/checker.py`` 现在没有"两份来源冲突"这个概念,只有"缺了东西"。所以这个 -模块先只做测量:把冲突数出来,再决定要不要、以及怎么把它接进契约。 +``spatial/checker.py`` 目前没有"两份来源冲突"这个概念,只有"缺了东西"。所以这里先 +只做测量,把冲突数数出来,再决定要不要、以及怎么把它接进契约。 -用法(服务器):``python3 -m spatial.providers.kicad_board ...`` +用法(服务器):: + + python3 -m spatial.providers.kicad_board ... + python3 -m spatial.providers.kicad_board # 覆盖度 + python3 -m spatial.providers.kicad_board control # 阳性对照 + +关于"按网统计":``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 ") + return 2 + control(argv[1]) elif len(argv) == 2: coverage(argv[0], argv[1]) elif argv: report(argv) else: - print("usage: kicad_board ... | kicad_board | " + print("usage: kicad_board ... | kicad_board | " "kicad_board control ") return 2 return 0 diff --git a/spatial/providers/kicad_netlist.py b/spatial/providers/kicad_netlist.py index 28e21ef..a9bc7c6 100644 --- a/spatial/providers/kicad_netlist.py +++ b/spatial/providers/kicad_netlist.py @@ -13,11 +13,13 @@ M2 的契约说得很清楚:`conduct` 这类关系在几何里没有签名, 边。用生成树也能让可达性一样,但那样"这两个脚是同一张铜"这个事实就没了, 而模型的边特征正是靠它。 -**三、网表不告诉你它漏了什么。** 一个封装有 8 个脚,网表可能只提到 2 个 -(NC 脚、机械脚、被 exclude 的脚都不出现)。这个盲区在意料之中,但**无法** -从网表本身算出来:它需要一个知道封装有几个脚的来源。所以 ``scope`` 在这里 -只能是"这份网表描述的就是全部",真正的缺口留给板子/封装库那个 provider 去说。 -报告里把这条单独列出来,不许悄悄当成"没有"。 +**三、网表对它自己的覆盖程度是沉默的。** 一开始的猜测是"网表不提 NC 脚和机械脚", +在 KiCad 10.0.6 上实测**只对了一半**:KiCad 给每个 NC 脚单独建一条单点网 +(名字形如 ``unconnected-(U1-Pad7)``),所以 NC 脚是覆盖的;真正漏掉的是**没有 +焊盘编号的机械焊盘**(安装孔、晶振屏蔽脚),占一块板的 0–0.7%。 + +这个空白有多大,只能拿板子那一侧来量(``kicad_board.coverage``),网表自己算不出来。 +所以 ``scope`` 在这里只能声明"这份网表描述的就是全部",缺口留给另一份来源。 """ from __future__ import annotations @@ -143,9 +145,8 @@ def report(paths) -> None: print("最大网 = 节点最多的那条网的节点数") print("无器件节点 = 出现在网里、但没有器件条目的节点(网表自相矛盾)") print() - print("没测的:封装到底有几个脚。网表不提 NC 脚和机械脚,所以'这个器件还有脚没被") - print("描述'这件事无法从网表本身算出来,必须由知道封装的那个来源声明。这条是空着") - print("的,不是零。") + print("单点网不是缺陷:KiCad 给每个 NC 脚单独建一条网,正是'这个脚什么也没连'的") + print("显式说法。真正漏掉的是无编号机械焊盘,实测占 0-0.7%(见 kicad_board 覆盖度)。") def main(argv=None) -> int: