traceforge-pcb 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. traceforge/__init__.py +3 -0
  2. traceforge/__main__.py +3 -0
  3. traceforge/acp_server.py +570 -0
  4. traceforge/agent.py +680 -0
  5. traceforge/altium/__init__.py +6 -0
  6. traceforge/altium/cfb.py +70 -0
  7. traceforge/altium/cli.py +60 -0
  8. traceforge/altium/model.py +163 -0
  9. traceforge/altium/outputs.py +24 -0
  10. traceforge/altium/pcb.py +301 -0
  11. traceforge/altium/project.py +328 -0
  12. traceforge/altium/schematic.py +400 -0
  13. traceforge/altium/tools.py +166 -0
  14. traceforge/approval.py +219 -0
  15. traceforge/attachments.py +346 -0
  16. traceforge/background.py +253 -0
  17. traceforge/bench/__init__.py +5 -0
  18. traceforge/bench/adapters.py +337 -0
  19. traceforge/bench/checks.py +410 -0
  20. traceforge/bench/cli.py +121 -0
  21. traceforge/bench/design.py +439 -0
  22. traceforge/bench/kicad.py +99 -0
  23. traceforge/bench/partscheck.py +159 -0
  24. traceforge/bench/review.py +100 -0
  25. traceforge/bench/runner.py +226 -0
  26. traceforge/bench/score.py +204 -0
  27. traceforge/bench/tasks.py +102 -0
  28. traceforge/chat.py +1185 -0
  29. traceforge/checks.py +328 -0
  30. traceforge/checks_sides.py +118 -0
  31. traceforge/cli.py +2224 -0
  32. traceforge/clipboard.py +107 -0
  33. traceforge/config.py +299 -0
  34. traceforge/context.py +276 -0
  35. traceforge/design/__init__.py +1 -0
  36. traceforge/design/constraints.py +397 -0
  37. traceforge/design/generate.py +1789 -0
  38. traceforge/design/outline.py +905 -0
  39. traceforge/design/schematic_layout.py +932 -0
  40. traceforge/design/schematic_lint.py +329 -0
  41. traceforge/design/schematic_route.py +207 -0
  42. traceforge/design/sheets.py +854 -0
  43. traceforge/design/sides.py +328 -0
  44. traceforge/design/spec.py +462 -0
  45. traceforge/design/specsheet.py +2351 -0
  46. traceforge/design/specsheet_render.py +183 -0
  47. traceforge/desktop/__init__.py +109 -0
  48. traceforge/desktop/keys.py +90 -0
  49. traceforge/desktop/project.py +443 -0
  50. traceforge/desktop/review.py +20 -0
  51. traceforge/desktop/server.py +1277 -0
  52. traceforge/desktop/static/app.css +223 -0
  53. traceforge/desktop/static/app.js +683 -0
  54. traceforge/desktop/static/highlight.js +77 -0
  55. traceforge/desktop/static/index.html +89 -0
  56. traceforge/desktop/static/md.js +90 -0
  57. traceforge/desktop/static/viewer.js +213 -0
  58. traceforge/desktop/symbols.py +212 -0
  59. traceforge/desktop/update.py +65 -0
  60. traceforge/diagnostics.py +67 -0
  61. traceforge/errata.py +219 -0
  62. traceforge/fab.py +108 -0
  63. traceforge/fab_layers.py +44 -0
  64. traceforge/features/__init__.py +6 -0
  65. traceforge/features/candidates.py +117 -0
  66. traceforge/features/cli.py +200 -0
  67. traceforge/features/package.py +433 -0
  68. traceforge/features/revdiff.py +224 -0
  69. traceforge/features/sarif.py +145 -0
  70. traceforge/features/viewer.py +265 -0
  71. traceforge/firmware/__init__.py +3 -0
  72. traceforge/firmware/cli.py +174 -0
  73. traceforge/firmware/drivers.py +372 -0
  74. traceforge/firmware/drivers_data.py +256 -0
  75. traceforge/firmware/mcus.py +177 -0
  76. traceforge/firmware/netlist.py +55 -0
  77. traceforge/firmware/pinmap.py +296 -0
  78. traceforge/firmware/scaffold.py +466 -0
  79. traceforge/firmware/toolchain.py +262 -0
  80. traceforge/hooks.py +237 -0
  81. traceforge/kicad/__init__.py +0 -0
  82. traceforge/kicad/cli.py +519 -0
  83. traceforge/kicad/diffpair.py +174 -0
  84. traceforge/kicad/edgegeom.py +191 -0
  85. traceforge/kicad/edit.py +405 -0
  86. traceforge/kicad/escape.py +1410 -0
  87. traceforge/kicad/formats.py +1073 -0
  88. traceforge/kicad/impedance.py +320 -0
  89. traceforge/kicad/install.py +75 -0
  90. traceforge/kicad/libraries.py +490 -0
  91. traceforge/kicad/models3d.py +942 -0
  92. traceforge/kicad/outputs.py +81 -0
  93. traceforge/kicad/pcb.py +787 -0
  94. traceforge/kicad/planes.py +1242 -0
  95. traceforge/kicad/project.py +136 -0
  96. traceforge/kicad/route.py +2698 -0
  97. traceforge/kicad/routegeom.py +164 -0
  98. traceforge/kicad/schematic.py +268 -0
  99. traceforge/kicad/sides.py +34 -0
  100. traceforge/kicad/stackup.py +424 -0
  101. traceforge/kicad_plugin/__init__.py +12 -0
  102. traceforge/kicad_plugin/actions.py +92 -0
  103. traceforge/kicad_plugin/cli.py +66 -0
  104. traceforge/kicad_plugin/client.py +86 -0
  105. traceforge/kicad_plugin/context.py +257 -0
  106. traceforge/kicad_plugin/discovery.py +81 -0
  107. traceforge/kicad_plugin/install.py +203 -0
  108. traceforge/kicad_plugin/overlay.py +60 -0
  109. traceforge/kicad_plugin/payload/action_plugin.py +65 -0
  110. traceforge/kicad_plugin/payload/ipc_main.py +42 -0
  111. traceforge/kicad_plugin/payload/plugin.json +90 -0
  112. traceforge/kicad_plugin/payload/requirements.txt +1 -0
  113. traceforge/kicad_plugin/views.py +202 -0
  114. traceforge/langchain.py +57 -0
  115. traceforge/local.py +580 -0
  116. traceforge/mcp_server.py +304 -0
  117. traceforge/models.py +310 -0
  118. traceforge/next_steps.py +110 -0
  119. traceforge/parts/__init__.py +52 -0
  120. traceforge/parts/alternates.py +488 -0
  121. traceforge/parts/bom.py +423 -0
  122. traceforge/parts/brief.py +705 -0
  123. traceforge/parts/catalog.py +297 -0
  124. traceforge/parts/cli_sourcing.py +156 -0
  125. traceforge/parts/data/duty_rates.yaml +37 -0
  126. traceforge/parts/data/hs_codes.yaml +103 -0
  127. traceforge/parts/datasheet.py +278 -0
  128. traceforge/parts/fx.py +100 -0
  129. traceforge/parts/model.py +185 -0
  130. traceforge/parts/net.py +187 -0
  131. traceforge/parts/offers.py +46 -0
  132. traceforge/parts/packages.py +397 -0
  133. traceforge/parts/pinout.py +714 -0
  134. traceforge/parts/providers/__init__.py +17 -0
  135. traceforge/parts/providers/base.py +100 -0
  136. traceforge/parts/providers/jlc.py +364 -0
  137. traceforge/parts/providers/keyed.py +661 -0
  138. traceforge/parts/report.py +508 -0
  139. traceforge/parts/supply.py +330 -0
  140. traceforge/parts/verify.py +455 -0
  141. traceforge/parts/web.py +575 -0
  142. traceforge/plans.py +70 -0
  143. traceforge/preferences.py +127 -0
  144. traceforge/prices.py +130 -0
  145. traceforge/prices.yaml +28 -0
  146. traceforge/prompts/__init__.py +54 -0
  147. traceforge/prompts/system.md +103 -0
  148. traceforge/providers.py +764 -0
  149. traceforge/remote/__init__.py +33 -0
  150. traceforge/remote/client.py +422 -0
  151. traceforge/remote/oidc.py +240 -0
  152. traceforge/remote/orgs.py +510 -0
  153. traceforge/remote/server.py +690 -0
  154. traceforge/remote/store.py +100 -0
  155. traceforge/review_changes.py +187 -0
  156. traceforge/routing.py +99 -0
  157. traceforge/runtime.py +435 -0
  158. traceforge/sessions.py +324 -0
  159. traceforge/sexpr.py +279 -0
  160. traceforge/sim/__init__.py +17 -0
  161. traceforge/sim/acmath.py +234 -0
  162. traceforge/sim/circuit.py +499 -0
  163. traceforge/sim/cli.py +162 -0
  164. traceforge/sim/engine.py +172 -0
  165. traceforge/sim/ltspice.py +175 -0
  166. traceforge/sim/measure.py +123 -0
  167. traceforge/sim/models.py +76 -0
  168. traceforge/sim/project.py +218 -0
  169. traceforge/sim/rawfile.py +123 -0
  170. traceforge/sim/results.py +298 -0
  171. traceforge/sim/tune.py +172 -0
  172. traceforge/skill_commands.py +165 -0
  173. traceforge/skill_library/circuit-simulation/SKILL.md +30 -0
  174. traceforge/skill_library/compliance-review/SKILL.md +51 -0
  175. traceforge/skill_library/design-review/SKILL.md +47 -0
  176. traceforge/skill_library/errata-hunt/SKILL.md +30 -0
  177. traceforge/skill_library/firmware/SKILL.md +26 -0
  178. traceforge/skill_library/power-budget/SKILL.md +27 -0
  179. traceforge/skill_library/release-package/SKILL.md +29 -0
  180. traceforge/skill_library/sourcing-brief/SKILL.md +24 -0
  181. traceforge/skill_library/thermal-review/SKILL.md +15 -0
  182. traceforge/skills.py +131 -0
  183. traceforge/thermal.py +557 -0
  184. traceforge/tools/__init__.py +48 -0
  185. traceforge/tools/agent_tools.py +213 -0
  186. traceforge/tools/base.py +303 -0
  187. traceforge/tools/batch.py +155 -0
  188. traceforge/tools/connections.py +245 -0
  189. traceforge/tools/files.py +777 -0
  190. traceforge/tools/firmware_tools.py +218 -0
  191. traceforge/tools/kicad_tools.py +1072 -0
  192. traceforge/tools/models3d_tools.py +141 -0
  193. traceforge/tools/parts_tools.py +473 -0
  194. traceforge/tools/processes.py +246 -0
  195. traceforge/tools/review_tools.py +178 -0
  196. traceforge/tools/sim_tools.py +230 -0
  197. traceforge/tui.py +620 -0
  198. traceforge/updates.py +124 -0
  199. traceforge/validate/__init__.py +77 -0
  200. traceforge/validate/builtins.py +1091 -0
  201. traceforge/validate/circuits.py +1240 -0
  202. traceforge/validate/config.py +410 -0
  203. traceforge/validate/default.yaml +113 -0
  204. traceforge/validate/design.py +191 -0
  205. traceforge/validate/explain.py +112 -0
  206. traceforge/validate/grounding.py +169 -0
  207. traceforge/validate/ipc2221.py +350 -0
  208. traceforge/validate/multilayer.py +805 -0
  209. traceforge/validate/netmodel.py +261 -0
  210. traceforge/validate/partcheck.py +472 -0
  211. traceforge/validate/report.py +280 -0
  212. traceforge/validate/review.py +322 -0
  213. traceforge/validate/runner.py +662 -0
  214. traceforge/workspace.py +171 -0
  215. traceforge_pcb-1.0.0.dist-info/METADATA +463 -0
  216. traceforge_pcb-1.0.0.dist-info/RECORD +219 -0
  217. traceforge_pcb-1.0.0.dist-info/WHEEL +4 -0
  218. traceforge_pcb-1.0.0.dist-info/entry_points.txt +2 -0
  219. traceforge_pcb-1.0.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2351 @@
