-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautorouter.py
More file actions
1695 lines (1434 loc) · 68 KB
/
autorouter.py
File metadata and controls
1695 lines (1434 loc) · 68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
KiCAD Autorouter — A* maze routing with rip-up and reroute.
Key features
------------
- Reads track width, clearance and via constraints directly from the board's
design settings and default net class (respects DRC rules).
- Per-net track widths are read from KiCAD net classes and applied when placing
each connection.
- Copper zones are filled before routing; pad pairs already connected through a
zone are skipped (no wire needed).
- Supports 45° diagonal routing (default) or strict 90° routing.
- Supports 2-layer and multi-layer (4, 6, … copper layer) boards.
- Two-phase routing: first attempts a single-layer (via-free) path; only
inserts vias when no single-layer solution exists.
- Minimises trace length and via count.
- run_rur(): AI-guided rip-up and reroute, configurable attempt budget
(default 100 total routing attempts across all connections).
- Router-cost settings (via cost, turn cost, layer costs) are persistent and
saved to ~/.kicad_autorouter_settings.json.
Quick start (scripting console):
import sys; sys.path.insert(0, '/path/to/kicad_autorouter')
from autorouter import KiCADAutorouter
routed, failed, total = KiCADAutorouter().run_rur()
With AI guidance:
from ai_advisor import RouteAdvisor
routed, failed, total = KiCADAutorouter().run_rur(advisor=RouteAdvisor())
"""
import heapq
import json
import math
import os
from collections import deque
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple
import pcbnew
# ── A* cost weight defaults (tunable via dialog) ───────────────────────────────
_DEFAULT_VIA_COST = 40 # penalty per layer switch (>> 1 so vias are genuinely avoided)
_DEFAULT_TURN_COST = 1 # small: keeps wire count low without inflating total length
# ── Search limit ──────────────────────────────────────────────────────────────
MAX_ITER = 3_000_000 # A* iterations before declaring a connection unroutable
# ── Fallback constants (used only when board has no constraints set) ──────────
_FB_TRACK_MM = 0.2
_FB_CLEARANCE_MM = 0.2
_FB_VIA_SIZE_MM = 0.6
_FB_VIA_DRILL_MM = 0.3
_FB_GRID_MM = 0.1
def _nm(mm: float) -> int:
return int(pcbnew.FromMM(mm))
# ── Persistent user-settings file ────────────────────────────────────────────
_SETTINGS_FILE = os.path.expanduser("~/.kicad_autorouter_settings.json")
def _load_defaults() -> dict:
try:
with open(_SETTINGS_FILE) as f:
return json.load(f)
except Exception:
return {}
def _save_defaults(settings: dict) -> None:
try:
with open(_SETTINGS_FILE, "w") as f:
json.dump(settings, f, indent=2)
except Exception as exc:
print(f"[router] Could not save defaults: {exc}")
# Physical inner-layer constants in stackup order (KiCAD 10)
_INNER_CU_ATTRS = [f"In{i}_Cu" for i in range(1, 31)]
# Move direction sets: 4-directional (90°) and 8-directional (45°)
_DIRS_4 = ((1, 0), (-1, 0), (0, 1), (0, -1))
_DIRS_8 = (
(1, 0), (-1, 0), (0, 1), (0, -1),
(1, 1), (-1, 1), (1, -1), (-1, -1),
)
# ── Board constraints reader ──────────────────────────────────────────────────
@dataclass
class BoardConstraints:
"""
Reads routing constraints from the board's design settings and default
net class. All dimensions are in KiCAD internal units (nanometres).
"""
track_w: int
clearance: int
via_size: int
via_drill: int
cu_layers: List[int] # copper layer IDs in physical stackup order
@classmethod
def from_board(cls, board) -> "BoardConstraints":
ds = board.GetDesignSettings()
# Default net class — may be None on a brand-new empty board
nc = board.GetAllNetClasses().get("Default")
def _nc(method: str) -> int:
if nc is None:
return 0
try:
return int(getattr(nc, method)())
except Exception:
return 0
# Track width: strictest of board minimum and netclass value
track_w = max(
ds.m_TrackMinWidth or 0,
_nc("GetTrackWidth"),
) or _nm(_FB_TRACK_MM)
# Clearance
clearance = max(
ds.m_MinClearance or 0,
_nc("GetClearance"),
) or _nm(_FB_CLEARANCE_MM)
# Via outer diameter
via_size = max(
ds.m_ViasMinSize or 0,
_nc("GetViaDiameter"),
) or _nm(_FB_VIA_SIZE_MM)
# Via drill
via_drill = max(
ds.m_MinThroughDrill or 0,
_nc("GetViaDrill"),
) or _nm(_FB_VIA_DRILL_MM)
return cls(
track_w = track_w,
clearance = clearance,
via_size = via_size,
via_drill = via_drill,
cu_layers = cls._enumerate_cu_layers(board),
)
@staticmethod
def _enumerate_cu_layers(board) -> List[int]:
"""Return copper layer IDs in physical stackup order."""
n = board.GetCopperLayerCount()
layers = [pcbnew.F_Cu]
n_inner = max(0, n - 2)
for attr in _INNER_CU_ATTRS[:n_inner]:
lid = getattr(pcbnew, attr, None)
if lid is not None:
layers.append(lid)
layers.append(pcbnew.B_Cu)
return layers
@property
def n_layers(self) -> int:
return len(self.cu_layers)
def kicad_layer(self, li: int) -> int:
"""Grid layer index → KiCAD layer ID."""
return self.cu_layers[li]
def grid_index(self, kicad_layer: int) -> Optional[int]:
"""KiCAD layer ID → grid layer index, or None if not a routed layer."""
try:
return self.cu_layers.index(kicad_layer)
except ValueError:
return None
def summary(self) -> str:
mm = pcbnew.ToMM
return (
f"track={mm(self.track_w):.3f}mm "
f"clearance={mm(self.clearance):.3f}mm "
f"via={mm(self.via_size):.3f}mm drill={mm(self.via_drill):.3f}mm "
f"layers={self.n_layers} {[self.kicad_layer(i) for i in range(self.n_layers)]}"
)
# ── Routing grid ──────────────────────────────────────────────────────────────
class RoutingGrid:
"""
N-layer flat bytearray occupancy grid.
All public methods that accept world coordinates expect KiCAD nm integers.
"""
def __init__(self, bbox, n_layers: int = 2, grid_nm: int = 0):
self.grid_nm = grid_nm or _nm(_FB_GRID_MM)
self.ox = bbox.GetX()
self.oy = bbox.GetY()
self.cols = max(1, bbox.GetWidth() // self.grid_nm + 3)
self.rows = max(1, bbox.GetHeight() // self.grid_nm + 3)
self.n_layers = n_layers
self._obs = [bytearray(self.cols * self.rows) for _ in range(n_layers)]
# ── coordinate conversion ─────────────────────────────────────────────
def w2g(self, wx: int, wy: int) -> Tuple[int, int]:
return (wx - self.ox) // self.grid_nm, (wy - self.oy) // self.grid_nm
def g2w(self, c: int, r: int) -> Tuple[int, int]:
g = self.grid_nm
return self.ox + c * g + g // 2, self.oy + r * g + g // 2
def in_bounds(self, c: int, r: int) -> bool:
return 0 <= c < self.cols and 0 <= r < self.rows
# ── obstacle primitives ───────────────────────────────────────────────
def _idx(self, c: int, r: int) -> int:
return r * self.cols + c
def is_obs(self, c: int, r: int, li: int) -> bool:
if not self.in_bounds(c, r) or li < 0 or li >= self.n_layers:
return True
return bool(self._obs[li][self._idx(c, r)])
def set_obs(self, c: int, r: int, li: int) -> None:
if self.in_bounds(c, r) and 0 <= li < self.n_layers:
self._obs[li][self._idx(c, r)] = 1
def clear_obs(self, c: int, r: int, li: int) -> None:
if self.in_bounds(c, r) and 0 <= li < self.n_layers:
self._obs[li][self._idx(c, r)] = 0
def block_disk(self, c: int, r: int, li: int, radius: int) -> None:
r2 = radius * radius + radius
for dr in range(-radius, radius + 1):
for dc in range(-radius, radius + 1):
if dc * dc + dr * dr <= r2:
self.set_obs(c + dc, r + dr, li)
def block_rect(
self,
wx0: int, wy0: int, wx1: int, wy1: int,
li: int,
margin_nm: int = 0,
) -> None:
g = self.grid_nm
c0, r0 = self.w2g(wx0 - margin_nm, wy0 - margin_nm)
c1, r1 = self.w2g(wx1 + margin_nm, wy1 + margin_nm)
for r in range(max(0, r0), min(self.rows, r1 + 2)):
for c in range(max(0, c0), min(self.cols, c1 + 2)):
self._obs[li][self._idx(c, r)] = 1
def block_segment(
self,
wx0: int, wy0: int, wx1: int, wy1: int,
li: int,
margin_nm: int = 0,
) -> None:
c0, r0 = self.w2g(wx0, wy0)
c1, r1 = self.w2g(wx1, wy1)
steps = max(abs(c1 - c0), abs(r1 - r0), 1)
m = max(1, margin_nm // self.grid_nm)
for i in range(steps + 1):
t = i / steps
c = round(c0 + t * (c1 - c0))
r = round(r0 + t * (r1 - r0))
self.block_disk(c, r, li, m)
# ── A* path search ─────────────────────────────────────────────────────────────
def _astar(
grid: RoutingGrid,
sc: int, sr: int, sl: int,
ec: int, er: int, el: int,
start_clear: int = 0,
end_clear: int = 0,
allow_vias: bool = True,
via_grid: Optional[RoutingGrid] = None,
via_cost: int = _DEFAULT_VIA_COST,
turn_cost: int = _DEFAULT_TURN_COST,
use_45: bool = False,
layer_costs: Optional[List[int]] = None,
) -> Optional[List[Tuple[int, int, int]]]:
"""
A* from (sc, sr, sl) to (ec, er). Preferred arrival layer is el.
start_clear / end_clear: Manhattan radius around start / end that ignores
obstacles — needed to exit / enter the pad's clearance zone.
allow_vias: if False, layer transitions are forbidden (single-layer mode).
use_45: if True, 8-directional movement (45° diagonals allowed);
otherwise 4-directional (90° only).
layer_costs: per-layer move cost multipliers; index matches grid layer index.
None means all layers cost 1.
Returns list of (col, row, layer_idx) or None.
"""
n = grid.n_layers
dirs = _DIRS_8 if use_45 else _DIRS_4
def passable(nc: int, nr: int, li: int) -> bool:
if not grid.in_bounds(nc, nr) or li < 0 or li >= n:
return False
if (nc, nr) == (ec, er):
return True
if start_clear and abs(nc - sc) + abs(nr - sr) <= start_clear:
return True
if end_clear and abs(nc - ec) + abs(nr - er) <= end_clear:
return True
return not grid.is_obs(nc, nr, li)
def h(c: int, r: int, li: int) -> int:
if use_45:
# Chebyshev distance — admissible for 8-directional grid
dist = max(abs(c - ec), abs(r - er))
else:
dist = abs(c - ec) + abs(r - er)
layer_dist = abs(li - el) if allow_vias else 0
return dist + layer_dist * via_cost
INF = MAX_ITER * 10
g_best: Dict[Tuple[int, int, int], int] = {(sc, sr, sl): 0}
came_from: Dict[Tuple[int, int, int], Optional[Tuple[int, int, int]]] = {
(sc, sr, sl): None
}
# heap: (f, g, col, row, layer, prev_dc, prev_dr, _)
heap: list = [(h(sc, sr, sl), 0, sc, sr, sl, 0, 0, None)]
iters = 0
while heap and iters < MAX_ITER:
iters += 1
f, g, c, r, li, pdc, pdr, _ = heapq.heappop(heap)
key = (c, r, li)
if g > g_best.get(key, INF):
continue
if (c, r) == (ec, er):
path: List[Tuple[int, int, int]] = []
k: Optional[Tuple[int, int, int]] = key
while k is not None:
path.append(k)
k = came_from[k]
path.reverse()
return path
# Same-layer moves
for dc, dr in dirs:
nc, nr = c + dc, r + dr
# Prevent diagonal corner-cutting: both orthogonal neighbours must be clear
if dc != 0 and dr != 0:
if grid.is_obs(c + dc, r, li) or grid.is_obs(c, r + dr, li):
continue
if not passable(nc, nr, li):
continue
turn = turn_cost if (pdc, pdr) not in ((0, 0), (dc, dr)) else 0
lc = layer_costs[li] if layer_costs else 1
ng = g + lc + turn
nkey = (nc, nr, li)
if ng < g_best.get(nkey, INF):
g_best[nkey] = ng
came_from[nkey] = key
heapq.heappush(heap, (ng + h(nc, nr, li), ng, nc, nr, li, dc, dr, key))
# Via: transition to any other layer (through-hole via model).
# Use via_grid for a strict all-layers check — no start/end bypass,
# preventing vias from being placed inside pad clearance zones.
if allow_vias and via_grid is not None:
if not any(via_grid.is_obs(c, r, li2) for li2 in range(n)):
for other in range(n):
if other == li:
continue
ng = g + via_cost
nkey = (c, r, other)
if ng < g_best.get(nkey, INF):
g_best[nkey] = ng
came_from[nkey] = key
heapq.heappush(heap, (ng + h(c, r, other), ng, c, r, other, 0, 0, key))
return None
# ── Main autorouter class ──────────────────────────────────────────────────────
class KiCADAutorouter:
"""
Routes all unconnected pads on a KiCAD board.
Constraints are read automatically from the board's design settings.
Override any constraint by setting the corresponding attribute before
calling run() / run_rur():
router.track_mm = 0.15 # override track width in mm
router.clearance_mm = 0.15
router.via_size_mm = 0.5
router.via_drill_mm = 0.25
router.grid_mm = 0.05 # finer grid for dense boards
router.via_cost = 40 # A* via penalty
router.turn_cost = 1 # A* turn penalty
router.inner_layer_cost = None # None → auto (prefer emptiest layer by density)
router.use_45_degree = True # allow 45° diagonal traces
router.fill_zones = True # fill zones before routing
"""
def __init__(self, board=None):
self.board = board or pcbnew.GetBoard()
# Physical constraint overrides — None means "read from board"
self.track_mm = None
self.clearance_mm = None
self.via_size_mm = None
self.via_drill_mm = None
self.grid_mm = None
# Router cost overrides
self.via_cost = None # None → _DEFAULT_VIA_COST
self.turn_cost = None # None → _DEFAULT_TURN_COST
self.inner_layer_cost = None # None → 1 (equal preference for all layers)
# Routing mode
self.use_45_degree = True # default: allow 45° diagonal traces
self.fill_zones = True # default: fill zones before routing
# Runtime state (set by _init_run)
self._cst: Optional[BoardConstraints] = None
self._grid: Optional[RoutingGrid] = None
self._via_grid: Optional[RoutingGrid] = None
self._bbox = None
self._grid_nm: int = 0
self._margin: int = 0
self._margin_cells: int = 0
self._via_margin: int = 0
self._via_margin_cells: int = 0
self._via_cost: int = _DEFAULT_VIA_COST
self._turn_cost: int = _DEFAULT_TURN_COST
self._layer_costs: Optional[List[int]] = None
self._use_45: bool = True
self._net_track_w: Dict[int, int] = {}
self._conn_tracks: Dict[int, list] = {}
self._conn_cells: Dict[int, Set[Tuple[int,int,int]]] = {}
self._cell_to_conn: Dict[Tuple[int,int,int], int] = {}
self._conn_via_cells: Dict[int, Set[Tuple[int,int]]] = {}
self._conn_margin_cells: Dict[int, int] = {}
# ── public entry points ───────────────────────────────────────────────
def run(self, progress_cb=None) -> Tuple[int, int, int]:
"""Single-pass routing (no rip-up). Returns (routed, failed, total)."""
self._init_run()
connections = self._build_mst_connections()
total = len(connections)
routed = failed = 0
for i, (net, pa, pb) in enumerate(connections):
if progress_cb:
progress_cb(i, total, net.GetNetname())
if self._route_one(net, pa, pb, conn_id=i):
routed += 1
else:
failed += 1
pcbnew.Refresh()
return routed, failed, total
def run_rur(
self,
advisor=None,
max_retries: int = 100,
progress_cb=None,
) -> Tuple[int, int, int]:
"""
Rip-up and reroute with optional AI guidance.
max_retries: maximum number of rip-up retries *per connection* before
that connection is declared permanently failed. Every
connection is always attempted at least once regardless of
this value. Default 100.
advisor: RouteAdvisor instance for AI-assisted ordering and rip-up
decisions. Falls back to built-in heuristics when None
or when the API is unavailable.
Returns (routed, failed, total) where failed = total - routed, so the
numbers always add up correctly.
"""
self._init_run()
connections = self._build_mst_connections()
total = len(connections)
if total == 0:
return 0, 0, 0
conn_meta = self._build_conn_meta(connections)
# Per-connection retry counter (separate from "was it attempted" tracking)
ripup_count: Dict[int, int] = {i: 0 for i in range(total)}
# AI or heuristic initial ordering
ordered = self._get_order(advisor, conn_meta, connections, pass_num=0)
queue = deque(ordered)
routed_set: Set[int] = set()
perm_failed: Set[int] = set()
stuck_since: int = 0
while queue:
conn_id = queue.popleft()
if conn_id in routed_set or conn_id in perm_failed:
continue
net, pa, pb = connections[conn_id]
retry_num = ripup_count[conn_id]
conn_meta[conn_id]["attempts"] = retry_num + 1
if progress_cb:
pending = len(queue)
progress_cb(
len(routed_set),
total,
f"{net.GetNetname()} "
f"[retry {retry_num}/{max_retries}, "
f"routed {len(routed_set)}/{total}, "
f"pending {pending}]",
)
if self._route_one(net, pa, pb, conn_id=conn_id):
routed_set.add(conn_id)
stuck_since = 0
continue
# Route failed — find what's blocking it
blockers = [b for b in self._find_blockers(net, pa, pb) if b in routed_set]
stuck_since += 1
# Geometrically impossible regardless of other routes
if not blockers:
perm_failed.add(conn_id)
continue
# Retry budget for this connection exhausted
if ripup_count[conn_id] >= max_retries:
perm_failed.add(conn_id)
continue
# Decide what to rip up (AI or heuristic)
re_query = stuck_since > 0 and stuck_since % 5 == 0
to_ripup = self._decide_ripup(
advisor, conn_id, blockers, conn_meta,
ask_ai=re_query,
)
for rid in to_ripup:
self._ripup_connection(rid)
routed_set.discard(rid)
perm_failed.discard(rid)
queue.appendleft(rid)
ripup_count[conn_id] += 1
queue.appendleft(conn_id)
# Periodically re-ask AI to reorder the pending work
if re_query and advisor is not None and len(queue) > 1:
remaining_ids = list(dict.fromkeys(queue))
try:
reordered = self._get_order(
advisor, conn_meta, connections,
pass_num=sum(ripup_count.values()),
subset=remaining_ids,
)
queue = deque(reordered)
except Exception:
pass
pcbnew.Refresh()
routed = len(routed_set)
return routed, total - routed, total
def unroute_all(self) -> None:
for t in list(self.board.GetTracks()):
self.board.Remove(t)
pcbnew.Refresh()
def constraints_summary(self) -> str:
if self._cst is None:
cst = BoardConstraints.from_board(self.board)
else:
cst = self._cst
return cst.summary()
# ── initialisation ────────────────────────────────────────────────────
def _init_run(self) -> None:
board = self.board
cst = BoardConstraints.from_board(board)
self._cst = cst
# Apply physical constraint overrides
self._track_w = _nm(self.track_mm) if self.track_mm else cst.track_w
self._clear = _nm(self.clearance_mm) if self.clearance_mm else cst.clearance
self._via_sz = _nm(self.via_size_mm) if self.via_size_mm else cst.via_size
self._via_dr = _nm(self.via_drill_mm) if self.via_drill_mm else cst.via_drill
self._grid_nm = _nm(self.grid_mm) if self.grid_mm else _nm(_FB_GRID_MM)
# Per-net track widths from KiCAD net classes
self._net_track_w = self._build_net_width_map()
# Use maximum net track width for obstacle margins so the grid is
# conservative enough regardless of which net is being routed.
max_tw = max(self._net_track_w.values(), default=self._track_w)
self._margin = self._clear + max_tw // 2
self._margin_cells = max(1, self._margin // self._grid_nm)
# Via clearance: via_outer_radius + clearance
self._via_margin = self._via_sz // 2 + self._clear
self._via_margin_cells = max(1, self._via_margin // self._grid_nm)
# Router cost parameters
self._via_cost = self.via_cost if self.via_cost is not None else _DEFAULT_VIA_COST
self._turn_cost = self.turn_cost if self.turn_cost is not None else _DEFAULT_TURN_COST
self._use_45 = self.use_45_degree
bbox = board.GetBoardEdgesBoundingBox()
if bbox.GetWidth() == 0 or bbox.GetHeight() == 0:
bbox = board.GetBoundingBox()
self._bbox = bbox
self._grid = RoutingGrid(bbox, cst.n_layers, self._grid_nm)
self._via_grid = RoutingGrid(bbox, cst.n_layers, self._grid_nm)
self._conn_tracks = {}
self._conn_cells = {}
self._cell_to_conn = {}
self._conn_via_cells = {}
self._conn_margin_cells = {}
# Fill zones before marking obstacles so that zone-connected pad pairs
# can be detected and skipped during MST building.
if self.fill_zones:
self._fill_zones()
self._mark_obstacles(self._grid)
self._mark_via_obstacles(self._via_grid)
# Per-layer move costs: if inner_layer_cost is set, use the old static
# model (inner layers cost more to prefer surface layers). Otherwise,
# compute costs dynamically from obstacle density so that A* naturally
# prefers routing on the emptiest layer (e.g. a free inner plane).
n_layers = cst.n_layers
if self.inner_layer_cost is not None:
ilc = max(1, self.inner_layer_cost)
self._layer_costs = [1] * n_layers
for i in range(1, n_layers - 1):
self._layer_costs[i] = ilc
else:
self._layer_costs = self._density_layer_costs(self._grid)
print(f"[router] Constraints: {cst.summary()}")
print(f"[router] Layer costs: {self._layer_costs}")
# ── layer congestion costs ────────────────────────────────────────────
@staticmethod
def _density_layer_costs(grid: RoutingGrid) -> List[int]:
"""
Compute per-layer A* move costs from obstacle density.
The emptiest layer gets cost 1. Other layers scale up proportionally,
capped at 8×. This lets A* discover free inner layers as natural
highways without needing an explicit via-then-inner detour.
"""
occupied = [sum(grid._obs[li]) for li in range(grid.n_layers)]
min_occ = max(1, min(occupied))
costs = [max(1, min(8, round(occ / min_occ))) for occ in occupied]
return costs
# ── per-net track width map ───────────────────────────────────────────
def _build_net_width_map(self) -> Dict[int, int]:
"""Return a dict mapping net code → track width in nm."""
all_classes = self.board.GetAllNetClasses()
result: Dict[int, int] = {}
for fp in self.board.GetFootprints():
for pad in fp.Pads():
nc_val = pad.GetNetCode()
if nc_val in result or nc_val <= 0:
continue
try:
nc_name = pad.GetNet().GetNetClassName()
nc = all_classes.get(nc_name)
if nc is not None:
w = int(nc.GetTrackWidth())
if w > 0:
result[nc_val] = w
continue
except Exception:
pass
result[nc_val] = self._track_w
return result
# ── zone fill and zone-connectivity helpers ───────────────────────────
def _fill_zones(self) -> None:
try:
filler = pcbnew.ZONE_FILLER(self.board)
filler.Fill(self.board.Zones())
pcbnew.Refresh()
print("[router] Copper zones filled.")
except Exception as exc:
print(f"[router] Zone fill skipped: {exc}")
def _pad_in_zone(self, pad, zone) -> bool:
"""True if pad is electrically inside the given copper zone."""
if not zone.IsOnCopperLayer():
return False
zone_layer = zone.GetLayer()
try:
pth = pad.GetAttribute() == pcbnew.PAD_ATTRIB_PTH
if not pth and not pad.IsOnLayer(zone_layer):
return False
pt = pcbnew.VECTOR2I(pad.GetX(), pad.GetY())
return zone.Outline().Contains(pt)
except Exception:
return False
# ── obstacle marking ──────────────────────────────────────────────────
def _pad_layer_indices(self, pad) -> List[int]:
cst = self._cst
indices = [i for i, lid in enumerate(cst.cu_layers) if pad.IsOnLayer(lid)]
return indices or [0]
def _mark_pads(self, grid: RoutingGrid, margin: int) -> None:
cst = self._cst
for fp in self.board.GetFootprints():
for pad in fp.Pads():
cx, cy = pad.GetX(), pad.GetY()
sx, sy = pad.GetSizeX() // 2, pad.GetSizeY() // 2
pli = self._pad_layer_indices(pad)
if len(pli) == grid.n_layers or pad.GetAttribute() == pcbnew.PAD_ATTRIB_PTH:
pli = list(range(grid.n_layers))
for li in pli:
grid.block_rect(cx - sx, cy - sy, cx + sx, cy + sy, li, margin)
def _mark_obstacles(self, grid: RoutingGrid) -> None:
cst = self._cst
margin = self._margin
self._mark_pads(grid, margin)
for track in self.board.GetTracks():
cls = track.GetClass()
if cls == "PCB_TRACK":
li = cst.grid_index(track.GetLayer())
if li is not None:
s, e = track.GetStart(), track.GetEnd()
grid.block_segment(s.x, s.y, e.x, e.y, li, margin)
elif cls in ("PCB_VIA", "VIA"):
cx, cy = track.GetX(), track.GetY()
r = track.GetWidth() // 2
for li in range(grid.n_layers):
grid.block_rect(cx - r, cy - r, cx + r, cy + r, li, margin)
def _mark_via_obstacles(self, grid: RoutingGrid) -> None:
"""
Build a separate grid for via-centre validity.
Every cell (c, r) that is set means a new via centred there would
violate DRC. Three types of expansion:
• pads / via holes → via_sz/2 + clearance beyond pad edge
• existing vias → same margin beyond existing via edge
• existing tracks → via_sz/2 + track_w/2 + clearance from track centre
"""
cst = self._cst
r_v = self._via_sz // 2
via_pad_margin = r_v + self._clear
via_track_margin = r_v + self._track_w // 2 + self._clear
# Pads
for fp in self.board.GetFootprints():
for pad in fp.Pads():
cx, cy = pad.GetX(), pad.GetY()
sx, sy = pad.GetSizeX() // 2, pad.GetSizeY() // 2
pli = self._pad_layer_indices(pad)
if len(pli) == grid.n_layers or pad.GetAttribute() == pcbnew.PAD_ATTRIB_PTH:
pli = list(range(grid.n_layers))
for li in pli:
grid.block_rect(cx - sx, cy - sy, cx + sx, cy + sy, li, via_pad_margin)
# Tracks and vias already on the board
for track in self.board.GetTracks():
cls = track.GetClass()
if cls == "PCB_TRACK":
li = cst.grid_index(track.GetLayer())
if li is not None:
s, e = track.GetStart(), track.GetEnd()
grid.block_segment(s.x, s.y, e.x, e.y, li, via_track_margin)
elif cls in ("PCB_VIA", "VIA"):
cx, cy = track.GetX(), track.GetY()
r = track.GetWidth() // 2
for li in range(grid.n_layers):
grid.block_rect(cx - r, cy - r, cx + r, cy + r, li, via_pad_margin)
# ── connection extraction ─────────────────────────────────────────────
def _build_mst_connections(self) -> List[Tuple]:
"""
Build minimum-spanning-tree connections for all nets.
Pads that are already connected through a filled copper zone are
pre-joined in a union-find structure so that no wire is routed
between them.
"""
net_pads: Dict[int, list] = {}
for fp in self.board.GetFootprints():
for pad in fp.Pads():
nc = pad.GetNetCode()
if nc > 0:
net_pads.setdefault(nc, []).append(pad)
connections = []
for pads in net_pads.values():
if len(pads) < 2:
continue
n = len(pads)
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(x: int, y: int) -> None:
px, py = find(x), find(y)
if px != py:
parent[px] = py
# Pre-connect pads that share a filled copper zone of their net
net_code = pads[0].GetNetCode()
for zone in self.board.Zones():
if zone.GetNetCode() != net_code or not zone.IsFilled():
continue
zone_pad_indices = [
i for i, p in enumerate(pads) if self._pad_in_zone(p, zone)
]
for k in range(1, len(zone_pad_indices)):
union(zone_pad_indices[0], zone_pad_indices[k])
# Prim's MST over the resulting components
in_tree: Set[int] = {find(0)}
while True:
best = None
for i in range(n):
if find(i) not in in_tree:
continue
for j in range(n):
if find(j) in in_tree:
continue
d = self._dist2(pads[i], pads[j])
if best is None or d < best[0]:
best = (d, i, j)
if best is None:
break
_, a, b = best
connections.append((pads[a].GetNet(), pads[a], pads[b]))
comp_b = find(b)
in_tree.add(comp_b)
return connections
def _dist2(self, pa, pb) -> int:
return (pa.GetX() - pb.GetX()) ** 2 + (pa.GetY() - pb.GetY()) ** 2
def _build_conn_meta(self, connections) -> Dict[int, dict]:
meta = {}
for i, (net, pa, pb) in enumerate(connections):
length_mm = math.hypot(
(pa.GetX() - pb.GetX()) / 1e6,
(pa.GetY() - pb.GetY()) / 1e6,
)
meta[i] = {
"id": i,
"net": net.GetNetname(),
"start_mm": (pa.GetX() / 1e6, pa.GetY() / 1e6),
"end_mm": (pb.GetX() / 1e6, pb.GetY() / 1e6),
"length_mm": length_mm,
"attempts": 0,
}
return meta
# ── routing one connection ────────────────────────────────────────────
def _pad_clear_cells(self, pad) -> int:
half = max(pad.GetSizeX(), pad.GetSizeY()) // 2
return max(1, (half + self._margin) // self._grid_nm + 1)
def _route_one(self, net, pad_a, pad_b, conn_id: int = -1) -> bool:
"""
Two-phase routing:
Phase 1 — via-free (single layer). Minimises via count.
Phase 2 — vias allowed. Used only when Phase 1 fails.
"""
grid = self._grid
via_grid = self._via_grid
# Per-net track width and corresponding margin
track_w = self._net_track_w.get(net.GetNetCode(), self._track_w)
net_margin = self._clear + track_w // 2
net_margin_cells = max(1, net_margin // self._grid_nm)
sc, sr = grid.w2g(pad_a.GetX(), pad_a.GetY())
ec, er = grid.w2g(pad_b.GetX(), pad_b.GetY())
sl = self._pad_layer_indices(pad_a)[0]
el = self._pad_layer_indices(pad_b)[0]
sc2 = self._pad_clear_cells(pad_a)
ec2 = self._pad_clear_cells(pad_b)
_astar_kw = dict(
via_cost = self._via_cost,
turn_cost = self._turn_cost,
use_45 = self._use_45,
layer_costs = self._layer_costs,
)
# Phase 1: no vias
path = _astar(grid, sc, sr, sl, ec, er, el, sc2, ec2,
allow_vias=False, via_grid=via_grid, **_astar_kw)
# Phase 2: allow vias only if needed
if path is None:
path = _astar(grid, sc, sr, sl, ec, er, el, sc2, ec2,
allow_vias=True, via_grid=via_grid, **_astar_kw)
if path is None:
return False
# Identify via positions and pre-validate them
via_positions: Set[Tuple[int, int]] = set()
for i in range(len(path) - 1):
c, r, li = path[i]
_, _, nli = path[i + 1]
if li != nli:
via_positions.add((c, r))
if not self._can_place_via(c, r):
mm = pcbnew.ToMM
wx, wy = grid.g2w(c, r)
print(
f"[router] WARN: via at "
f"({mm(wx):.2f}, {mm(wy):.2f}) mm "
f"failed safety check — connection skipped"
)
return False
self._place_path(path, net, conn_id, track_w=track_w)
if conn_id >= 0:
self._conn_cells[conn_id] = set(path)
self._conn_via_cells[conn_id] = via_positions
self._conn_margin_cells[conn_id] = net_margin_cells
for cell in path:
self._cell_to_conn[cell] = conn_id
m = net_margin_cells
vm = self._via_margin_cells
n = grid.n_layers
# Block track path (per-layer, track margin)
for c, r, li in path:
grid.block_disk(c, r, li, m)
# Block via positions on ALL layers in both grids to prevent duplicates
for vc, vr in via_positions:
for li in range(n):
grid.block_disk(vc, vr, li, m)
via_grid.block_disk(vc, vr, li, vm)
return True
def _place_path(
self,
path: List[Tuple[int, int, int]],
net,
conn_id: int = -1,
track_w: Optional[int] = None,
) -> None:
board = self.board
grid = self._grid
cst = self._cst
tw = track_w if track_w is not None else self._track_w
i = 0
while i < len(path) - 1:
c, r, li = path[i]
nc, nr, nli = path[i + 1]