163 lines
6.8 KiB
Python
163 lines
6.8 KiB
Python
"""KiCad 网表 → Observation:第一个真实的元数据 provider。
|
|
|
|
M2 的契约说得很清楚:`conduct` 这类关系在几何里没有签名,只能来自元数据。
|
|
这个模块就是那份元数据——KiCad 导出的网表——到 `Observation` 的翻译层。
|
|
|
|
三件事要在这里说清楚,因为它们决定了这个 provider 能回答什么、不能回答什么:
|
|
|
|
**一、网表只有拓扑,没有几何。** 文件里没有坐标,所以翻译出来的实体没有
|
|
``box``,接触关系一条也提不出来。这不是缺陷,是分工:几何来自另一台相机/另一份
|
|
导出,两者在 ``Observation`` 这一层汇合。
|
|
|
|
**二、同一条网 = 两两连通。** 一个网里有 k 个节点就生成 k(k-1)/2 条 conduct
|
|
边。用生成树也能让可达性一样,但那样"这两个脚是同一张铜"这个事实就没了,
|
|
而模型的边特征正是靠它。
|
|
|
|
**三、网表对它自己的覆盖程度是沉默的。** 一开始的猜测是"网表不提 NC 脚和机械脚",
|
|
在 KiCad 10.0.6 上实测**只对了一半**:KiCad 给每个 NC 脚单独建一条单点网
|
|
(名字形如 ``unconnected-(U1-Pad7)``),所以 NC 脚是覆盖的;真正漏掉的是**没有
|
|
焊盘编号的机械焊盘**(安装孔、晶振屏蔽脚),占一块板的 0–0.7%。
|
|
|
|
这个空白有多大,只能拿板子那一侧来量(``kicad_board.coverage``),网表自己算不出来。
|
|
所以 ``scope`` 在这里只能声明"这份网表描述的就是全部",缺口留给另一份来源。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
from dataclasses import dataclass, field
|
|
|
|
from ..schema import Edge, Entity, Observation
|
|
from . import sexpr
|
|
|
|
GENERATED_BY = "kicad-netlist"
|
|
|
|
|
|
@dataclass
|
|
class Net:
|
|
code: str
|
|
name: str
|
|
nodes: list = field(default_factory=list) # [(ref, pin), ...]
|
|
|
|
|
|
@dataclass
|
|
class Netlist:
|
|
comps: dict = field(default_factory=dict) # ref -> {value, footprint}
|
|
nets: list = field(default_factory=list)
|
|
|
|
def nodes(self) -> list:
|
|
seen, out = set(), []
|
|
for net in self.nets:
|
|
for ref, pin in net.nodes:
|
|
key = (ref, pin)
|
|
if key not in seen:
|
|
seen.add(key)
|
|
out.append(key)
|
|
return out
|
|
|
|
|
|
def load(path: str) -> Netlist:
|
|
with open(path, encoding="utf-8") as f:
|
|
tree = sexpr.parse(f.read())
|
|
root = tree[0] if tree else []
|
|
if not isinstance(root, list) or root[0] != "export":
|
|
raise ValueError(f"{path}: not a KiCad netlist export")
|
|
|
|
comps = {}
|
|
for comp in sexpr.find_all(sexpr.find(root, "components"), "comp"):
|
|
ref = sexpr.value(comp, "ref")
|
|
if ref is None:
|
|
continue
|
|
comps[ref] = {"value": sexpr.value(comp, "value", ""),
|
|
"footprint": sexpr.value(comp, "footprint", "")}
|
|
|
|
nets = []
|
|
for net in sexpr.find_all(sexpr.find(root, "nets"), "net"):
|
|
nodes = []
|
|
for node in sexpr.find_all(net, "node"):
|
|
ref, pin = sexpr.value(node, "ref"), sexpr.value(node, "pin")
|
|
if ref is not None and pin is not None:
|
|
nodes.append((ref, pin))
|
|
nets.append(Net(code=sexpr.value(net, "code", "0"),
|
|
name=sexpr.value(net, "name", ""), nodes=nodes))
|
|
return Netlist(comps=comps, nets=nets)
|
|
|
|
|
|
def _eid(ref: str, pin: str) -> str:
|
|
return f"{ref}.{pin}"
|
|
|
|
|
|
def to_observation(nl: Netlist) -> Observation:
|
|
"""The netlist as an observation: pads plus pairwise conduct edges."""
|
|
entities, edges = [], []
|
|
for ref, pin in nl.nodes():
|
|
entities.append(Entity(_eid(ref, pin), "pad", source=GENERATED_BY,
|
|
attrs={"ref": ref, "pin": pin}))
|
|
# nothing else: a netlist carries no coordinates, and inventing them
|
|
# would make the geometry provider's disagreement invisible
|
|
for net in nl.nets:
|
|
for i in range(len(net.nodes)):
|
|
for j in range(i + 1, len(net.nodes)):
|
|
a = _eid(*net.nodes[i])
|
|
b = _eid(*net.nodes[j])
|
|
edges.append(Edge(f"n{net.code}_{i}_{j}", "conduct", a, b,
|
|
source=GENERATED_BY, attrs={"net": net.name}))
|
|
scope = {
|
|
"parts": {"part": len(nl.comps)} if nl.comps else {},
|
|
"rendered": {"part": len(nl.comps)} if nl.comps else {},
|
|
"relations": {"conduct": len(edges)},
|
|
"rendered_relations": {"conduct": len(edges)},
|
|
"layers": [],
|
|
"rendered_layers": [],
|
|
}
|
|
return Observation(entities=entities, edges=edges, scope=scope,
|
|
units={"length": "mm", "per_unit": 1})
|
|
|
|
|
|
def report(paths) -> None:
|
|
"""What a netlist can and cannot say, per file.
|
|
|
|
The interesting numbers are not "did the translation work" -- the edges are
|
|
built from the same membership they are checked against, so that part is a
|
|
construction. What is worth measuring is what the file leaves out:
|
|
|
|
``单点网`` are nets with exactly one node: the pin exists and connects to
|
|
nothing. A system that treats "not in any pair" as "unknown" would abstain
|
|
on them; one that treats it as "false" is right here. Only the netlist
|
|
distinguishes those two cases, so this count is the one that has to be
|
|
carried into the observation.
|
|
"""
|
|
print(f"{'file':28s} {'器件':>4s} {'节点':>4s} {'网':>4s} {'单点网':>5s} "
|
|
f"{'最大网':>5s} {'边':>6s} {'无器件节点':>6s}")
|
|
print("-" * 74)
|
|
for path in paths:
|
|
nl = load(path)
|
|
nodes = len(nl.nodes())
|
|
singles = sum(1 for n in nl.nets if len(n.nodes) == 1)
|
|
biggest = max((len(n.nodes) for n in nl.nets), default=0)
|
|
obs = to_observation(nl)
|
|
orphans = sum(1 for e in obs.entities if e.attrs["ref"] not in nl.comps)
|
|
print(f"{path.rsplit('/', 1)[-1]:28s} {len(nl.comps):4d} {nodes:4d} "
|
|
f"{len(nl.nets):4d} {singles:5d} {biggest:5d} {len(obs.edges):6d} "
|
|
f"{orphans:6d}")
|
|
print()
|
|
print("器件 = 网表列出的器件数;节点 = 出现过的 (器件,脚) 对数")
|
|
print("单点网 = 只有一个节点的网:脚存在,但什么也没连 —— 这是'假'而不是'不知道'")
|
|
print("最大网 = 节点最多的那条网的节点数")
|
|
print("无器件节点 = 出现在网里、但没有器件条目的节点(网表自相矛盾)")
|
|
print()
|
|
print("单点网不是缺陷:KiCad 给每个 NC 脚单独建一条网,正是'这个脚什么也没连'的")
|
|
print("显式说法。真正漏掉的是无编号机械焊盘,实测占 0-0.7%(见 kicad_board 覆盖度)。")
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
argv = list(sys.argv[1:] if argv is None else argv)
|
|
if not argv:
|
|
print("usage: python3 -m spatial.providers.kicad_netlist <file.net> ...")
|
|
return 2
|
|
report(argv)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|