1
+ """Engineering design specification ("spec sheet") of a board.
2
+
3
+ The document an engineer hands to a fab, a reviewer or a colleague: board and stackup, the design rules
4
+ against the fab's limits, net classes with current capacity, the copper that was actually routed,
5
+ differential pairs and length groups, a placement table with rotation angles, mechanical features,
6
+ assembly notes and revision data. Everything is measured from the board and project files (a design spec
7
+ is built first, no routing needed); nothing is invented. Each number says where it comes from, and
8
+ assumptions are listed once at the end (:data:`ASSUMPTIONS`).
9
+
10
+ ``build_sheet`` returns a JSON-able dict made of sections; ``specsheet_render`` turns it into Markdown or
11
+ printable HTML. Section layout: ``{"title", "facts": [[label, value], ...], "tables": [{"title",
12
+ "columns", "rows", "note"}], "notes": [...], "data": {...raw numbers...}}``.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import datetime
18
+ import json
19
+ import math
20
+ import re
21
+ import subprocess
22
+ import tempfile
23
+ from collections import Counter, defaultdict
24
+ from dataclasses import dataclass, field
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from traceforge import sexpr
29
+ from traceforge.fab import FabProfile, get_fab
30
+ from traceforge.kicad import diffpair, impedance, stackup
31
+ from traceforge.kicad.edgegeom import _seg_seg_dist
32
+ from traceforge.kicad.pcb import Board, Footprint, Pad, read_board
33
+ from traceforge.sexpr import find
34
+ from traceforge.validate import circuits, ipc2221
35
+
36
+ SCHEMA = "traceforge.design-spec/1"
37
+ OZ_MM = 0.035 # copper thickness of 1 oz/ft2 as used by KiCad and the stackup presets
38
+ SECTIONS = (
39
+ "board",
40
+ "stackup",
41
+ "rules",
42
+ "net_classes",
43
+ "copper",
44
+ "pairs",
45
+ "placement",
46
+ "mechanical",
47
+ "assembly",
48
+ "revision",
49
+ )
50
+
51
+ ASSUMPTIONS = (
52
+ "Copper weight is derived from each layer's thickness (1 oz = 0.035 mm).",
53
+ "Surface finish, solder mask colour and board Tg are not recorded in KiCad files; the fab order "
54
+ "decides them (the fab profile's note is shown).",
55
+ "Impedances are closed-form estimates (Wheeler/Hammerstad/Cohn, see kicad/impedance.py), not a field "
56
+ "solver; the fab's own stackup has the final say.",
57
+ "Current capacity is IPC-2221: I = k * dT^0.44 * A^0.725 (A in mil^2, k = 0.048 outer, 0.024 inner) "
58
+ "at the stated temperature rise and the layer's copper weight. IPC-2152 (measured data, accounts "
59
+ "for plane proximity and board thickness) is more accurate and usually allows more current; treat "
60
+ "IPC-2221 as the conservative screening value.",
61
+ "Measured clearance uses the routed tracks, vias and pads as stored in the board file (zone fills "
62
+ "and pad-to-pad spacing inside footprint libraries are not included); KiCad DRC is authoritative.",
63
+ "Height classes are estimated from footprint names, not measured from 3D models.",
64
+ "Rotation angles are KiCad's: degrees counter-clockwise seen from the top; bottom-side parts are "
65
+ "mirrored and the angle is as stored in the file.",
66
+ )
67
+
68
+
69
+ class SpecSheetError(ValueError):
70
+ """The source could not be turned into a spec sheet (message is user-facing)."""
71
+
72
+
73
+ # ------------------------------------------------------------------------------------ loading
74
+ @dataclass
75
+ class Source:
76
+ pcb: Path
77
+ pro: Path | None
78
+ sch: Path | None
79
+ board: Board
80
+ project: dict
81
+ fab: FabProfile
82
+ workspace: Path
83
+ stack: stackup.Stackup | None = None
84
+ stack_assumed: bool = False
85
+ spec: Any = None # DesignSpec when built from a spec
86
+ title_block: dict[str, str] = field(default_factory=dict)
87
+ aux_origin: tuple[float, float] | None = None
88
+ _tmp: tempfile.TemporaryDirectory | None = None
89
+
90
+ def close(self) -> None:
91
+ if self._tmp is not None:
92
+ self._tmp.cleanup()
93
+ self._tmp = None
94
+
95
+
96
+ def load_source(path: str | Path, fab: str | None = None, spec: Any = None) -> Source:
97
+ """A spec (``.yaml``), a ``.kicad_pcb`` or a folder holding one, as a :class:`Source`."""
98
+ p = Path(path)
99
+ if not p.exists():
100
+ raise SpecSheetError(f"{p} does not exist")
101
+ if p.is_dir():
102
+ boards = sorted(p.glob("*.kicad_pcb"))
103
+ specs = sorted(p.glob("design.y*ml"))
104
+ if len(boards) == 1:
105
+ p = boards[0]
106
+ elif not boards and specs:
107
+ p = specs[0]
108
+ else:
109
+ raise SpecSheetError(
110
+ f"{p}: expected one .kicad_pcb (or a design.yaml), found {len(boards)}"
111
+ )
112
+ tmp = None
113
+ if p.suffix.lower() in {".yaml", ".yml", ".json"}:
114
+ from traceforge.design.generate import DesignError, generate
115
+ from traceforge.design.spec import load_spec
116
+ from traceforge.kicad.libraries import LibraryError
117
+
118
+ try:
119
+ spec = load_spec(p)
120
+ tmp = tempfile.TemporaryDirectory(prefix="traceforge-spec-")
121
+ built = generate(spec, Path(tmp.name), overwrite=True)
122
+ except (DesignError, LibraryError, ValueError) as exc:
123
+ if tmp is not None:
124
+ tmp.cleanup()
125
+ raise SpecSheetError(f"cannot build {p.name}: {exc}") from exc
126
+ pcb, sch = built.pcb, built.schematic
127
+ workspace = p.parent
128
+ elif p.suffix.lower() == ".kicad_pcb":
129
+ pcb = p
130
+ sch = p.with_suffix(".kicad_sch") if p.with_suffix(".kicad_sch").exists() else None
131
+ workspace = p.parent
132
+ else:
133
+ raise SpecSheetError(f"{p.name}: give a design spec (.yaml) or a board (.kicad_pcb)")
134
+ if pcb is None or not Path(pcb).exists():
135
+ if tmp is not None:
136
+ tmp.cleanup()
137
+ raise SpecSheetError("the design has no board to describe")
138
+ pro = Path(pcb).with_suffix(".kicad_pro")
139
+ project: dict = {}
140
+ if pro.exists():
141
+ try:
142
+ project = json.loads(pro.read_text(encoding="utf-8"))
143
+ except ValueError:
144
+ project = {}
145
+ board = read_board(pcb)
146
+ fab_name = fab or (spec.fab if spec is not None else None) or "jlcpcb"
147
+ try:
148
+ fab_profile = get_fab(fab_name)
149
+ except ValueError as exc:
150
+ if tmp is not None:
151
+ tmp.cleanup()
152
+ raise SpecSheetError(str(exc)) from exc
153
+ src = Source(
154
+ Path(pcb), pro if pro.exists() else None, sch, board, project, fab_profile, workspace
155
+ )
156
+ src.spec, src._tmp = spec, tmp
157
+ _read_raw(src)
158
+ _read_stack(src)
159
+ return src
160
+
161
+
162
+ def _read_raw(src: Source) -> None:
163
+ """Title block and auxiliary origin straight from the board file."""
164
+ try:
165
+ root = sexpr.parse(src.pcb.read_text(encoding="utf-8"))
166
+ except (OSError, ValueError):
167
+ return
168
+ tb = find(root, "title_block")
169
+ if tb is not None:
170
+ for key in ("title", "date", "rev", "company"):
171
+ item = find(tb, key)
172
+ if item is not None and len(item) > 1:
173
+ src.title_block[key] = str(item[1])
174
+ setup = find(root, "setup")
175
+ if setup is not None:
176
+ aux = find(setup, "aux_axis_origin")
177
+ if aux is not None and len(aux) > 2:
178
+ src.aux_origin = (float(aux[1]), float(aux[2]))
179
+
180
+
181
+ def _read_stack(src: Source) -> None:
182
+ count = len(src.board.copper_layers)
183
+ try:
184
+ found = stackup.read_stackup(src.pcb)
185
+ except (OSError, ValueError, stackup.StackupError):
186
+ found = None
187
+ if found is None or found.count != count:
188
+ found = stackup.default_for(count if count in (2, 4, 6, 8) else 2)
189
+ src.stack_assumed = True
190
+ info = (src.project.get("traceforge") or {}).get("stackup") or {}
191
+ planes = info.get("planes") or {}
192
+ known = {name: nets for name, nets in planes.items() if name in found.names}
193
+ if known: # KiCad files carry no layer roles: the generator records the planes in the project
194
+ try:
195
+ found = found.with_planes(known)
196
+ except stackup.StackupError:
197
+ pass
198
+ src.stack = found
199
+
200
+
201
+ # ------------------------------------------------------------------------------------ helpers
202
+ def _num(x: float, digits: int = 3) -> str:
203
+ text = f"{x:.{digits}f}".rstrip("0").rstrip(".")
204
+ return "0" if text in {"", "-0"} else text
205
+
206
+
207
+ def _table(title: str, columns: list[str], rows: list[list[Any]], note: str = "") -> dict:
208
+ return {
209
+ "title": title,
210
+ "columns": columns,
211
+ "rows": [[_cell(c) for c in r] for r in rows],
212
+ "note": note,
213
+ }
214
+
215
+
216
+ def _cell(c: Any) -> Any:
217
+ """Numbers stay numbers (rounded) so JSON consumers can use them; renderers format them."""
218
+ if isinstance(c, float):
219
+ return 0.0 if c == 0 else round(c, 4)
220
+ return c
221
+
222
+
223
+ def _section(
224
+ title: str,
225
+ facts: list[tuple[str, Any]] | None = None,
226
+ tables: list[dict] | None = None,
227
+ notes: list[str] | None = None,
228
+ data: dict | None = None,
229
+ ) -> dict:
230
+ return {
231
+ "title": title,
232
+ "facts": [[k, _cell(v)] for k, v in (facts or [])],
233
+ "tables": [t for t in (tables or []) if t["rows"]],
234
+ "notes": notes or [],
235
+ "data": data or {},
236
+ }
237
+
238
+
239
+ class _Warnings:
240
+ def __init__(self) -> None:
241
+ self.items: list[dict] = []
242
+
243
+ def add(self, severity: str, section: str, message: str) -> None:
244
+ self.items.append({"severity": severity, "section": section, "message": message})
245
+
246
+
247
+ def _oz(thickness_mm: float) -> float:
248
+ return round(thickness_mm / OZ_MM * 2) / 2 or round(thickness_mm / OZ_MM, 2)
249
+
250
+
251
+ def _is_inner(src: Source, layer: str) -> bool:
252
+ names = src.board.copper_layers
253
+ return layer in names and layer not in (names[0], names[-1])
254
+
255
+
256
+ def _layer_oz(src: Source, layer: str) -> float:
257
+ assert src.stack is not None
258
+ try:
259
+ return _oz(src.stack.copper[src.stack.index(layer)].thickness)
260
+ except stackup.StackupError:
261
+ return 1.0
262
+
263
+
264
+ def _stack_info(src: Source) -> dict:
265
+ return (src.project.get("traceforge") or {}).get("stackup") or {}
266
+
267
+
268
+ def _net_class_of(src: Source) -> dict[str, str]:
269
+ return ipc2221._expand_classes(src.board, ipc2221.netclasses_of(src.pro))
270
+
271
+
272
+ def _classes(src: Source) -> list[dict]:
273
+ return list(((src.project.get("net_settings") or {}).get("classes")) or [])
274
+
275
+
276
+ def _class_values(src: Source, name: str) -> dict:
277
+ for item in _classes(src):
278
+ if item.get("name") == name:
279
+ return item
280
+ return {}
281
+
282
+
283
+ def _farads(text: str) -> float | None:
284
+ """'100n' / '0.1u' / '4.7uF' / '10pF' / '1k' (not a cap) -> farads."""
285
+ m = re.match(r"^\s*(\d+(?:\.\d+)?)\s*([pnuµm]?)\s*F?\s*$", text or "", re.I)
286
+ if not m:
287
+ m = re.match(r"^\s*(\d+)([pnuµ])(\d+)\s*F?\s*$", text or "", re.I)
288
+ if not m:
289
+ return None
290
+ number, unit = float(f"{m.group(1)}.{m.group(3)}"), m.group(2)
291
+ else:
292
+ number, unit = float(m.group(1)), m.group(2)
293
+ return number * {"p": 1e-12, "n": 1e-9, "u": 1e-6, "µ": 1e-6, "m": 1e-3, "": 1.0}[unit.lower()]
294
+
295
+
296
+ def _fp_height_class(fp: Footprint) -> tuple[str, str]:
297
+ """(class, basis) estimated from the footprint name and value; not a 3D measurement."""
298
+ lib = fp.lib_id
299
+ name = lib.split(":")[-1].lower()
300
+ if re.search(
301
+ r"(usb|hdmi|rj45|rj_|barrel|audio|jack|header|pinheader|pinsocket|terminalblock|"
302
+ r"screw|jst|molex|sma|battery|relay|transformer)",
303
+ name,
304
+ ) or lib.startswith(
305
+ ("Connector_USB", "Connector_HDMI", "Connector_RJ", "Connector_BarrelJack")
306
+ ):
307
+ return "tall (connector/through-hole)", "footprint name"
308
+ if re.search(
309
+ r"(cp_elec|elec|radial|hc-?49|crystal_hc|inductor_.*(?:[1-9]\d{3}|powerinductor)|"
310
+ r"c_?(?:12|18|22)\d{2}_\d{4}|to-220|to-247)",
311
+ name,
312
+ ):
313
+ return "tall", "footprint name"
314
+ if re.search(
315
+ r"(bga|qfn|dfn|lqfp|tqfp|qfp|soic|sop|ssop|tssop|msop|sot-?23|sot-?223|to-252|"
316
+ r"to-263|dpak)",
317
+ name,
318
+ ):
319
+ return "medium (IC)", "footprint name"
320
+ if re.search(
321
+ r"(0201|0402|0603|0805|1206|1210|sod-?\d+|led_|mounting|fiducial|testpoint)", name
322
+ ):
323
+ return "low (chip)", "footprint name"
324
+ return "unknown", "no rule matches"
325
+
326
+
327
+ def _rotation_bucket(angle: float) -> str:
328
+ a = round(angle % 360.0, 3)
329
+ for nominal in (0, 90, 180, 270):
330
+ if abs(a - nominal) < 0.01 or abs(a - nominal - 360) < 0.01:
331
+ return str(nominal)
332
+ return "other"
333
+
334
+
335
+ def _rel(src: Source, x: float, y: float) -> tuple[float, float]:
336
+ """Position measured from the outline's top-left corner (what a drawing dimensions)."""
337
+ if src.board.outline is None:
338
+ return x, y
339
+ return round(x - src.board.outline[0], 3), round(y - src.board.outline[1], 3)
340
+
341
+
342
+ def _placed(src: Source) -> list[Footprint]:
343
+ return [f for f in src.board.footprints if f.reference and not f.reference.startswith("#")]
344
+
345
+
346
+ def _bottom(fp: Footprint) -> bool:
347
+ return fp.layer.startswith("B.")
348
+
349
+
350
+ def _net_lengths(board: Board) -> dict[str, float]:
351
+ out: dict[str, float] = defaultdict(float)
352
+ for t in board.tracks:
353
+ out[t.net] += t.length
354
+ return out
355
+
356
+
357
+ # ------------------------------------------------------------------------------------ meta
358
+ def _git_hash(folder: Path) -> str | None:
359
+ try:
360
+ done = subprocess.run( # noqa: S603
361
+ ["git", "-C", str(folder), "rev-parse", "--short", "HEAD"], # noqa: S607
362
+ capture_output=True,
363
+ text=True,
364
+ timeout=10,
365
+ check=False,
366
+ )
367
+ except (OSError, subprocess.SubprocessError):
368
+ return None
369
+ out = done.stdout.strip()
370
+ return out if done.returncode == 0 and re.fullmatch(r"[0-9a-f]{7,40}", out) else None
371
+
372
+
373
+ # ------------------------------------------------------------------------------------ board
374
+ def _outline_area(board: Board) -> tuple[float, str]:
375
+ """Outline area in mm2: bounding box for a plain rectangle, sampled for shaped outlines."""
376
+ if board.outline is None:
377
+ return 0.0, "no outline"
378
+ x0, y0, x1, y1 = board.outline
379
+ box = (x1 - x0) * (y1 - y0)
380
+ geom = board.edge_geometry
381
+ if not board.edge_segments or geom is None:
382
+ return box, "bounding box"
383
+ step = max(0.25, max(x1 - x0, y1 - y0) / 220)
384
+ inside = 0
385
+ nx = int((x1 - x0) / step) + 1
386
+ ny = int((y1 - y0) / step) + 1
387
+ for i in range(nx):
388
+ x = x0 + (i + 0.5) * step
389
+ for j in range(ny):
390
+ if geom.inside(x, y0 + (j + 0.5) * step):
391
+ inside += 1
392
+ return inside * step * step, f"sampled at {_num(step, 2)} mm; corner radii and cut-outs removed"
393
+
394
+
395
+ def _board_section(src: Source, warn: _Warnings) -> dict:
396
+ board, stack, spec = src.board, src.stack, src.spec
397
+ assert stack is not None
398
+ size = board.size_mm
399
+ area, area_basis = _outline_area(board)
400
+ coppers = {c.name: _oz(c.thickness) for c in stack.copper}
401
+ weights = ", ".join(f"{n} {o:g} oz" for n, o in coppers.items())
402
+ materials = sorted({d.material for d in stack.dielectrics})
403
+ facts: list[tuple[str, Any]] = []
404
+ if size:
405
+ facts += [
406
+ ("Outline size", f"{_num(size[0], 2)} x {_num(size[1], 2)} mm (width x height)"),
407
+ ("Outline area", f"{_num(area / 100, 2)} cm2 ({area_basis})"),
408
+ ]
409
+ mx, my = src.fab.max_board_mm
410
+ if size[0] > mx or size[1] > my:
411
+ warn.add(
412
+ "P1",
413
+ "board",
414
+ f"board {size[0]:.0f} x {size[1]:.0f} mm exceeds {src.fab.name}'s {mx:.0f} x {my:.0f} mm",
415
+ )
416
+ facts += [
417
+ ("Copper layers", len(board.copper_layers)),
418
+ (
419
+ "Board thickness",
420
+ f"{_num(board.thickness, 3)} mm (board file), {_num(stack.thickness, 3)} mm (stackup sum)",
421
+ ),
422
+ ("Finished copper weight", weights),
423
+ (
424
+ "Core / prepreg material",
425
+ ", ".join(materials) + (f" (preset {stack.name})" if stack.name != "custom" else ""),
426
+ ),
427
+ (
428
+ "Surface finish",
429
+ "not recorded in the design; fab standard (" + (src.fab.notes or src.fab.name) + ")",
430
+ ),
431
+ ("Fab profile", src.fab.name),
432
+ ]
433
+ if spec is not None and spec.board.corner_radius:
434
+ facts.append(("Corner radius", f"{_num(spec.board.corner_radius, 2)} mm"))
435
+ if spec is not None and spec.board.outline is not None:
436
+ facts.append(("Outline", "shaped (cut-outs/slots, see mechanical)"))
437
+ elif board.edge_segments and len(board.edge_segments) > 4:
438
+ facts.append(("Outline", f"shaped, {len(board.edge_segments)} edge segments"))
439
+ panel = spec.board.panel if spec is not None else None
440
+ facts.append(
441
+ (
442
+ "Panelisation",
443
+ f"{panel.model_dump(exclude_none=True)}"
444
+ if panel is not None
445
+ else "none recorded in the design",
446
+ )
447
+ )
448
+ if spec is not None:
449
+ facts.append(
450
+ (
451
+ "Board origin (spec)",
452
+ f"{spec.board.origin[0]:g}, {spec.board.origin[1]:g} mm (top-left of the outline)",
453
+ )
454
+ )
455
+ elif board.outline is not None:
456
+ facts.append(
457
+ (
458
+ "Outline top-left",
459
+ f"{_num(board.outline[0], 3)}, {_num(board.outline[1], 3)} mm (KiCad coordinates, Y down)",
460
+ )
461
+ )
462
+ if src.aux_origin is not None:
463
+ facts.append(
464
+ ("Drill/place origin", f"{_num(src.aux_origin[0], 3)}, {_num(src.aux_origin[1], 3)} mm")
465
+ )
466
+ if src.stack_assumed:
467
+ warn.add(
468
+ "P3",
469
+ "board",
470
+ "the board file has no usable stackup; the typical stackup for the layer count is shown",
471
+ )
472
+ return _section(
473
+ "Board",
474
+ facts,
475
+ data={
476
+ "size_mm": list(size) if size else None,
477
+ "area_mm2": round(area, 2),
478
+ "layers": len(board.copper_layers),
479
+ "thickness_mm": board.thickness,
480
+ "copper_oz": coppers,
481
+ },
482
+ )
483
+
484
+
485
+ # ------------------------------------------------------------------------------------ stackup
486
+ def _stackup_section(src: Source, warn: _Warnings) -> dict:
487
+ stack = src.stack
488
+ assert stack is not None
489
+ default_track = _class_values(src, "Default").get("track_width") or src.fab.default_track
490
+ rows: list[list[Any]] = []
491
+ roles = _stack_info(src).get("roles") or {}
492
+ for i, c in enumerate(stack.copper):
493
+ try:
494
+ geometry = impedance.geometry_name(stack, c.name) if c.role == "signal" else "-"
495
+ z0 = (
496
+ f"{impedance.single_ended(stack, c.name, float(default_track)):.1f}"
497
+ if c.role == "signal"
498
+ else "-"
499
+ )
500
+ except (stackup.StackupError, ValueError):
501
+ geometry, z0 = "n/a", "n/a"
502
+ net = c.net or ""
503
+ if c.splits:
504
+ net = " / ".join(n for n, _ in c.splits)
505
+ rows.append(
506
+ [
507
+ c.name,
508
+ "copper",
509
+ c.role,
510
+ c.thickness,
511
+ f"{_oz(c.thickness):g}",
512
+ net,
513
+ "",
514
+ "",
515
+ geometry,
516
+ z0,
517
+ ]
518
+ )
519
+ if i < len(stack.dielectrics):
520
+ d = stack.dielectrics[i]
521
+ rows.append(["", d.kind, d.material, d.thickness, "", "", d.er, d.loss_tangent, "", ""])
522
+ note = (
523
+ f"Z0 is single-ended at the default track width {_num(float(default_track))} mm, from "
524
+ "kicad/impedance.py (closed-form). Differential impedances are in the pairs section. "
525
+ f"Soldermask {_num(stack.mask_thickness * 1000, 1)} um, er {stack.mask_er}."
526
+ )
527
+ if roles and any(r == "plane" for r in roles.values()):
528
+ note += " Plane roles come from the project's recorded stackup."
529
+ return _section(
530
+ "Stackup",
531
+ [
532
+ ("Preset / source", stack.name + (" (assumed)" if src.stack_assumed else "")),
533
+ ("Total thickness", f"{_num(stack.thickness, 3)} mm"),
534
+ ],
535
+ [
536
+ _table(
537
+ "Layers, top to bottom",
538
+ [
539
+ "Layer",
540
+ "Type",
541
+ "Role / material",
542
+ "Thickness mm",
543
+ "oz",
544
+ "Plane net",
545
+ "er",
546
+ "tan d",
547
+ "Geometry",
548
+ "Z0 ohm",
549
+ ],
550
+ rows,
551
+ note,
552
+ )
553
+ ],
554
+ data=stack.summary(),
555
+ )
556
+
557
+
558
+ # ------------------------------------------------------------------------------------ rules
559
+ def _status(value_: float, limit: float, *, minimum: bool = True) -> str:
560
+ if limit <= 0:
561
+ return "n/a"
562
+ ok = value_ >= limit - 1e-9 if minimum else value_ <= limit + 1e-9
563
+ if not ok:
564
+ return "BELOW FAB LIMIT" if minimum else "ABOVE FAB LIMIT"
565
+ margin = (value_ - limit) / limit if minimum else (limit - value_) / limit
566
+ return "ok (at limit)" if margin < 0.10 else "ok"
567
+
568
+
569
+ def _rules_section(src: Source, warn: _Warnings) -> dict:
570
+ ds = ((src.project.get("board") or {}).get("design_settings")) or {}
571
+ rules = ds.get("rules") or {}
572
+ default = _class_values(src, "Default")
573
+ fab = src.fab
574
+ thickness = src.board.thickness
575
+
576
+ def row(
577
+ label: str,
578
+ design: float | None,
579
+ limit: float | None,
580
+ minimum: bool = True,
581
+ unit: str = "mm",
582
+ advisory: bool = False,
583
+ ):
584
+ if design is None:
585
+ return [label, "not set", _num(limit) if limit is not None else "-", "-", "-", unit]
586
+ if not limit:
587
+ return [label, _num(design), "-", "-", "n/a", unit]
588
+ status = _status(design, limit, minimum=minimum)
589
+ if status.startswith(("BELOW", "ABOVE")):
590
+ if advisory: # a DRC floor, not a measured feature: say so instead of failing the board
591
+ return [
592
+ label,
593
+ _num(design),
594
+ _num(limit),
595
+ _num(design - limit, 3),
596
+ "rule floor below fab limit: check actual silk widths",
597
+ unit,
598
+ ]
599
+ warn.add(
600
+ "P1",
601
+ "rules",
602
+ f"{label}: {_num(design)} {unit} is outside {fab.name}'s limit {_num(limit)} {unit}",
603
+ )
604
+ return [label, _num(design), _num(limit), _num(design - limit, 3), status, unit]
605
+
606
+ rows = [
607
+ row("Minimum track width", rules.get("min_track_width"), fab.min_track),
608
+ row("Minimum clearance", rules.get("min_clearance"), fab.min_clearance),
609
+ row("Minimum via diameter", rules.get("min_via_diameter"), fab.min_via_diameter),
610
+ row("Minimum drill (through hole)", rules.get("min_through_hole_diameter"), fab.min_drill),
611
+ row("Minimum via annular ring", rules.get("min_via_annular_width"), fab.min_annular_ring),
612
+ row(
613
+ "Minimum copper to board edge",
614
+ rules.get("min_copper_edge_clearance"),
615
+ fab.min_copper_edge,
616
+ ),
617
+ row(
618
+ "Minimum silkscreen text height",
619
+ rules.get("min_text_height"),
620
+ fab.min_silk_text_height,
621
+ advisory=True,
622
+ ),
623
+ row(
624
+ "Minimum silkscreen line width",
625
+ rules.get("min_text_thickness"),
626
+ fab.min_silk_line,
627
+ advisory=True,
628
+ ),
629
+ row("Minimum hole to hole", rules.get("min_hole_to_hole"), None),
630
+ row("Minimum hole to copper", rules.get("min_hole_clearance"), None),
631
+ row("Minimum silk to copper", rules.get("min_silk_clearance"), None),
632
+ ]
633
+ mask = rules.get(
634
+ "solder_mask_clearance", (ds.get("defaults") or {}).get("solder_mask_clearance")
635
+ )
636
+ web = rules.get(
637
+ "solder_mask_min_width", (ds.get("defaults") or {}).get("solder_mask_min_width")
638
+ )
639
+ rows.append(
640
+ [
641
+ "Solder mask expansion",
642
+ _num(mask) if mask is not None else "0 (file default)",
643
+ "-",
644
+ "-",
645
+ "set by the fab/CAM unless stated",
646
+ "mm",
647
+ ]
648
+ )
649
+ rows.append(
650
+ [
651
+ "Solder mask minimum web",
652
+ _num(web) if web is not None else "not set",
653
+ "-",
654
+ "-",
655
+ "ask the fab (typically 0.1 mm)",
656
+ "mm",
657
+ ]
658
+ )
659
+ defaults = [
660
+ ["Default track width", _num(default.get("track_width") or fab.default_track), "mm"],
661
+ ["Default clearance", _num(default.get("clearance") or fab.default_clearance), "mm"],
662
+ [
663
+ "Default via diameter / drill",
664
+ f"{_num(default.get('via_diameter') or fab.default_via_diameter)} / {_num(default.get('via_drill') or fab.default_via_drill)}",
665
+ "mm",
666
+ ],
667
+ ]
668
+ drill = default.get("via_drill") or fab.default_via_drill
669
+ if drill:
670
+ defaults.append(
671
+ [
672
+ "Via aspect ratio (board thickness / drill)",
673
+ f"{thickness / drill:.1f} : 1",
674
+ "common through-via limit about 10 : 1, confirm with the fab",
675
+ ]
676
+ )
677
+ if thickness / drill > 10:
678
+ warn.add(
679
+ "P2",
680
+ "rules",
681
+ f"via aspect ratio {thickness / drill:.1f}:1 is high for the default {drill} mm drill",
682
+ )
683
+ return _section(
684
+ "Design rules",
685
+ [("Fab limits from", f"{fab.name} profile ({fab.notes})")],
686
+ [
687
+ _table(
688
+ "Rules against the fab's limits",
689
+ ["Rule", "Design", "Fab limit", "Margin", "Status", "Unit"],
690
+ rows,
691
+ "Design values: the project's design rules. Fab limits: traceforge/fab.py (standard service; check the fab's current capability page).",
692
+ ),
693
+ _table("Defaults used when a net has no class", ["Setting", "Value", "Note"], defaults),
694
+ ],
695
+ data={"rules": rules, "defaults": default},
696
+ )
697
+
698
+
699
+ # ------------------------------------------------------------------------------------ copper geometry
700
+ def _track_widths(board: Board) -> dict[str, Counter]:
701
+ per: dict[str, Counter] = defaultdict(Counter)
702
+ for t in board.tracks:
703
+ per[t.layer][round(t.width, 4)] += t.length
704
+ return per
705
+
706
+
707
+ def _shape_of_pad(p: Pad) -> tuple:
708
+ if p.shape in ("circle", "oval"):
709
+ r = min(p.width, p.height) / 2
710
+ if p.width >= p.height:
711
+ d = (p.width - p.height) / 2
712
+ return ("cap", p.x - d, p.y, p.x + d, p.y, r)
713
+ d = (p.height - p.width) / 2
714
+ return ("cap", p.x, p.y - d, p.x, p.y + d, r)
715
+ return ("rect", p.x - p.width / 2, p.y - p.height / 2, p.x + p.width / 2, p.y + p.height / 2)
716
+
717
+
718
+ def _seg_rect_dist(
719
+ seg: tuple[float, float, float, float], rect: tuple[float, float, float, float]
720
+ ) -> float:
721
+ x0, y0, x1, y1 = rect
722
+ for px, py in ((seg[0], seg[1]), (seg[2], seg[3])):
723
+ if x0 <= px <= x1 and y0 <= py <= y1:
724
+ return 0.0
725
+ edges = ((x0, y0, x1, y0), (x1, y0, x1, y1), (x1, y1, x0, y1), (x0, y1, x0, y0))
726
+ return min(_seg_seg_dist(seg, e) for e in edges)
727
+
728
+
729
+ def _shape_dist(a: tuple, b: tuple) -> float:
730
+ if a[0] == "cap" and b[0] == "cap":
731
+ return _seg_seg_dist(a[1:5], b[1:5]) - a[5] - b[5]
732
+ if a[0] == "rect" and b[0] == "rect":
733
+ dx = max(0.0, a[1] - b[3], b[1] - a[3])
734
+ dy = max(0.0, a[2] - b[4], b[2] - a[4])
735
+ return math.hypot(dx, dy)
736
+ cap, rect = (a, b) if a[0] == "cap" else (b, a)
737
+ return _seg_rect_dist(cap[1:5], rect[1:5]) - cap[5]
738
+
739
+
740
+ def _bbox(shape: tuple) -> tuple[float, float, float, float]:
741
+ if shape[0] == "cap":
742
+ r = shape[5]
743
+ return (
744
+ min(shape[1], shape[3]) - r,
745
+ min(shape[2], shape[4]) - r,
746
+ max(shape[1], shape[3]) + r,
747
+ max(shape[2], shape[4]) + r,
748
+ )
749
+ return shape[1:5]
750
+
751
+
752
+ def track_angles(board: Board) -> dict:
753
+ """Direction of every straight segment and the angle at every two-segment bend.
754
+
755
+ Directions are folded to 0..180 degrees from the X axis and bucketed to 0, 45, 90, 135 (within
756
+ 1 degree) or ``other``. A bend is a point where exactly two segments of one net end on a layer; its
757
+ interior angle is 180 minus the turn: under 90 acute, 90 right, over 90 obtuse.
758
+ """
759
+ by_dir: Counter = Counter()
760
+ ends: dict[tuple, list[tuple[float, float]]] = defaultdict(list)
761
+ for t in board.tracks:
762
+ if t.mid is not None:
763
+ continue
764
+ dx, dy = t.x2 - t.x1, t.y2 - t.y1
765
+ length = math.hypot(dx, dy)
766
+ if length < 1e-9:
767
+ continue
768
+ theta = math.degrees(math.atan2(dy, dx)) % 180.0
769
+ bucket = "other"
770
+ for nominal in (0, 45, 90, 135, 180):
771
+ if abs(theta - nominal) <= 1.0:
772
+ bucket = str(nominal % 180)
773
+ break
774
+ by_dir[bucket] += length
775
+ ends[(t.net, t.layer, round(t.x1, 3), round(t.y1, 3))].append((dx / length, dy / length))
776
+ ends[(t.net, t.layer, round(t.x2, 3), round(t.y2, 3))].append((-dx / length, -dy / length))
777
+ bends = {"acute": 0, "right": 0, "obtuse": 0}
778
+ for directions in ends.values():
779
+ if len(directions) != 2:
780
+ continue
781
+ (ax, ay), (bx, by) = directions # both point away from the shared end
782
+ cos = max(-1.0, min(1.0, ax * bx + ay * by))
783
+ interior = math.degrees(math.acos(cos))
784
+ if interior > 179.0:
785
+ continue # a straight continuation
786
+ if interior < 89.0:
787
+ bends["acute"] += 1
788
+ elif interior <= 91.0:
789
+ bends["right"] += 1
790
+ else:
791
+ bends["obtuse"] += 1
792
+ order = ["0", "45", "90", "135", "other"]
793
+ return {"length_by_direction": {k: round(by_dir.get(k, 0.0), 3) for k in order}, "bends": bends}
794
+
795
+
796
+ def measure_clearance(board: Board, rule_min: float | None = None) -> dict:
797
+ """Smallest copper-to-copper distance between different nets for routed items.
798
+
799
+ Pairs checked: track/track, track/via, via/via, track/pad, via/pad on the same copper layer.
800
+ Returns overall and per-layer minimum, a short list of the tightest spots and how many pairs are
801
+ below ``rule_min``.
802
+ """
803
+ names = board.copper_layers
804
+ items: list[tuple[str, int, str, tuple, bool]] = [] # kind, layer index, net, shape, routed
805
+ index = {n: i for i, n in enumerate(names)}
806
+ for t in board.tracks:
807
+ if t.layer in index:
808
+ items.append(
809
+ ("track", index[t.layer], t.net, ("cap", t.x1, t.y1, t.x2, t.y2, t.width / 2), True)
810
+ )
811
+ for v in board.vias:
812
+ spans = [index[n] for n in v.layers if n in index]
813
+ lo, hi = (min(spans), max(spans)) if len(spans) >= 2 else (0, len(names) - 1)
814
+ for li in range(lo, hi + 1):
815
+ items.append(("via", li, v.net, ("cap", v.x, v.y, v.x, v.y, v.size / 2), True))
816
+ for fp in board.footprints:
817
+ for p in fp.pads:
818
+ if p.kind == "np_thru_hole":
819
+ continue
820
+ for n in names:
821
+ if p.on_layer(n):
822
+ items.append(("pad", index[n], p.net, _shape_of_pad(p), False))
823
+ cell = 2.0
824
+ grid: dict[tuple[int, int, int], list[int]] = defaultdict(list)
825
+ for i, (_, li, _, shape, _) in enumerate(items):
826
+ x0, y0, x1, y1 = _bbox(shape)
827
+ for gx in range(int(x0 // cell) - 0, int(x1 // cell) + 1):
828
+ for gy in range(int(y0 // cell), int(y1 // cell) + 1):
829
+ grid[(li, gx, gy)].append(i)
830
+ seen: set[tuple[int, int]] = set()
831
+ best = math.inf
832
+ per_layer: dict[int, float] = {}
833
+ tight: list[tuple[float, int, int]] = []
834
+ below = 0
835
+ for members in grid.values():
836
+ for a_i in range(len(members)):
837
+ for b_i in range(a_i + 1, len(members)):
838
+ i, j = members[a_i], members[b_i]
839
+ key = (i, j) if i < j else (j, i)
840
+ if key in seen:
841
+ continue
842
+ seen.add(key)
843
+ ka, la, na, sa, ra = items[i]
844
+ kb, lb, nb, sb, rb = items[j]
845
+ if not (ra or rb) or (na and na == nb):
846
+ continue
847
+ d = _shape_dist(sa, sb)
848
+ if d < per_layer.get(la, math.inf):
849
+ per_layer[la] = d
850
+ if d < best:
851
+ best = d
852
+ if rule_min is not None and d < rule_min - 1e-4:
853
+ below += 1
854
+ if d < 0.5:
855
+ tight.append((d, i, j))
856
+ tight.sort()
857
+ spots = []
858
+ for d, i, j in tight[:5]:
859
+ a, b = items[i], items[j]
860
+ x0, y0, x1, y1 = _bbox(a[3])
861
+ spots.append(
862
+ {
863
+ "clearance_mm": round(d, 4),
864
+ "layer": names[a[1]],
865
+ "items": f"{a[0]}[{a[2] or '-'}] / {b[0]}[{b[2] or '-'}]",
866
+ "at": [round((x0 + x1) / 2, 2), round((y0 + y1) / 2, 2)],
867
+ }
868
+ )
869
+ return {
870
+ "min_mm": None if best == math.inf else round(best, 4),
871
+ "per_layer": {names[k]: round(v, 4) for k, v in sorted(per_layer.items())},
872
+ "below_rule": below,
873
+ "tightest": spots,
874
+ "pairs_checked": len(seen),
875
+ }
876
+
877
+
878
+ def _copper_section(src: Source, warn: _Warnings) -> dict:
879
+ board = src.board
880
+ per = _track_widths(board)
881
+ rules = (((src.project.get("board") or {}).get("design_settings")) or {}).get("rules") or {}
882
+ rule_min = rules.get("min_clearance")
883
+ length_rows: list[list[Any]] = []
884
+ hist_rows: list[list[Any]] = []
885
+ counts = Counter(t.layer for t in board.tracks)
886
+ for layer in board.copper_layers:
887
+ hist = per.get(layer, Counter())
888
+ total = sum(hist.values())
889
+ length_rows.append(
890
+ [
891
+ layer,
892
+ counts.get(layer, 0),
893
+ round(total, 2),
894
+ min(hist) if hist else "-",
895
+ max(hist) if hist else "-",
896
+ ]
897
+ )
898
+ for w in sorted(hist):
899
+ hist_rows.append(
900
+ [
901
+ layer,
902
+ w,
903
+ sum(1 for t in board.tracks if t.layer == layer and abs(t.width - w) < 1e-4),
904
+ round(hist[w], 2),
905
+ ]
906
+ )
907
+ vias: Counter = Counter()
908
+ names = board.copper_layers
909
+ for v in board.vias:
910
+ span = [n for n in v.layers if n in names]
911
+ label = f"{span[0]}-{span[-1]}" if len(span) >= 2 else f"{names[0]}-{names[-1]}"
912
+ vias[(round(v.size, 3), round(v.drill, 3), label)] += 1
913
+ via_rows = [[s, d, span, n] for (s, d, span), n in sorted(vias.items())]
914
+ if board.vias:
915
+ ring = min((v.size - v.drill) / 2 for v in board.vias)
916
+ facts_via = f"{len(board.vias)} vias, smallest annular ring {_num(ring, 3)} mm"
917
+ if ring < src.fab.min_annular_ring - 1e-9:
918
+ warn.add(
919
+ "P1",
920
+ "copper",
921
+ f"annular ring {ring:.3f} mm is below {src.fab.name}'s {src.fab.min_annular_ring} mm",
922
+ )
923
+ else:
924
+ facts_via = "no vias"
925
+ clear = measure_clearance(board, rule_min)
926
+ if clear["min_mm"] is not None and rule_min and clear["min_mm"] < rule_min - 1e-3:
927
+ warn.add(
928
+ "P1",
929
+ "copper",
930
+ f"measured clearance {clear['min_mm']} mm is below the rule {rule_min} mm ({clear['below_rule']} pairs)",
931
+ )
932
+ clear_rows = [[layer, _num(v, 3)] for layer, v in clear["per_layer"].items()]
933
+ # neck-downs: segments narrower than the class width of their net
934
+ classes = _net_class_of(src)
935
+ class_width: dict[str, float] = {}
936
+ for net, cname in classes.items():
937
+ w = _class_values(src, cname).get("track_width")
938
+ if w:
939
+ class_width[net] = float(w)
940
+ default_w = float(_class_values(src, "Default").get("track_width") or src.fab.default_track)
941
+ small_pads = [
942
+ p
943
+ for fp in board.footprints
944
+ for p in fp.pads
945
+ if p.kind == "smd" and min(p.width, p.height) <= 0.35
946
+ ]
947
+ necks: dict[str, dict] = {}
948
+ for t in board.tracks:
949
+ want = class_width.get(t.net, default_w)
950
+ if t.width < want - 1e-4:
951
+ entry = necks.setdefault(
952
+ t.net, {"want": want, "min": t.width, "segments": 0, "length": 0.0, "pad_escape": 0}
953
+ )
954
+ entry["segments"] += 1
955
+ entry["length"] += t.length
956
+ entry["min"] = min(entry["min"], t.width)
957
+ if any(
958
+ math.hypot(t.x1 - p.x, t.y1 - p.y) < 1.0 or math.hypot(t.x2 - p.x, t.y2 - p.y) < 1.0
959
+ for p in small_pads
960
+ ):
961
+ entry["pad_escape"] += 1
962
+ neck_rows = [
963
+ [n, e["want"], e["min"], e["segments"], round(e["length"], 2), e["pad_escape"]]
964
+ for n, e in sorted(necks.items(), key=lambda kv: -kv[1]["length"])
965
+ ]
966
+ tables = [
967
+ _table(
968
+ "Tracks per layer",
969
+ ["Layer", "Segments", "Length mm", "Narrowest mm", "Widest mm"],
970
+ length_rows,
971
+ ),
972
+ _table("Track width histogram", ["Layer", "Width mm", "Segments", "Length mm"], hist_rows),
973
+ _table("Vias by size and span", ["Diameter mm", "Drill mm", "Span", "Count"], via_rows),
974
+ _table(
975
+ "Measured minimum clearance per layer",
976
+ ["Layer", "Clearance mm"],
977
+ clear_rows,
978
+ "Different-net copper only; tracks, vias and pads as stored in the file (zone fill excluded).",
979
+ ),
980
+ ]
981
+ if neck_rows:
982
+ tables.append(
983
+ _table(
984
+ "Neck-downs (segments narrower than the net's class width)",
985
+ [
986
+ "Net",
987
+ "Class width mm",
988
+ "Narrowest mm",
989
+ "Segments",
990
+ "Length mm",
991
+ "Near fine-pitch pads",
992
+ ],
993
+ neck_rows,
994
+ "Fine-pitch pad escapes (pad 0.35 mm or narrower within 1 mm) are expected to neck down.",
995
+ )
996
+ )
997
+ angles = track_angles(board)
998
+ if board.tracks:
999
+ total_straight = sum(angles["length_by_direction"].values()) or 1.0
1000
+ tables.append(
1001
+ _table(
1002
+ "Track directions and bends",
1003
+ ["Direction (deg from X axis)", "Length mm", "Share %"],
1004
+ [
1005
+ [k, round(v, 2), round(v / total_straight * 100, 1)]
1006
+ for k, v in angles["length_by_direction"].items()
1007
+ if v
1008
+ ],
1009
+ f"Bends between two segments of one net: {angles['bends']['acute']} acute (under 90 deg), "
1010
+ f"{angles['bends']['right']} right-angle, {angles['bends']['obtuse']} obtuse (135 deg or softer); "
1011
+ "arcs excluded. Acute and right-angle bends are a DFM note (acid traps, etch uniformity); "
1012
+ "45 deg corners are the usual practice.",
1013
+ )
1014
+ )
1015
+ if angles["bends"]["acute"]:
1016
+ warn.add(
1017
+ "P2",
1018
+ "copper",
1019
+ f"{angles['bends']['acute']} acute-angle track bend(s) (under 90 deg)",
1020
+ )
1021
+ if clear["tightest"]:
1022
+ tables.append(
1023
+ _table(
1024
+ "Tightest spots",
1025
+ ["Clearance mm", "Layer", "Items", "At (x, y) mm"],
1026
+ [
1027
+ [s["clearance_mm"], s["layer"], s["items"], f"{s['at'][0]}, {s['at'][1]}"]
1028
+ for s in clear["tightest"]
1029
+ ],
1030
+ )
1031
+ )
1032
+ total_len = sum(sum(c.values()) for c in per.values())
1033
+ notes = (
1034
+ []
1035
+ if board.tracks
1036
+ else [
1037
+ "The board has no routed tracks yet; track, via and clearance figures appear after routing."
1038
+ ]
1039
+ )
1040
+ return _section(
1041
+ "Routed copper",
1042
+ [
1043
+ ("Tracks", f"{len(board.tracks)} segments, {_num(total_len, 1)} mm total"),
1044
+ ("Vias", facts_via),
1045
+ (
1046
+ "Measured minimum clearance",
1047
+ f"{_num(clear['min_mm'], 3)} mm"
1048
+ if clear["min_mm"] is not None
1049
+ else "no routed copper",
1050
+ ),
1051
+ ("Rule minimum clearance", f"{_num(rule_min, 3)} mm" if rule_min else "not set"),
1052
+ ("Neck-downed nets", len(neck_rows)),
1053
+ ],
1054
+ tables,
1055
+ notes,
1056
+ data={
1057
+ "clearance": clear,
1058
+ "angles": angles,
1059
+ "vias": len(board.vias),
1060
+ "tracks": len(board.tracks),
1061
+ "necks": necks,
1062
+ "track_length_mm": round(total_len, 2),
1063
+ },
1064
+ )
1065
+
1066
+
1067
+ # ------------------------------------------------------------------------------------ net classes
1068
+ def _declared(src: Source, electrical: dict | None) -> tuple[dict[str, float], dict[str, float]]:
1069
+ spec = electrical if electrical is not None else ipc2221.load_electrical(src.workspace)
1070
+ return ipc2221.declared(src.board, spec, _net_class_of(src))
1071
+
1072
+
1073
+ def _power_nets(src: Source, currents: dict[str, float]) -> list[str]:
1074
+ nets = {n for n in src.board.nets.values() if n}
1075
+ found = set(currents)
1076
+ if src.spec is not None:
1077
+ found |= {n for n in src.spec.power_nets if n in nets}
1078
+ classes = _net_class_of(src)
1079
+ for net, cname in classes.items():
1080
+ if re.search(r"power|pwr|supply|rail", cname, re.I):
1081
+ found.add(net)
1082
+ for net in nets:
1083
+ v = circuits.rail_voltage(net)
1084
+ if v is not None and v != 0:
1085
+ found.add(net)
1086
+ return sorted(found)
1087
+
1088
+
1089
+ def _net_classes_section(
1090
+ src: Source, warn: _Warnings, delta_t: float, electrical: dict | None
1091
+ ) -> dict:
1092
+ board = src.board
1093
+ classes = _classes(src)
1094
+ assignment = _net_class_of(src)
1095
+ layer_map = (((src.project.get("traceforge") or {}).get("constraints")) or {}).get(
1096
+ "net_layers"
1097
+ ) or {}
1098
+ members: dict[str, list[str]] = defaultdict(list)
1099
+ for net in sorted({n for n in board.nets.values() if n}):
1100
+ members[assignment.get(net, "Default")].append(net)
1101
+ min_width: dict[str, float] = {}
1102
+ for t in board.tracks:
1103
+ min_width[t.net] = min(min_width.get(t.net, math.inf), t.width)
1104
+ rows = []
1105
+ for c in classes:
1106
+ name = c.get("name", "Default")
1107
+ nets = members.get(name, [])
1108
+ if name != "Default" and not nets:
1109
+ continue
1110
+ layers = (
1111
+ sorted(
1112
+ {layer for n in nets for layer in layer_map.get(n, [])},
1113
+ key=board.copper_layers.index,
1114
+ )
1115
+ if nets
1116
+ else []
1117
+ )
1118
+ shown = ", ".join(nets[:6]) + (f" (+{len(nets) - 6} more)" if len(nets) > 6 else "")
1119
+ rows.append(
1120
+ [
1121
+ name,
1122
+ len(nets),
1123
+ c.get("track_width", ""),
1124
+ c.get("clearance", ""),
1125
+ f"{c.get('via_diameter', '')} / {c.get('via_drill', '')}",
1126
+ f"{c.get('diff_pair_width', '')} / {c.get('diff_pair_gap', '')}"
1127
+ if name.startswith("DiffPair")
1128
+ else "-",
1129
+ ", ".join(layers) if layers else "all signal layers",
1130
+ shown if name != "Default" else f"{len(nets)} nets",
1131
+ ]
1132
+ )
1133
+ tables = [
1134
+ _table(
1135
+ "Net classes",
1136
+ [
1137
+ "Class",
1138
+ "Nets",
1139
+ "Track mm",
1140
+ "Clearance mm",
1141
+ "Via / drill mm",
1142
+ "Pair width / gap mm",
1143
+ "Allowed layers",
1144
+ "Members",
1145
+ ],
1146
+ rows,
1147
+ )
1148
+ ]
1149
+ # ---- current capacity of the power nets
1150
+ currents, volts = _declared(src, electrical)
1151
+ power = _power_nets(src, currents)
1152
+ cap_rows: list[list[Any]] = []
1153
+ plane_nets = (
1154
+ {n for ls in src.stack.plane_net_lists().values() for n in ls} if src.stack else set()
1155
+ )
1156
+ by_net_layer: dict[str, dict[str, float]] = defaultdict(dict)
1157
+ for t in board.tracks:
1158
+ cur = by_net_layer[t.net].get(t.layer, math.inf)
1159
+ by_net_layer[t.net][t.layer] = min(cur, t.width)
1160
+ for net in power:
1161
+ if net in plane_nets and net not in by_net_layer:
1162
+ cap_rows.append(
1163
+ [
1164
+ net,
1165
+ "plane",
1166
+ "-",
1167
+ "-",
1168
+ "-",
1169
+ currents.get(net, ""),
1170
+ volts.get(net, ""),
1171
+ "poured plane",
1172
+ ]
1173
+ )
1174
+ continue
1175
+ layers = by_net_layer.get(net)
1176
+ if not layers:
1177
+ cap_rows.append(
1178
+ [
1179
+ net,
1180
+ "-",
1181
+ "-",
1182
+ "-",
1183
+ "-",
1184
+ currents.get(net, ""),
1185
+ volts.get(net, ""),
1186
+ "no routed tracks",
1187
+ ]
1188
+ )
1189
+ continue
1190
+ worst = None
1191
+ for layer, w in layers.items():
1192
+ amps = ipc2221.max_current_a(
1193
+ w, delta_t=delta_t, copper_oz=_layer_oz(src, layer), internal=_is_inner(src, layer)
1194
+ )
1195
+ if worst is None or amps < worst[2]:
1196
+ worst = (layer, w, amps)
1197
+ assert worst is not None
1198
+ layer, w, amps = worst
1199
+ declared = currents.get(net)
1200
+ status = "ok"
1201
+ if declared is not None and amps < declared:
1202
+ need = ipc2221.min_width_mm(
1203
+ declared,
1204
+ delta_t=delta_t,
1205
+ copper_oz=_layer_oz(src, layer),
1206
+ internal=_is_inner(src, layer),
1207
+ )
1208
+ status = f"NARROW: needs {need:.2f} mm for {declared:g} A"
1209
+ warn.add(
1210
+ "P1",
1211
+ "net_classes",
1212
+ f"{net}: narrowest segment {w:.3f} mm on {layer} carries {amps:.2f} A (IPC-2221, {delta_t:g} K) but {declared:g} A is declared",
1213
+ )
1214
+ elif declared is None:
1215
+ status = "no current declared"
1216
+ cls_w = _class_values(src, assignment.get(net, "Default")).get("track_width")
1217
+ if cls_w and w < float(cls_w) - 1e-4 and status == "ok":
1218
+ status = f"necked below class width {cls_w}"
1219
+ cap_rows.append(
1220
+ [
1221
+ net,
1222
+ layer,
1223
+ w,
1224
+ round(amps, 2),
1225
+ _layer_oz(src, layer),
1226
+ declared if declared is not None else "",
1227
+ volts.get(net, ""),
1228
+ status,
1229
+ ]
1230
+ )
1231
+ tables.append(
1232
+ _table(
1233
+ f"Current capacity of power nets (IPC-2221, {delta_t:g} K rise)",
1234
+ [
1235
+ "Net",
1236
+ "Narrowest on",
1237
+ "Width mm",
1238
+ "Capacity A",
1239
+ "Copper oz",
1240
+ "Declared A",
1241
+ "Voltage V",
1242
+ "Status",
1243
+ ],
1244
+ cap_rows,
1245
+ "I = k * dT^0.44 * A^0.725, A = width(mil) * oz * 1.378 mil; k = 0.048 outer, 0.024 inner. "
1246
+ "Declare currents with a net class such as Power_3A or .traceforge/electrical.yaml. "
1247
+ "IPC-2152 is more accurate (it accounts for plane proximity); this is the conservative screen.",
1248
+ )
1249
+ )
1250
+ # width needed for a given current, at the board's own copper weights
1251
+ outer_oz = _layer_oz(src, board.copper_layers[0]) if board.copper_layers else 1.0
1252
+ inner_layers = board.copper_layers[1:-1]
1253
+ inner_oz = _layer_oz(src, inner_layers[0]) if inner_layers else None
1254
+ ref_rows = []
1255
+ for amps in (0.5, 1, 2, 3, 5, 10):
1256
+ outer = ipc2221.min_width_mm(amps, delta_t=delta_t, copper_oz=outer_oz, internal=False)
1257
+ inner = (
1258
+ ipc2221.min_width_mm(amps, delta_t=delta_t, copper_oz=inner_oz, internal=True)
1259
+ if inner_oz
1260
+ else None
1261
+ )
1262
+ ref_rows.append([amps, f"{outer:.2f}", f"{inner:.2f}" if inner is not None else "-"])
1263
+ tables.append(
1264
+ _table(
1265
+ "Track width needed for a current (IPC-2221)",
1266
+ [
1267
+ "Current A",
1268
+ f"Outer, {outer_oz:g} oz mm",
1269
+ f"Inner, {inner_oz:g} oz mm" if inner_oz else "Inner mm",
1270
+ ],
1271
+ ref_rows,
1272
+ f"{delta_t:g} K rise. Inner layers cool worse, so the same current needs a wider track.",
1273
+ )
1274
+ )
1275
+ # spacing vs voltage
1276
+ space_rows = []
1277
+ default_clear = float(
1278
+ _class_values(src, "Default").get("clearance") or src.fab.default_clearance
1279
+ )
1280
+ for net in power:
1281
+ v = volts.get(net)
1282
+ if not v:
1283
+ continue
1284
+ cls = _class_values(src, assignment.get(net, "Default"))
1285
+ clear = float(cls.get("clearance") or default_clear)
1286
+ ext, internal = ipc2221.spacing_mm(abs(v), "B2"), ipc2221.spacing_mm(abs(v), "B1")
1287
+ status = (
1288
+ "ok"
1289
+ if clear >= ext - 1e-9
1290
+ else ("ok internal only" if clear >= internal else "BELOW IPC-2221")
1291
+ )
1292
+ if status == "BELOW IPC-2221" and abs(v) > 50:
1293
+ warn.add(
1294
+ "P2",
1295
+ "net_classes",
1296
+ f"{net} at {v:g} V: clearance {clear} mm is below IPC-2221B's {ext} mm external spacing",
1297
+ )
1298
+ space_rows.append([net, v, clear, ext, internal, status])
1299
+ if space_rows:
1300
+ tables.append(
1301
+ _table(
1302
+ "Conductor spacing against voltage (IPC-2221B Table 6-1)",
1303
+ [
1304
+ "Net",
1305
+ "Voltage V",
1306
+ "Class clearance mm",
1307
+ "External, uncoated (B2) mm",
1308
+ "Internal (B1) mm",
1309
+ "Status",
1310
+ ],
1311
+ space_rows,
1312
+ "Guide values; creepage/clearance for safety approval follow the product standard.",
1313
+ )
1314
+ )
1315
+ return _section(
1316
+ "Net classes and current capacity",
1317
+ [
1318
+ ("Temperature rise assumed", f"{delta_t:g} K above ambient"),
1319
+ ("Classes", len(rows)),
1320
+ ("Power nets", len(power)),
1321
+ ],
1322
+ tables,
1323
+ data={"power_nets": power, "declared_current_a": currents, "delta_t": delta_t},
1324
+ )
1325
+
1326
+
1327
+ # ------------------------------------------------------------------------------------ pairs and groups
1328
+ def _tracks_of(board: Board, net: str):
1329
+ return [t for t in board.tracks if t.net == net]
1330
+
1331
+
1332
+ def _coupled_profile(pos_tracks, neg_tracks, pitch: float) -> dict:
1333
+ """Where the two nets run side by side: coupled length per (layer, width) and measured gaps.
1334
+
1335
+ The positive net is sampled every 0.25 mm; a sample is coupled when the negative net runs on the
1336
+ same layer within 1.25 pitches (edge to edge gap = centre distance minus both half widths).
1337
+ """
1338
+ neg_segs = [(t.x1, t.y1, t.x2, t.y2, t.width / 2, t.layer) for t in neg_tracks]
1339
+ by_key: Counter = Counter()
1340
+ gaps: dict[str, list[float]] = defaultdict(list)
1341
+ for t in pos_tracks:
1342
+ length = t.length
1343
+ steps = max(1, math.ceil(length / 0.25))
1344
+ for k in range(steps):
1345
+ f = (k + 0.5) / steps
1346
+ px, py = t.x1 + (t.x2 - t.x1) * f, t.y1 + (t.y2 - t.y1) * f
1347
+ best = math.inf
1348
+ for x1, y1, x2, y2, r, layer in neg_segs:
1349
+ if layer != t.layer:
1350
+ continue
1351
+ best = min(
1352
+ best, _seg_seg_dist((px, py, px, py), (x1, y1, x2, y2)) - r - t.width / 2
1353
+ )
1354
+ if best <= max(pitch, 0.1) * 1.25:
1355
+ by_key[(t.layer, round(t.width, 4))] += length / steps
1356
+ gaps[t.layer].append(best)
1357
+ return {"by_key": by_key, "gaps": gaps}
1358
+
1359
+
1360
+ def _terminals(board: Board, pos: str, neg: str) -> list[tuple[list[Pad], list[Pad]]]:
1361
+ """Places where both nets of a pair meet: each footprint's pads of ``pos`` with the nearest
1362
+ footprint's pads of ``neg`` (the same part, or the twin series resistor beside it)."""
1363
+ groups: dict[str, dict[str, list[Pad]]] = {pos: defaultdict(list), neg: defaultdict(list)}
1364
+ for fp in board.footprints:
1365
+ for pad in fp.pads:
1366
+ if pad.net in groups:
1367
+ groups[pad.net][fp.reference].append(pad)
1368
+
1369
+ def centre(pads: list[Pad]) -> tuple[float, float]:
1370
+ return sum(q.x for q in pads) / len(pads), sum(q.y for q in pads) / len(pads)
1371
+
1372
+ found = []
1373
+ for pads in groups[pos].values():
1374
+ cx, cy = centre(pads)
1375
+ near = min(
1376
+ groups[neg].values(),
1377
+ key=lambda g: math.dist(centre(g), (cx, cy)),
1378
+ default=None,
1379
+ )
1380
+ if near is not None and math.dist(centre(near), (cx, cy)) <= 5.0:
1381
+ found.append((pads, near))
1382
+ return found
1383
+
1384
+
1385
+ def _path_length(board: Board, net: str, ends_a: list[Pad], ends_b: list[Pad]) -> float | None:
1386
+ """Shortest track path of ``net`` between two pad groups (stubs and jumpers do not count)."""
1387
+ import heapq
1388
+
1389
+ tracks = [t for t in board.tracks if t.net == net]
1390
+ if not tracks:
1391
+ return None
1392
+ graph: dict[tuple, list[tuple[tuple, float]]] = defaultdict(list)
1393
+
1394
+ def link(u, v, w: float) -> None:
1395
+ graph[u].append((v, w))
1396
+ graph[v].append((u, w))
1397
+
1398
+ points: dict[str, set[tuple[float, float]]] = defaultdict(set)
1399
+ for t in tracks:
1400
+ points[t.layer] |= {(round(t.x1, 3), round(t.y1, 3)), (round(t.x2, 3), round(t.y2, 3))}
1401
+ for t in tracks:
1402
+ a, b = (round(t.x1, 3), round(t.y1, 3)), (round(t.x2, 3), round(t.y2, 3))
1403
+ straight = math.dist(a, b)
1404
+ scale = t.length / straight if straight > 1e-9 else 1.0
1405
+ inner = [
1406
+ q for q in points[t.layer] if q not in (a, b) and diffpair.point_on_segment(q, a, b)
1407
+ ]
1408
+ inner.sort(key=lambda q: math.dist(q, a))
1409
+ chain = [a, *inner, b]
1410
+ for p, q in zip(chain, chain[1:]):
1411
+ link((p, t.layer), (q, t.layer), math.dist(p, q) * scale)
1412
+ for v in (v for v in board.vias if v.net == net):
1413
+ at = [
1414
+ (q, layer)
1415
+ for layer, pts in points.items()
1416
+ for q in pts
1417
+ if math.hypot(q[0] - v.x, q[1] - v.y) <= v.size / 2 + 0.01
1418
+ ]
1419
+ for i in range(len(at) - 1):
1420
+ link(at[i], at[i + 1], 0.0)
1421
+
1422
+ def pad_nodes(pads: list[Pad]) -> list[tuple]:
1423
+ nodes: list[tuple] = []
1424
+ for pad in pads:
1425
+ mine = [
1426
+ (q, layer)
1427
+ for layer, pts in points.items()
1428
+ for q in pts
1429
+ if pad.on_layer(layer) and pad.contains(q[0], q[1], 0.01)
1430
+ ]
1431
+ for i in range(len(mine) - 1): # a through-hole pad joins its layers
1432
+ link(mine[i], mine[i + 1], 0.0)
1433
+ nodes += mine
1434
+ return nodes
1435
+
1436
+ sources, targets = pad_nodes(ends_a), set(pad_nodes(ends_b))
1437
+ if not sources or not targets:
1438
+ return None
1439
+ dist = {n: 0.0 for n in sources}
1440
+ heap = [(0.0, i, n) for i, n in enumerate(sources)]
1441
+ heapq.heapify(heap)
1442
+ count = len(heap)
1443
+ while heap:
1444
+ d, _, node = heapq.heappop(heap)
1445
+ if node in targets:
1446
+ return d
1447
+ if d > dist.get(node, math.inf):
1448
+ continue
1449
+ for nb, w in graph.get(node, []):
1450
+ if d + w < dist.get(nb, math.inf) - 1e-12:
1451
+ dist[nb] = d + w
1452
+ count += 1
1453
+ heapq.heappush(heap, (d + w, count, nb))
1454
+ return None
1455
+
1456
+
1457
+ def _pair_lengths(
1458
+ board: Board, pos: str, neg: str, whole: dict[str, float]
1459
+ ) -> tuple[float, float, str]:
1460
+ """(length of pos, length of neg, basis): terminal to terminal when both can be traced."""
1461
+ terms = _terminals(board, pos, neg)
1462
+ if len(terms) >= 2:
1463
+ best = max(
1464
+ ((a, b) for i, a in enumerate(terms) for b in terms[i + 1 :]),
1465
+ key=lambda ab: math.dist(
1466
+ (ab[0][0][0].x, ab[0][0][0].y), (ab[1][0][0].x, ab[1][0][0].y)
1467
+ ),
1468
+ )
1469
+ (p1, n1), (p2, n2) = best
1470
+ lp = _path_length(board, pos, p1, p2)
1471
+ ln = _path_length(board, neg, n1, n2)
1472
+ if lp is not None and ln is not None:
1473
+ return lp, ln, "between the pair's ends"
1474
+ return whole.get(pos, 0.0), whole.get(neg, 0.0), "whole nets"
1475
+
1476
+
1477
+ def _pairs_section(src: Source, warn: _Warnings, route_report: dict | None) -> dict:
1478
+ board, stack = src.board, src.stack
1479
+ assert stack is not None
1480
+ cfg = (src.project.get("traceforge") or {}).get("diff_pairs") or []
1481
+ items: list[dict] = [dict(c) for c in cfg if len(c.get("nets") or []) == 2]
1482
+ detected = False
1483
+ if not items:
1484
+ names = [n for n in board.nets.values() if n]
1485
+ items = [{"nets": [p, n]} for p, n in diffpair.pair_names(names)]
1486
+ detected = bool(items)
1487
+ lengths = _net_lengths(board)
1488
+ report = (route_report or {}).get("differential_pairs") or {}
1489
+ rows: list[list[Any]] = []
1490
+ data: dict[str, Any] = {}
1491
+ for item in items:
1492
+ pos, neg = item["nets"]
1493
+ pt, nt = _tracks_of(board, pos), _tracks_of(board, neg)
1494
+ if not pt and not nt:
1495
+ rows.append(
1496
+ [
1497
+ f"{pos}/{neg}",
1498
+ "-",
1499
+ "-",
1500
+ "-",
1501
+ item.get("impedance", ""),
1502
+ "-",
1503
+ "-",
1504
+ "-",
1505
+ "-",
1506
+ "-",
1507
+ "-",
1508
+ "not routed",
1509
+ ]
1510
+ )
1511
+ continue
1512
+ design_gap = float(item.get("gap") or 0.2)
1513
+ profile = _coupled_profile(pt, nt, 0.25 + design_gap)
1514
+ if profile["by_key"]:
1515
+ (layer, width), _ = profile["by_key"].most_common(1)[0]
1516
+ coupled = sum(profile["by_key"].values())
1517
+ gaps = sorted(profile["gaps"][layer])
1518
+ gap_med = gaps[len(gaps) // 2] if gaps else None
1519
+ else: # never side by side: describe the most-used layer and width
1520
+ by_layer: Counter = Counter()
1521
+ for t in (*pt, *nt):
1522
+ by_layer[t.layer] += t.length
1523
+ layer = by_layer.most_common(1)[0][0]
1524
+ widths: Counter = Counter()
1525
+ for t in (*pt, *nt):
1526
+ if t.layer == layer:
1527
+ widths[round(t.width, 4)] += t.length
1528
+ width = widths.most_common(1)[0][0]
1529
+ coupled, gap_med = 0.0, None
1530
+ gap_used = gap_med if gap_med is not None and gap_med > 0 else design_gap
1531
+ target = float(item.get("impedance") or diffpair.USB_IMPEDANCE)
1532
+ try:
1533
+ achieved = impedance.differential(stack, layer, width, gap_used)
1534
+ geometry = impedance.geometry_name(stack, layer)
1535
+ except (stackup.StackupError, ValueError):
1536
+ achieved, geometry = float("nan"), "n/a"
1537
+ error = (achieved - target) / target * 100 if achieved == achieved else float("nan")
1538
+ lp, ln, basis = _pair_lengths(board, pos, neg, lengths)
1539
+ skew = abs(lp - ln)
1540
+ tol = float(item.get("tolerance") or 0.1)
1541
+ vias = sum(1 for v in board.vias if v.net in (pos, neg))
1542
+ refs = []
1543
+ for ref in (stack.reference_above(layer), stack.reference_below(layer)):
1544
+ if ref is not None:
1545
+ refs.append(stack.copper[ref[0]].name)
1546
+ status = []
1547
+ shorter = max(min(lp, ln), 1e-9)
1548
+ mostly_uncoupled = coupled < 0.2 * shorter
1549
+ if mostly_uncoupled:
1550
+ # impedance of a pair is only meaningful where the two nets run side by side
1551
+ status.append(f"mostly uncoupled: {coupled:.1f} of {shorter:.1f} mm side by side")
1552
+ warn.add(
1553
+ "P2",
1554
+ "pairs",
1555
+ f"{pos}/{neg}: only {coupled:.1f} of {shorter:.1f} mm run side by side",
1556
+ )
1557
+ elif achieved == achieved and abs(error) > 10:
1558
+ status.append(f"impedance {error:+.0f}%")
1559
+ warn.add(
1560
+ "P2",
1561
+ "pairs",
1562
+ f"{pos}/{neg}: {achieved:.0f} ohm on {layer}, target {target:g} ohm ({error:+.0f}%)",
1563
+ )
1564
+ if skew > tol + 1e-6:
1565
+ status.append(f"skew {skew:.2f} > {tol:g}")
1566
+ warn.add("P2", "pairs", f"{pos}/{neg}: skew {skew:.2f} mm exceeds {tol:g} mm")
1567
+ if basis == "whole nets":
1568
+ status.append("lengths: whole nets")
1569
+ rep = report.get(f"{pos}/{neg}") or {}
1570
+ if rep.get("note"):
1571
+ status.append(rep["note"][:60])
1572
+ rows.append(
1573
+ [
1574
+ f"{pos}/{neg}",
1575
+ layer,
1576
+ geometry,
1577
+ f"{width} / {_num(gap_used, 3)}",
1578
+ target,
1579
+ "n/a" if achieved != achieved else f"{achieved:.1f}",
1580
+ "n/a" if error != error else f"{error:+.1f}",
1581
+ f"{lp:.2f} / {ln:.2f}",
1582
+ f"{skew:.2f}",
1583
+ f"{coupled:.1f}",
1584
+ ", ".join(refs) or "none",
1585
+ "; ".join(status) or "ok",
1586
+ ]
1587
+ )
1588
+ data[f"{pos}/{neg}"] = {
1589
+ "layer": layer,
1590
+ "width_mm": width,
1591
+ "gap_mm": gap_used,
1592
+ "target_ohm": target,
1593
+ "achieved_ohm": None if achieved != achieved else round(achieved, 2),
1594
+ "skew_mm": round(skew, 3),
1595
+ "length_basis": basis,
1596
+ "coupled_mm": round(coupled, 2),
1597
+ "vias": vias,
1598
+ }
1599
+ tables = []
1600
+ if rows:
1601
+ tables.append(
1602
+ _table(
1603
+ "Differential pairs (measured on the board)",
1604
+ [
1605
+ "Pair",
1606
+ "Layer",
1607
+ "Geometry",
1608
+ "Width / gap mm",
1609
+ "Target ohm",
1610
+ "Achieved ohm",
1611
+ "Error %",
1612
+ "Length P / N mm",
1613
+ "Skew mm",
1614
+ "Coupled mm",
1615
+ "Reference planes",
1616
+ "Status",
1617
+ ],
1618
+ rows,
1619
+ "Layer and width: where the two nets run side by side for the longest distance. Gap: median measured edge-to-edge "
1620
+ "gap over that run (design gap if never coupled). Impedance recomputed from the stackup (kicad/impedance.py). "
1621
+ "Lengths: shortest track path between the pair's two ends, so stubs and jumpers do not count; 'whole nets' in the "
1622
+ "status column when a path could not be traced.",
1623
+ )
1624
+ )
1625
+ groups = (src.project.get("traceforge") or {}).get("length_groups") or []
1626
+ group_rows = []
1627
+ pair_of = {n: (p["nets"][0], p["nets"][1]) for p in items for n in p["nets"]}
1628
+ for g in groups:
1629
+ seen: set[str] = set()
1630
+ members: dict[str, float] = {}
1631
+ for net in g.get("nets", []):
1632
+ if net in seen:
1633
+ continue
1634
+ twin = pair_of.get(net)
1635
+ group = [twin[0], twin[1]] if twin else [net]
1636
+ seen |= set(group)
1637
+ if all(lengths.get(n, 0) > 0 for n in group):
1638
+ if len(group) == 2:
1639
+ lp, ln, _ = _pair_lengths(board, group[0], group[1], lengths)
1640
+ members["/".join(group)] = (lp + ln) / 2
1641
+ else:
1642
+ members[group[0]] = lengths[group[0]]
1643
+ tol = float(g.get("tolerance", 0.5))
1644
+ if len(members) < 2:
1645
+ group_rows.append(
1646
+ [g.get("name"), len(g.get("nets", [])), "-", "-", tol, "not all members routed"]
1647
+ )
1648
+ continue
1649
+ spread = max(members.values()) - min(members.values())
1650
+ status = "ok" if spread <= tol else f"spread {spread:.2f} > {tol:g}"
1651
+ if spread > tol:
1652
+ warn.add(
1653
+ "P2",
1654
+ "pairs",
1655
+ f"length group {g.get('name')}: spread {spread:.2f} mm exceeds {tol:g} mm",
1656
+ )
1657
+ group_rows.append(
1658
+ [
1659
+ g.get("name"),
1660
+ len(members),
1661
+ f"{min(members.values()):.2f} - {max(members.values()):.2f}",
1662
+ f"{spread:.2f}",
1663
+ tol,
1664
+ status,
1665
+ ]
1666
+ )
1667
+ if group_rows:
1668
+ tables.append(
1669
+ _table(
1670
+ "Length groups",
1671
+ ["Group", "Members", "Length range mm", "Spread mm", "Tolerance mm", "Status"],
1672
+ group_rows,
1673
+ )
1674
+ )
1675
+ notes = []
1676
+ if detected:
1677
+ notes.append(
1678
+ "No pairs are declared in the project; pairs were detected by net name (X+/X-, X_P/X_N)."
1679
+ )
1680
+ if not items:
1681
+ notes.append("No differential pairs on this board.")
1682
+ return _section(
1683
+ "Differential pairs and length groups",
1684
+ [("Pairs", len(items)), ("Length groups", len(groups))],
1685
+ tables,
1686
+ notes,
1687
+ data,
1688
+ )
1689
+
1690
+
1691
+ # ------------------------------------------------------------------------------------ placement
1692
+ def _courtyard_gap(a: tuple, b: tuple) -> float:
1693
+ dx = max(a[0] - b[2], b[0] - a[2])
1694
+ dy = max(a[1] - b[3], b[1] - a[3])
1695
+ if dx >= 0 and dy >= 0:
1696
+ return math.hypot(dx, dy)
1697
+ if dx < 0 and dy < 0:
1698
+ return max(dx, dy) # overlap depth (negative)
1699
+ return max(dx, dy)
1700
+
1701
+
1702
+ def _edge_distance(fp: Footprint, board: Board) -> float | None:
1703
+ geom = board.edge_geometry
1704
+ if geom is None or fp.courtyard is None:
1705
+ return None
1706
+ x0, y0, x1, y1 = fp.courtyard
1707
+ pts = [
1708
+ (x0, y0),
1709
+ (x1, y0),
1710
+ (x1, y1),
1711
+ (x0, y1),
1712
+ ((x0 + x1) / 2, y0),
1713
+ ((x0 + x1) / 2, y1),
1714
+ (x0, (y0 + y1) / 2),
1715
+ (x1, (y0 + y1) / 2),
1716
+ ]
1717
+ worst = math.inf
1718
+ for x, y in pts:
1719
+ d = geom.distance(x, y)
1720
+ worst = min(worst, d if geom.inside(x, y) else -d)
1721
+ return worst
1722
+
1723
+
1724
+ def _decoupling(board: Board) -> list[dict]:
1725
+ ics = [f for f in board.footprints if f.reference.startswith("U")]
1726
+ rows = []
1727
+ for fp in board.footprints:
1728
+ if not fp.reference.startswith("C") or len(fp.pads) != 2:
1729
+ continue
1730
+ farads = _farads(fp.value)
1731
+ if farads is None or farads > 1e-6 + 1e-12:
1732
+ continue
1733
+ nets = [p.net for p in fp.pads]
1734
+ ground = [n for n in nets if n and circuits.rail_voltage(n) == 0.0]
1735
+ rails = [n for n in nets if n and n not in ground]
1736
+ if len(ground) != 1 or len(rails) != 1:
1737
+ continue
1738
+ pad = next(p for p in fp.pads if p.net == rails[0])
1739
+ best = None
1740
+ for ic in ics:
1741
+ for q in ic.pads:
1742
+ if q.net == rails[0]:
1743
+ d = math.hypot(pad.x - q.x, pad.y - q.y)
1744
+ if best is None or d < best[0]:
1745
+ best = (d, ic.reference, q.number)
1746
+ if best is not None:
1747
+ rows.append(
1748
+ {
1749
+ "cap": fp.reference,
1750
+ "value": fp.value,
1751
+ "rail": rails[0],
1752
+ "distance_mm": round(best[0], 2),
1753
+ "ic": best[1],
1754
+ "pin": best[2],
1755
+ }
1756
+ )
1757
+ return rows
1758
+
1759
+
1760
+ def _placement_section(src: Source, warn: _Warnings) -> dict:
1761
+ board = src.board
1762
+ fps = sorted(
1763
+ _placed(src),
1764
+ key=lambda f: (
1765
+ re.sub(r"\d+", "", f.reference),
1766
+ int("".join(c for c in f.reference if c.isdigit()) or 0),
1767
+ ),
1768
+ )
1769
+ rows = []
1770
+ buckets: Counter = Counter()
1771
+ off_angle: list[str] = []
1772
+ for f in fps:
1773
+ hc, _ = _fp_height_class(f)
1774
+ bucket = _rotation_bucket(f.angle)
1775
+ buckets[bucket] += 1
1776
+ if bucket == "other":
1777
+ off_angle.append(f"{f.reference} ({f.angle:g})")
1778
+ rows.append(
1779
+ [
1780
+ f.reference,
1781
+ f.value,
1782
+ f.lib_id.split(":")[-1],
1783
+ "bottom" if _bottom(f) else "top",
1784
+ f.x,
1785
+ f.y,
1786
+ _rel(src, f.x, f.y)[0],
1787
+ _rel(src, f.x, f.y)[1],
1788
+ round(f.angle % 360, 3),
1789
+ "yes" if _bottom(f) else "no",
1790
+ "yes" if f.locked else "no",
1791
+ hc,
1792
+ ]
1793
+ )
1794
+ top = sum(1 for f in fps if not _bottom(f))
1795
+ stats = [[k, buckets.get(k, 0)] for k in ("0", "90", "180", "270", "other")]
1796
+ if off_angle:
1797
+ non45 = [a for a in off_angle]
1798
+ warn.add(
1799
+ "P3",
1800
+ "placement",
1801
+ f"{len(non45)} part(s) at angles other than 0/90/180/270: {', '.join(non45[:6])}",
1802
+ )
1803
+ # courtyard spacing
1804
+ by_side: dict[str, list[Footprint]] = {"top": [], "bottom": []}
1805
+ for f in fps:
1806
+ if (
1807
+ f.courtyard is not None
1808
+ and f.reference[0] not in "HM"
1809
+ and not f.lib_id.startswith(("MountingHole", "Fiducial"))
1810
+ ):
1811
+ by_side["bottom" if _bottom(f) else "top"].append(f)
1812
+ gaps: list[tuple[float, str, str]] = []
1813
+ for group in by_side.values():
1814
+ cell = 5.0
1815
+ grid: dict[tuple[int, int], list[int]] = defaultdict(list)
1816
+ for i, f in enumerate(group):
1817
+ x0, y0, x1, y1 = f.courtyard # type: ignore[misc]
1818
+ for gx in range(int((x0 - 1) // cell), int((x1 + 1) // cell) + 1):
1819
+ for gy in range(int((y0 - 1) // cell), int((y1 + 1) // cell) + 1):
1820
+ grid[(gx, gy)].append(i)
1821
+ seen: set[tuple[int, int]] = set()
1822
+ for members in grid.values():
1823
+ for a in range(len(members)):
1824
+ for b in range(a + 1, len(members)):
1825
+ i, j = members[a], members[b]
1826
+ key = (min(i, j), max(i, j))
1827
+ if key in seen:
1828
+ continue
1829
+ seen.add(key)
1830
+ gaps.append(
1831
+ (
1832
+ _courtyard_gap(group[i].courtyard, group[j].courtyard),
1833
+ group[i].reference,
1834
+ group[j].reference,
1835
+ )
1836
+ ) # type: ignore[arg-type]
1837
+ gaps.sort()
1838
+ overlaps = [g for g in gaps if g[0] < -1e-6]
1839
+ tight = [g for g in gaps if -1e-6 <= g[0] < 0.25]
1840
+ if overlaps:
1841
+ warn.add(
1842
+ "P2",
1843
+ "placement",
1844
+ f"{len(overlaps)} courtyard overlap(s), worst {overlaps[0][1]}/{overlaps[0][2]} by {-overlaps[0][0]:.2f} mm",
1845
+ )
1846
+ # edge distance
1847
+ edge_rows = []
1848
+ for f in fps:
1849
+ if (
1850
+ f.edge is not None
1851
+ or f.reference[0] in "HM"
1852
+ or f.lib_id.startswith(("MountingHole", "Fiducial"))
1853
+ ):
1854
+ continue # edge connectors sit on the edge; holes and fiducials are placed by the outline
1855
+ d = _edge_distance(f, board)
1856
+ if d is not None:
1857
+ edge_rows.append((d, f.reference))
1858
+ edge_rows.sort()
1859
+ if edge_rows and edge_rows[0][0] < 0:
1860
+ warn.add("P1", "placement", f"{edge_rows[0][1]} extends past the board edge")
1861
+ deco = _decoupling(board)
1862
+ deco_sorted = sorted(deco, key=lambda r: -r["distance_mm"])
1863
+ far = [r for r in deco if r["distance_mm"] > 5.0]
1864
+ if far:
1865
+ warn.add(
1866
+ "P3",
1867
+ "placement",
1868
+ f"{len(far)} decoupling capacitor(s) are more than 5 mm from the supply pin they serve (worst {far[0]['cap']} at {deco_sorted[0]['distance_mm']} mm)",
1869
+ )
1870
+ checks = [
1871
+ ["Courtyard overlaps", len(overlaps), "none expected", "ok" if not overlaps else "REVIEW"],
1872
+ [
1873
+ "Courtyard gaps under 0.25 mm",
1874
+ len(tight),
1875
+ "typical assembly minimum; fab/assembler dependent",
1876
+ "ok" if not tight else "review",
1877
+ ],
1878
+ [
1879
+ "Smallest courtyard gap",
1880
+ _num(gaps[0][0], 3) + " mm" if gaps else "-",
1881
+ f"{gaps[0][1]} / {gaps[0][2]}" if gaps else "",
1882
+ "",
1883
+ ],
1884
+ [
1885
+ "Smallest courtyard to board edge",
1886
+ _num(edge_rows[0][0], 3) + " mm" if edge_rows else "-",
1887
+ edge_rows[0][1] if edge_rows else "",
1888
+ "ok" if not edge_rows or edge_rows[0][0] >= 0 else "REVIEW",
1889
+ ],
1890
+ [
1891
+ "Decoupling caps (<= 1 uF) checked",
1892
+ len(deco),
1893
+ "distance from the cap's supply pad to the nearest supply pin of an IC",
1894
+ "",
1895
+ ],
1896
+ [
1897
+ "Furthest decoupling cap",
1898
+ f"{deco_sorted[0]['distance_mm']} mm ({deco_sorted[0]['cap']} -> {deco_sorted[0]['ic']}.{deco_sorted[0]['pin']})"
1899
+ if deco_sorted
1900
+ else "-",
1901
+ "guideline: within about 5 mm; check the datasheet",
1902
+ "ok" if not far else "review",
1903
+ ],
1904
+ ]
1905
+ tables = [
1906
+ _table(
1907
+ "Rotation statistics",
1908
+ ["Angle (deg)", "Parts"],
1909
+ stats,
1910
+ "Angles other than 0/90/180/270 are flagged: some assemblers and pick-and-place files handle them poorly.",
1911
+ ),
1912
+ _table("Placement checks", ["Check", "Result", "Basis", "Status"], checks),
1913
+ _table(
1914
+ "Component placement",
1915
+ [
1916
+ "Ref",
1917
+ "Value",
1918
+ "Footprint",
1919
+ "Side",
1920
+ "X mm",
1921
+ "Y mm",
1922
+ "From corner X",
1923
+ "From corner Y",
1924
+ "Rotation deg",
1925
+ "Mirrored",
1926
+ "Locked",
1927
+ "Height class (estimated)",
1928
+ ],
1929
+ rows,
1930
+ "X/Y are KiCad board coordinates (Y grows downward) of the footprint origin; 'From corner' is measured from the outline's top-left corner. Rotation is counter-clockwise seen from the top, as stored in the board file.",
1931
+ ),
1932
+ ]
1933
+ if deco_sorted:
1934
+ tables.insert(
1935
+ 2,
1936
+ _table(
1937
+ "Furthest decoupling capacitors",
1938
+ ["Cap", "Value", "Rail", "Distance mm", "To"],
1939
+ [
1940
+ [r["cap"], r["value"], r["rail"], r["distance_mm"], f"{r['ic']}.{r['pin']}"]
1941
+ for r in deco_sorted[:5]
1942
+ ],
1943
+ ),
1944
+ )
1945
+ return _section(
1946
+ "Placement",
1947
+ [
1948
+ ("Parts", len(fps)),
1949
+ ("Top side", top),
1950
+ ("Bottom side", len(fps) - top),
1951
+ ("Off-angle parts", len(off_angle)),
1952
+ ("Locked parts", sum(1 for f in fps if f.locked)),
1953
+ ],
1954
+ tables,
1955
+ data={
1956
+ "rotation": dict(buckets),
1957
+ "courtyard_overlaps": len(overlaps),
1958
+ "decoupling": deco_sorted[:20],
1959
+ "parts": len(fps),
1960
+ },
1961
+ )
1962
+
1963
+
1964
+ # ------------------------------------------------------------------------------------ mechanical
1965
+ def _mechanical_section(src: Source, warn: _Warnings) -> dict:
1966
+ board = src.board
1967
+ rows = []
1968
+ for fp in board.footprints:
1969
+ low = fp.lib_id.lower()
1970
+ if "fiducial" in low:
1971
+ kind = "fiducial"
1972
+ elif "mountinghole" in low or fp.reference.startswith("H"):
1973
+ kind = "mounting hole"
1974
+ elif any(p.kind == "np_thru_hole" and p.drill >= 2.0 for p in fp.pads):
1975
+ kind = "part locating hole" # board-lock pegs of connectors and the like
1976
+ elif "tooling" in low:
1977
+ kind = "tooling hole"
1978
+ elif "testpoint" in low:
1979
+ kind = "test point"
1980
+ else:
1981
+ continue
1982
+ pad = fp.pads[0] if fp.pads else None
1983
+ diameter = (pad.drill or pad.width) if pad else 0.0
1984
+ plated = "yes" if pad and pad.kind == "thru_hole" else "no"
1985
+ rx, ry = _rel(src, fp.x, fp.y)
1986
+ rows.append(
1987
+ [
1988
+ fp.reference,
1989
+ kind,
1990
+ fp.x,
1991
+ fp.y,
1992
+ rx,
1993
+ ry,
1994
+ diameter,
1995
+ plated,
1996
+ "bottom" if _bottom(fp) else "top",
1997
+ ]
1998
+ )
1999
+ fiducials = sum(1 for r in rows if r[1] == "fiducial")
2000
+ if not fiducials and any(
2001
+ f.reference.startswith("U") and len(f.pads) > 20 for f in board.footprints
2002
+ ):
2003
+ warn.add(
2004
+ "P3",
2005
+ "mechanical",
2006
+ "no fiducials on a board with fine-pitch ICs; most assemblers want 2-3",
2007
+ )
2008
+ areas = []
2009
+ for a in board.rule_areas:
2010
+ pts = a.get("points") or a.get("polygon") or []
2011
+ if pts:
2012
+ xs, ys = [p[0] for p in pts], [p[1] for p in pts]
2013
+ bbox = f"{_num(min(xs), 1)},{_num(min(ys), 1)} - {_num(max(xs), 1)},{_num(max(ys), 1)}"
2014
+ else:
2015
+ bbox = "-"
2016
+ keep = a.get("keepout") or a.get("rules") or ""
2017
+ areas.append(
2018
+ [
2019
+ a.get("name", ""),
2020
+ ", ".join(a.get("layers", []))
2021
+ if isinstance(a.get("layers"), list)
2022
+ else a.get("layers", ""),
2023
+ str(keep),
2024
+ bbox,
2025
+ ]
2026
+ )
2027
+ conn_rows = []
2028
+ geom = board.edge_geometry
2029
+ for fp in sorted(_placed(src), key=lambda f: f.reference):
2030
+ if not re.match(r"^(J|P|USB|CN)", fp.reference):
2031
+ continue
2032
+ d = geom.distance(fp.x, fp.y) if geom is not None else None
2033
+ if fp.edge is not None and geom is not None:
2034
+ (ux, uy), (ex, ey) = fp.edge
2035
+ seat = geom.distance(ex, ey)
2036
+ facing = {
2037
+ (1, 0): "right",
2038
+ (-1, 0): "left",
2039
+ (0, 1): "bottom edge (+Y)",
2040
+ (0, -1): "top edge (-Y)",
2041
+ }.get((round(ux), round(uy)), f"{ux:.2f},{uy:.2f}")
2042
+ status = "seated on edge" if seat <= 0.3 else f"{seat:.2f} mm from the edge"
2043
+ if seat > 0.3:
2044
+ warn.add(
2045
+ "P2",
2046
+ "mechanical",
2047
+ f"{fp.reference} opening is {seat:.2f} mm from the board edge",
2048
+ )
2049
+ conn_rows.append(
2050
+ [
2051
+ fp.reference,
2052
+ fp.lib_id.split(":")[-1],
2053
+ round(fp.angle % 360, 2),
2054
+ "edge-mount, opening toward " + facing,
2055
+ _num(seat, 2) if seat is not None else "-",
2056
+ status,
2057
+ ]
2058
+ )
2059
+ else:
2060
+ conn_rows.append(
2061
+ [
2062
+ fp.reference,
2063
+ fp.lib_id.split(":")[-1],
2064
+ round(fp.angle % 360, 2),
2065
+ "not edge-mount",
2066
+ _num(d, 2) if d is not None else "-",
2067
+ "",
2068
+ ]
2069
+ )
2070
+ tables = []
2071
+ if rows:
2072
+ tables.append(
2073
+ _table(
2074
+ "Holes, fiducials and test points",
2075
+ [
2076
+ "Ref",
2077
+ "Type",
2078
+ "X mm",
2079
+ "Y mm",
2080
+ "From corner X",
2081
+ "From corner Y",
2082
+ "Diameter mm",
2083
+ "Plated",
2084
+ "Side",
2085
+ ],
2086
+ rows,
2087
+ "Diameter: drill for holes, copper diameter for fiducials.",
2088
+ )
2089
+ )
2090
+ if areas:
2091
+ tables.append(
2092
+ _table(
2093
+ "Keep-outs and rule areas", ["Name", "Layers", "Rules", "Bounding box mm"], areas
2094
+ )
2095
+ )
2096
+ if conn_rows:
2097
+ tables.append(
2098
+ _table(
2099
+ "Connectors and board edge",
2100
+ [
2101
+ "Ref",
2102
+ "Footprint",
2103
+ "Rotation deg",
2104
+ "Orientation",
2105
+ "Distance to edge mm",
2106
+ "Status",
2107
+ ],
2108
+ conn_rows,
2109
+ "Edge-mount: the connector's opening line must sit on the outline; distance is measured from that line. Others: distance from the footprint origin to the outline.",
2110
+ )
2111
+ )
2112
+ return _section(
2113
+ "Mechanical",
2114
+ [
2115
+ ("Mounting holes", sum(1 for r in rows if r[1] == "mounting hole")),
2116
+ ("Fiducials", fiducials),
2117
+ ("Tooling holes", sum(1 for r in rows if r[1] == "tooling hole")),
2118
+ ("Test points", sum(1 for r in rows if r[1] == "test point")),
2119
+ ("Keep-out areas", len(areas)),
2120
+ ("Connectors", len(conn_rows)),
2121
+ ],
2122
+ tables,
2123
+ )
2124
+
2125
+
2126
+ # ------------------------------------------------------------------------------------ assembly
2127
+ _SUPPLIER_FIELDS = ("LCSC", "LCSC Part", "LCSC Part #", "JLCPCB", "MPN", "Manufacturer_Part_Number")
2128
+
2129
+
2130
+ def _polarity(fp: Footprint) -> str | None:
2131
+ ref, low = fp.reference, (fp.lib_id + " " + fp.value).lower()
2132
+ if ref.startswith("D") or low.startswith("led") or "led_" in low:
2133
+ return "diode/LED: cathode orientation"
2134
+ if ref.startswith("Q"):
2135
+ return "transistor: pin 1 / tab orientation"
2136
+ if ref.startswith("U"):
2137
+ return "IC: pin 1 orientation"
2138
+ if re.search(r"(cp_|elec|tantalum|polarized)", low) and ref.startswith("C"):
2139
+ return "polarised capacitor: + marking"
2140
+ if ref.startswith(("J", "P")) and len(fp.pads) > 2:
2141
+ return "connector: keying / pin 1"
2142
+ if ref.startswith("SW") or ref.startswith("Y"):
2143
+ return None
2144
+ return None
2145
+
2146
+
2147
+ def _assembly_section(src: Source, warn: _Warnings) -> dict:
2148
+ fps = _placed(src)
2149
+ groups: dict[tuple, list[str]] = defaultdict(list)
2150
+ missing = 0
2151
+ dnp = 0
2152
+ for f in fps:
2153
+ if "exclude_from_bom" in f.attrs or "board_only" in f.attrs:
2154
+ continue
2155
+ has_pn = any(f.fields.get(k) for k in _SUPPLIER_FIELDS)
2156
+ if not has_pn:
2157
+ missing += 1
2158
+ if f.dnp:
2159
+ dnp += 1
2160
+ groups[
2161
+ (f.value, f.lib_id.split(":")[-1], f.fields.get("LCSC", ""), "DNP" if f.dnp else "")
2162
+ ].append(f.reference)
2163
+ bom_rows = []
2164
+ for (value_, footprint, lcsc, d), refs in sorted(groups.items(), key=lambda kv: kv[1][0]):
2165
+ bom_rows.append(
2166
+ [
2167
+ ", ".join(
2168
+ sorted(
2169
+ refs,
2170
+ key=lambda r: (
2171
+ re.sub(r"\d", "", r),
2172
+ int("".join(c for c in r if c.isdigit()) or 0),
2173
+ ),
2174
+ )
2175
+ ),
2176
+ len(refs),
2177
+ value_,
2178
+ footprint,
2179
+ lcsc,
2180
+ d,
2181
+ ]
2182
+ )
2183
+ if missing:
2184
+ warn.add(
2185
+ "P3", "assembly", f"{missing} part(s) have no supplier part number (LCSC/MPN field)"
2186
+ )
2187
+ bottom = [f for f in fps if _bottom(f)]
2188
+ from traceforge.kicad.sides import jlc_rotation
2189
+
2190
+ cpl_rows = [
2191
+ [
2192
+ f.reference,
2193
+ round(f.angle % 360, 3),
2194
+ round(jlc_rotation(f.angle, f.layer), 3),
2195
+ "bottom: 180 - angle (mirrored)",
2196
+ ]
2197
+ for f in sorted(bottom, key=lambda f: f.reference)
2198
+ ]
2199
+ odd = [f for f in fps if _rotation_bucket(f.angle) == "other"]
2200
+ pol = []
2201
+ for f in sorted(fps, key=lambda f: f.reference):
2202
+ kind = _polarity(f)
2203
+ if kind:
2204
+ pol.append(
2205
+ [
2206
+ f.reference,
2207
+ kind,
2208
+ "bottom" if _bottom(f) else "top",
2209
+ round(f.angle % 360, 2),
2210
+ round(jlc_rotation(f.angle, f.layer), 2),
2211
+ ]
2212
+ )
2213
+ tables = [
2214
+ _table(
2215
+ "Bill of materials (grouped)",
2216
+ ["References", "Qty", "Value", "Footprint", "LCSC", "DNP"],
2217
+ bom_rows,
2218
+ )
2219
+ ]
2220
+ if cpl_rows:
2221
+ tables.append(
2222
+ _table(
2223
+ "Bottom-side parts: placement file rotation",
2224
+ ["Ref", "Board angle deg", "CPL rotation deg", "Rule"],
2225
+ cpl_rows[:40],
2226
+ )
2227
+ )
2228
+ if pol:
2229
+ tables.append(
2230
+ _table(
2231
+ "Polarity- and orientation-sensitive parts",
2232
+ ["Ref", "Check", "Side", "Board angle deg", "CPL rotation deg"],
2233
+ pol[:80],
2234
+ "Confirm these in the assembler's placement preview: library pin-1 conventions differ from the pick-and-place machine's, and some packages need a per-package rotation offset.",
2235
+ )
2236
+ )
2237
+ notes = [
2238
+ "Placement file (JLCPCB layout): X as stored, Y negated, side Top/Bottom, rotation = angle (top) or 180 - angle (bottom), normalised to 0-360.",
2239
+ "traceforge writes no per-package rotation offsets; verify rotation of SOT-23, SOIC, QFN and polarised parts in the assembler's preview.",
2240
+ ]
2241
+ if odd:
2242
+ notes.append(
2243
+ f"{len(odd)} part(s) at non-orthogonal angles ({', '.join(f.reference for f in odd[:6])}): check the placement file for them."
2244
+ )
2245
+ return _section(
2246
+ "Assembly",
2247
+ [
2248
+ ("BOM lines", len(bom_rows)),
2249
+ ("Placed parts", sum(len(v) for v in groups.values())),
2250
+ ("DNP", dnp),
2251
+ ("Missing supplier part number", missing),
2252
+ ("Top / bottom", f"{len(fps) - len(bottom)} / {len(bottom)}"),
2253
+ ],
2254
+ tables,
2255
+ notes,
2256
+ data={"bom_lines": len(bom_rows), "missing_part_numbers": missing},
2257
+ )
2258
+
2259
+
2260
+ # ------------------------------------------------------------------------------------ revision
2261
+ def _revision_section(src: Source, generated: str | None, name: str) -> tuple[dict, dict]:
2262
+ import traceforge
2263
+
2264
+ folder = src.workspace
2265
+ git = _git_hash(folder)
2266
+ meta = {
2267
+ "name": name,
2268
+ "description": (src.spec.description if src.spec is not None else None)
2269
+ or src.title_block.get("title", ""),
2270
+ "revision": src.title_block.get("rev", ""),
2271
+ "date": generated or datetime.date.today().isoformat(),
2272
+ "git": git,
2273
+ "generator": f"{src.board.generator} {src.board.generator_version}".strip(),
2274
+ "kicad_file_version": src.board.kicad_major,
2275
+ "traceforge": getattr(traceforge, "__version__", ""),
2276
+ "fab": src.fab.name,
2277
+ "source": str(src.pcb.name),
2278
+ }
2279
+ facts = [
2280
+ ("Design", name),
2281
+ ("Revision", meta["revision"] or "not set (title block)"),
2282
+ ("Generated", meta["date"]),
2283
+ ("Git commit", git or "not in a git repository"),
2284
+ (
2285
+ "Board file",
2286
+ f"{meta['generator'] or 'unknown'}, KiCad {meta['kicad_file_version'] or '?'} format",
2287
+ ),
2288
+ ("traceforge", meta["traceforge"] or "unknown"),
2289
+ ]
2290
+ return _section(
2291
+ "Revision and test",
2292
+ facts,
2293
+ notes=[
2294
+ "Run `traceforge check` for ERC/DRC and the built-in checks; this sheet reports the design, not its verification status."
2295
+ ],
2296
+ ), meta
2297
+
2298
+
2299
+ # ------------------------------------------------------------------------------------ entry points
2300
+ def build_sheet(
2301
+ source: str | Path,
2302
+ *,
2303
+ fab: str | None = None,
2304
+ delta_t: float = 10.0,
2305
+ route_report: dict | None = None,
2306
+ electrical: dict | None = None,
2307
+ generated: str | None = None,
2308
+ spec: Any = None,
2309
+ ) -> dict:
2310
+ """The full design specification of ``source`` (a spec, a ``.kicad_pcb`` or a folder) as a dict.
2311
+
2312
+ ``delta_t``: allowed temperature rise for the current-capacity table, K. ``route_report``: a
2313
+ route result (``RouteResult.to_dict()``) to merge pair notes from. ``electrical``: declared
2314
+ currents/voltages like ``.traceforge/electrical.yaml``. ``generated``: date string (default today).
2315
+ ``spec``: the DesignSpec the board was built from, when ``source`` is its ``.kicad_pcb``.
2316
+ """
2317
+ src = load_source(source, fab, spec)
2318
+ try:
2319
+ warn = _Warnings()
2320
+ name = (src.spec.name if src.spec is not None else None) or src.pcb.stem
2321
+ sections = {
2322
+ "board": _board_section(src, warn),
2323
+ "stackup": _stackup_section(src, warn),
2324
+ "rules": _rules_section(src, warn),
2325
+ "net_classes": _net_classes_section(src, warn, delta_t, electrical),
2326
+ "copper": _copper_section(src, warn),
2327
+ "pairs": _pairs_section(src, warn, route_report),
2328
+ "placement": _placement_section(src, warn),
2329
+ "mechanical": _mechanical_section(src, warn),
2330
+ "assembly": _assembly_section(src, warn),
2331
+ }
2332
+ revision, meta = _revision_section(src, generated, name)
2333
+ sections["revision"] = revision
2334
+ order = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}
2335
+ warnings = sorted(warn.items, key=lambda w: (order.get(w["severity"], 9), w["section"]))
2336
+ return {
2337
+ "schema": SCHEMA,
2338
+ "meta": meta,
2339
+ "summary": {
2340
+ "warnings": len(warnings),
2341
+ "by_severity": dict(Counter(w["severity"] for w in warnings)),
2342
+ "layers": len(src.board.copper_layers),
2343
+ "size_mm": list(src.board.size_mm) if src.board.size_mm else None,
2344
+ "parts": sections["placement"]["data"].get("parts", 0),
2345
+ },
2346
+ "warnings": warnings,
2347
+ "sections": sections,
2348
+ "assumptions": list(ASSUMPTIONS),
2349
+ }
2350
+ finally:
2351
+ src.close()