diff --git a/spatial/cli.py b/spatial/cli.py index 5934f00..312aac0 100644 --- a/spatial/cli.py +++ b/spatial/cli.py @@ -13,7 +13,7 @@ import os import sys from . import checker, generator -from .schema import FullState +from .schema import FullState, Query def _load_config(path: str) -> dict: @@ -223,12 +223,46 @@ def check_scope_agrees(n: int = 24) -> bool: return True +def check_netlist_provider() -> bool: + """The netlist provider must reproduce membership, and must not over-claim. + + Built from the same membership it is checked against, so "the edges are + right" is a construction. What this pins is the mapping's *shape*: one + entity per (ref, pin), pairwise conduct inside a net, nothing invented + across nets, and a single-node net that stays isolated instead of being + silently promoted to "connected to something". + """ + from .providers import kicad_netlist + path = os.path.join(os.path.dirname(__file__), "providers", "fixtures", "tiny.net") + nl = kicad_netlist.load(path) + obs = kicad_netlist.to_observation(nl) + want = {"comp": 3, "node": 6, "net": 3, "edge": 4} + got = {"comp": len(nl.comps), "node": len(nl.nodes()), "net": len(nl.nets), + "edge": len(obs.edges)} + if got != want: + return _fail(f"netlist mapping changed: {got} != {want}") + if checker.withheld_flag(obs): + return _fail("a complete netlist reported itself as incomplete") + pairs = [("R1.2", "U1.1", True), # same net + ("R1.1", "R1.2", False), # same part, different nets + ("U1.7", "R1.2", False)] # single-node net: connected to nothing + for a, b, want_ans in pairs: + got_ans = checker.evaluate(obs.entities, obs.edges, + Query(kind="connection", a=a, b=b)) + if got_ans is not want_ans: + return _fail(f"netlist says {a}-{b} is {got_ans}, expected {want_ans}") + print("ok netlist provider: 3 comps / 6 pads / 4 conduct edges, " + "no cross-net edge, isolated pin stays isolated") + return True + + def cmd_smoke(args) -> int: cfg = _load_config(args.config) print(f"config {args.config} out {cfg['out_dir']}") results = [check_splits(cfg), check_determinism(), check_labels(), check_insufficient(), check_invariances(), check_cross_family_digest(), - check_extract_contacts(), check_scope_agrees()] + check_extract_contacts(), check_scope_agrees(), + check_netlist_provider()] # one update, then interrupt and resume: the step counter must advance from . import train as trainer diff --git a/spatial/providers/__init__.py b/spatial/providers/__init__.py new file mode 100644 index 0000000..db5e46e --- /dev/null +++ b/spatial/providers/__init__.py @@ -0,0 +1,6 @@ +"""输入 provider:把真实来源翻译成 ``Observation``。 + +几何一类在 ``spatial/extract.py``(从盒子/面推接触),元数据一类在这里。 +两者的产物形状相同,所以主干不需要知道数据是从相机来的还是从网表来的 —— +这正是 ``docs/M2_INPUT_SOURCE.md`` 说的"接口不用改,缺的是 provider"。 +""" diff --git a/spatial/providers/fixtures/tiny.net b/spatial/providers/fixtures/tiny.net new file mode 100644 index 0000000..226031d --- /dev/null +++ b/spatial/providers/fixtures/tiny.net @@ -0,0 +1,69 @@ +(export + (version "E") + (design + (source "fixtures/tiny.kicad_sch") + (tool "synthetic") + ) + (components + (comp + (ref "R1") + (value "10k") + (footprint "Resistor_SMD:R_0805_2012Metric") + ) + (comp + (ref "C1") + (value "100n") + (footprint "Capacitor_SMD:C_0805_2012Metric") + ) + (comp + (ref "U1") + (value "NE555") + (footprint "Package_DIP:DIP-8_W7.62mm") + ) + ) + (nets + (net + (code "1") + (name "GND") + (node + (ref "R1") + (pin "2") + (pintype "passive") + ) + (node + (ref "C1") + (pin "2") + (pintype "passive") + ) + (node + (ref "U1") + (pin "1") + (pinfunction "GND") + (pintype "power_in") + ) + ) + (net + (code "2") + (name "OUT") + (node + (ref "R1") + (pin "1") + (pintype "passive") + ) + (node + (ref "C1") + (pin "1") + (pintype "passive") + ) + ) + (net + (code "3") + (name "unconnected-(U1-Pad7)") + (node + (ref "U1") + (pin "7") + (pintype "no_connect") + ) + ) + ) +) diff --git a/spatial/providers/kicad_netlist.py b/spatial/providers/kicad_netlist.py new file mode 100644 index 0000000..28e21ef --- /dev/null +++ b/spatial/providers/kicad_netlist.py @@ -0,0 +1,161 @@ +"""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 ...") + return 2 + report(argv) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/spatial/providers/sexpr.py b/spatial/providers/sexpr.py new file mode 100644 index 0000000..0f69be2 --- /dev/null +++ b/spatial/providers/sexpr.py @@ -0,0 +1,80 @@ +"""s-表达式:KiCad 的网表、工程文件、封装库都是这个形状。 + +只做一件小事——把 ``(a (b "c") d)`` 变成嵌套列表 ``["a", ["b", "c"], "d"]``。 +不做 schema 校验,不做单位换算,也不试图理解语义:上层自己按路径取值。 + +写它的理由不是"不想用第三方库",而是这里必须零依赖:provider 要能在只有 +Python 的机器上跑,否则每换一台机器就要先把环境装一遍,而装环境这件事 +正在 M2 的验收路径上(服务器连不上时整条链路就断了)。 +""" +from __future__ import annotations + + +def parse(text: str) -> list: + """Parse one s-expression into nested lists of strings.""" + out, stack, i, n = [], [], 0, len(text) + token = [] + while i < n: + ch = text[i] + if ch == '"': + i += 1 + buf = [] + while i < n and text[i] != '"': + if text[i] == "\\" and i + 1 < n: + i += 1 + buf.append({"n": "\n", "t": "\t", '"': '"', "\\": "\\"}.get(text[i], text[i])) + else: + buf.append(text[i]) + i += 1 + token.append("".join(buf)) + i += 1 + continue + if ch == "(": + stack.append([]) + token = [] + elif ch == ")": + if token: + stack[-1].append("".join(token)) + token = [] + if not stack: + raise ValueError(f"unbalanced ')' at {i}") + done = stack.pop() + (stack[-1] if stack else out).append(done) + elif ch in " \t\r\n": + if token: + stack[-1].append("".join(token)) + token = [] + else: + token.append(ch) + i += 1 + if token: + out.append("".join(token)) + if stack: + raise ValueError("unbalanced '('") + return out + + +def find(node, name: str): + """First child list whose head is ``name``, or None.""" + if isinstance(node, list): + for child in node: + if isinstance(child, list) and child and child[0] == name: + return child + return None + + +def find_all(node, name: str) -> list: + if not isinstance(node, list): + return [] + return [c for c in node if isinstance(c, list) and c and c[0] == name] + + +def value(node, name: str, default=None): + """The first atom of ``(name atom)``, or ``default``.""" + child = find(node, name) + if child is None: + return default + for item in child[1:]: + if not isinstance(item, list): + return item + return default