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,2698 @@
1
+ """A negotiated-congestion grid autorouter for 2-layer boards, with an optional ground plane.
2
+
3
+ How it works:
4
+
5
+ * **Grid.** Each copper layer is rasterised on a square grid (0.2 mm by
6
+ default). A cell is free, owned by one net, or blocked. Fixed copper (pads,
7
+ existing tracks and vias, holes, the board edge) claims the cells whose
8
+ centre is closer than clearance + half the default track width + a small
9
+ rounding margin, using exact distances to the real pad shape.
10
+ * **Off-grid pad entry.** Pads are never snapped to the grid. Every pad gets a
11
+ set of escape stubs: short exact polylines from the pad centre to nearby
12
+ free grid cells, leaving rectangular pads along their long axis (straight,
13
+ or with a 45 or 90 degree dogleg once clear of the pad). Each stub uses the
14
+ widest of (net-class width, default width, minimum width) that clears all
15
+ foreign copper exactly, so a 0.5 mm-pitch USB-C or QFN pad escapes with a
16
+ neck-down instead of failing. Same-net pads that overlap (USB-C A4/B9) are
17
+ merged, and close same-net pads are joined by a direct segment when it is
18
+ legal.
19
+ * **Search.** Each net grows a tree: the nearest unconnected pad is joined by
20
+ A* (8 directions, turn penalty, via cost, plane-layer cost). Wide nets
21
+ prefer cells where their full width fits and neck down to the default width
22
+ where it does not, at a cost.
23
+ * **Rip-up and reroute.** Nets are routed PathFinder-style: other nets'
24
+ copper is a soft cost (present congestion) plus a history cost that grows
25
+ where conflicts keep happening. After each pass every track and via is
26
+ checked exactly against every other net and the fixed copper; nets in
27
+ conflict are ripped up and rerouted with a higher congestion penalty. Any
28
+ conflict left at the end is resolved by removing the worst net and routing
29
+ it again with other nets' copper as a hard obstacle.
30
+ * **Escape corridors.** The cells in front of each elongated SMD pad cost
31
+ other nets extra, so nothing (a ground via in particular) parks in front of
32
+ a fine-pitch pad and blocks its escape.
33
+ * **Plane nets** (typically GND) are not routed as tracks: each SMD pad gets a
34
+ stub to a via (or a direct segment to a nearby same-net through-hole pad),
35
+ and the net is poured on both layers and filled by KiCad.
36
+
37
+ * **Differential pairs** (named X+/X-, X_P/X_N, X_DP/X_DM, or listed in the
38
+ project) are routed first as one wide centreline on the signal layer, A* with
39
+ room for both tracks and their gap; the two tracks are that centreline offset
40
+ each way (constant gap), split apart at 45 degrees at the ends, and become
41
+ fixed copper. Width and gap come from the project (the generator works them out
42
+ for the target impedance); when no corridor fits that width, or it would couple
43
+ only a little of the run, narrower widths are tried and the report says so. The
44
+ pads join the pair's ends like any other net. If coupling leaves other nets
45
+ unrouted, the board is routed again with the coupled sections further from the
46
+ pads, then with the pair as plain nets. Lengths are measured along the path
47
+ between the pair's two ends (connector jumpers such as USB-C A6-B6 do not
48
+ count); the shorter net gets serpentine bumps, on the outer side of its coupled
49
+ section first, until the skew is within tolerance.
50
+
51
+ Limits: pads at angles other than multiples of 90 degrees are treated as their
52
+ bounding box, board outlines as their bounding box, pairs couple only between
53
+ two terminals (pad groups where both nets meet). KiCad's DRC is the final
54
+ authority.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import heapq
60
+ import json
61
+ import math
62
+ import os
63
+ import time
64
+ from dataclasses import dataclass, field, replace
65
+ from pathlib import Path
66
+
67
+ from traceforge.kicad import diffpair, edit, escape, impedance
68
+ from traceforge.kicad import planes as planes_mod
69
+ from traceforge.kicad import stackup as stackups
70
+ from traceforge.kicad.pcb import Board, Pad, connectivity, read_board
71
+ from traceforge.kicad.routegeom import Shape, SpatialIndex
72
+
73
+ _SQRT2 = math.sqrt(2)
74
+ _TURN = 0.3 # cost of a change of direction, in cells
75
+ _NECK = 1.6 # cost multiplier for a wide net running at the default width
76
+ _ESC = 2.5 # cost per cell for another net's escape corridor
77
+ _GOAL = -1
78
+
79
+
80
+ @dataclass
81
+ class RouteOptions:
82
+ grid: float = 0.2
83
+ clearance: float = 0.2
84
+ track_width: float = 0.25
85
+ min_track_width: float = 0.15 # neck-down limit for escapes from fine-pitch pads
86
+ via_size: float = 0.6
87
+ via_drill: float = 0.3
88
+ via_cost: float = 8.0
89
+ hole_clearance: float = 0.25 # hole to hole, and copper to non-plated hole
90
+ edge_clearance: float = 0.5
91
+ # Copper layers to route on; None: the board's signal layers (plane layers are left out).
92
+ layers: tuple[str, ...] | None = None
93
+ # Multi-layer boards: net -> plane layers it is poured on (default: the project's stackup).
94
+ plane_assign: dict[str, list[str]] | None = None
95
+ use_plane_layers: bool = False # also route signals on plane-role layers
96
+ layer_costs: dict[str, float] = field(default_factory=dict) # per-layer cost multiplier
97
+ # Preferred direction: alternate horizontal/vertical layers; None switches it on from three
98
+ # signal layers up. Moving against it costs ``cross_direction_cost`` times more.
99
+ preferred_direction: bool | None = None
100
+ cross_direction_cost: float = 1.6
101
+ via_span_cost: float = 0.25 # via cost grows by this fraction per extra layer crossed
102
+ via_in_pad: bool = False # allow vias inside the own-net pads of SMD parts (off by default)
103
+ # Fan-out of fine-pitch packages before routing (kicad/escape.py): None switches it on
104
+ # from four copper layers up; ``escape_layers`` maps (reference, pad) to a preferred layer.
105
+ escape: bool | None = None
106
+ escape_layers: dict[tuple[str, str], str] = field(default_factory=dict)
107
+ fab: str | None = None
108
+ net_widths: dict[str, float] = field(default_factory=dict)
109
+ nets: list[str] | None = None # route only these
110
+ skip_nets: list[str] = field(default_factory=list) # left alone entirely
111
+ plane_nets: list[str] = field(default_factory=list) # connected through a pour instead
112
+ plane_layer: str = "B.Cu"
113
+ plane_layer_cost: float = 3.0 # cost multiplier for signal tracks on the plane layer
114
+ plane_both_sides: bool = True # pour the plane net on every copper layer, joined by the vias
115
+ attempts: int = 12 # rip-up-and-reroute passes (negotiated congestion)
116
+ max_expansions: int = 400_000
117
+ escape_reach: float = 1.2 # how far beyond a pad escape stubs may reach, mm
118
+ direct_join: float = 3.0 # join same-net pads closer than this with one segment if legal
119
+ time_limit: float = 90.0 # seconds before the rip-up loop stops improving
120
+ repair_time: float = 120.0 # seconds for rip-up and reroute of nets that still failed
121
+ repair_search_factor: int = 6 # search limit multiplier while repairing
122
+ # Differential pairs: None finds them by net name and in the project's net classes.
123
+ diff_pairs: list[tuple[str, str]] | None = None
124
+ pair_tolerance: float = 0.1 # allowed length skew, mm, unless the project says otherwise
125
+
126
+ @property
127
+ def margin(self) -> float:
128
+ # Covers the dip of a straight grid step past a convex corner (exact checks follow).
129
+ return self.grid * 0.15 + 0.01
130
+
131
+
132
+ @dataclass
133
+ class RouteResult:
134
+ routed: list[str]
135
+ failed: list[str]
136
+ segments: int
137
+ vias: int
138
+ unrouted_after: int
139
+ planes: dict[str, str] = field(default_factory=dict)
140
+ narrowed: list[str] = field(default_factory=list)
141
+ attempts: int = 1
142
+ unrouted_source: str = "traceforge"
143
+ lengths: dict[str, float] = field(default_factory=dict)
144
+ pairs: dict[str, dict] = field(default_factory=dict)
145
+ seconds: float = 0.0
146
+ plane_report: dict = field(default_factory=dict) # planes.PlaneReport as a dict
147
+ escape: dict = field(default_factory=dict)
148
+ net_report: dict = field(default_factory=dict)
149
+ length_groups: dict = field(default_factory=dict)
150
+ failure_reasons: dict = field(default_factory=dict)
151
+
152
+ def to_dict(self) -> dict:
153
+ data = {
154
+ "routed_nets": self.routed,
155
+ "failed_nets": self.failed,
156
+ "segments_added": self.segments,
157
+ "vias_added": self.vias,
158
+ "planes": self.planes,
159
+ "attempts": self.attempts,
160
+ "unrouted_connections_remaining": self.unrouted_after,
161
+ "unrouted_counted_by": self.unrouted_source,
162
+ "route_seconds": round(self.seconds, 2),
163
+ }
164
+ if self.plane_report:
165
+ data["plane_report"] = self.plane_report
166
+ if self.escape:
167
+ data["fan_out"] = self.escape
168
+ if self.lengths:
169
+ data["track_length_mm"] = self.lengths
170
+ if self.pairs:
171
+ data["differential_pairs"] = self.pairs
172
+ if self.failure_reasons:
173
+ data["failure_reasons"] = self.failure_reasons
174
+ if self.length_groups:
175
+ data["length_groups"] = self.length_groups
176
+ if self.net_report:
177
+ data["net_report"] = self.net_report
178
+ if self.narrowed:
179
+ data["narrowed_nets"] = self.narrowed
180
+ data["note"] = (
181
+ "some track on these nets necks down below the net-class width (pad escapes "
182
+ "between fine-pitch pins, or tight spots); widen by hand if they carry high current"
183
+ )
184
+ return data
185
+
186
+
187
+ def _project_net_settings(pcb: Path) -> tuple[dict[str, float], dict[str, float]]:
188
+ """Per-net track widths and clearances from the KiCad project's net classes."""
189
+ project = pcb.with_suffix(".kicad_pro")
190
+ if not project.exists():
191
+ return {}, {}
192
+ try:
193
+ data = json.loads(project.read_text(encoding="utf-8"))
194
+ except (OSError, ValueError):
195
+ return {}, {}
196
+ settings = data.get("net_settings", {})
197
+ classes = {c.get("name"): c for c in settings.get("classes", [])}
198
+ widths: dict[str, float] = {}
199
+ clearances: dict[str, float] = {}
200
+ for net, cls in (settings.get("netclass_assignments") or {}).items():
201
+ info = classes.get(cls) or {}
202
+ if info.get("track_width"):
203
+ widths[net] = float(info["track_width"])
204
+ if info.get("clearance"):
205
+ clearances[net] = float(info["clearance"])
206
+ return widths, clearances
207
+
208
+
209
+ def _project_pairs(pcb: Path) -> dict[tuple[str, str], dict]:
210
+ """Differential pairs with width/gap/tolerance: the generator's list, then any net
211
+ class holding exactly two nets with diff-pair settings."""
212
+ project = pcb.with_suffix(".kicad_pro")
213
+ try:
214
+ data = json.loads(project.read_text(encoding="utf-8"))
215
+ except (OSError, ValueError):
216
+ return {}
217
+ found: dict[tuple[str, str], dict] = {}
218
+ for item in (data.get("traceforge") or {}).get("diff_pairs") or []:
219
+ nets = item.get("nets") or []
220
+ if len(nets) == 2:
221
+ found[(str(nets[0]), str(nets[1]))] = item
222
+ settings = data.get("net_settings", {})
223
+ classes = {c.get("name"): c for c in settings.get("classes", [])}
224
+ members: dict[str, list[str]] = {}
225
+ for net, cls in (settings.get("netclass_assignments") or {}).items():
226
+ members.setdefault(cls, []).append(net)
227
+ taken = {n for pair in found for n in pair}
228
+ for cls, nets in members.items():
229
+ info = classes.get(cls) or {}
230
+ if len(nets) != 2 or taken & set(nets) or not info.get("diff_pair_width"):
231
+ continue
232
+ pairs = diffpair.pair_names(nets)
233
+ if pairs:
234
+ found[pairs[0]] = {"width": info["diff_pair_width"], "gap": info.get("diff_pair_gap")}
235
+ return found
236
+
237
+
238
+ def _project_groups(pcb: Path) -> list[dict]:
239
+ """Length-matching groups written by the generator: ``{name, nets, tolerance}``."""
240
+ try:
241
+ data = json.loads(pcb.with_suffix(".kicad_pro").read_text(encoding="utf-8"))
242
+ except (OSError, ValueError):
243
+ return []
244
+ return [g for g in (data.get("traceforge") or {}).get("length_groups") or [] if g.get("nets")]
245
+
246
+
247
+ def _project_planes(pcb: Path) -> tuple[dict[str, str], dict[str, list[str]]]:
248
+ """Layer roles and plane nets written by the generator: ``({layer: role}, {net: [layers]})``."""
249
+ return planes_mod.project_roles(pcb), planes_mod.project_assignment(pcb)
250
+
251
+
252
+ def _net_widths_from_project(pcb: Path) -> dict[str, float]:
253
+ return _project_net_settings(pcb)[0]
254
+
255
+
256
+ class _Stub:
257
+ """An exact escape from a pad centre to a grid node."""
258
+
259
+ __slots__ = ("node", "points", "width", "cost", "pad")
260
+
261
+ def __init__(
262
+ self, node: int, points: list[tuple[float, float]], width: float, cost: float, pad
263
+ ):
264
+ self.node = node
265
+ self.points = points
266
+ self.width = width
267
+ self.cost = cost
268
+ self.pad = pad
269
+
270
+
271
+ class _Pair:
272
+ __slots__ = (
273
+ "pos",
274
+ "neg",
275
+ "width",
276
+ "gap",
277
+ "tolerance",
278
+ "height",
279
+ "side",
280
+ "layer",
281
+ "note",
282
+ "tuned",
283
+ "terms",
284
+ "target",
285
+ "widths",
286
+ "fixed",
287
+ )
288
+
289
+ def __init__(self, pos: str, neg: str, width: float, gap: float, tolerance: float):
290
+ self.pos, self.neg = pos, neg
291
+ self.height = diffpair.dielectric_height()
292
+ self.terms: list[dict] = []
293
+ self.width, self.gap, self.tolerance = width, gap, tolerance
294
+ self.side: dict[str, float] = {}
295
+ self.layer = 0
296
+ self.note = ""
297
+ self.tuned = 0.0
298
+ self.target = diffpair.USB_IMPEDANCE
299
+ self.fixed = False # width given in the spec: not solved per layer
300
+ self.widths: dict[int, float] = {} # layer index -> width for ``target`` there
301
+
302
+
303
+ class _NetRoute:
304
+ __slots__ = ("segs", "vias", "keep", "holes", "shapes", "necked", "failed")
305
+
306
+ def __init__(self, layers: int):
307
+ self.segs: list[tuple[int, float, float, float, float, float]] = []
308
+ self.vias: list[tuple[float, float]] = []
309
+ self.keep: list[set[int]] = [set() for _ in range(layers)]
310
+ self.holes: set[int] = set()
311
+ self.shapes: list[Shape] = []
312
+ self.necked = False
313
+ self.failed = 0
314
+
315
+
316
+ def _pad_shape(pad: Pad, net: int, layers: int) -> Shape:
317
+ hw, hh = pad.width / 2, pad.height / 2
318
+ if pad.shape == "circle":
319
+ r = min(hw, hh)
320
+ return Shape.capsule(pad.x, pad.y, pad.x, pad.y, r, net, layers, pad)
321
+ if pad.shape == "oval":
322
+ if hw >= hh:
323
+ return Shape.capsule(
324
+ pad.x - hw + hh, pad.y, pad.x + hw - hh, pad.y, hh, net, layers, pad
325
+ )
326
+ return Shape.capsule(pad.x, pad.y - hh + hw, pad.x, pad.y + hh - hw, hw, net, layers, pad)
327
+ return Shape.rect(pad.x - hw, pad.y - hh, pad.x + hw, pad.y + hh, net, layers, pad)
328
+
329
+
330
+ class _Router:
331
+ def __init__(self, pcb: Path, options: RouteOptions):
332
+ self.pcb = pcb
333
+ self.opt = opt = options
334
+ widths, clearances = _project_net_settings(pcb)
335
+ self.widths = {**widths, **options.net_widths}
336
+ self.clearances = clearances
337
+ self.board: Board = read_board(pcb)
338
+ board = self.board
339
+ self.fanned = escape.attach_fanout(board) # pins that start at the end of a fan-out stub
340
+ if board.outline is None:
341
+ raise ValueError("the board needs an Edge.Cuts outline before routing")
342
+ self.stack = self._read_stack()
343
+ self.plane_roles, project_planes = _project_planes(pcb)
344
+ assign = options.plane_assign if options.plane_assign is not None else project_planes
345
+ self.plane_assign: dict[str, list[str]] = {n: list(ls) for n, ls in assign.items()}
346
+ planes = {name for ls in self.plane_assign.values() for name in ls}
347
+ planes |= {name for name, role in self.plane_roles.items() if role == "plane"}
348
+ self.plane_layers = sorted(planes & set(board.copper_layers))
349
+ if opt.layers is not None:
350
+ wanted = list(opt.layers)
351
+ elif opt.use_plane_layers:
352
+ wanted = list(board.copper_layers)
353
+ else:
354
+ wanted = [name for name in board.copper_layers if name not in planes]
355
+ self.layers = [layer for layer in wanted if layer in board.copper_layers] or ["F.Cu"]
356
+ self.L = len(self.layers)
357
+ self.all_layers = (1 << self.L) - 1
358
+ g = opt.grid
359
+ x0, y0, x1, y1 = board.outline
360
+ self.x0, self.y0, self.x1, self.y1 = x0, y0, x1, y1
361
+ self.geom = board.edge_geometry # the real outline: L-shapes, circles, cut-outs
362
+ self.W = int(math.ceil((x1 - x0) / g)) + 1
363
+ self.H = int(math.ceil((y1 - y0) / g)) + 1
364
+ self.N = self.W * self.H
365
+ self.margin = opt.margin
366
+ self.w0 = opt.track_width
367
+ self.wmin = min(opt.min_track_width, opt.track_width)
368
+ self.keep0 = opt.clearance + self.w0 / 2 + self.margin
369
+ N, L = self.N, self.L
370
+ self.fixed = [[0] * N for _ in range(L)]
371
+ self.occ = [[0] * N for _ in range(L)]
372
+ self.hist = [[0.0] * N for _ in range(L)]
373
+ self.esc = [[0] * N for _ in range(L)]
374
+ self.novia = bytearray(N)
375
+ self.novia_pad = bytearray(N) # near SMD pads; ``padvia`` cells are open to the pad's net
376
+ self.padvia: dict[int, int] = {}
377
+ self.viahole = [0] * N
378
+ self.fixed_index = SpatialIndex()
379
+ self.routed_index = SpatialIndex()
380
+ self.holes: list[tuple[float, float, float]] = []
381
+ self.net_ids: dict[str, int] = {}
382
+ self.net_names: dict[int, str] = {}
383
+ self.net_clear: dict[int, float] = {}
384
+ self.pads_by_net: dict[str, list[Pad]] = {}
385
+ self.pad_shapes: dict[int, Shape] = {}
386
+ self.routes: dict[str, _NetRoute] = {}
387
+ self._stub_cache: dict[tuple, list[_Stub]] = {}
388
+ self._wide_cache: dict[tuple[int, int], dict[int, bool]] = {}
389
+ self._viafix_cache: dict[int, dict[int, bool]] = {}
390
+ self._discs: dict[int, list[tuple[int, int]]] = {}
391
+ self.plane_links: dict[str, list[Pad]] = {}
392
+ self.cores: dict[str, tuple[int, float, list[tuple[float, float]]]] = {}
393
+ self.core_shapes: dict[str, list[Shape]] = {}
394
+ self.core_ends: dict[str, list[Pad]] = {}
395
+ self.fail_reason: dict[str, str] = {}
396
+ self.group_lists: dict[str, list[list[str]]] = {}
397
+ self.search_limited = False
398
+ self.pair_standoff = 0.8 # mm between a pair's coupled section and its pads
399
+ self.pad_owner = {id(p): fp.reference for fp in self.board.footprints for p in fp.pads}
400
+ plane = opt.plane_layer
401
+ self.layer_cost = [
402
+ (
403
+ opt.plane_layer_cost
404
+ if (opt.plane_nets and not self.plane_assign and name == plane)
405
+ else 1.0
406
+ )
407
+ * opt.layer_costs.get(name, 1.0)
408
+ for name in self.layers
409
+ ]
410
+ directional = opt.preferred_direction
411
+ if directional is None:
412
+ directional = self.L > 2
413
+ # Per layer, a cost multiplier for each of the 8 moves (see ``search``): the layers
414
+ # alternate horizontal (even) and vertical (odd); diagonals count as half against.
415
+ x = opt.cross_direction_cost if directional else 1.0
416
+ horizontal = (1.0, 1.0, x, x, (1 + x) / 2, (1 + x) / 2, (1 + x) / 2, (1 + x) / 2)
417
+ vertical = (x, x, 1.0, 1.0, (1 + x) / 2, (1 + x) / 2, (1 + x) / 2, (1 + x) / 2)
418
+ self.dir_mult = [horizontal if i % 2 == 0 else vertical for i in range(self.L)]
419
+ self.max_clear = max([opt.clearance, *clearances.values()])
420
+ self._build_fixed()
421
+
422
+ def _read_stack(self) -> stackups.Stackup:
423
+ """The board's stackup, or the typical JLCPCB one for its copper-layer count."""
424
+ try:
425
+ found = stackups.read_stackup(self.pcb)
426
+ except (OSError, ValueError, stackups.StackupError):
427
+ found = None
428
+ count = len(self.board.copper_layers)
429
+ if found is None or found.count != count:
430
+ found = stackups.default_for(count if count in (2, 4, 6, 8) else 2)
431
+ # KiCad's file has no layer roles: the generator records the planes in the project.
432
+ known = {
433
+ layer: [net for net, _ in nets]
434
+ for layer, nets in planes_mod.project_layers(self.pcb).items()
435
+ if layer in found.names and nets
436
+ }
437
+ if known:
438
+ try:
439
+ found = found.with_planes(known)
440
+ except stackups.StackupError:
441
+ pass
442
+ return found
443
+
444
+ # ------------------------------------------------------------------ basics
445
+ def net_id(self, net: str) -> int:
446
+ if net not in self.net_ids:
447
+ nid = len(self.net_ids) + 1
448
+ self.net_ids[net] = nid
449
+ self.net_names[nid] = net
450
+ self.net_clear[nid] = max(self.opt.clearance, self.clearances.get(net, 0.0))
451
+ return self.net_ids[net]
452
+
453
+ def width(self, net: str) -> float:
454
+ return max(self.widths.get(net, self.w0), self.w0)
455
+
456
+ def extra_cells(self, net: str) -> int:
457
+ extra = (self.width(net) - self.w0) / 2
458
+ return int(math.ceil(extra / self.opt.grid - 1e-9)) if extra > 1e-9 else 0
459
+
460
+ def clear(self, a: int, b: int) -> float:
461
+ return max(
462
+ self.net_clear.get(a, self.opt.clearance), self.net_clear.get(b, self.opt.clearance)
463
+ )
464
+
465
+ def disc(self, r: int) -> list[tuple[int, int]]:
466
+ if r not in self._discs:
467
+ self._discs[r] = [
468
+ (dx, dy)
469
+ for dx in range(-r, r + 1)
470
+ for dy in range(-r, r + 1)
471
+ if dx * dx + dy * dy <= r * r + r
472
+ ]
473
+ return self._discs[r]
474
+
475
+ def xy(self, idx: int) -> tuple[float, float]:
476
+ gy, gx = divmod(idx, self.W)
477
+ g = self.opt.grid
478
+ return round(self.x0 + gx * g, 4), round(self.y0 + gy * g, 4)
479
+
480
+ def cell(self, x: float, y: float) -> int:
481
+ g = self.opt.grid
482
+ gx = min(self.W - 1, max(0, int(round((x - self.x0) / g))))
483
+ gy = min(self.H - 1, max(0, int(round((y - self.y0) / g))))
484
+ return gy * self.W + gx
485
+
486
+ def layer_mask(self, pad: Pad) -> int:
487
+ mask = 0
488
+ for i, layer in enumerate(self.layers):
489
+ if pad.on_layer(layer):
490
+ mask |= 1 << i
491
+ return mask
492
+
493
+ def cells_within(self, shape: Shape, radius: float):
494
+ """Grid indices whose centre is closer than ``radius`` to ``shape``."""
495
+ g = self.opt.grid
496
+ bx0, by0, bx1, by1 = shape.bbox
497
+ gx0 = max(0, int(math.floor((bx0 - radius - self.x0) / g)))
498
+ gx1 = min(self.W - 1, int(math.ceil((bx1 + radius - self.x0) / g)))
499
+ gy0 = max(0, int(math.floor((by0 - radius - self.y0) / g)))
500
+ gy1 = min(self.H - 1, int(math.ceil((by1 + radius - self.y0) / g)))
501
+ W, x0, y0 = self.W, self.x0, self.y0
502
+ dist = shape.dist_point
503
+ for gy in range(gy0, gy1 + 1):
504
+ cy = y0 + gy * g
505
+ row = gy * W
506
+ for gx in range(gx0, gx1 + 1):
507
+ if dist(x0 + gx * g, cy) < radius:
508
+ yield row + gx
509
+
510
+ def _claim_fixed(self, shape: Shape, radius: float) -> None:
511
+ owner = shape.net if shape.net else -1
512
+ cells = list(self.cells_within(shape, radius))
513
+ for li in range(self.L):
514
+ if not shape.layers & (1 << li):
515
+ continue
516
+ fixed = self.fixed[li]
517
+ for idx in cells:
518
+ cur = fixed[idx]
519
+ if cur == 0:
520
+ fixed[idx] = owner
521
+ elif cur != owner:
522
+ fixed[idx] = -1
523
+
524
+ def _build_fixed_outline(self, edge: float) -> None:
525
+ """Edge keep-out for a non-rectangular outline: outside it, or near any edge."""
526
+ opt, g = self.opt, self.opt.grid
527
+ W, H = self.W, self.H
528
+ blocked = self.geom.blocked_cells(self.x0, self.y0, g, W, H, edge)
529
+ for gy in range(H):
530
+ for gx in (0, W - 1):
531
+ blocked[gy * W + gx] = 1
532
+ for gx in range(W):
533
+ for gy in (0, H - 1):
534
+ blocked[gy * W + gx] = 1
535
+ for li in range(self.L):
536
+ fixed = self.fixed[li]
537
+ for idx, flag in enumerate(blocked):
538
+ if flag:
539
+ fixed[idx] = -1
540
+ via_blocked = self.geom.blocked_cells(
541
+ self.x0, self.y0, g, W, H, opt.edge_clearance + opt.via_size / 2
542
+ )
543
+ for idx, flag in enumerate(via_blocked):
544
+ if flag:
545
+ self.novia[idx] = 1
546
+
547
+ def _build_fixed(self) -> None:
548
+ opt, g = self.opt, self.opt.grid
549
+ W, H = self.W, self.H
550
+ edge = opt.edge_clearance + self.w0 / 2 + self.margin
551
+ if not self.geom.is_rect:
552
+ self._build_fixed_outline(edge)
553
+ else:
554
+ for li in range(self.L):
555
+ fixed = self.fixed[li]
556
+ for gy in range(H):
557
+ y = self.y0 + gy * g
558
+ near_y = y - self.y0 < edge or self.y1 - y < edge or gy in (0, H - 1)
559
+ for gx in range(W):
560
+ x = self.x0 + gx * g
561
+ if near_y or x - self.x0 < edge or self.x1 - x < edge or gx in (0, W - 1):
562
+ fixed[gy * W + gx] = -1
563
+ via_edge = opt.edge_clearance + opt.via_size / 2
564
+ for gy in range(H):
565
+ y = self.y0 + gy * g
566
+ for gx in range(W):
567
+ x = self.x0 + gx * g
568
+ if min(x - self.x0, self.x1 - x, y - self.y0, self.y1 - y) < via_edge:
569
+ self.novia[gy * W + gx] = 1
570
+ self.castellated = [
571
+ (pad.x, pad.y, max(pad.width, pad.height) / 2)
572
+ for footprint in self.board.footprints
573
+ for pad in footprint.pads
574
+ if pad.castellated and pad.net
575
+ ]
576
+ for footprint in self.board.footprints: # half-cut holes sit on the edge: open their copper
577
+ for pad in footprint.pads:
578
+ if pad.castellated and pad.net:
579
+ shape = _pad_shape(pad, 0, self.all_layers)
580
+ for idx in self.cells_within(shape, 0.0):
581
+ if self.geom.room(self.x0 + (idx % W) * g, self.y0 + (idx // W) * g) >= 0:
582
+ for li in range(self.L):
583
+ self.fixed[li][idx] = 0
584
+ hole_extra = max(0.0, opt.hole_clearance - opt.clearance)
585
+ via_keep = opt.via_size / 2 + opt.clearance + self.margin
586
+ for footprint in self.board.footprints:
587
+ for pad in footprint.pads:
588
+ nid = self.net_id(pad.net) if pad.net else 0
589
+ if pad.net and id(pad) not in self.fanned:
590
+ self.pads_by_net.setdefault(pad.net, []).append(pad)
591
+ if pad.kind == "np_thru_hole":
592
+ r = max(max(pad.width, pad.height) / 2, pad.drill / 2 + hole_extra)
593
+ shape = Shape.capsule(pad.x, pad.y, pad.x, pad.y, r, 0, self.all_layers, pad)
594
+ else:
595
+ mask = self.layer_mask(pad)
596
+ if not mask:
597
+ continue
598
+ shape = _pad_shape(pad, nid, mask)
599
+ self.pad_shapes[id(pad)] = shape
600
+ self.fixed_index.add(shape)
601
+ self._claim_fixed(shape, self.keep0 + (self.clear(nid, 0) - opt.clearance))
602
+ if pad.drill:
603
+ self.holes.append((pad.x, pad.y, pad.drill))
604
+ if pad.kind == "smd" or pad.kind == "connect":
605
+ for idx in self.cells_within(shape, via_keep):
606
+ self.novia_pad[idx] = 1
607
+ if opt.via_in_pad and pad.kind == "smd" and pad.net:
608
+ self._open_pad_for_via(pad, nid)
609
+ for track in self.board.tracks:
610
+ if track.layer not in self.layers:
611
+ continue
612
+ nid = self.net_id(track.net) if track.net else 0
613
+ shape = Shape.capsule(
614
+ track.x1,
615
+ track.y1,
616
+ track.x2,
617
+ track.y2,
618
+ track.width / 2,
619
+ nid,
620
+ 1 << self.layers.index(track.layer),
621
+ )
622
+ self.fixed_index.add(shape)
623
+ self._claim_fixed(shape, self.keep0)
624
+ for via in self.board.vias:
625
+ nid = self.net_id(via.net) if via.net else 0
626
+ shape = Shape.capsule(via.x, via.y, via.x, via.y, via.size / 2, nid, self.all_layers)
627
+ self.fixed_index.add(shape)
628
+ self._claim_fixed(shape, self.keep0)
629
+ self.holes.append((via.x, via.y, getattr(via, "drill", opt.via_drill) or opt.via_drill))
630
+ for hx, hy, drill in self.holes:
631
+ r = drill / 2 + opt.via_drill / 2 + opt.hole_clearance + self.margin
632
+ probe = Shape.capsule(hx, hy, hx, hy, 0.0, 0, self.all_layers)
633
+ for idx in self.cells_within(probe, r):
634
+ self.novia[idx] = 1
635
+ self._build_escape_corridors()
636
+
637
+ def _open_pad_for_via(self, pad: Pad, nid: int) -> None:
638
+ """Cells where a via fits wholly inside ``pad``: its own net may drop one there."""
639
+ r = self.opt.via_size / 2 + self.margin
640
+ hw, hh = pad.width / 2 - r, pad.height / 2 - r
641
+ if hw < 0 or hh < 0:
642
+ return
643
+ g = self.opt.grid
644
+ x_lo, x_hi = pad.x - hw, pad.x + hw
645
+ y_lo, y_hi = pad.y - hh, pad.y + hh
646
+ gx0 = int(math.ceil((x_lo - self.x0) / g - 1e-9))
647
+ gx1 = int(math.floor((x_hi - self.x0) / g + 1e-9))
648
+ gy0 = int(math.ceil((y_lo - self.y0) / g - 1e-9))
649
+ gy1 = int(math.floor((y_hi - self.y0) / g + 1e-9))
650
+ for gy in range(max(0, gy0), min(self.H - 1, gy1) + 1):
651
+ for gx in range(max(0, gx0), min(self.W - 1, gx1) + 1):
652
+ idx = gy * self.W + gx
653
+ self.padvia[idx] = nid if self.padvia.get(idx, nid) == nid else -1
654
+
655
+ def _build_escape_corridors(self) -> None:
656
+ """Mark the cells in front of elongated SMD pads; other nets pay to use them."""
657
+ reach = 1.0
658
+ for footprint in self.board.footprints:
659
+ for pad in footprint.pads:
660
+ if not pad.net or pad.kind != "smd":
661
+ continue
662
+ hw, hh = pad.width / 2, pad.height / 2
663
+ if hw >= 1.3 * hh:
664
+ axis = (1.0, 0.0)
665
+ half_long, half_short = hw, hh
666
+ elif hh >= 1.3 * hw:
667
+ axis = (0.0, 1.0)
668
+ half_long, half_short = hh, hw
669
+ else:
670
+ continue
671
+ along = (pad.x - footprint.x) * axis[0] + (pad.y - footprint.y) * axis[1]
672
+ signs = [1.0 if along > 0 else -1.0] if abs(along) > half_long else [1.0, -1.0]
673
+ nid = self.net_id(pad.net)
674
+ mask = self.layer_mask(pad)
675
+ for sign in signs:
676
+ ax, ay = axis[0] * sign, axis[1] * sign
677
+ sx, sy = pad.x + ax * half_long, pad.y + ay * half_long
678
+ ex, ey = sx + ax * reach, sy + ay * reach
679
+ self._mark_corridor(Shape.capsule(sx, sy, ex, ey, half_short + 0.05, nid, mask))
680
+ # Thermal spokes: a plane-net pad joins the pour through four spokes (orthogonal,
681
+ # or diagonal for round pads). Keep other nets' tracks out of where they go, or
682
+ # KiCad reports a starved thermal.
683
+ spoke = 0.5 + 0.3 + 0.1 # thermal gap + zone clearance + a little
684
+ owner = {id(p): fp for fp in self.board.footprints for p in fp.pads}
685
+ for net in self.opt.plane_nets:
686
+ if net in self.plane_assign:
687
+ continue # poured on an inner layer: no spokes on the outer layers
688
+ for pad in self.pads_by_net.get(net, []):
689
+ mask = self.layer_mask(pad)
690
+ if not mask:
691
+ continue
692
+ nid = self.net_id(net)
693
+ hw, hh = pad.width / 2, pad.height / 2
694
+ if pad.shape == "circle" or (pad.shape == "oval" and abs(hw - hh) < 1e-6):
695
+ d = min(hw, hh) / _SQRT2
696
+ dirs = [(d, d, 1, 1), (d, -d, 1, -1), (-d, d, -1, 1), (-d, -d, -1, -1)]
697
+ reach = spoke / _SQRT2
698
+ else:
699
+ dirs = [(hw, 0, 1, 0), (-hw, 0, -1, 0), (0, hh, 0, 1), (0, -hh, 0, -1)]
700
+ reach = spoke
701
+ fp = owner.get(id(pad))
702
+ viable = []
703
+ for ox, oy, ux, uy in dirs:
704
+ sx, sy = pad.x + ox, pad.y + oy
705
+ corridor = Shape.capsule(
706
+ sx, sy, sx + ux * reach, sy + uy * reach, 0.3, nid, mask
707
+ )
708
+ self._mark_corridor(corridor)
709
+ blocked = any(
710
+ (other.net != nid or not other.net)
711
+ and other.layers & mask
712
+ and other.dist_shape(corridor) < 0.3
713
+ for other in self.fixed_index.near(corridor.bbox, 0.5)
714
+ )
715
+ edge = (
716
+ min(
717
+ corridor.bbox[0] - self.x0,
718
+ self.x1 - corridor.bbox[2],
719
+ corridor.bbox[1] - self.y0,
720
+ self.y1 - corridor.bbox[3],
721
+ )
722
+ if self.geom.is_rect
723
+ else self.geom.segment_room(sx, sy, sx + ux * reach, sy + uy * reach) - 0.3
724
+ )
725
+ if not blocked and edge > self.opt.edge_clearance:
726
+ outward = (pad.x - fp.x) * ux + (pad.y - fp.y) * uy if fp else 0.0
727
+ viable.append((-outward, corridor))
728
+ viable.sort(key=lambda item: item[0])
729
+ for _, corridor in viable[:2]:
730
+ self._reserve(corridor, 0.3 + self.w0 / 2 + self.margin)
731
+
732
+ def _reserve(self, shape: Shape, radius: float) -> None:
733
+ """Hand free cells near ``shape`` to its net, so no other net may route there."""
734
+ cells = list(self.cells_within(shape, radius))
735
+ for li in range(self.L):
736
+ if shape.layers & (1 << li):
737
+ fixed = self.fixed[li]
738
+ for idx in cells:
739
+ if fixed[idx] == 0:
740
+ fixed[idx] = shape.net
741
+
742
+ def _mark_corridor(self, corridor: Shape) -> None:
743
+ cells = list(self.cells_within(corridor, 1e-6))
744
+ for li in range(self.L):
745
+ if not corridor.layers & (1 << li):
746
+ continue
747
+ esc = self.esc[li]
748
+ for idx in cells:
749
+ cur = esc[idx]
750
+ esc[idx] = corridor.net if cur in (0, corridor.net) else -1
751
+
752
+ # ------------------------------------------------------------ legality
753
+ def edge_ok(self, ax: float, ay: float, bx: float, by: float, edge: float) -> bool:
754
+ """Run clear of the board edge, except where it leaves a half-cut (castellated) pad."""
755
+ if self.geom.segment_room(ax, ay, bx, by) >= edge:
756
+ return True
757
+ for px, py, r in self.castellated:
758
+ for (sx, sy), (ex, ey) in (((ax, ay), (bx, by)), ((bx, by), (ax, ay))):
759
+ if math.hypot(sx - px, sy - py) <= r and self.geom.room(ex, ey) >= edge:
760
+ return True
761
+ return False
762
+
763
+ def seg_legal(
764
+ self,
765
+ ax: float,
766
+ ay: float,
767
+ bx: float,
768
+ by: float,
769
+ width: float,
770
+ layer: int,
771
+ nid: int,
772
+ routed: bool,
773
+ near: list[Shape] | None = None,
774
+ ) -> bool:
775
+ half = width / 2
776
+ edge = self.opt.edge_clearance + half - 1e-6
777
+ if not self.edge_ok(ax, ay, bx, by, edge):
778
+ return False
779
+ bit = 1 << layer
780
+ reach = half + self.max_clear + 0.05
781
+ bbox = (min(ax, bx), min(ay, by), max(ax, bx), max(ay, by))
782
+ candidates = near if near is not None else self.fixed_index.near(bbox, reach)
783
+ if routed:
784
+ candidates = candidates + self.routed_index.near(bbox, reach)
785
+ for shape in candidates:
786
+ if shape.net == nid and shape.net or not shape.layers & bit:
787
+ continue
788
+ need = self.clear(nid, shape.net) + half - 1e-6
789
+ sb = shape.bbox
790
+ if (
791
+ sb[0] - need > bbox[2]
792
+ or sb[2] + need < bbox[0]
793
+ or sb[1] - need > bbox[3]
794
+ or sb[3] + need < bbox[1]
795
+ ):
796
+ continue
797
+ if shape.dist_seg(ax, ay, bx, by) < need:
798
+ return False
799
+ return True
800
+
801
+ def poly_legal(self, points, width: float, layer: int, nid: int, routed: bool, near=None):
802
+ return all(
803
+ self.seg_legal(a[0], a[1], b[0], b[1], width, layer, nid, routed, near)
804
+ for a, b in zip(points, points[1:])
805
+ )
806
+
807
+ def wide_ok(self, nid: int, extra: int, node: int) -> bool:
808
+ cache = self._wide_cache.setdefault((nid, extra), {})
809
+ ok = cache.get(node)
810
+ if ok is None:
811
+ layer, idx = divmod(node, self.N)
812
+ fixed = self.fixed[layer]
813
+ gy, gx = divmod(idx, self.W)
814
+ W, H = self.W, self.H
815
+ ok = True
816
+ for dx, dy in self.disc(extra):
817
+ x, y = gx + dx, gy + dy
818
+ if x < 0 or y < 0 or x >= W or y >= H:
819
+ ok = False
820
+ break
821
+ f = fixed[y * W + x]
822
+ if f and f != nid:
823
+ ok = False
824
+ break
825
+ cache[node] = ok
826
+ return ok
827
+
828
+ def via_fixed_ok(self, nid: int, idx: int) -> bool:
829
+ cache = self._viafix_cache.setdefault(nid, {})
830
+ ok = cache.get(idx)
831
+ if ok is None:
832
+ ok = not self.novia[idx] and (not self.novia_pad[idx] or self.padvia.get(idx) == nid)
833
+ if ok:
834
+ r = self.opt.via_size / 2 - self.w0 / 2 + self.margin
835
+ cells = self.disc(max(0, int(math.ceil(r / self.opt.grid - 1e-9))))
836
+ gy, gx = divmod(idx, self.W)
837
+ W, H = self.W, self.H
838
+ for li in range(self.L):
839
+ fixed = self.fixed[li]
840
+ for dx, dy in cells:
841
+ x, y = gx + dx, gy + dy
842
+ if x < 0 or y < 0 or x >= W or y >= H:
843
+ ok = False
844
+ break
845
+ f = fixed[y * W + x]
846
+ if f and f != nid:
847
+ ok = False
848
+ break
849
+ if not ok:
850
+ break
851
+ cache[idx] = ok
852
+ return ok
853
+
854
+ def via_cost(self, nid: int, idx: int, pres: float, hard: bool) -> float | None:
855
+ if self.viahole[idx] or not self.via_fixed_ok(nid, idx):
856
+ return None
857
+ r = self.opt.via_size / 2 - self.w0 / 2 + self.margin
858
+ cells = self.disc(max(0, int(math.ceil(r / self.opt.grid - 1e-9))))
859
+ gy, gx = divmod(idx, self.W)
860
+ W = self.W
861
+ congestion = 0
862
+ escape = 0.0
863
+ for li in range(self.L):
864
+ occ, esc = self.occ[li], self.esc[li]
865
+ for dx, dy in cells:
866
+ j = (gy + dy) * W + gx + dx
867
+ congestion += occ[j]
868
+ e = esc[j]
869
+ if e and e != nid:
870
+ escape += _ESC
871
+ if hard and congestion:
872
+ return None
873
+ return self.opt.via_cost * (1.0 + self.hist[0][idx]) * (1.0 + pres * congestion) + escape
874
+
875
+ def explain(self, nid: int, sources: dict, targets: dict, extra: int) -> str:
876
+ """Debug aid: how far a search could get ignoring routed copper, and which fixed
877
+ copper closes the region around the pads it is trying to reach."""
878
+ N, W, L = self.N, self.W, self.L
879
+ fixed = self.fixed
880
+ offs = (1, -1, W, -W, W + 1, W - 1, -W + 1, -W - 1)
881
+
882
+ def ok(node: int) -> bool:
883
+ layer, idx = divmod(node, N)
884
+ f = fixed[layer][idx]
885
+ return not (f and f != nid)
886
+
887
+ def flood(seeds):
888
+ seen = set(n for n in seeds if ok(n))
889
+ stack = list(seen)
890
+ edge: dict[int, int] = {}
891
+ while stack:
892
+ node = stack.pop()
893
+ layer, idx = divmod(node, N)
894
+ for off in offs:
895
+ nb = node + off
896
+ j = idx + off
897
+ if j < 0 or j >= N or abs((j % W) - (idx % W)) > 1:
898
+ continue
899
+ if nb in seen:
900
+ continue
901
+ if ok(nb):
902
+ seen.add(nb)
903
+ stack.append(nb)
904
+ else:
905
+ f = fixed[layer][j]
906
+ edge[f] = edge.get(f, 0) + 1
907
+ if L > 1 and not self.viahole[idx] and self.via_fixed_ok(nid, idx):
908
+ for other in range(L):
909
+ nb = other * N + idx
910
+ if nb not in seen and ok(nb):
911
+ seen.add(nb)
912
+ stack.append(nb)
913
+ return seen, edge
914
+
915
+ reach_t, edge_t = flood(targets)
916
+ reach_s, _ = flood(sources)
917
+ if reach_t:
918
+ xs = [self.xy(n % N)[0] for n in reach_t]
919
+ ys = [self.xy(n % N)[1] for n in reach_t]
920
+ box = (min(xs) - 0.6, min(ys) - 0.6, max(xs) + 0.6, max(ys) + 0.6)
921
+ seen_shapes = []
922
+ for sh in self.fixed_index.near(box, 0.3):
923
+ tag = sh.tag if isinstance(sh.tag, str) else "pad"
924
+ seen_shapes.append(
925
+ f"{tag}:{self.net_names.get(sh.net, sh.net)}@({sh.c[0]:.2f},{sh.c[1]:.2f})"
926
+ )
927
+ print(
928
+ " region box", [round(v, 2) for v in box], "shapes", seen_shapes[:40], flush=True
929
+ )
930
+ names = {k: self.net_names.get(k, "fixed" if k == -1 else str(k)) for k in edge_t}
931
+ top = sorted(edge_t.items(), key=lambda kv: -kv[1])[:6]
932
+ return (
933
+ f"target region {len(reach_t)} nodes, source region {len(reach_s)}, "
934
+ f"shared {len(reach_t & reach_s)}; walls: "
935
+ + ", ".join(f"{names[k]}={v}" for k, v in top)
936
+ )
937
+
938
+ # --------------------------------------------------------------- stubs
939
+ def stubs(self, pad: Pad, nid: int, width: float) -> list[_Stub]:
940
+ """Exact escapes from a pad to nearby free grid nodes, best first (cached)."""
941
+ key = (id(pad), nid, width)
942
+ if key in self._stub_cache:
943
+ return self._stub_cache[key]
944
+ opt, g = self.opt, self.opt.grid
945
+ mask = self.layer_mask(pad)
946
+ cx, cy = round(pad.x, 4), round(pad.y, 4)
947
+ hw, hh = pad.width / 2, pad.height / 2
948
+ if hw >= 1.25 * hh:
949
+ axis: tuple[float, float] | None = (1.0, 0.0)
950
+ elif hh >= 1.25 * hw:
951
+ axis = (0.0, 1.0)
952
+ else:
953
+ axis = None
954
+ reach = max(hw, hh) + opt.escape_reach
955
+ widths = sorted({width, self.w0, self.wmin}, reverse=True)
956
+ bbox = (cx - reach, cy - reach, cx + reach, cy + reach)
957
+ near = [
958
+ s
959
+ for s in self.fixed_index.near(bbox, self.max_clear + width)
960
+ if not (s.net and s.net == nid)
961
+ ]
962
+ cells = []
963
+ W = self.W
964
+ gx0, gy0 = (
965
+ int(math.floor((cx - reach - self.x0) / g)),
966
+ int(math.floor((cy - reach - self.y0) / g)),
967
+ )
968
+ gx1, gy1 = (
969
+ int(math.ceil((cx + reach - self.x0) / g)),
970
+ int(math.ceil((cy + reach - self.y0) / g)),
971
+ )
972
+ for gy in range(max(1, gy0), min(self.H - 1, gy1 + 1)):
973
+ for gx in range(max(1, gx0), min(W - 1, gx1 + 1)):
974
+ x, y = self.x0 + gx * g, self.y0 + gy * g
975
+ d = math.hypot(x - cx, y - cy)
976
+ if d <= reach:
977
+ cells.append((d, gy * W + gx, round(x, 4), round(y, 4)))
978
+ cells.sort()
979
+ found: list[_Stub] = []
980
+ for layer in range(self.L):
981
+ if not mask & (1 << layer):
982
+ continue
983
+ fixed = self.fixed[layer]
984
+ per_octant = [0] * 8
985
+ total = 0
986
+ for _d, idx, x, y in cells:
987
+ f = fixed[idx]
988
+ if f and f != nid:
989
+ continue
990
+ octant = int((math.atan2(y - cy, x - cx) + math.pi) / (2 * math.pi) * 8) % 8
991
+ if per_octant[octant] >= 4:
992
+ continue
993
+ best: tuple[float, list, float] | None = None
994
+ for poly in self._stub_shapes(cx, cy, x, y, axis, hw, hh):
995
+ length = sum(
996
+ math.hypot(b[0] - a[0], b[1] - a[1]) for a, b in zip(poly, poly[1:])
997
+ )
998
+ for w in widths:
999
+ if self.poly_legal(poly, w, layer, nid, False, near):
1000
+ cost = length / g * (1.0 if w >= width - 1e-9 else _NECK) + (
1001
+ _TURN * (len(poly) - 2)
1002
+ )
1003
+ if best is None or (w, -cost) > (best[2], -best[0]):
1004
+ best = (cost, poly, w)
1005
+ break
1006
+ if best is not None and best[2] >= width - 1e-9:
1007
+ break
1008
+ if best is None:
1009
+ continue
1010
+ per_octant[octant] += 1
1011
+ total += 1
1012
+ found.append(_Stub(layer * self.N + idx, best[1], best[2], best[0], pad))
1013
+ if total >= 28:
1014
+ break
1015
+ hint = self.opt.escape_layers.get((self.pad_owner.get(id(pad), ""), pad.number))
1016
+ if hint in self.layers: # a fan-out via: leave it on the layer its ring was given
1017
+ for s in found:
1018
+ if s.node // self.N != self.layers.index(hint):
1019
+ s.cost += 2.0
1020
+ found.sort(key=lambda s: s.cost)
1021
+ self._stub_cache[key] = found
1022
+ return found
1023
+
1024
+ @staticmethod
1025
+ def _stub_shapes(cx, cy, x, y, axis, hw, hh) -> list[list[tuple[float, float]]]:
1026
+ dx, dy = x - cx, y - cy
1027
+ polys: list[list[tuple[float, float]]] = []
1028
+ inside = abs(dx) <= hw and abs(dy) <= hh
1029
+ if axis is None or inside:
1030
+ polys.append([(cx, cy), (x, y)])
1031
+ if inside:
1032
+ return polys
1033
+ if axis is not None:
1034
+ along = dx * axis[0] + dy * axis[1]
1035
+ across = dx * axis[1] + dy * axis[0]
1036
+ half_long = hw if axis[0] else hh
1037
+ sign = 1.0 if along >= 0 else -1.0
1038
+ if abs(along) >= half_long * 0.5:
1039
+ if abs(across) < 1e-6:
1040
+ polys.append([(cx, cy), (x, y)])
1041
+ else:
1042
+ # 45-degree dogleg after running out along the axis, then a 90-degree one.
1043
+ t45 = abs(along) - abs(across)
1044
+ for t in (t45, abs(along)):
1045
+ if t <= 1e-6:
1046
+ continue
1047
+ px = round(cx + axis[0] * sign * t, 4)
1048
+ py = round(cy + axis[1] * sign * t, 4)
1049
+ if (px, py) != (x, y):
1050
+ polys.append([(cx, cy), (px, py), (x, y)])
1051
+ return polys
1052
+
1053
+ def stub_dynamic(self, stub: _Stub, nid: int, pres: float, hard: bool) -> float | None:
1054
+ """Extra cost (or None when blocked) from other nets' current copper."""
1055
+ layer = stub.node // self.N
1056
+ if self.poly_legal(stub.points, stub.width, layer, nid, True, []):
1057
+ return 0.0
1058
+ return None if hard else 6.0 * (1.0 + pres)
1059
+
1060
+ # -------------------------------------------------------------- search
1061
+ def search(
1062
+ self,
1063
+ nid: int,
1064
+ sources: dict[int, float],
1065
+ targets: dict[int, float] | None,
1066
+ extra: int,
1067
+ pres: float,
1068
+ hard: bool,
1069
+ goal: tuple[int, int] | None,
1070
+ limit: int,
1071
+ via_goal: int = 0,
1072
+ wide_hard: bool = False,
1073
+ only_layer: int | None = None,
1074
+ target_costs: bool = False,
1075
+ ) -> list[int] | None:
1076
+ N, W, L = self.N, self.W, self.L
1077
+ fixed, occ, hist, esc = self.fixed, self.occ, self.hist, self.esc
1078
+ lc = self.layer_cost
1079
+ wide_ok = self.wide_ok
1080
+ memo: dict[int, float] = {}
1081
+ via_memo: dict[int, float | None] = {} # occupancy is fixed during one search
1082
+ via_cost_of = self.via_cost
1083
+
1084
+ def cost_of(node: int) -> float:
1085
+ v = memo.get(node)
1086
+ if v is not None:
1087
+ return v
1088
+ layer, idx = divmod(node, N)
1089
+ f = fixed[layer][idx]
1090
+ if f and f != nid or (only_layer is not None and layer != only_layer):
1091
+ v = -1.0
1092
+ else:
1093
+ o = occ[layer][idx]
1094
+ if hard and o:
1095
+ v = -1.0
1096
+ else:
1097
+ v = lc[layer] * (1.0 + hist[layer][idx]) * (1.0 + pres * o)
1098
+ e = esc[layer][idx]
1099
+ if e and e != nid:
1100
+ v += _ESC
1101
+ if extra and not wide_ok(nid, extra, node):
1102
+ v = -1.0 if wide_hard else v * _NECK
1103
+ memo[node] = v
1104
+ return v
1105
+
1106
+ hmin = min(lc)
1107
+ if goal is not None:
1108
+ gx, gy = goal
1109
+
1110
+ def heuristic(node: int) -> float:
1111
+ y, x = divmod(node % N, W)
1112
+ dx, dy = abs(x - gx), abs(y - gy)
1113
+ return (dx + dy + (_SQRT2 - 2) * min(dx, dy)) * hmin
1114
+
1115
+ else:
1116
+
1117
+ def heuristic(node: int) -> float:
1118
+ return 0.0
1119
+
1120
+ offsets = [
1121
+ (1, 1.0, 0, 0),
1122
+ (-1, 1.0, 0, 0),
1123
+ (W, 1.0, 0, 0),
1124
+ (-W, 1.0, 0, 0),
1125
+ (W + 1, _SQRT2, 1, W),
1126
+ (W - 1, _SQRT2, -1, W),
1127
+ (-W + 1, _SQRT2, 1, -W),
1128
+ (-W - 1, _SQRT2, -1, -W),
1129
+ ]
1130
+ dir_mult = self.dir_mult
1131
+ span = self.opt.via_span_cost
1132
+ self.search_limited = False
1133
+ heap: list = []
1134
+ best: dict[int, float] = {}
1135
+ parent: dict[int, int] = {}
1136
+ for node, c in sources.items():
1137
+ if cost_of(node) < 0:
1138
+ continue
1139
+ best[node] = c
1140
+ parent[node] = -2
1141
+ heap.append((c + heuristic(node), c, node, -1))
1142
+ heapq.heapify(heap)
1143
+ push, pop = heapq.heappush, heapq.heappop
1144
+ expansions = 0
1145
+ while heap:
1146
+ _, c, node, d = pop(heap)
1147
+ if node == _GOAL:
1148
+ path = []
1149
+ cur = parent[_GOAL]
1150
+ while cur != -2:
1151
+ path.append(cur)
1152
+ cur = parent[cur]
1153
+ return path[::-1]
1154
+ if c > best.get(node, math.inf) + 1e-9:
1155
+ continue
1156
+ if target_costs and targets is not None and node in targets:
1157
+ nc = c + targets[node] # finishing here costs this much more
1158
+ if nc < best.get(_GOAL, math.inf) - 1e-9:
1159
+ best[_GOAL] = nc
1160
+ parent[_GOAL] = node
1161
+ push(heap, (nc, nc, _GOAL, -1))
1162
+ elif targets is not None and node in targets:
1163
+ path = []
1164
+ cur = node
1165
+ while cur != -2:
1166
+ path.append(cur)
1167
+ cur = parent[cur]
1168
+ return path[::-1]
1169
+ expansions += 1
1170
+ if expansions > limit:
1171
+ self.search_limited = True
1172
+ return None
1173
+ layer, idx = divmod(node, N)
1174
+ dm = dir_mult[layer]
1175
+ for k, (off, length, ox, oy) in enumerate(offsets):
1176
+ nb = node + off
1177
+ m = cost_of(nb)
1178
+ if m < 0:
1179
+ continue
1180
+ if ox and (cost_of(node + ox) < 0 or cost_of(node + oy) < 0):
1181
+ continue # no corner cutting past obstacles
1182
+ nc = c + length * m * dm[k]
1183
+ if d >= 0 and d != k:
1184
+ nc += _TURN
1185
+ if nc < best.get(nb, math.inf) - 1e-9:
1186
+ best[nb] = nc
1187
+ parent[nb] = node
1188
+ push(heap, (nc + heuristic(nb), nc, nb, k))
1189
+ if L > 1 or (via_goal and via_goal & (1 << layer)):
1190
+ if idx in via_memo:
1191
+ vc = via_memo[idx]
1192
+ else:
1193
+ vc = via_memo[idx] = via_cost_of(nid, idx, pres, hard)
1194
+ if vc is None:
1195
+ continue
1196
+ if via_goal and via_goal & (1 << layer):
1197
+ nc = c + vc
1198
+ if nc < best.get(_GOAL, math.inf) - 1e-9:
1199
+ best[_GOAL] = nc
1200
+ parent[_GOAL] = node
1201
+ push(heap, (nc, nc, _GOAL, -1))
1202
+ for other in range(L):
1203
+ if other == layer:
1204
+ continue
1205
+ nb = other * N + idx
1206
+ if cost_of(nb) < 0:
1207
+ continue
1208
+ nc = c + vc * (1.0 + span * (abs(other - layer) - 1))
1209
+ if nc < best.get(nb, math.inf) - 1e-9:
1210
+ best[nb] = nc
1211
+ parent[nb] = node
1212
+ push(heap, (nc + heuristic(nb), nc, nb, -1))
1213
+ return None
1214
+
1215
+ # -------------------------------------------------------------- commit
1216
+ def _add_seg(self, route: _NetRoute, nid: int, layer: int, a, b, width: float) -> None:
1217
+ if (a[0], a[1]) == (b[0], b[1]):
1218
+ return
1219
+ route.segs.append((layer, a[0], a[1], b[0], b[1], width))
1220
+ shape = Shape.capsule(a[0], a[1], b[0], b[1], width / 2, nid, 1 << layer, "seg")
1221
+ route.shapes.append(shape)
1222
+ self.routed_index.add(shape)
1223
+ radius = self.clear(nid, 0) + width / 2 + self.w0 / 2 + self.margin
1224
+ route.keep[layer].update(self.cells_within(shape, radius))
1225
+
1226
+ def _add_via(self, route: _NetRoute, nid: int, x: float, y: float) -> None:
1227
+ opt = self.opt
1228
+ route.vias.append((x, y))
1229
+ shape = Shape.capsule(x, y, x, y, opt.via_size / 2, nid, self.all_layers, "via")
1230
+ route.shapes.append(shape)
1231
+ self.routed_index.add(shape)
1232
+ radius = self.clear(nid, 0) + opt.via_size / 2 + self.w0 / 2 + self.margin
1233
+ cells = list(self.cells_within(shape, radius))
1234
+ for keep in route.keep:
1235
+ keep.update(cells)
1236
+ hole = Shape.capsule(x, y, x, y, 0.0, nid, self.all_layers)
1237
+ for idx in self.cells_within(hole, opt.via_drill + opt.hole_clearance + self.margin):
1238
+ if idx not in route.holes:
1239
+ route.holes.add(idx)
1240
+ self.viahole[idx] += 1
1241
+
1242
+ def commit(
1243
+ self,
1244
+ route: _NetRoute,
1245
+ nid: int,
1246
+ path: list[int],
1247
+ src: _Stub | None,
1248
+ dst: _Stub | None,
1249
+ width: float,
1250
+ extra: int,
1251
+ end_via: bool = False,
1252
+ ) -> None:
1253
+ N = self.N
1254
+ points: list[tuple[int, tuple[float, float], float | None]] = [] # layer, xy, width in
1255
+ if src is not None:
1256
+ layer = src.node // N
1257
+ for i, p in enumerate(src.points):
1258
+ points.append((layer, p, None if i == 0 else src.width))
1259
+ prev = None
1260
+ for node in path:
1261
+ layer, idx = divmod(node, N)
1262
+ p = self.xy(idx)
1263
+ if points and points[-1][1] == p and points[-1][0] == layer:
1264
+ prev = node
1265
+ continue
1266
+ if prev is None:
1267
+ w_in = None
1268
+ elif prev % N == idx:
1269
+ w_in = -1.0 # via
1270
+ elif not extra or (self.wide_ok(nid, extra, prev) and self.wide_ok(nid, extra, node)):
1271
+ w_in = width
1272
+ else:
1273
+ w_in = self.w0
1274
+ route.necked = True
1275
+ if prev is None and points:
1276
+ w_in = -1.0 if points[-1][0] != layer else self.w0
1277
+ points.append((layer, p, w_in))
1278
+ prev = node
1279
+ if dst is not None:
1280
+ layer = dst.node // N
1281
+ for p in reversed(dst.points[:-1]):
1282
+ points.append((layer, p, dst.width))
1283
+ if (
1284
+ src is not None
1285
+ and src.width < width - 1e-9
1286
+ or dst is not None
1287
+ and dst.width < width - 1e-9
1288
+ ):
1289
+ route.necked = True
1290
+ # Merge collinear runs and emit segments and vias.
1291
+ runs: list[tuple[int, float, list[tuple[float, float]]]] = []
1292
+ for i in range(1, len(points)):
1293
+ layer, p, w = points[i]
1294
+ a = points[i - 1][1]
1295
+ if w is not None and w < 0:
1296
+ self._add_via(route, nid, p[0], p[1])
1297
+ continue
1298
+ if w is None:
1299
+ continue
1300
+ if runs and runs[-1][0] == layer and runs[-1][1] == w and runs[-1][2][-1] == a:
1301
+ pts = runs[-1][2]
1302
+ if len(pts) >= 2:
1303
+ ux, uy = pts[-1][0] - pts[-2][0], pts[-1][1] - pts[-2][1]
1304
+ vx, vy = p[0] - a[0], p[1] - a[1]
1305
+ if abs(ux * vy - uy * vx) < 1e-9 and ux * vx + uy * vy > 0:
1306
+ pts[-1] = p
1307
+ continue
1308
+ pts.append(p)
1309
+ else:
1310
+ runs.append((layer, w, [a, p]))
1311
+ for layer, w, pts in runs:
1312
+ for a, b in zip(pts, pts[1:]):
1313
+ self._add_seg(route, nid, layer, a, b, w)
1314
+ if end_via and points:
1315
+ x, y = points[-1][1]
1316
+ self._add_via(route, nid, x, y)
1317
+
1318
+ def ripup(self, net: str) -> None:
1319
+ route = self.routes.pop(net, None)
1320
+ if route is None:
1321
+ return
1322
+ for li, keep in enumerate(route.keep):
1323
+ occ = self.occ[li]
1324
+ for idx in keep:
1325
+ occ[idx] -= 1
1326
+ for idx in route.holes:
1327
+ self.viahole[idx] -= 1
1328
+ for shape in route.shapes:
1329
+ self.routed_index.remove(shape)
1330
+
1331
+ def restore(self, net: str, route: _NetRoute) -> None:
1332
+ """Put back a route taken out with ``ripup`` (its copper, holes and occupancy)."""
1333
+ self.ripup(net)
1334
+ self._publish(net, route)
1335
+ for idx in route.holes:
1336
+ self.viahole[idx] += 1
1337
+ for shape in route.shapes:
1338
+ self.routed_index.add(shape)
1339
+
1340
+ def _publish(self, net: str, route: _NetRoute) -> None:
1341
+ self.routes[net] = route
1342
+ for li, keep in enumerate(route.keep):
1343
+ occ = self.occ[li]
1344
+ for idx in keep:
1345
+ occ[idx] += 1
1346
+
1347
+ # ---------------------------------------------------------------- nets
1348
+ def clusters(self, net: str) -> list[list[Pad]]:
1349
+ """The net's pads grouped by copper that already touches (e.g. USB-C A4/B9)."""
1350
+ pads = sorted(self.pads_by_net.get(net, []), key=lambda p: (p.x, p.y))
1351
+ groups: list[list[Pad]] = []
1352
+ for pad in pads:
1353
+ shape = self.pad_shapes.get(id(pad))
1354
+ if shape is None:
1355
+ continue
1356
+ joined = [
1357
+ grp
1358
+ for grp in groups
1359
+ if any(
1360
+ self.pad_shapes[id(o)].layers & shape.layers
1361
+ and self.pad_shapes[id(o)].dist_shape(shape) <= 1e-6
1362
+ for o in grp
1363
+ )
1364
+ ]
1365
+ merged = [pad]
1366
+ for grp in joined:
1367
+ merged.extend(grp)
1368
+ groups.remove(grp)
1369
+ groups.append(merged)
1370
+ return groups
1371
+
1372
+ def _direct(self, route, nid, width, connected: list[Pad], target: list[Pad]) -> bool:
1373
+ """Join two same-net pads with one straight segment when that is legal."""
1374
+ best = None
1375
+ for s in connected:
1376
+ for t in target:
1377
+ d = math.hypot(s.x - t.x, s.y - t.y)
1378
+ if d <= self.opt.direct_join and (best is None or d < best[0]):
1379
+ common = self.pad_shapes[id(s)].layers & self.pad_shapes[id(t)].layers
1380
+ if common:
1381
+ best = (d, s, t, common)
1382
+ if best is None:
1383
+ return False
1384
+ _, s, t, common = best
1385
+ a, b = (round(s.x, 4), round(s.y, 4)), (round(t.x, 4), round(t.y, 4))
1386
+ for layer in range(self.L):
1387
+ if not common & (1 << layer):
1388
+ continue
1389
+ for w in sorted({width, self.w0}, reverse=True):
1390
+ if self.seg_legal(a[0], a[1], b[0], b[1], w, layer, nid, True):
1391
+ self._add_seg(route, nid, layer, a, b, w)
1392
+ if w < width - 1e-9:
1393
+ route.necked = True
1394
+ return True
1395
+ return False
1396
+
1397
+ def route_net(self, net: str, pres: float, hard: bool) -> bool:
1398
+ nid = self.net_id(net)
1399
+ width = self.width(net)
1400
+ extra = self.extra_cells(net)
1401
+ groups = self.clusters(net)
1402
+ if net in self.core_ends: # a pair's coupled section: both ends already joined
1403
+ groups = [list(self.core_ends[net]), *groups]
1404
+ route = _NetRoute(self.L)
1405
+ if len(groups) < 2:
1406
+ self._publish(net, route)
1407
+ return True
1408
+ connected: list[Pad] = list(groups[0])
1409
+ tree: set[int] = set()
1410
+ remaining = groups[1:]
1411
+ ok = True
1412
+ while remaining:
1413
+ remaining.sort(
1414
+ key=lambda grp: min(abs(p.x - c.x) + abs(p.y - c.y) for p in grp for c in connected)
1415
+ )
1416
+ target = remaining.pop(0)
1417
+ if self._direct(route, nid, width, connected, target):
1418
+ connected.extend(target)
1419
+ continue
1420
+ sources: dict[int, float] = {node: 0.0 for node in tree}
1421
+ src_stub: dict[int, _Stub] = {}
1422
+ for pad in connected:
1423
+ for stub in self.stubs(pad, nid, width):
1424
+ if stub.node in tree:
1425
+ continue
1426
+ dyn = self.stub_dynamic(stub, nid, pres, hard)
1427
+ if dyn is None:
1428
+ continue
1429
+ cost = stub.cost + dyn
1430
+ if cost < sources.get(stub.node, math.inf):
1431
+ sources[stub.node] = cost
1432
+ src_stub[stub.node] = stub
1433
+ targets: dict[int, float] = {}
1434
+ dst_stub: dict[int, _Stub] = {}
1435
+ for pad in target:
1436
+ for stub in self.stubs(pad, nid, width):
1437
+ dyn = self.stub_dynamic(stub, nid, pres, hard)
1438
+ if dyn is None:
1439
+ continue
1440
+ cost = stub.cost + dyn
1441
+ if cost < targets.get(stub.node, math.inf):
1442
+ targets[stub.node] = cost
1443
+ dst_stub[stub.node] = stub
1444
+ path = None
1445
+ if sources and targets:
1446
+ tx = sum(p.x for p in target) / len(target)
1447
+ ty = sum(p.y for p in target) / len(target)
1448
+ gidx = self.cell(tx, ty)
1449
+ path = self.search(
1450
+ nid,
1451
+ sources,
1452
+ targets,
1453
+ extra,
1454
+ pres,
1455
+ hard,
1456
+ (gidx % self.W, gidx // self.W),
1457
+ self.opt.max_expansions,
1458
+ )
1459
+ if path is None:
1460
+ ok = False
1461
+ route.failed += 1
1462
+ if not sources:
1463
+ why = "no free start: every escape from the connected pads is blocked"
1464
+ elif not targets:
1465
+ why = "no free end: every escape from the next pad group is blocked"
1466
+ elif self.search_limited:
1467
+ why = "search limit reached before a path was found"
1468
+ else:
1469
+ why = "no path: the other nets' copper closes every way through"
1470
+ where = ", ".join(sorted({f"{q.number}" for q in target})[:4])
1471
+ self.fail_reason[net] = f"{why} (to pad {where})"
1472
+ if os.environ.get("TF_ROUTE_DEBUG") and sources and targets:
1473
+ print(" EXPLAIN", net, self.explain(nid, sources, targets, extra), flush=True)
1474
+ if os.environ.get("TF_ROUTE_DEBUG"):
1475
+ print(
1476
+ f" FAIL {net}: sources={len(sources)} targets={len(targets)} "
1477
+ f"limited={self.search_limited} pads={[(q.x, q.y) for q in target][:2]}",
1478
+ flush=True,
1479
+ )
1480
+ continue
1481
+ src = src_stub.get(path[0]) if path[0] not in tree else None
1482
+ self.commit(route, nid, path, src, dst_stub[path[-1]], width, extra)
1483
+ tree.update(path)
1484
+ connected.extend(target)
1485
+ self._publish(net, route)
1486
+ return ok
1487
+
1488
+ def route_plane(self, net: str, pres: float, hard: bool) -> bool:
1489
+ """Give every pad of a plane net that is not on the plane layer a way down to it."""
1490
+ if net in self.plane_assign:
1491
+ plane_bit = 0 # an inner plane: only through-hole pads touch it without a via
1492
+ elif self.opt.plane_layer not in self.layers:
1493
+ return False
1494
+ else:
1495
+ plane_bit = 1 << self.layers.index(self.opt.plane_layer)
1496
+ nid = self.net_id(net)
1497
+ width = self.width(net)
1498
+ extra = self.extra_cells(net)
1499
+ route = _NetRoute(self.L)
1500
+ ok = True
1501
+
1502
+ def on_plane(p: Pad) -> bool:
1503
+ return (
1504
+ p.kind == "thru_hole"
1505
+ if net in self.plane_assign
1506
+ else bool(self.layer_mask(p) & plane_bit)
1507
+ )
1508
+
1509
+ anchors = [p for p in self.pads_by_net.get(net, []) if on_plane(p)]
1510
+ for group in self.clusters(net):
1511
+ if any(on_plane(p) for p in group):
1512
+ continue # through-hole: the pour reaches it directly
1513
+ if any(v.net == net and p.contains(v.x, v.y) for v in self.board.vias for p in group):
1514
+ continue # a via already sits in the pad (planes.reserve)
1515
+ if anchors and self._direct(route, nid, width, group, anchors):
1516
+ continue
1517
+ sources: dict[int, float] = {}
1518
+ src_stub: dict[int, _Stub] = {}
1519
+ via_layers = 0
1520
+ for pad in group:
1521
+ via_layers |= self.layer_mask(pad)
1522
+ for stub in self.stubs(pad, nid, width):
1523
+ dyn = self.stub_dynamic(stub, nid, pres, hard)
1524
+ if dyn is None:
1525
+ continue
1526
+ cost = stub.cost + dyn
1527
+ if cost < sources.get(stub.node, math.inf):
1528
+ sources[stub.node] = cost
1529
+ src_stub[stub.node] = stub
1530
+ path = (
1531
+ self.search(nid, sources, None, extra, pres, hard, None, 30_000, via_layers)
1532
+ if sources
1533
+ else None
1534
+ )
1535
+ if path is None:
1536
+ ok = False
1537
+ route.failed += 1
1538
+ continue
1539
+ self.commit(route, nid, path, src_stub.get(path[0]), None, width, extra, end_via=True)
1540
+ for pad in self.plane_links.get(net, []):
1541
+ if not self._link_plane_pad(route, net, pad, pres, hard):
1542
+ ok = False
1543
+ route.failed += 1
1544
+ self._publish(net, route)
1545
+ return ok
1546
+
1547
+ def _link_plane_pad(self, route: _NetRoute, net: str, pad: Pad, pres: float, hard: bool):
1548
+ """Tie a plane pad the pour left isolated to plane-net pads on other parts."""
1549
+ nid, width, extra = self.net_id(net), self.width(net), self.extra_cells(net)
1550
+ home = self.pad_owner.get(id(pad))
1551
+ others = sorted(
1552
+ (
1553
+ p
1554
+ for p in self.pads_by_net.get(net, [])
1555
+ if self.pad_owner.get(id(p)) != home and math.hypot(p.x - pad.x, p.y - pad.y) > 2
1556
+ ),
1557
+ key=lambda p: math.hypot(p.x - pad.x, p.y - pad.y),
1558
+ )[:4]
1559
+
1560
+ def ends(pads: list[Pad]) -> tuple[dict[int, float], dict[int, _Stub]]:
1561
+ costs: dict[int, float] = {}
1562
+ stubs: dict[int, _Stub] = {}
1563
+ for p in pads:
1564
+ for stub in self.stubs(p, nid, width):
1565
+ dyn = self.stub_dynamic(stub, nid, pres, hard)
1566
+ if dyn is not None and stub.cost + dyn < costs.get(stub.node, math.inf):
1567
+ costs[stub.node] = stub.cost + dyn
1568
+ stubs[stub.node] = stub
1569
+ return costs, stubs
1570
+
1571
+ sources, src_stub = ends([pad])
1572
+ targets, dst_stub = ends(others)
1573
+ if not sources or not targets:
1574
+ return False
1575
+ gidx = self.cell(others[0].x, others[0].y)
1576
+ path = self.search(
1577
+ nid,
1578
+ sources,
1579
+ targets,
1580
+ extra,
1581
+ pres,
1582
+ hard,
1583
+ (gidx % self.W, gidx // self.W),
1584
+ self.opt.max_expansions,
1585
+ )
1586
+ if path is None:
1587
+ return False
1588
+ self.commit(route, nid, path, src_stub.get(path[0]), dst_stub[path[-1]], width, extra)
1589
+ return True
1590
+
1591
+ # --------------------------------------------------------- diff pairs
1592
+ def find_pairs(self, nets: list[str]) -> list[_Pair]:
1593
+ """Pairs among ``nets``: the options' list, else project settings and net names."""
1594
+ configured = _project_pairs(self.pcb)
1595
+ if self.opt.diff_pairs is not None:
1596
+ names = [tuple(p) for p in self.opt.diff_pairs]
1597
+ else:
1598
+ names = list(configured)
1599
+ taken = {n for pair in names for n in pair}
1600
+ for pos, neg in diffpair.pair_names(nets):
1601
+ if not {pos, neg} & taken and max(self.width(pos), self.width(neg)) <= self.w0:
1602
+ names.append((pos, neg))
1603
+ pairs = []
1604
+ for pos, neg in names:
1605
+ if pos not in nets or neg not in nets:
1606
+ continue
1607
+ cfg = configured.get((pos, neg), {})
1608
+ gap = float(cfg.get("gap") or self.opt.clearance)
1609
+ width = cfg.get("width")
1610
+ if not width: # USB's 90 ohms on the board's own stackup
1611
+ try:
1612
+ width = impedance.solve_pair(
1613
+ diffpair.USB_IMPEDANCE,
1614
+ self.layers[0],
1615
+ self.stack,
1616
+ gap=gap,
1617
+ max_width=2.0,
1618
+ )[0]
1619
+ except impedance.ImpedanceError:
1620
+ width = self.wmin
1621
+ gap = max(gap, max(self.net_clear.get(self.net_id(n), 0.0) for n in (pos, neg)))
1622
+ tol = float(cfg.get("tolerance", self.opt.pair_tolerance))
1623
+ pair = _Pair(pos, neg, max(float(width), self.wmin), gap, tol)
1624
+ if cfg.get("height"):
1625
+ pair.height = float(cfg["height"])
1626
+ pair.target = float(cfg.get("impedance") or diffpair.USB_IMPEDANCE)
1627
+ pair.fixed = bool(cfg.get("width_given"))
1628
+ pairs.append(pair)
1629
+ return pairs
1630
+
1631
+ def _pair_terminals(self, pair: _Pair) -> list[dict]:
1632
+ """Where both nets of the pair meet: groups of nearby P and N pads."""
1633
+ groups: dict[tuple[str, str], list[Pad]] = {}
1634
+ for net in (pair.pos, pair.neg):
1635
+ for pad in self.pads_by_net.get(net, []):
1636
+ groups.setdefault((net, self.pad_owner.get(id(pad), "")), []).append(pad)
1637
+
1638
+ def centre(pads: list[Pad]) -> tuple[float, float]:
1639
+ return sum(p.x for p in pads) / len(pads), sum(p.y for p in pads) / len(pads)
1640
+
1641
+ # Each footprint's P pads meet the nearest footprint's N pads (the same part, or
1642
+ # the twin series resistor next to it).
1643
+ terms: list[dict] = []
1644
+ negs = [(k, v) for k, v in groups.items() if k[0] == pair.neg]
1645
+ for key, pads in groups.items():
1646
+ if key[0] != pair.pos or not negs:
1647
+ continue
1648
+ px, py = centre(pads)
1649
+ nkey, npads = min(negs, key=lambda kv: math.dist(centre(kv[1]), (px, py)))
1650
+ if math.dist(centre(npads), (px, py)) > 5.0:
1651
+ continue
1652
+ for term in terms:
1653
+ if term["nkey"] == nkey:
1654
+ term["p"] += pads
1655
+ break
1656
+ else:
1657
+ terms.append({"p": list(pads), "n": list(npads), "nkey": nkey})
1658
+ for term in terms:
1659
+ members = term["p"] + term["n"]
1660
+ term["x"] = sum(q.x for q in members) / len(members)
1661
+ term["y"] = sum(q.y for q in members) / len(members)
1662
+ px = sum(q.x for q in term["p"]) / len(term["p"])
1663
+ py = sum(q.y for q in term["p"]) / len(term["p"])
1664
+ nx = sum(q.x for q in term["n"]) / len(term["n"])
1665
+ ny = sum(q.y for q in term["n"]) / len(term["n"])
1666
+ term["ref"] = (px - nx, py - ny)
1667
+ return terms
1668
+
1669
+ def _pair_nodes(self, pid: int, extra: int, layer: int, x, y, ox, oy) -> dict:
1670
+ """Grid nodes near (x, y), and nearer it than the far end (ox, oy), where the
1671
+ whole pair fits; the cost grows with the distance to (x, y)."""
1672
+ g = self.opt.grid
1673
+ probe = Shape.capsule(x, y, x, y, 0.0, 0, 1)
1674
+ found = []
1675
+ fixed = self.fixed[layer]
1676
+ for idx in self.cells_within(probe, 8.0):
1677
+ if fixed[idx] and fixed[idx] != pid:
1678
+ continue
1679
+ node = layer * self.N + idx
1680
+ if self.wide_ok(pid, extra, node):
1681
+ cx, cy = self.xy(idx)
1682
+ d = math.hypot(cx - x, cy - y)
1683
+ if d < math.hypot(cx - ox, cy - oy):
1684
+ found.append((d, node))
1685
+ if not found:
1686
+ return {}
1687
+ # Stand off a little from the pads, so other nets can still pass in front of them.
1688
+ near = min(d for d, _ in found) + self.pair_standoff
1689
+ return {
1690
+ node: (1.5 * max(0.0, d - near) + 4.0 * max(0.0, near - d)) / g for d, node in found
1691
+ }
1692
+
1693
+ def route_pair_core(self, pair: _Pair) -> bool:
1694
+ """Route the coupled section of a pair and freeze it as fixed copper."""
1695
+ terms = self._pair_terminals(pair)
1696
+ pair.terms = terms
1697
+ if len(terms) != 2:
1698
+ pair.note = f"not coupled: {len(terms)} places where both nets meet (need 2)"
1699
+ return False
1700
+ plane = self.opt.plane_layer if self.opt.plane_nets and not self.plane_assign else None
1701
+ signal = [i for i, name in enumerate(self.layers) if name != plane] or [0]
1702
+ if self.L > 2:
1703
+ # Outer microstrip layers first (the width is cheapest to fit there), then the
1704
+ # inner signal layers as stripline, each with the width solved for its own geometry.
1705
+ def kind(i: int) -> str:
1706
+ try:
1707
+ return impedance.geometry_name(self.stack, self.layers[i])
1708
+ except (stackups.StackupError, ValueError):
1709
+ return ""
1710
+
1711
+ outer = [i for i in signal if kind(i) == "microstrip"]
1712
+ inner = [i for i in signal if kind(i) in ("stripline", "embedded")]
1713
+ signal = (outer + inner) or signal
1714
+ pair.widths = {}
1715
+ for i in signal:
1716
+ try:
1717
+ w = impedance.solve_pair(
1718
+ pair.target,
1719
+ self.layers[i],
1720
+ self.stack,
1721
+ gap=pair.gap,
1722
+ min_width=self.wmin,
1723
+ max_width=2.0,
1724
+ )[0]
1725
+ except (impedance.ImpedanceError, stackups.StackupError, ValueError):
1726
+ w = pair.width
1727
+ pair.widths[i] = pair.width if pair.fixed else max(round(w, 2), self.wmin)
1728
+ g = self.opt.grid
1729
+ pid = self.net_id(f"{pair.pos}/{pair.neg}")
1730
+ a, b = terms
1731
+ best = None
1732
+
1733
+ # The impedance width first; narrower (higher impedance) when no corridor is wide
1734
+ # enough. USB full speed tolerates that; the report says what was achieved.
1735
+ def width_on(layer: int) -> float:
1736
+ return pair.widths.get(layer, pair.width)
1737
+
1738
+ tries: list[tuple[float, int]] = []
1739
+ for f in (1.0, 0.75, 0.55, 0.4, 0.3):
1740
+ for layer in signal:
1741
+ w = round(width_on(layer) * f, 2)
1742
+ if f == 1.0 or (w >= self.w0 and w < width_on(layer)):
1743
+ tries.append((w, layer))
1744
+ direct = math.hypot(a["x"] - b["x"], a["y"] - b["y"])
1745
+ short = False
1746
+ for width, layer in tries:
1747
+ half = pair.gap / 2 + width
1748
+ for grow in (0, 1):
1749
+ extra = max(0, int(math.ceil((half - self.w0 / 2) / g - 1e-9))) + grow
1750
+ sources = self._pair_nodes(pid, extra, layer, a["x"], a["y"], b["x"], b["y"])
1751
+ targets = self._pair_nodes(pid, extra, layer, b["x"], b["y"], a["x"], a["y"])
1752
+ if not sources or not targets:
1753
+ continue
1754
+ gidx = self.cell(b["x"], b["y"])
1755
+ path = self.search(
1756
+ pid,
1757
+ sources,
1758
+ targets,
1759
+ extra,
1760
+ 0.0,
1761
+ False,
1762
+ (gidx % self.W, gidx // self.W),
1763
+ self.opt.max_expansions,
1764
+ wide_hard=True,
1765
+ only_layer=layer,
1766
+ target_costs=True,
1767
+ )
1768
+ if path is None:
1769
+ continue
1770
+ pts = diffpair.simplify([self.xy(node % self.N) for node in path])
1771
+ if len(pts) < 2 or diffpair.polyline_length(pts) < 1.0:
1772
+ short = True # a narrower pair may still fit between the ends
1773
+ break
1774
+ n0 = diffpair._normal(pts[0], pts[1])
1775
+ n1 = diffpair._normal(pts[-2], pts[-1])
1776
+ score = a["ref"][0] * n0[0] + a["ref"][1] * n0[1]
1777
+ score += b["ref"][0] * n1[0] + b["ref"][1] * n1[1]
1778
+ sign = 1.0 if score >= 0 else -1.0
1779
+ s = (pair.gap + width) / 2
1780
+ tracks = {
1781
+ pair.pos: diffpair.offset_polyline(pts, sign * s),
1782
+ pair.neg: diffpair.offset_polyline(pts, -sign * s),
1783
+ }
1784
+ # Split the two tracks apart at 45 degrees at each end, so each fans out
1785
+ # from free space instead of from between its partner and the gap.
1786
+ for net, side in ((pair.pos, sign), (pair.neg, -sign)):
1787
+ poly = tracks[net]
1788
+ nid = self.net_id(net)
1789
+ split = max(0.4, width)
1790
+ for at_start in (True, False):
1791
+ a0, a1 = (pts[0], pts[1]) if at_start else (pts[-1], pts[-2])
1792
+ ux, uy = a0[0] - a1[0], a0[1] - a1[1]
1793
+ d = math.hypot(ux, uy) or 1.0
1794
+ ux, uy = ux / d, uy / d
1795
+ nx, ny = (
1796
+ diffpair._normal(pts[0], pts[1])
1797
+ if at_start
1798
+ else diffpair._normal(pts[-2], pts[-1])
1799
+ )
1800
+ end = poly[0] if at_start else poly[-1]
1801
+ tip = (
1802
+ round(end[0] + (ux + side * nx) * split, 4),
1803
+ round(end[1] + (uy + side * ny) * split, 4),
1804
+ )
1805
+ if self.seg_legal(*end, *tip, width, layer, nid, False):
1806
+ poly = [tip, *poly] if at_start else [*poly, tip]
1807
+ tracks[net] = poly
1808
+ if all(
1809
+ self.poly_legal(poly, width, layer, self.net_id(net), False)
1810
+ for net, poly in tracks.items()
1811
+ ):
1812
+ # Total run: fan-in, coupled section, fan-out.
1813
+ run = (
1814
+ diffpair.polyline_length(pts)
1815
+ + math.hypot(pts[0][0] - a["x"], pts[0][1] - a["y"])
1816
+ + math.hypot(pts[-1][0] - b["x"], pts[-1][1] - b["y"])
1817
+ )
1818
+ core = diffpair.polyline_length(pts)
1819
+ score = core - 0.5 * max(0.0, run - direct)
1820
+ if best is None or score > best[0] + 1e-6:
1821
+ best = (score, layer, tracks, sign, width, core, run)
1822
+ break
1823
+ if best and best[5] >= 0.5 * direct and best[6] <= 1.4 * direct + 4.0:
1824
+ break # mostly coupled, no long detour: keep this width
1825
+ if best is None:
1826
+ pair.note = (
1827
+ "routed as two tracks: the two ends are too close to couple"
1828
+ if short
1829
+ else "not coupled: no corridor wide enough for both tracks"
1830
+ )
1831
+ return False
1832
+ _, layer, tracks, sign, width, _, _ = best
1833
+ nominal = pair.widths.get(layer, pair.width)
1834
+ if width < nominal - 1e-9:
1835
+ z = impedance.differential(self.stack, self.layers[layer], width, pair.gap)
1836
+ pair.note = f"narrowed from {nominal} mm to {width} mm to fit (about {z:.0f} ohm)"
1837
+ pair.width = width
1838
+ pair.layer = layer
1839
+ pair.side = {pair.pos: sign, pair.neg: -sign}
1840
+ for net, poly in tracks.items():
1841
+ self._set_core(net, layer, pair.width, poly)
1842
+ nid = self.net_id(net)
1843
+ ends = []
1844
+ for x, y in (poly[0], poly[-1]):
1845
+ end = Pad(
1846
+ "~", "smd", "circle", x, y, pair.width, pair.width, [self.layers[layer]], net
1847
+ )
1848
+ self.pad_shapes[id(end)] = _pad_shape(end, nid, 1 << layer)
1849
+ ends.append(end)
1850
+ self.core_ends[net] = ends
1851
+ self._stub_cache.clear()
1852
+ self._wide_cache.clear()
1853
+ self._viafix_cache.clear()
1854
+ return True
1855
+
1856
+ def _set_core(self, net: str, layer: int, width: float, poly) -> None:
1857
+ nid = self.net_id(net)
1858
+ for shape in self.core_shapes.pop(net, []):
1859
+ self.fixed_index.remove(shape)
1860
+ shapes = []
1861
+ for p, q in zip(poly, poly[1:]):
1862
+ shape = Shape.capsule(p[0], p[1], q[0], q[1], width / 2, nid, 1 << layer, "core")
1863
+ self.fixed_index.add(shape)
1864
+ self._claim_fixed(shape, self.keep0)
1865
+ shapes.append(shape)
1866
+ self.core_shapes[net] = shapes
1867
+ self.cores[net] = (layer, width, list(poly))
1868
+
1869
+ def net_length(self, net: str) -> float:
1870
+ """Copper length of the net as it will be written: routed tracks, a pair's coupled
1871
+ section and the fan-out stubs the escape stage already put on its pins."""
1872
+ route = self.routes.get(net)
1873
+ total = sum(math.hypot(s[3] - s[1], s[4] - s[2]) for s in route.segs) if route else 0.0
1874
+ if net in self.cores:
1875
+ total += diffpair.polyline_length(self.cores[net][2])
1876
+ total += sum(getattr(p, "stub_mm", 0.0) for p in self.pads_by_net.get(net, []))
1877
+ return total
1878
+
1879
+ def signal_length(self, net: str, start: list[Pad], end: list[Pad]) -> float | None:
1880
+ """Track length along the path from ``start`` pads to ``end`` pads (stubs such as
1881
+ a USB-C A6-B6 jumper do not count); None when they are not joined. Fan-out stubs
1882
+ already on the pins count, as they will be on the written board."""
1883
+ segs: list[tuple[tuple[float, float], tuple[float, float], float | None]] = []
1884
+ route = self.routes.get(net)
1885
+ if route:
1886
+ segs += [((s[1], s[2]), (s[3], s[4]), None) for s in route.segs]
1887
+ if net in self.cores:
1888
+ poly = self.cores[net][2]
1889
+ segs += [(p, q, None) for p, q in zip(poly, poly[1:])]
1890
+ return path_length(segs, start, end)
1891
+
1892
+ def pair_lengths(self, pair: _Pair) -> tuple[float, float, bool]:
1893
+ """Lengths of the two nets between the pair's terminals (else whole nets)."""
1894
+ if len(pair.terms) == 2:
1895
+ a, b = pair.terms
1896
+ lp = self.signal_length(pair.pos, a["p"], b["p"])
1897
+ ln = self.signal_length(pair.neg, a["n"], b["n"])
1898
+ if lp is not None and ln is not None:
1899
+ return lp, ln, True
1900
+ return self.net_length(pair.pos), self.net_length(pair.neg), False
1901
+
1902
+ def tune(self, pair: _Pair) -> None:
1903
+ """Serpentine bumps on the shorter net until the skew is within tolerance: on its
1904
+ coupled section (outer side) first, then on its other tracks."""
1905
+ if len(pair.terms) != 2:
1906
+ return
1907
+ lp, ln, _ = self.pair_lengths(pair)
1908
+ start = delta = abs(lp - ln)
1909
+ for _ in range(6):
1910
+ if delta <= pair.tolerance:
1911
+ break
1912
+ short = pair.pos if lp < ln else pair.neg
1913
+ if not any(self._lengthen(pair, short, delta * f) for f in (1.0, 0.5, 0.25)):
1914
+ break
1915
+ lp, ln, _ = self.pair_lengths(pair)
1916
+ delta = abs(lp - ln)
1917
+ if start - delta > 1e-3:
1918
+ pair.tuned = round(start - delta, 3)
1919
+ if delta > pair.tolerance:
1920
+ left = f"skew {delta:.2f} mm left: no room for more serpentine tuning"
1921
+ pair.note = f"{pair.note}; {left}" if pair.note else left
1922
+
1923
+ def _lengthen(self, pair: _Pair, net: str, amount: float) -> bool:
1924
+ if amount < 0.05:
1925
+ return False
1926
+ nid = self.net_id(net)
1927
+ clear = self.clear(nid, 0)
1928
+ layer, width, poly = self.cores.get(net, (0, 0.0, []))
1929
+
1930
+ def amplitudes(w: float) -> tuple[float, ...]:
1931
+ return (w + pair.gap, 2 * (w + pair.gap), 0.5 * w + clear)
1932
+
1933
+ def pitch(w: float) -> float:
1934
+ return math.ceil((w + clear + 0.05) / 0.05) * 0.05
1935
+
1936
+ spans = sorted(range(max(0, len(poly) - 1)), key=lambda i: -math.dist(poly[i], poly[i + 1]))
1937
+ for i in spans:
1938
+ for amplitude in amplitudes(width):
1939
+ bumps = diffpair.serpentine(
1940
+ poly[i], poly[i + 1], amount, pair.side[net], amplitude, pitch(width)
1941
+ )
1942
+ if bumps is not None and self.poly_legal(bumps, width, layer, nid, True):
1943
+ self._set_core(net, layer, width, poly[:i] + bumps + poly[i + 2 :])
1944
+ return True
1945
+ route = self.routes.get(net)
1946
+ if route is None:
1947
+ return False
1948
+ before = self.pair_lengths(pair)
1949
+ for seg in sorted(route.segs, key=lambda s: -math.hypot(s[3] - s[1], s[4] - s[2])):
1950
+ lay, x1, y1, x2, y2, w = seg
1951
+ for side in (1.0, -1.0):
1952
+ for amplitude in amplitudes(w):
1953
+ bumps = diffpair.serpentine(
1954
+ (x1, y1), (x2, y2), amount, side, amplitude, pitch(w)
1955
+ )
1956
+ if bumps is None or not self.poly_legal(bumps, w, lay, nid, True):
1957
+ continue
1958
+ new = [(lay, *a, *b, w) for a, b in zip(bumps, bumps[1:])]
1959
+ self._replace_segs(route, nid, [seg], new)
1960
+ after = self.pair_lengths(pair)
1961
+ gained = (after[0] + after[1]) - (before[0] + before[1])
1962
+ if gained > 0.5 * amount:
1963
+ return True
1964
+ self._replace_segs(route, nid, new, [seg]) # not on the signal path
1965
+ return False
1966
+
1967
+ # ------------------------------------------------------- length groups
1968
+ def group_members(self, nets: list[str], pairs: list[_Pair]) -> list[list[str]]:
1969
+ """A pair listed by one or both nets is a single member of the group."""
1970
+ members: list[list[str]] = []
1971
+ seen: set[str] = set()
1972
+ for net in nets:
1973
+ if net in seen:
1974
+ continue
1975
+ twin = next(
1976
+ ([p.pos, p.neg] for p in pairs if net in (p.pos, p.neg)),
1977
+ None,
1978
+ )
1979
+ group = twin or [net]
1980
+ seen |= set(group)
1981
+ members.append([n for n in group if n in self.routes or n in self.cores])
1982
+ return [m for m in members if m]
1983
+
1984
+ def member_length(self, member: list[str]) -> float:
1985
+ return sum(self.net_length(n) for n in member) / len(member)
1986
+
1987
+ def _lengthen_net(self, net: str, amount: float, near: list[str]) -> float:
1988
+ """Serpentine bumps on the routed segments of ``net``; returns the length gained."""
1989
+ route = self.routes.get(net)
1990
+ if route is None or amount < 0.05:
1991
+ return 0.0
1992
+ nid = self.net_id(net)
1993
+ clear = self.clear(nid, 0)
1994
+ before = self.net_length(net)
1995
+ for seg in sorted(route.segs, key=lambda s: -math.hypot(s[3] - s[1], s[4] - s[2])):
1996
+ lay, x1, y1, x2, y2, w = seg
1997
+ for side in (1.0, -1.0):
1998
+ for amplitude in (2 * (w + clear), 4 * (w + clear), w + clear):
1999
+ pitch = math.ceil((w + clear + 0.05) / 0.05) * 0.05
2000
+ bumps = diffpair.serpentine((x1, y1), (x2, y2), amount, side, amplitude, pitch)
2001
+ if bumps is None or not self.poly_legal(bumps, w, lay, nid, True):
2002
+ continue
2003
+ new = [(lay, *a, *b, w) for a, b in zip(bumps, bumps[1:])]
2004
+ self._replace_segs(route, nid, [seg], new)
2005
+ return self.net_length(net) - before
2006
+ return 0.0
2007
+
2008
+ def match_groups(
2009
+ self, groups: list[dict], pairs: list[_Pair], failed: set[str]
2010
+ ) -> dict[str, dict]:
2011
+ """Lengthen the shorter members of each group towards the longest one."""
2012
+ report: dict[str, dict] = {}
2013
+ for group in groups:
2014
+ tol = float(group.get("tolerance", 0.5))
2015
+ members = self.group_members([str(n) for n in group["nets"]], pairs)
2016
+ open_nets = sorted({n for m in members for n in m if n in failed})
2017
+ if open_nets:
2018
+ # A half-routed member has no meaningful length: match nothing, say why.
2019
+ report[group["name"]] = {"note": f"not matched: unrouted {', '.join(open_nets)}"}
2020
+ continue
2021
+ if len(members) < 2:
2022
+ report[group["name"]] = {"note": "fewer than two routed members"}
2023
+ continue
2024
+ for _ in range(6):
2025
+ lengths = [self.member_length(m) for m in members]
2026
+ longest = max(lengths)
2027
+ moved = False
2028
+ for member, length in zip(members, lengths):
2029
+ if longest - length <= tol / 2:
2030
+ continue
2031
+ for net in member:
2032
+ moved |= self._lengthen_net(net, longest - length, member) > 0.0
2033
+ if not moved:
2034
+ break
2035
+ self.group_lists[group["name"]] = members
2036
+ lengths = [self.member_length(m) for m in members]
2037
+ spread = max(lengths) - min(lengths)
2038
+ entry = {
2039
+ "members": {"/".join(m): round(x, 2) for m, x in zip(members, lengths)},
2040
+ "spread_mm": round(spread, 2),
2041
+ "tolerance_mm": tol,
2042
+ }
2043
+ if spread > tol:
2044
+ entry["note"] = f"spread {spread:.2f} mm left: no room for more serpentine tuning"
2045
+ report[group["name"]] = entry
2046
+ for pair in pairs: # bumps on one net of a pair upset its skew: tune it again
2047
+ if any(pair.pos in m for m in members):
2048
+ self.tune(pair)
2049
+ return report
2050
+
2051
+ def _replace_segs(self, route: _NetRoute, nid: int, old: list, new: list) -> None:
2052
+ """Swap routed segments ``old`` for ``new`` (same tuple form as ``route.segs``)."""
2053
+ k = route.segs.index(old[0])
2054
+ for seg in old:
2055
+ route.segs.remove(seg)
2056
+ lay, x1, y1, x2, y2, _w = seg
2057
+ for shape in route.shapes:
2058
+ if (
2059
+ shape.tag == "seg"
2060
+ and shape.c[:4] == (x1, y1, x2, y2)
2061
+ and shape.layers == 1 << lay
2062
+ ):
2063
+ route.shapes.remove(shape)
2064
+ self.routed_index.remove(shape)
2065
+ break
2066
+ for n, seg in enumerate(new):
2067
+ lay, x1, y1, x2, y2, w = seg
2068
+ route.segs.insert(k + n, seg)
2069
+ shape = Shape.capsule(x1, y1, x2, y2, w / 2, nid, 1 << lay, "seg")
2070
+ route.shapes.append(shape)
2071
+ self.routed_index.add(shape)
2072
+
2073
+ def pair_report(self, pair: _Pair, written: dict | None = None) -> dict:
2074
+ model = self.pair_lengths(pair)
2075
+ lp, ln, between = model
2076
+ measured_on = "router model"
2077
+ if written is not None and f"{pair.pos}/{pair.neg}" in written["pairs"]:
2078
+ lp, ln, between = written["pairs"][f"{pair.pos}/{pair.neg}"]
2079
+ measured_on = "written board"
2080
+ data = {
2081
+ "length_mm": [round(lp, 2), round(ln, 2)],
2082
+ "measured": ("between the pair's two ends" if between else "whole nets")
2083
+ + f", on the {measured_on}",
2084
+ "skew_mm": round(abs(lp - ln), 2),
2085
+ "tolerance_mm": pair.tolerance,
2086
+ "coupled": pair.pos in self.cores,
2087
+ }
2088
+ if pair.pos in self.cores:
2089
+ data["width_mm"] = pair.width
2090
+ data["gap_mm"] = pair.gap
2091
+ data["coupled_mm"] = round(
2092
+ diffpair.polyline_length(diffpair.simplify(self.cores[pair.pos][2])), 2
2093
+ )
2094
+ data["layer"] = self.layers[pair.layer]
2095
+ name = self.layers[pair.layer]
2096
+ try:
2097
+ data["geometry"] = impedance.geometry_name(self.stack, name)
2098
+ z = impedance.differential(self.stack, name, pair.width, pair.gap)
2099
+ data["impedance_ohm"] = round(z, 1)
2100
+ data["target_ohm"] = pair.target
2101
+ data["impedance_error_pct"] = round(100 * (z - pair.target) / pair.target, 1)
2102
+ except (stackups.StackupError, ValueError):
2103
+ pass
2104
+ data["reference_planes"] = self.reference_names(name)
2105
+ if measured_on == "written board" and (
2106
+ abs(model[0] - lp) > 0.05 or abs(model[1] - ln) > 0.05
2107
+ ):
2108
+ data["model_mm"] = [round(model[0], 2), round(model[1], 2)] # what tune() worked from
2109
+ if pair.tuned:
2110
+ data["tuned_mm"] = pair.tuned
2111
+ if pair.note:
2112
+ data["note"] = pair.note
2113
+ return data
2114
+
2115
+ def reference_names(self, layer: str) -> list[str]:
2116
+ """Plane layers (with their nets) that return the current of a track on ``layer``."""
2117
+ found = []
2118
+ for ref in (self.stack.reference_above(layer), self.stack.reference_below(layer)):
2119
+ if ref is None:
2120
+ continue
2121
+ name = self.stack.copper[ref[0]].name
2122
+ nets = self.stack.plane_nets().get(name)
2123
+ found.append(f"{name} ({nets})" if nets else name)
2124
+ return found
2125
+
2126
+ def net_report(self, planes: list[str], written: dict | None = None) -> dict[str, dict]:
2127
+ """Per routed net: length, length and impedance per layer, reference planes, vias.
2128
+ From the written board when given, else from the router's model."""
2129
+ report: dict[str, dict] = {}
2130
+ for net, route in self.routes.items():
2131
+ if net in planes:
2132
+ continue
2133
+ per_layer: dict[str, float] = {}
2134
+ widths: dict[str, float] = {}
2135
+ if written is not None:
2136
+ for name, (length, width) in written["layers"].get(net, {}).items():
2137
+ per_layer[name] = length
2138
+ widths[name] = width
2139
+ vias = written["vias"].get(net, 0)
2140
+ else:
2141
+ segs = [(s[0], s[1], s[2], s[3], s[4], s[5]) for s in route.segs]
2142
+ if net in self.cores:
2143
+ layer, w, poly = self.cores[net]
2144
+ segs += [(layer, *a, *b, w) for a, b in zip(poly, poly[1:])]
2145
+ for layer, x1, y1, x2, y2, w in segs:
2146
+ name = self.layers[layer]
2147
+ per_layer[name] = per_layer.get(name, 0.0) + math.hypot(x2 - x1, y2 - y1)
2148
+ widths[name] = max(widths.get(name, 0.0), w)
2149
+ vias = len(route.vias)
2150
+ if not per_layer:
2151
+ continue
2152
+ layers: dict[str, dict] = {}
2153
+ for name, length in per_layer.items():
2154
+ entry: dict = {"length_mm": round(length, 2), "width_mm": widths[name]}
2155
+ try:
2156
+ entry["geometry"] = impedance.geometry_name(self.stack, name)
2157
+ entry["z0_ohm"] = round(
2158
+ impedance.single_ended(self.stack, name, widths[name]), 1
2159
+ )
2160
+ except (stackups.StackupError, ValueError):
2161
+ pass
2162
+ entry["reference_planes"] = self.reference_names(name)
2163
+ layers[name] = entry
2164
+ report[net] = {
2165
+ "length_mm": round(sum(per_layer.values()), 2),
2166
+ "vias": vias,
2167
+ "layers": layers,
2168
+ }
2169
+ return report
2170
+
2171
+ # --------------------------------------------------------------- check
2172
+ def conflicts(self) -> list[tuple[str, str | None, float, float, int]]:
2173
+ """Exact clearance violations between routed copper and everything else."""
2174
+ opt = self.opt
2175
+ found: list[tuple[str, str | None, float, float, int]] = []
2176
+ routed_vias: list[tuple[float, float, int]] = []
2177
+ for net, route in self.routes.items():
2178
+ nid = self.net_ids[net]
2179
+ for shape in route.shapes:
2180
+ radius = shape.c[4]
2181
+ reach = radius + self.max_clear + 0.05
2182
+ others = self.fixed_index.near(shape.bbox, reach) + self.routed_index.near(
2183
+ shape.bbox, reach
2184
+ )
2185
+ for other in others:
2186
+ if other is shape or (other.net and other.net == nid):
2187
+ continue
2188
+ if not other.layers & shape.layers:
2189
+ continue
2190
+ if other.tag in ("seg", "via") and other.net < nid:
2191
+ continue # each routed pair once
2192
+ need = self.clear(nid, other.net) - 1e-4
2193
+ if shape.dist_shape(other) < need:
2194
+ c = shape.c
2195
+ x, y = (c[0] + c[2]) / 2, (c[1] + c[3]) / 2
2196
+ found.append(
2197
+ (
2198
+ net,
2199
+ self.net_names.get(other.net)
2200
+ if other.tag in ("seg", "via")
2201
+ else None,
2202
+ x,
2203
+ y,
2204
+ shape.layers,
2205
+ )
2206
+ )
2207
+ edge = opt.edge_clearance + radius - 1e-4
2208
+ c = shape.c
2209
+ if not self.edge_ok(c[0], c[1], c[2], c[3], edge):
2210
+ found.append((net, None, c[0], c[1], shape.layers))
2211
+ for x, y in route.vias:
2212
+ routed_vias.append((x, y, nid))
2213
+ drill = opt.via_drill
2214
+ for i, (x, y, nid) in enumerate(routed_vias):
2215
+ net = self.net_names[nid]
2216
+ for hx, hy, hd in self.holes:
2217
+ if math.hypot(x - hx, y - hy) - (drill + hd) / 2 < opt.hole_clearance - 1e-4:
2218
+ found.append((net, None, x, y, self.all_layers))
2219
+ for x2, y2, nid2 in routed_vias[i + 1 :]:
2220
+ if math.hypot(x - x2, y - y2) - drill < opt.hole_clearance - 1e-4:
2221
+ found.append((net, self.net_names[nid2], x, y, self.all_layers))
2222
+ return found
2223
+
2224
+ def penalise(self, conflicts, amount: float) -> None:
2225
+ """Raise the history cost around each conflict, once per cell however many conflicts
2226
+ share it (dense fan-outs otherwise drive the cost up so fast that nets detour for
2227
+ good)."""
2228
+ g = self.opt.grid
2229
+ cells = self.disc(3)
2230
+ touched: set[tuple[int, int]] = set()
2231
+ for _, _, x, y, layers in conflicts:
2232
+ gx = int(round((x - self.x0) / g))
2233
+ gy = int(round((y - self.y0) / g))
2234
+ for li in range(self.L):
2235
+ if not layers & (1 << li):
2236
+ continue
2237
+ for dx, dy in cells:
2238
+ if 0 <= gx + dx < self.W and 0 <= gy + dy < self.H:
2239
+ touched.add((li, (gy + dy) * self.W + gx + dx))
2240
+ for li, idx in touched:
2241
+ self.hist[li][idx] += amount
2242
+
2243
+ def solid_plane_pads(self, planes: list[str]) -> list[tuple[str, str]]:
2244
+ """Fine-pitch SMD pads of plane nets: thermal spokes cannot fit between their
2245
+ neighbours (KiCad then reports a starved thermal), so they join the pour solidly."""
2246
+ found = []
2247
+ for footprint in self.board.footprints:
2248
+ for pad in footprint.pads:
2249
+ if pad.net not in planes or pad.kind != "smd":
2250
+ continue
2251
+ shape = self.pad_shapes.get(id(pad))
2252
+ if shape is None:
2253
+ continue
2254
+ crowded = any(
2255
+ other.net != shape.net
2256
+ and other.layers & shape.layers
2257
+ and other.dist_shape(shape) < 0.5 + 0.3 # thermal gap + zone clearance
2258
+ for other in self.fixed_index.near(shape.bbox, 1.0)
2259
+ if other is not shape
2260
+ )
2261
+ if crowded and min(pad.width, pad.height) < 0.8:
2262
+ found.append((footprint.reference, pad.number))
2263
+ return found
2264
+
2265
+ # --------------------------------------------------------------- write
2266
+ def write(self) -> tuple[int, int]:
2267
+ tracks = []
2268
+ vias = []
2269
+ for net, route in self.routes.items():
2270
+ for layer, x1, y1, x2, y2, w in route.segs:
2271
+ tracks.append((net, self.layers[layer], w, [(x1, y1), (x2, y2)]))
2272
+ for x, y in route.vias:
2273
+ vias.append((net, x, y))
2274
+ for net, (layer, w, poly) in self.cores.items():
2275
+ for p, q in zip(poly, poly[1:]):
2276
+ tracks.append((net, self.layers[layer], w, [p, q]))
2277
+ edit.pcb_add_routing(self.pcb, tracks, vias, self.opt.via_size, self.opt.via_drill)
2278
+ return len(tracks), len(vias)
2279
+
2280
+
2281
+ def _pairs(lengths: dict[str, float]) -> dict[str, dict]:
2282
+ """Differential-pair candidates by name (D+/D-, DP/DM, _P/_N) and their length skew."""
2283
+ pairs: dict[str, dict] = {}
2284
+ for net, other in diffpair.pair_names(lengths):
2285
+ a, b = lengths[net], lengths[other]
2286
+ pairs[f"{net}/{other}"] = {
2287
+ "length_mm": [round(a, 2), round(b, 2)],
2288
+ "skew_mm": round(abs(a - b), 2),
2289
+ }
2290
+ return pairs
2291
+
2292
+
2293
+ def path_length(segs, start: list[Pad], end: list[Pad]) -> float | None:
2294
+ """Shortest copper path from any ``start`` pad to any ``end`` pad over ``segs``
2295
+ (``(a, b, weight)``; a weight of None means the straight distance). A fan-out stub
2296
+ behind a pin (``stub_mm`` on the stand-in pad) is added at either end. None when the
2297
+ pads are not joined by the segments."""
2298
+ if not segs:
2299
+ return None
2300
+
2301
+ def key(p) -> tuple[float, float]:
2302
+ return (round(p[0], 3), round(p[1], 3))
2303
+
2304
+ points = {key(p) for s in segs for p in s[:2]}
2305
+ graph: dict = {}
2306
+
2307
+ def link(a, b, w: float) -> None:
2308
+ graph.setdefault(a, []).append((b, w))
2309
+ graph.setdefault(b, []).append((a, w))
2310
+
2311
+ for a, b, weight in segs:
2312
+ if weight is not None: # an arc: keep its own length, no splitting
2313
+ link(key(a), key(b), weight)
2314
+ continue
2315
+ # split at T-junctions inside merged runs
2316
+ inner = [
2317
+ p for p in points if p not in (key(a), key(b)) and diffpair.point_on_segment(p, a, b)
2318
+ ]
2319
+ inner.sort(key=lambda p: math.dist(p, a))
2320
+ chain = [key(a), *inner, key(b)]
2321
+ for p, q in zip(chain, chain[1:]):
2322
+ link(p, q, math.dist(p, q))
2323
+ for i, pad in enumerate(start + end):
2324
+ node = ("pad", i)
2325
+ for p in points:
2326
+ if pad.contains(p[0], p[1], 0.01):
2327
+ link(node, p, 0.0)
2328
+ goal = {("pad", i) for i in range(len(start), len(start) + len(end))}
2329
+ stubs = [getattr(p, "stub_mm", 0.0) for p in start + end]
2330
+ dist = {("pad", i): stubs[i] for i in range(len(start))}
2331
+ heap = [(stubs[i], i, ("pad", i)) for i in range(len(start))]
2332
+ count = len(heap)
2333
+ while heap:
2334
+ d, _, node = heapq.heappop(heap)
2335
+ if node in goal:
2336
+ return d + stubs[node[1]]
2337
+ if d > dist.get(node, math.inf):
2338
+ continue
2339
+ for nb, w in graph.get(node, []):
2340
+ if d + w < dist.get(nb, math.inf) - 1e-12:
2341
+ dist[nb] = d + w
2342
+ count += 1
2343
+ heapq.heappush(heap, (d + w, count, nb))
2344
+ return None
2345
+
2346
+
2347
+ def written_report(pcb: Path, router: _Router, pairs: list[_Pair], planes: list[str]) -> dict:
2348
+ """What the written board says, measured on the saved file (not on the router's model):
2349
+ pair lengths between the pair's terminal pads, per-net copper per layer, via counts."""
2350
+ final = read_board(pcb)
2351
+ by_key: dict[tuple[str, str], Pad] = {}
2352
+ for fp in final.footprints:
2353
+ for pad in fp.pads:
2354
+ by_key[(fp.reference, pad.number)] = pad
2355
+
2356
+ def real(pads: list[Pad]) -> list[Pad]:
2357
+ found = []
2358
+ for pad in pads:
2359
+ key = getattr(pad, "stub_of", None) or (router.pad_owner.get(id(pad), ""), pad.number)
2360
+ if key in by_key:
2361
+ found.append(by_key[key])
2362
+ return found
2363
+
2364
+ def segs_of(net: str):
2365
+ out = []
2366
+ for t in final.tracks:
2367
+ if t.net != net:
2368
+ continue
2369
+ out.append(((t.x1, t.y1), (t.x2, t.y2), t.length if t.mid is not None else None))
2370
+ return out
2371
+
2372
+ pair_lengths: dict[str, tuple[float, float, bool]] = {}
2373
+ for pair in pairs:
2374
+ if len(pair.terms) == 2:
2375
+ a, b = pair.terms
2376
+ lp = path_length(segs_of(pair.pos), real(a["p"]), real(b["p"]))
2377
+ ln = path_length(segs_of(pair.neg), real(a["n"]), real(b["n"]))
2378
+ if lp is not None and ln is not None:
2379
+ pair_lengths[f"{pair.pos}/{pair.neg}"] = (lp, ln, True)
2380
+ continue
2381
+ pair_lengths[f"{pair.pos}/{pair.neg}"] = (
2382
+ sum(t.length for t in final.tracks if t.net == pair.pos),
2383
+ sum(t.length for t in final.tracks if t.net == pair.neg),
2384
+ False,
2385
+ )
2386
+ totals: dict[str, float] = {}
2387
+ per_layer: dict[str, dict[str, list[float]]] = {}
2388
+ for t in final.tracks:
2389
+ if not t.net or t.net in planes:
2390
+ continue
2391
+ totals[t.net] = totals.get(t.net, 0.0) + t.length
2392
+ entry = per_layer.setdefault(t.net, {}).setdefault(t.layer, [0.0, 0.0])
2393
+ entry[0] += t.length
2394
+ entry[1] = max(entry[1], t.width)
2395
+ vias: dict[str, int] = {}
2396
+ for v in final.vias:
2397
+ vias[v.net] = vias.get(v.net, 0) + 1
2398
+ return {"pairs": pair_lengths, "totals": totals, "layers": per_layer, "vias": vias}
2399
+
2400
+
2401
+ def route_board(pcb: str | Path, options: RouteOptions | None = None) -> RouteResult:
2402
+ started = time.monotonic()
2403
+ pcb = Path(pcb)
2404
+ options = options or RouteOptions()
2405
+ assign = (
2406
+ options.plane_assign
2407
+ if options.plane_assign is not None
2408
+ else planes_mod.project_assignment(pcb)
2409
+ )
2410
+ if assign:
2411
+ # Vias inside the fine-pitch plane pads go in first, so signals route around them.
2412
+ planes_mod.reserve(
2413
+ pcb,
2414
+ assign,
2415
+ clearance=options.clearance,
2416
+ via_size=options.via_size,
2417
+ via_drill=options.via_drill,
2418
+ edge_clearance=options.edge_clearance,
2419
+ hole_clearance=options.hole_clearance,
2420
+ track_width=options.track_width,
2421
+ )
2422
+ fan = escape.fan_out(pcb, options, options.escape)
2423
+ if fan.fanouts:
2424
+ options = replace(options, escape_layers=fan.layer_hints)
2425
+ router = _Router(pcb, options)
2426
+ status = {s.net: s for s in connectivity(router.board)}
2427
+ planes = [
2428
+ n
2429
+ for n in dict.fromkeys([*options.plane_nets, *router.plane_assign])
2430
+ if n in router.pads_by_net and n not in options.skip_nets
2431
+ ]
2432
+ wanted = [
2433
+ n
2434
+ for n in router.pads_by_net
2435
+ if (options.nets is None or n in options.nets)
2436
+ and n not in options.skip_nets
2437
+ and n not in planes
2438
+ and (status.get(n) is None or status[n].unrouted > 0)
2439
+ ]
2440
+
2441
+ def span(net: str) -> float:
2442
+ pads = router.pads_by_net[net]
2443
+ return (max(p.x for p in pads) - min(p.x for p in pads)) + (
2444
+ max(p.y for p in pads) - min(p.y for p in pads)
2445
+ )
2446
+
2447
+ # Short, simple nets first; wide and many-pin nets last.
2448
+ order = planes + sorted(
2449
+ wanted,
2450
+ key=lambda n: (
2451
+ len(router.pads_by_net[n]) > 6,
2452
+ router.width(n) > options.track_width,
2453
+ span(n),
2454
+ ),
2455
+ )
2456
+
2457
+ def route(net: str, pres: float, hard: bool) -> bool:
2458
+ router.ripup(net)
2459
+ if net in planes:
2460
+ return router.route_plane(net, pres, hard)
2461
+ return router.route_net(net, pres, hard)
2462
+
2463
+ failed: set[str] = set()
2464
+ state = {"pres": 0.5, "passes": 0}
2465
+
2466
+ def negotiate(todo: list[str], until: float | None = None) -> None:
2467
+ """PathFinder passes over ``todo``, then the hard fallback for what still conflicts."""
2468
+ conflicts: list = []
2469
+ for _ in range(max(1, options.attempts)):
2470
+ state["passes"] += 1
2471
+ for net in order:
2472
+ if net in todo:
2473
+ if route(net, state["pres"], False):
2474
+ failed.discard(net)
2475
+ else:
2476
+ failed.add(net)
2477
+ conflicts = router.conflicts()
2478
+ stop = started + options.time_limit if until is None else until
2479
+ if not conflicts or time.monotonic() > stop:
2480
+ break
2481
+ router.penalise(conflicts, 1.0)
2482
+ state["pres"] *= 1.8
2483
+ involved = {c[0] for c in conflicts} | {c[1] for c in conflicts if c[1]}
2484
+ todo = [n for n in order if n in involved]
2485
+ # Anything still in conflict: drop the worst net, re-route it with others' copper hard.
2486
+ dropped: list[str] = []
2487
+ while conflicts:
2488
+ count: dict[str, int] = {}
2489
+ for a, b, *_ in conflicts:
2490
+ count[a] = count.get(a, 0) + 1
2491
+ if b:
2492
+ count[b] = count.get(b, 0) + 1
2493
+ worst = max(count, key=lambda n: (count[n], order.index(n)))
2494
+ router.ripup(worst)
2495
+ dropped.append(worst)
2496
+ conflicts = router.conflicts()
2497
+ for net in [n for n in order if n in dropped]:
2498
+ ok = route(net, state["pres"], True)
2499
+ if router.conflicts():
2500
+ router.ripup(net)
2501
+ ok = False
2502
+ if ok:
2503
+ failed.discard(net)
2504
+ else:
2505
+ failed.add(net)
2506
+
2507
+ def repair(deadline: float) -> None:
2508
+ """Rip-up and reroute: for a net that failed, route it through the others' copper,
2509
+ take out the nets it crosses, route it for real, then let those nets negotiate their
2510
+ way around it (history costs stay, so a repeat differs). Kept only when every net
2511
+ involved ends up routed; otherwise the board goes back as it was."""
2512
+ improved = True
2513
+ while failed and improved and time.monotonic() < deadline:
2514
+ improved = False
2515
+ for net in [n for n in order if n in failed and n not in planes]:
2516
+ if time.monotonic() > deadline:
2517
+ break
2518
+ snap = dict(router.routes)
2519
+ snap_failed, pres0 = set(failed), state["pres"]
2520
+ route(net, state["pres"], False) # soft: finds a way through other nets
2521
+ blockers: list[str] = []
2522
+ for a, b, *_ in router.conflicts():
2523
+ other = b if a == net else a if b == net else None
2524
+ if other and other not in blockers and other not in planes:
2525
+ blockers.append(other)
2526
+ router.ripup(net)
2527
+ ok = bool(blockers) and len(blockers) <= 6
2528
+ if ok:
2529
+ for n in blockers:
2530
+ router.ripup(n)
2531
+ ok = route(net, state["pres"], True) and not router.conflicts()
2532
+ if ok:
2533
+ todo = [net, *blockers]
2534
+ for n in blockers:
2535
+ route(n, state["pres"], False)
2536
+ negotiate(todo, deadline)
2537
+ ok = not (set(todo) & failed) and not router.conflicts()
2538
+ if os.environ.get("TF_ROUTE_DEBUG"):
2539
+ print("repair", net, "blockers", blockers, "->", ok, flush=True)
2540
+ if ok:
2541
+ improved = True
2542
+ continue
2543
+ for n in list(router.routes):
2544
+ router.ripup(n)
2545
+ for n, old in snap.items():
2546
+ router.restore(n, old)
2547
+ failed.clear()
2548
+ failed.update(snap_failed)
2549
+ state["pres"] = pres0
2550
+
2551
+ # Couple the pairs; if that leaves nets unrouted, retry with the coupled sections
2552
+ # standing further off the pads, and finally route the pairs as plain nets.
2553
+ pairs: list[_Pair] = []
2554
+ for mode in ("couple", "standoff", "plain"):
2555
+ if mode != "couple":
2556
+ router = _Router(pcb, options)
2557
+ failed.clear()
2558
+ state["pres"] = 0.5
2559
+ pairs = router.find_pairs(wanted)
2560
+ if mode != "plain":
2561
+ router.pair_standoff = 0.8 if mode == "couple" else 2.0
2562
+ for pair in pairs:
2563
+ router.route_pair_core(pair)
2564
+ negotiate(list(order))
2565
+ coupled = any(p.pos in router.cores for p in pairs)
2566
+ if not failed or not coupled or time.monotonic() - started > options.time_limit / 2:
2567
+ break
2568
+ if failed:
2569
+ # A net the search gave up on (limit reached) may well have a way through other
2570
+ # nets' copper: give the repair searches more room than the first pass had.
2571
+ budget = options.max_expansions
2572
+ options.max_expansions = budget * options.repair_search_factor
2573
+ try:
2574
+ repair(time.monotonic() + options.repair_time)
2575
+ finally:
2576
+ options.max_expansions = budget
2577
+ for pair in pairs:
2578
+ if pair.pos not in router.cores and not pair.note:
2579
+ pair.note = "routed as two tracks: coupling left other nets unrouted"
2580
+ for pair in pairs:
2581
+ router.tune(pair)
2582
+ group_info = router.match_groups(_project_groups(pcb), pairs, failed)
2583
+
2584
+ def pour_layers(net: str) -> list[str]:
2585
+ if net in router.plane_assign:
2586
+ return router.plane_assign[net]
2587
+ return list(router.layers) if options.plane_both_sides else [options.plane_layer]
2588
+
2589
+ layers = sorted(
2590
+ {layer for n in planes for layer in pour_layers(n)}, key=router.board.copper_layers.index
2591
+ )
2592
+ filled = False
2593
+ plane_report = None
2594
+ segments, vias = router.write()
2595
+ if planes:
2596
+ # Zones, pad-to-plane vias, stitching, fill and KiCad's re-check: see planes.py.
2597
+ plane_report = planes_mod.finish(
2598
+ pcb,
2599
+ {n: pour_layers(n) for n in planes},
2600
+ clearance=options.clearance,
2601
+ via_size=options.via_size,
2602
+ via_drill=options.via_drill,
2603
+ edge_clearance=options.edge_clearance,
2604
+ hole_clearance=options.hole_clearance,
2605
+ track_width=options.track_width,
2606
+ via_in_pad=options.via_in_pad,
2607
+ solid_pads=router.solid_plane_pads(planes),
2608
+ )
2609
+ filled = plane_report.filled
2610
+
2611
+ # Every length reported below is measured on the board as written, not on the model.
2612
+ written = written_report(pcb, router, pairs, planes)
2613
+ lengths = {
2614
+ net: round(written["totals"][net], 2)
2615
+ for net in router.routes
2616
+ if net not in planes and written["totals"].get(net, 0.0) > 0
2617
+ }
2618
+ pair_info = _pairs(lengths)
2619
+ for pair in pairs:
2620
+ pair_info[f"{pair.pos}/{pair.neg}"] = router.pair_report(pair, written)
2621
+ for name, members in router.group_lists.items():
2622
+ entry = group_info.get(name)
2623
+ if not entry or "members" not in entry:
2624
+ continue
2625
+ sizes = [sum(written["totals"].get(n, 0.0) for n in m) / len(m) for m in members]
2626
+ spread = max(sizes) - min(sizes)
2627
+ entry["members"] = {"/".join(m): round(x, 2) for m, x in zip(members, sizes)}
2628
+ entry["spread_mm"] = round(spread, 2)
2629
+ entry.pop("note", None)
2630
+ if spread > entry["tolerance_mm"]:
2631
+ entry["note"] = f"spread {spread:.2f} mm left: no room for more serpentine tuning"
2632
+ narrowed = sorted(n for n, r in router.routes.items() if r.necked and n not in planes)
2633
+ plane_status: dict[str, str] = {}
2634
+ for net in planes:
2635
+ plane_status[net] = (
2636
+ f"poured on {', '.join(layers)} and filled"
2637
+ if filled
2638
+ else f"poured on {', '.join(layers)}; not filled yet (open in KiCad and press B)"
2639
+ )
2640
+ unrouted = kicad_unconnected(pcb)
2641
+ source = "kicad"
2642
+ if unrouted is None:
2643
+ unrouted = sum(s.unrouted for s in connectivity(read_board(pcb)))
2644
+ source = "traceforge (approximate for pours)"
2645
+ routed = [n for n in order if n not in failed]
2646
+ return RouteResult(
2647
+ routed,
2648
+ [n for n in order if n in failed],
2649
+ segments,
2650
+ vias,
2651
+ unrouted,
2652
+ plane_status,
2653
+ narrowed,
2654
+ state["passes"],
2655
+ source,
2656
+ lengths,
2657
+ pair_info,
2658
+ time.monotonic() - started,
2659
+ plane_report.to_dict() if plane_report else {},
2660
+ fan.to_dict() if fan.packages else {},
2661
+ router.net_report(planes, written),
2662
+ group_info,
2663
+ {n: router.fail_reason[n] for n in order if n in failed and n in router.fail_reason},
2664
+ )
2665
+
2666
+
2667
+ _UNCONNECTED_SCRIPT = (
2668
+ "import sys, pcbnew\n"
2669
+ "b = pcbnew.LoadBoard(sys.argv[1])\n"
2670
+ "b.BuildConnectivity()\n"
2671
+ "print(b.GetConnectivity().GetUnconnectedCount(False))\n"
2672
+ )
2673
+
2674
+
2675
+ def kicad_unconnected(pcb: Path) -> int | None:
2676
+ """Unrouted connections as KiCad's connectivity engine counts them, when pcbnew is available."""
2677
+ import os
2678
+ import subprocess
2679
+
2680
+ from traceforge.kicad.cli import find_kicad_python
2681
+
2682
+ python = find_kicad_python()
2683
+ if python is None:
2684
+ return None
2685
+ completed = subprocess.run( # noqa: S603
2686
+ [python, "-c", _UNCONNECTED_SCRIPT, str(Path(pcb).resolve())],
2687
+ capture_output=True,
2688
+ text=True,
2689
+ encoding="utf-8",
2690
+ errors="replace",
2691
+ timeout=300,
2692
+ env={**os.environ, "QT_QPA_PLATFORM": "offscreen"},
2693
+ check=False,
2694
+ )
2695
+ try:
2696
+ return int(completed.stdout.strip().splitlines()[-1])
2697
+ except (ValueError, IndexError):
2698
+ return None