Files
tiny-gpt/spatial/providers/kicad_netlist.py
T

162 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""KiCad 网表 → Observation:第一个真实的元数据 provider。
M2 的契约说得很清楚:`conduct` 这类关系在几何里没有签名,只能来自元数据。
这个模块就是那份元数据——KiCad 导出的网表——到 `Observation` 的翻译层。
三件事要在这里说清楚,因为它们决定了这个 provider 能回答什么、不能回答什么:
**一、网表只有拓扑,没有几何。** 文件里没有坐标,所以翻译出来的实体没有
``box``,接触关系一条也提不出来。这不是缺陷,是分工:几何来自另一台相机/另一份
导出,两者在 ``Observation`` 这一层汇合。
**二、同一条网 = 两两连通。** 一个网里有 k 个节点就生成 k(k-1)/2 条 conduct
边。用生成树也能让可达性一样,但那样"这两个脚是同一张铜"这个事实就没了,
而模型的边特征正是靠它。
**三、网表不告诉你它漏了什么。** 一个封装有 8 个脚,网表可能只提到 2 个
(NC 脚、机械脚、被 exclude 的脚都不出现)。这个盲区在意料之中,但**无法**
从网表本身算出来:它需要一个知道封装有几个脚的来源。所以 ``scope`` 在这里
只能是"这份网表描述的就是全部",真正的缺口留给板子/封装库那个 provider 去说。
报告里把这条单独列出来,不许悄悄当成"没有"。
"""
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("没测的:封装到底有几个脚。网表不提 NC 脚和机械脚,所以'这个器件还有脚没被")
print("描述'这件事无法从网表本身算出来,必须由知道封装的那个来源声明。这条是空着")
print("的,不是零。")
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())