-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathsingle_ended_routing.py
More file actions
2006 lines (1713 loc) · 91 KB
/
single_ended_routing.py
File metadata and controls
2006 lines (1713 loc) · 91 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
"""
Single-ended net routing functions.
Routes individual nets using A* pathfinding on a grid obstacle map.
"""
import math
import time
from typing import Dict, List, Optional, Set, Tuple
from terminal_colors import RED, YELLOW, RESET
from kicad_parser import PCBData, Segment, Via
from routing_config import GridRouteConfig, GridCoord
from routing_utils import build_layer_map
from connectivity import (
get_net_endpoints,
get_multipoint_net_pads,
find_closest_point_on_segments,
compute_mst_edges,
get_zone_connected_pad_groups
)
from obstacle_map import build_obstacle_map, get_same_net_through_hole_positions
from bresenham_utils import walk_line
from geometry_utils import simplify_path
# Import Rust router
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'rust_router'))
try:
from grid_router import GridObstacleMap, GridRouter, VisualRouter
except ImportError:
GridObstacleMap = None
GridRouter = None
VisualRouter = None
def print_route_stats(stats: dict, print_prefix: str = " "):
"""Print A* routing statistics in a readable format.
Args:
stats: Dictionary of statistics from route_multi_with_stats
print_prefix: Prefix for each line (default: " ")
"""
print(f"{print_prefix}A* Search Statistics:")
print(f"{print_prefix} Cells expanded: {int(stats.get('cells_expanded', 0)):,} (popped from open set)")
print(f"{print_prefix} Cells pushed: {int(stats.get('cells_pushed', 0)):,} (added to open set)")
print(f"{print_prefix} Cells revisited: {int(stats.get('cells_revisited', 0)):,} (path improvements)")
print(f"{print_prefix} Duplicate skips: {int(stats.get('duplicate_skips', 0)):,} (already in closed)")
print(f"{print_prefix} Path length: {int(stats.get('path_length', 0)):,} grid steps")
print(f"{print_prefix} Path cost: {int(stats.get('path_cost', 0)):,}")
print(f"{print_prefix} Via count: {int(stats.get('via_count', 0)):,}")
print(f"{print_prefix} Initial h: {int(stats.get('initial_h', 0)):,}")
print(f"{print_prefix} Final g: {int(stats.get('final_g', 0)):,}")
print(f"{print_prefix} Open set size: {int(stats.get('open_set_size', 0)):,} (at termination)")
print(f"{print_prefix} Closed set size: {int(stats.get('closed_set_size', 0)):,} (unique visited)")
# Computed ratios
h_ratio = stats.get('heuristic_ratio', 0)
if h_ratio > 0:
# Note: h_ratio > 1.0 is expected when using weighted A* (h_weight > 1.0)
# The heuristic is multiplied by h_weight to trade optimality for speed
if abs(h_ratio - 1.0) < 0.01:
quality = "perfect heuristic"
elif h_ratio < 1.0:
quality = "admissible (underestimate)"
else:
quality = f"weighted A* (h_weight ~{h_ratio:.1f})"
print(f"{print_prefix} Heuristic ratio: {h_ratio:.3f} (h/g, {quality})")
exp_ratio = stats.get('expansion_ratio', 0)
if exp_ratio > 0:
quality = "excellent" if exp_ratio < 2 else "good" if exp_ratio < 5 else "poor" if exp_ratio < 20 else "very poor"
print(f"{print_prefix} Expansion ratio: {exp_ratio:.1f}x path length ({quality})")
revisit_ratio = stats.get('revisit_ratio', 0)
if revisit_ratio >= 0:
print(f"{print_prefix} Revisit ratio: {revisit_ratio:.3f} (path improvements / expanded)")
skip_ratio = stats.get('skip_ratio', 0)
if skip_ratio >= 0:
print(f"{print_prefix} Skip ratio: {skip_ratio:.3f} (duplicates / total pops)")
def _print_obstacle_map(obstacles: 'GridObstacleMap', center_gx: int, center_gy: int, layer: int, radius: int = 20, print_prefix: str = ""):
"""Print a visual map of blocking around a center point."""
print(f"{print_prefix} Obstacle map around ({center_gx}, {center_gy}) layer={layer} (radius={radius}):")
for dy in range(-radius, radius + 1):
row = []
for dx in range(-radius, radius + 1):
cx, cy = center_gx + dx, center_gy + dy
if dx == 0 and dy == 0:
row.append('T')
elif obstacles.is_blocked(cx, cy, layer):
row.append('#')
else:
row.append('.')
print(f"{print_prefix} {''.join(row)}")
def _identify_blocking_obstacles(
blocked_positions: List[Tuple[int, int, int]],
pcb_data: PCBData,
config: GridRouteConfig,
current_net_id: int = -1
) -> Dict[int, Tuple[str, int]]:
"""
Identify which nets are blocking specific grid positions.
Args:
blocked_positions: List of (gx, gy, layer) blocked cells
pcb_data: PCB data with segments, vias, pads
config: Routing configuration
current_net_id: Current net ID to exclude from results
Returns:
Dict of net_id -> (net_name, count) for blocking nets
"""
coord = GridCoord(config.grid_step)
layer_map = build_layer_map(config.layers)
# Calculate expansion radius (same as obstacle map uses)
expansion_mm = config.track_width / 2 + config.clearance + config.track_width / 2
expansion_grid = max(1, coord.to_grid_dist(expansion_mm))
via_expansion_mm = config.via_size / 2 + config.track_width / 2 + config.clearance
via_expansion_grid = max(1, coord.to_grid_dist(via_expansion_mm))
blockers: Dict[int, Tuple[str, int]] = {}
# Convert blocked positions to set for faster lookup
blocked_set = set(blocked_positions)
# Check segments
for seg in pcb_data.segments:
if seg.net_id == current_net_id:
continue
layer_idx = layer_map.get(seg.layer)
if layer_idx is None:
continue
gx1, gy1 = coord.to_grid(seg.start_x, seg.start_y)
gx2, gy2 = coord.to_grid(seg.end_x, seg.end_y)
# Check if segment's expanded cells overlap with blocked positions
for gx, gy in walk_line(gx1, gy1, gx2, gy2):
for ex in range(-expansion_grid, expansion_grid + 1):
for ey in range(-expansion_grid, expansion_grid + 1):
if (gx + ex, gy + ey, layer_idx) in blocked_set:
net_name = pcb_data.nets[seg.net_id].name if seg.net_id in pcb_data.nets else f"net_{seg.net_id}"
if seg.net_id in blockers:
blockers[seg.net_id] = (net_name, blockers[seg.net_id][1] + 1)
else:
blockers[seg.net_id] = (net_name, 1)
break # Found overlap, move to next segment point
else:
continue
break
else:
continue
break
# Check vias
for via in pcb_data.vias:
if via.net_id == current_net_id:
continue
gx, gy = coord.to_grid(via.x, via.y)
# Vias block all layers within via expansion radius
for layer_idx in range(len(config.layers)):
for ex in range(-via_expansion_grid, via_expansion_grid + 1):
for ey in range(-via_expansion_grid, via_expansion_grid + 1):
if (gx + ex, gy + ey, layer_idx) in blocked_set:
net_name = pcb_data.nets[via.net_id].name if via.net_id in pcb_data.nets else f"net_{via.net_id}"
if via.net_id in blockers:
blockers[via.net_id] = (net_name, blockers[via.net_id][1] + 1)
else:
blockers[via.net_id] = (net_name, 1)
break
else:
continue
break
else:
continue
break
# Check pads (from other nets)
for ref, footprint in pcb_data.footprints.items():
for pad in footprint.pads:
if pad.net_id == current_net_id or pad.net_id == 0:
continue
gx, gy = coord.to_grid(pad.global_x, pad.global_y)
# Compute pad expansion
pad_half_x = pad.size_x / 2 if hasattr(pad, 'size_x') else 0.5
pad_half_y = pad.size_y / 2 if hasattr(pad, 'size_y') else 0.5
pad_expansion_x = max(1, coord.to_grid_dist(pad_half_x + config.clearance + config.track_width / 2))
pad_expansion_y = max(1, coord.to_grid_dist(pad_half_y + config.clearance + config.track_width / 2))
# Check pad layers
pad_layers = []
if pad.drill and pad.drill > 0:
# Through-hole pad - blocks all layers
pad_layers = list(range(len(config.layers)))
else:
# SMD pad - only specific layer
for layer_name in pad.layers:
if layer_name in layer_map:
pad_layers.append(layer_map[layer_name])
for layer_idx in pad_layers:
for ex in range(-pad_expansion_x, pad_expansion_x + 1):
for ey in range(-pad_expansion_y, pad_expansion_y + 1):
if (gx + ex, gy + ey, layer_idx) in blocked_set:
net_name = pcb_data.nets[pad.net_id].name if pad.net_id in pcb_data.nets else f"net_{pad.net_id}"
if pad.net_id in blockers:
blockers[pad.net_id] = (net_name, blockers[pad.net_id][1] + 1)
else:
blockers[pad.net_id] = (net_name, 1)
break
else:
continue
break
else:
continue
break
return blockers
def _diagnose_blocked_start(obstacles: 'GridObstacleMap', cells: List, label: str, print_prefix: str = "", track_margin: int = 0,
pcb_data: PCBData = None, config: GridRouteConfig = None, current_net_id: int = -1):
"""
Diagnose why routing couldn't start from the given cells.
Checks blocking status of start cells and their immediate neighbors.
If pcb_data and config are provided, also identifies which nets are blocking.
"""
if not cells:
print(f"{print_prefix} {label}: no cells to check")
return
# Check a sample of cells (first few)
sample_cells = cells[:3] if len(cells) > 3 else cells
for gx, gy, layer in sample_cells:
# Check if the cell itself is blocked
cell_blocked = obstacles.is_blocked(gx, gy, layer)
# Check neighbors (8-connected)
blocked_neighbors = 0
total_neighbors = 0
blocked_details = []
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
total_neighbors += 1
# Check with margin if specified
if track_margin > 0:
neighbor_blocked = False
for mx in range(-track_margin, track_margin + 1):
for my in range(-track_margin, track_margin + 1):
if obstacles.is_blocked(gx + dx + mx, gy + dy + my, layer):
neighbor_blocked = True
break
if neighbor_blocked:
break
else:
neighbor_blocked = obstacles.is_blocked(gx + dx, gy + dy, layer)
if neighbor_blocked:
blocked_neighbors += 1
blocked_details.append(f"({gx+dx},{gy+dy})")
status = "BLOCKED" if cell_blocked else "ok"
margin_str = f" (margin={track_margin})" if track_margin > 0 else ""
print(f"{print_prefix} {label} cell ({gx}, {gy}, layer={layer}): {status}, {blocked_neighbors}/{total_neighbors} neighbors blocked{margin_str}")
# Show which specific neighbors are blocked for debugging
if blocked_neighbors == total_neighbors and blocked_neighbors > 0:
print(f"{print_prefix} ALL neighbors blocked: {', '.join(blocked_details)}")
# Identify what's blocking if pcb_data and config are provided
if blocked_neighbors > 0 and pcb_data is not None and config is not None:
# Collect blocked neighbor positions
blocked_positions = []
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if dx == 0 and dy == 0:
continue
if track_margin > 0:
for mx in range(-track_margin, track_margin + 1):
for my in range(-track_margin, track_margin + 1):
if obstacles.is_blocked(gx + dx + mx, gy + dy + my, layer):
blocked_positions.append((gx + dx + mx, gy + dy + my, layer))
else:
if obstacles.is_blocked(gx + dx, gy + dy, layer):
blocked_positions.append((gx + dx, gy + dy, layer))
if blocked_positions:
blockers = _identify_blocking_obstacles(blocked_positions, pcb_data, config, current_net_id)
if blockers:
# Sort by count descending
sorted_blockers = sorted(blockers.items(), key=lambda x: x[1][1], reverse=True)
blocker_strs = [f"{name}({count})" for net_id, (name, count) in sorted_blockers[:5]]
print(f"{print_prefix} Blocking obstacles: {', '.join(blocker_strs)}")
def _probe_route_with_frontier(
router: 'GridRouter',
obstacles: 'GridObstacleMap',
forward_sources: List,
forward_targets: List,
config: 'GridRouteConfig',
print_prefix: str = "",
direction_labels: Tuple[str, str] = ("forward", "backward"),
track_margin: int = 0,
pcb_data: PCBData = None,
current_net_id: int = -1,
single_direction: bool = False
) -> Tuple[Optional[List], int, List, List, bool, int, int]:
"""
Probe routing with fail-fast on stuck directions.
Uses bidirectional probing to detect if either endpoint is blocked early,
avoiding expensive full searches that will fail anyway.
Args:
router: GridRouter instance
obstacles: Obstacle map
forward_sources: Source cells for forward direction
forward_targets: Target cells for forward direction
config: Routing configuration
print_prefix: Prefix for print messages (e.g., " " or " ")
direction_labels: Names for forward/backward directions
track_margin: Extra margin in grid cells for wide tracks (power nets)
pcb_data: Optional PCB data for blocking obstacle identification
current_net_id: Current net ID (for excluding from blocking analysis)
single_direction: If True, only try forward direction (for bus routing)
Returns:
(path, total_iterations, forward_blocked, backward_blocked, reversed_path, forward_iters, backward_iters)
- path: The found path or None
- total_iterations: Total iterations used
- forward_blocked: Blocked cells from forward direction (for rip-up analysis)
- backward_blocked: Blocked cells from backward direction (for rip-up analysis)
- reversed_path: Whether path was found going backwards
- forward_iters: Iterations used in forward direction
- backward_iters: Iterations used in backward direction
"""
first_label, second_label = direction_labels
probe_iterations = config.max_probe_iterations
# Track iterations per direction (first/second maps to forward/backward based on labels)
first_total_iters = 0
second_total_iters = 0
# Probe forward direction
path, iterations, blocked_cells = router.route_with_frontier(
obstacles, forward_sources, forward_targets, probe_iterations, track_margin=track_margin)
first_probe_iters = iterations
first_total_iters = first_probe_iters
first_blocked = blocked_cells
total_iterations = first_probe_iters
reversed_path = False
# Track blocked cells for both directions
forward_blocked = first_blocked
backward_blocked = []
# Helper to map first/second to forward/backward based on labels
def get_fwd_bwd_iters():
if first_label == "forward":
return first_total_iters, second_total_iters
else:
return second_total_iters, first_total_iters
if path is not None:
# Found in first probe
forward_blocked = [] # Success - clear blocked cells
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return path, total_iterations, forward_blocked, backward_blocked, reversed_path, fwd_iters, bwd_iters
# For single_direction mode (bus routing), skip backward probe entirely
if single_direction:
first_reached_max = first_probe_iters >= probe_iterations
if not first_reached_max:
# Forward is stuck
print(f"{print_prefix}{first_label} stuck ({first_probe_iters} < {probe_iterations}) [single-direction bus mode]")
_diagnose_blocked_start(obstacles, forward_sources, first_label, print_prefix, track_margin,
pcb_data=pcb_data, config=config, current_net_id=current_net_id)
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return None, total_iterations, forward_blocked, backward_blocked, False, fwd_iters, bwd_iters
# Forward probe reached max - do full search
print(f"{print_prefix}Probe: {first_label}={first_probe_iters} iters [single-direction bus mode], trying full iterations...")
path, full_iters, full_blocked = router.route_with_frontier(
obstacles, forward_sources, forward_targets, config.max_iterations, track_margin=track_margin)
first_total_iters += full_iters
total_iterations += full_iters
if path is not None:
forward_blocked = []
else:
forward_blocked = full_blocked
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return path, total_iterations, forward_blocked, backward_blocked, False, fwd_iters, bwd_iters
# Probe backward direction (bidirectional mode)
path, iterations, blocked_cells = router.route_with_frontier(
obstacles, forward_targets, forward_sources, probe_iterations, track_margin=track_margin)
second_probe_iters = iterations
second_total_iters = second_probe_iters
second_blocked = blocked_cells
total_iterations += second_probe_iters
backward_blocked = second_blocked
if path is not None:
# Found in second probe
backward_blocked = [] # Success - clear blocked cells
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return path, total_iterations, forward_blocked, backward_blocked, True, fwd_iters, bwd_iters
# Both probes failed to find a path - check if both reached max iterations
# Only try full search if BOTH probes reached max-probe-iterations (meaning both directions are worth exploring)
first_reached_max = first_probe_iters >= probe_iterations
second_reached_max = second_probe_iters >= probe_iterations
if not (first_reached_max and second_reached_max):
# At least one probe didn't reach max - that direction is stuck, skip full search
if not first_reached_max and not second_reached_max:
print(f"{print_prefix}Both directions stuck ({first_label}={first_probe_iters}, {second_label}={second_probe_iters} < {probe_iterations})")
_diagnose_blocked_start(obstacles, forward_sources, first_label, print_prefix, track_margin,
pcb_data=pcb_data, config=config, current_net_id=current_net_id)
_diagnose_blocked_start(obstacles, forward_targets, second_label, print_prefix, track_margin,
pcb_data=pcb_data, config=config, current_net_id=current_net_id)
elif not first_reached_max:
print(f"{print_prefix}{first_label} stuck ({first_probe_iters} < {probe_iterations}), {second_label}={second_probe_iters}")
_diagnose_blocked_start(obstacles, forward_sources, first_label, print_prefix, track_margin,
pcb_data=pcb_data, config=config, current_net_id=current_net_id)
else:
print(f"{print_prefix}{second_label} stuck ({second_probe_iters} < {probe_iterations}), {first_label}={first_probe_iters}")
_diagnose_blocked_start(obstacles, forward_targets, second_label, print_prefix, track_margin,
pcb_data=pcb_data, config=config, current_net_id=current_net_id)
# Print visual obstacle map around the stuck target
if forward_targets and config.debug_lines:
tgt = forward_targets[0]
_print_obstacle_map(obstacles, tgt[0], tgt[1], tgt[2], radius=15, print_prefix=print_prefix)
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return None, total_iterations, forward_blocked, backward_blocked, False, fwd_iters, bwd_iters
# Both probes reached max iterations - do full search on forward direction
print(f"{print_prefix}Probe: {first_label}={first_probe_iters}, {second_label}={second_probe_iters} iters, trying {first_label} with full iterations...")
path, full_iters, full_blocked = router.route_with_frontier(
obstacles, forward_sources, forward_targets, config.max_iterations, track_margin=track_margin)
first_total_iters += full_iters
total_iterations += full_iters
if path is not None:
forward_blocked = []
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return path, total_iterations, forward_blocked, backward_blocked, False, fwd_iters, bwd_iters
# Forward failed, try backward
print(f"{print_prefix}No route found after {full_iters} iterations ({first_label}), trying {second_label}...")
forward_blocked = full_blocked
path, backward_full_iters, backward_full_blocked = router.route_with_frontier(
obstacles, forward_targets, forward_sources, config.max_iterations, track_margin=track_margin)
second_total_iters += backward_full_iters
total_iterations += backward_full_iters
if path is not None:
backward_blocked = []
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return path, total_iterations, forward_blocked, backward_blocked, True, fwd_iters, bwd_iters
backward_blocked = backward_full_blocked
fwd_iters, bwd_iters = get_fwd_bwd_iters()
return None, total_iterations, forward_blocked, backward_blocked, False, fwd_iters, bwd_iters
def route_net(pcb_data: PCBData, net_id: int, config: GridRouteConfig,
unrouted_stubs: Optional[List[Tuple[float, float]]] = None) -> Optional[dict]:
"""Route a single net using the Rust router."""
# Find endpoints (segments or pads)
sources, targets, error = get_net_endpoints(pcb_data, net_id, config)
if error:
print(f" {error}")
return None
if not sources or not targets:
print(f" No valid source/target endpoints found")
return None
coord = GridCoord(config.grid_step)
layer_names = config.layers
# Extract grid-only coords for routing
sources_grid = [(s[0], s[1], s[2]) for s in sources]
targets_grid = [(t[0], t[1], t[2]) for t in targets]
# Get stub free ends for proximity zone checking (where routing actually starts/ends)
# This is more accurate than checking all segment endpoints
free_end_sources, free_end_targets, _ = get_net_endpoints(pcb_data, net_id, config, use_stub_free_ends=True)
if free_end_sources:
prox_check_sources = [(s[0], s[1], s[2]) for s in free_end_sources]
else:
prox_check_sources = sources_grid # Fallback to all endpoints
if free_end_targets:
prox_check_targets = [(t[0], t[1], t[2]) for t in free_end_targets]
else:
prox_check_targets = targets_grid # Fallback to all endpoints
# Build obstacles
obstacles = build_obstacle_map(pcb_data, config, net_id, unrouted_stubs)
# Add source and target positions as allowed cells to override BGA zone blocking
# This only affects BGA zone blocking, not regular obstacle blocking (tracks, stubs, pads)
allow_radius = 10
for gx, gy, _ in sources_grid + targets_grid:
for dx in range(-allow_radius, allow_radius + 1):
for dy in range(-allow_radius, allow_radius + 1):
obstacles.add_allowed_cell(gx + dx, gy + dy)
# Mark exact source/target cells so routing can start/end there even if blocked by
# adjacent track expansion (but NOT blocked by BGA zones - use allowed_cells for that)
# NOTE: Must pass layer to only allow override on the specific layer of the endpoint
for gx, gy, layer in sources_grid + targets_grid:
obstacles.add_source_target_cell(gx, gy, layer)
# Calculate vertical attraction parameters
attraction_radius_grid = coord.to_grid_dist(config.vertical_attraction_radius) if config.vertical_attraction_radius > 0 else 0
attraction_bonus = int(config.vertical_attraction_cost * 1000 / config.grid_step) if config.vertical_attraction_cost > 0 else 0
# Check which proximity zones the stub free ends are in for precise heuristic estimate
src_in_stub = any(obstacles.get_stub_proximity_cost(gx, gy) > 0 for gx, gy, _ in prox_check_sources)
src_in_bga = any(obstacles.is_in_bga_proximity(gx, gy) for gx, gy, _ in prox_check_sources)
tgt_in_stub = any(obstacles.get_stub_proximity_cost(gx, gy) > 0 for gx, gy, _ in prox_check_targets)
tgt_in_bga = any(obstacles.is_in_bga_proximity(gx, gy) for gx, gy, _ in prox_check_targets)
prox_h_cost = config.get_proximity_heuristic_for_zones(src_in_stub, src_in_bga, tgt_in_stub, tgt_in_bga)
if config.verbose:
zones = []
if src_in_stub: zones.append("src:stub")
if src_in_bga: zones.append("src:bga")
if tgt_in_stub: zones.append("tgt:stub")
if tgt_in_bga: zones.append("tgt:bga")
print(f" proximity_heuristic_cost={prox_h_cost} zones=[{', '.join(zones) if zones else 'none'}]")
router = GridRouter(via_cost=config.via_cost * 1000, h_weight=config.heuristic_weight,
turn_cost=config.turn_cost, via_proximity_cost=int(config.via_proximity_cost),
vertical_attraction_radius=attraction_radius_grid,
vertical_attraction_bonus=attraction_bonus,
layer_costs=config.get_layer_costs(),
proximity_heuristic_cost=prox_h_cost,
layer_direction_preferences=config.get_layer_direction_preferences(),
direction_preference_cost=config.direction_preference_cost)
# Calculate track margin for wide power tracks
# Use ceiling + 1 to account for grid quantization and diagonal track approaches
# Compare against layer-specific width (not base track_width) to handle impedance routing
net_track_width = config.get_net_track_width(net_id, config.layers[0])
layer_track_width = config.get_track_width(config.layers[0])
extra_half_width = (net_track_width - layer_track_width) / 2
track_margin = (int(math.ceil(extra_half_width / config.grid_step)) + 1) if extra_half_width > 0 else 0
# Determine direction order (always deterministic)
if config.direction_order in ("backwards", "backward"):
start_backwards = True
else: # "forward" or default
start_backwards = False
# Set up first and second direction based on order
if start_backwards:
first_sources, first_targets = targets_grid, sources_grid
second_sources, second_targets = sources_grid, targets_grid
first_label, second_label = "backward", "forward"
else:
first_sources, first_targets = sources_grid, targets_grid
second_sources, second_targets = targets_grid, sources_grid
first_label, second_label = "forward", "backward"
# Quick probe phase: test both directions with limited iterations to detect if stuck
reversed_path = False
total_iterations = 0
probe_iterations = config.max_probe_iterations
# Probe first direction
path, iterations, _ = router.route_multi(obstacles, first_sources, first_targets, probe_iterations, track_margin=track_margin)
first_probe_iters = iterations
total_iterations = first_probe_iters
if path is None:
# Probe second direction
path, iterations, _ = router.route_multi(obstacles, second_sources, second_targets, probe_iterations, track_margin=track_margin)
second_probe_iters = iterations
total_iterations += second_probe_iters
if path is not None:
reversed_path = not start_backwards
else:
# Both probes failed - only try full search if BOTH reached max iterations
first_reached_max = first_probe_iters >= probe_iterations
second_reached_max = second_probe_iters >= probe_iterations
if not (first_reached_max and second_reached_max):
# At least one probe didn't reach max - that direction is stuck, skip full search
if not first_reached_max and not second_reached_max:
print(f"Both directions stuck ({first_label}={first_probe_iters}, {second_label}={second_probe_iters} < {probe_iterations})")
_diagnose_blocked_start(obstacles, first_sources, first_label, "", track_margin,
pcb_data=pcb_data, config=config, current_net_id=net_id)
_diagnose_blocked_start(obstacles, second_sources, second_label, "", track_margin,
pcb_data=pcb_data, config=config, current_net_id=net_id)
elif not first_reached_max:
print(f"{first_label} stuck ({first_probe_iters} < {probe_iterations}), {second_label}={second_probe_iters}")
_diagnose_blocked_start(obstacles, first_sources, first_label, "", track_margin,
pcb_data=pcb_data, config=config, current_net_id=net_id)
else:
print(f"{second_label} stuck ({second_probe_iters} < {probe_iterations}), {first_label}={first_probe_iters}")
_diagnose_blocked_start(obstacles, second_sources, second_label, "", track_margin,
pcb_data=pcb_data, config=config, current_net_id=net_id)
else:
# Both probes reached max - do full search on first direction
print(f"Probe: {first_label}={first_probe_iters}, {second_label}={second_probe_iters} iters, trying {first_label} with full iterations...")
path, full_iters, _ = router.route_multi(obstacles, first_sources, first_targets, config.max_iterations, track_margin=track_margin)
total_iterations += full_iters
if path is not None:
reversed_path = not start_backwards
else:
# First direction failed, try second
print(f"No route found after {full_iters} iterations ({first_label}), trying {second_label}...")
path, fallback_full_iters, _ = router.route_multi(obstacles, second_sources, second_targets, config.max_iterations, track_margin=track_margin)
total_iterations += fallback_full_iters
if path is not None:
reversed_path = start_backwards
if path is None:
print(f"No route found after {total_iterations} iterations (both directions)")
return None
print(f"Route found in {total_iterations} iterations, path length: {len(path)}")
# If path was found in reverse direction, swap sources/targets for connection logic
if reversed_path:
sources, targets = targets, sources
# Find which source/target the path actually connects to
path_start = path[0]
path_end = path[-1]
start_original = None
for s in sources:
if s[0] == path_start[0] and s[1] == path_start[1] and s[2] == path_start[2]:
start_original = (s[3], s[4], layer_names[s[2]])
break
end_original = None
for t in targets:
if t[0] == path_end[0] and t[1] == path_end[1] and t[2] == path_end[2]:
end_original = (t[3], t[4], layer_names[t[2]])
break
# Get through-hole pad positions for this net (layer transitions without via)
through_hole_positions = get_same_net_through_hole_positions(pcb_data, net_id, config)
# Simplify path by removing collinear intermediate points
path = simplify_path(path)
# Convert path to segments and vias
new_segments = []
new_vias = []
# Add connecting segment from original start to first path point if needed
if start_original:
first_grid_x, first_grid_y = coord.to_float(path_start[0], path_start[1])
orig_x, orig_y, orig_layer = start_original
if abs(orig_x - first_grid_x) > 0.001 or abs(orig_y - first_grid_y) > 0.001:
seg = Segment(
start_x=orig_x, start_y=orig_y,
end_x=first_grid_x, end_y=first_grid_y,
width=config.get_net_track_width(net_id, orig_layer),
layer=orig_layer,
net_id=net_id
)
new_segments.append(seg)
for i in range(len(path) - 1):
gx1, gy1, layer1 = path[i]
gx2, gy2, layer2 = path[i + 1]
x1, y1 = coord.to_float(gx1, gy1)
x2, y2 = coord.to_float(gx2, gy2)
if layer1 != layer2:
# Check if layer change is at an existing through-hole pad
# If so, skip creating a via - the pad provides the layer transition
if (gx1, gy1) not in through_hole_positions:
via = Via(
x=x1, y=y1,
size=config.via_size,
drill=config.via_drill,
layers=["F.Cu", "B.Cu"], # Always through-hole
net_id=net_id
)
new_vias.append(via)
else:
if (x1, y1) != (x2, y2):
layer_name = layer_names[layer1]
seg = Segment(
start_x=x1, start_y=y1,
end_x=x2, end_y=y2,
width=config.get_net_track_width(net_id, layer_name),
layer=layer_name,
net_id=net_id
)
new_segments.append(seg)
# Add connecting segment from last path point to original end if needed
if end_original:
last_grid_x, last_grid_y = coord.to_float(path_end[0], path_end[1])
orig_x, orig_y, orig_layer = end_original
if abs(orig_x - last_grid_x) > 0.001 or abs(orig_y - last_grid_y) > 0.001:
seg = Segment(
start_x=last_grid_x, start_y=last_grid_y,
end_x=orig_x, end_y=orig_y,
width=config.get_net_track_width(net_id, orig_layer),
layer=orig_layer,
net_id=net_id
)
new_segments.append(seg)
return {
'new_segments': new_segments,
'new_vias': new_vias,
'iterations': total_iterations,
'path_length': len(path),
'path': path, # Include raw path for incremental obstacle updates
}
def route_net_with_obstacles(pcb_data: PCBData, net_id: int, config: GridRouteConfig,
obstacles: GridObstacleMap,
attraction_path: Optional[List[Tuple[int, int, int]]] = None,
reverse_direction: bool = False) -> Optional[dict]:
"""Route a single net using pre-built obstacles (for incremental routing).
Args:
pcb_data: PCB data
net_id: Net ID to route
config: Routing configuration
obstacles: Pre-built obstacle map
attraction_path: Optional path to attract to (for bus routing).
List of (gx, gy, layer) tuples from a previously routed neighbor.
reverse_direction: If True, swap sources and targets (route from targets to sources).
Used for bus routing when the clique was formed by targets.
"""
# Find endpoints (segments or pads)
sources, targets, error = get_net_endpoints(pcb_data, net_id, config)
if error:
print(f" {error}")
return None
if not sources or not targets:
print(f" No valid source/target endpoints found")
return None
# Swap source/target for bus routing from clustered targets
if reverse_direction:
sources, targets = targets, sources
coord = GridCoord(config.grid_step)
layer_names = config.layers
sources_grid = [(s[0], s[1], s[2]) for s in sources]
targets_grid = [(t[0], t[1], t[2]) for t in targets]
# Get stub free ends for proximity zone checking (where routing actually starts/ends)
free_end_sources, free_end_targets, _ = get_net_endpoints(pcb_data, net_id, config, use_stub_free_ends=True)
if free_end_sources:
prox_check_sources = [(s[0], s[1], s[2]) for s in free_end_sources]
else:
prox_check_sources = sources_grid
if free_end_targets:
prox_check_targets = [(t[0], t[1], t[2]) for t in free_end_targets]
else:
prox_check_targets = targets_grid
# Add source and target positions as allowed cells to override BGA zone blocking
# This only affects BGA zone blocking, not regular obstacle blocking (tracks, stubs, pads)
allow_radius = 10
for gx, gy, _ in sources_grid + targets_grid:
for dx in range(-allow_radius, allow_radius + 1):
for dy in range(-allow_radius, allow_radius + 1):
obstacles.add_allowed_cell(gx + dx, gy + dy)
# Mark exact source/target cells so routing can start/end there even if blocked by
# adjacent track expansion (but NOT blocked by BGA zones - use allowed_cells for that)
# NOTE: Must pass layer to only allow override on the specific layer of the endpoint
for gx, gy, layer in sources_grid + targets_grid:
obstacles.add_source_target_cell(gx, gy, layer)
# Calculate vertical attraction parameters
attraction_radius_grid = coord.to_grid_dist(config.vertical_attraction_radius) if config.vertical_attraction_radius > 0 else 0
attraction_bonus = int(config.vertical_attraction_cost * 1000 / config.grid_step) if config.vertical_attraction_cost > 0 else 0
# Check which proximity zones the stub free ends are in for precise heuristic estimate
src_in_stub = any(obstacles.get_stub_proximity_cost(gx, gy) > 0 for gx, gy, _ in prox_check_sources)
src_in_bga = any(obstacles.is_in_bga_proximity(gx, gy) for gx, gy, _ in prox_check_sources)
tgt_in_stub = any(obstacles.get_stub_proximity_cost(gx, gy) > 0 for gx, gy, _ in prox_check_targets)
tgt_in_bga = any(obstacles.is_in_bga_proximity(gx, gy) for gx, gy, _ in prox_check_targets)
prox_h_cost = config.get_proximity_heuristic_for_zones(src_in_stub, src_in_bga, tgt_in_stub, tgt_in_bga)
if config.verbose:
zones = []
if src_in_stub: zones.append("src:stub")
if src_in_bga: zones.append("src:bga")
if tgt_in_stub: zones.append("tgt:stub")
if tgt_in_bga: zones.append("tgt:bga")
print(f" proximity_heuristic_cost={prox_h_cost} zones=[{', '.join(zones) if zones else 'none'}]")
# Calculate bus attraction parameters
bus_attraction_radius_grid = coord.to_grid_dist(config.bus_attraction_radius) if config.bus_attraction_radius > 0 else 0
bus_attraction_bonus = int(config.bus_attraction_bonus) if config.bus_attraction_bonus > 0 else 0
router = GridRouter(via_cost=config.via_cost * 1000, h_weight=config.heuristic_weight,
turn_cost=config.turn_cost, via_proximity_cost=int(config.via_proximity_cost),
vertical_attraction_radius=attraction_radius_grid,
vertical_attraction_bonus=attraction_bonus,
layer_costs=config.get_layer_costs(),
proximity_heuristic_cost=prox_h_cost,
layer_direction_preferences=config.get_layer_direction_preferences(),
direction_preference_cost=config.direction_preference_cost,
attraction_radius=bus_attraction_radius_grid,
attraction_bonus=bus_attraction_bonus)
# Set attraction path for bus routing (if provided)
if attraction_path:
router.set_attraction_path(attraction_path)
if config.verbose:
layers_in_path = set(p[2] for p in attraction_path)
print(f" Bus attraction: {len(attraction_path)} path points, layers={layers_in_path}, radius={bus_attraction_radius_grid} grid, bonus={bus_attraction_bonus}")
# Calculate track margin for wide power tracks
# Use ceiling + 1 to account for grid quantization and diagonal track approaches
# Compare against layer-specific width (not base track_width) to handle impedance routing
net_track_width = config.get_net_track_width(net_id, config.layers[0])
layer_track_width = config.get_track_width(config.layers[0])
extra_half_width = (net_track_width - layer_track_width) / 2
track_margin = (int(math.ceil(extra_half_width / config.grid_step)) + 1) if extra_half_width > 0 else 0
# Determine direction order (always deterministic)
start_backwards = config.direction_order in ("backwards", "backward")
# Set up forward/backward based on direction preference
if start_backwards:
forward_sources, forward_targets = targets_grid, sources_grid
direction_labels = ("backward", "forward")
else:
forward_sources, forward_targets = sources_grid, targets_grid
direction_labels = ("forward", "backward")
# Use probe routing helper
# For bus routing with reverse_direction, use single-direction mode to ensure
# routes start from the clustered endpoints (where attraction can guide them)
use_single_direction = reverse_direction
if config.verbose:
print(f" GridRouter sources: {forward_sources[:3]}{'...' if len(forward_sources) > 3 else ''}")
print(f" GridRouter targets: {forward_targets[:3]}{'...' if len(forward_targets) > 3 else ''}")
if use_single_direction:
print(f" Bus routing: single-direction mode (start from clustered endpoints)")
path, total_iterations, forward_blocked, backward_blocked, reversed_path, fwd_iters, bwd_iters = _probe_route_with_frontier(
router, obstacles, forward_sources, forward_targets, config,
print_prefix="", direction_labels=direction_labels, track_margin=track_margin,
pcb_data=pcb_data, current_net_id=net_id, single_direction=use_single_direction
)
# Adjust reversed_path based on start direction
if start_backwards and path is not None:
reversed_path = not reversed_path
if path is None:
dir_msg = "single direction" if use_single_direction else "both directions"
print(f"No route found after {total_iterations} iterations ({dir_msg})")
return {
'failed': True,
'iterations': total_iterations,
'blocked_cells_forward': forward_blocked,
'blocked_cells_backward': backward_blocked,
'iterations_forward': fwd_iters,
'iterations_backward': bwd_iters,
}
print(f"Route found in {total_iterations} iterations, path length: {len(path)}")
# Collect and print stats if enabled
if config.collect_stats:
# Re-run with stats collection on the same direction that succeeded
# Use the actual source/target that worked
if reversed_path:
stats_sources, stats_targets = forward_targets, forward_sources
else:
stats_sources, stats_targets = forward_sources, forward_targets
_, _, stats = router.route_multi(
obstacles, stats_sources, stats_targets, config.max_iterations, track_margin=track_margin)
print_route_stats(stats)
if reversed_path:
sources, targets = targets, sources
path_start = path[0]
path_end = path[-1]
start_original = None
for s in sources:
if s[0] == path_start[0] and s[1] == path_start[1] and s[2] == path_start[2]:
start_original = (s[3], s[4], layer_names[s[2]])
break
end_original = None
for t in targets:
if t[0] == path_end[0] and t[1] == path_end[1] and t[2] == path_end[2]:
end_original = (t[3], t[4], layer_names[t[2]])
break
# Get through-hole pad positions for this net (layer transitions without via)
through_hole_positions = get_same_net_through_hole_positions(pcb_data, net_id, config)
# Simplify path by removing collinear intermediate points
path = simplify_path(path)
new_segments = []
new_vias = []
if start_original:
first_grid_x, first_grid_y = coord.to_float(path_start[0], path_start[1])
orig_x, orig_y, orig_layer = start_original
if abs(orig_x - first_grid_x) > 0.001 or abs(orig_y - first_grid_y) > 0.001:
seg = Segment(
start_x=orig_x, start_y=orig_y,
end_x=first_grid_x, end_y=first_grid_y,
width=config.get_net_track_width(net_id, orig_layer),
layer=orig_layer,
net_id=net_id
)
new_segments.append(seg)
for i in range(len(path) - 1):
gx1, gy1, layer1 = path[i]
gx2, gy2, layer2 = path[i + 1]
x1, y1 = coord.to_float(gx1, gy1)
x2, y2 = coord.to_float(gx2, gy2)
if layer1 != layer2:
# Check if layer change is at an existing through-hole pad
# If so, skip creating a via - the pad provides the layer transition
if (gx1, gy1) not in through_hole_positions:
via = Via(
x=x1, y=y1,
size=config.via_size,
drill=config.via_drill,
layers=["F.Cu", "B.Cu"], # Always through-hole
net_id=net_id
)
new_vias.append(via)
else:
if (x1, y1) != (x2, y2):
layer_name = layer_names[layer1]
seg = Segment(
start_x=x1, start_y=y1,
end_x=x2, end_y=y2,
width=config.get_net_track_width(net_id, layer_name),
layer=layer_name,
net_id=net_id
)
new_segments.append(seg)
if end_original:
last_grid_x, last_grid_y = coord.to_float(path_end[0], path_end[1])
orig_x, orig_y, orig_layer = end_original
if abs(orig_x - last_grid_x) > 0.001 or abs(orig_y - last_grid_y) > 0.001:
seg = Segment(
start_x=last_grid_x, start_y=last_grid_y,
end_x=orig_x, end_y=orig_y,
width=config.get_net_track_width(net_id, orig_layer),
layer=orig_layer,
net_id=net_id
)
new_segments.append(seg)
return {
'new_segments': new_segments,
'new_vias': new_vias,
'iterations': total_iterations,
'path_length': len(path),
'path': path,
}