-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdiff_pair_routing.py
More file actions
2209 lines (1903 loc) · 101 KB
/
diff_pair_routing.py
File metadata and controls
2209 lines (1903 loc) · 101 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
"""
Differential pair routing functions.
Routes differential pairs (P and N nets) together using centerline + offset approach.
"""
import math
from typing import List, Optional, Tuple, Dict
from kicad_parser import PCBData, Segment, Via
from routing_config import GridRouteConfig, GridCoord, DiffPairNet
from routing_utils import segment_length, build_layer_map
from connectivity import (
find_connected_groups, find_stub_free_ends, get_stub_direction, get_net_endpoints,
get_stub_segments, get_stub_vias, calculate_stub_via_barrel_length
)
from obstacle_map import check_line_clearance
from geometry_utils import simplify_path
# Note: Layer switching is now done upfront in route.py, not during routing
# 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, PoseRouter
except ImportError:
GridObstacleMap = None
GridRouter = None
PoseRouter = None
# Map direction (dx, dy) to theta_idx (0-7) for pose-based routing
# DIRECTIONS in Rust: E(1,0)=0, NE(1,-1)=1, N(0,-1)=2, NW(-1,-1)=3, W(-1,0)=4, SW(-1,1)=5, S(0,1)=6, SE(1,1)=7
DIRECTION_TO_THETA = {
(1, 0): 0, # East
(1, -1): 1, # NE
(0, -1): 2, # North
(-1, -1): 3, # NW
(-1, 0): 4, # West
(-1, 1): 5, # SW
(0, 1): 6, # South
(1, 1): 7, # SE
}
def direction_to_theta_idx(dx: float, dy: float) -> int:
"""Convert a direction vector (dx, dy) to a theta_idx (0-7) for pose-based routing."""
if abs(dx) < 0.01 and abs(dy) < 0.01:
return 0 # Default to East if no direction
# Normalize
length = math.sqrt(dx*dx + dy*dy)
ndx = dx / length
ndy = dy / length
# Find the angle and map to nearest 45-degree direction
angle = math.atan2(-ndy, ndx) # Note: negate y because grid y increases downward
# Convert to [0, 2*pi) range
if angle < 0:
angle += 2 * math.pi
# Map angle to theta_idx (each sector is 45 degrees = pi/4)
# Add pi/8 to center each sector around the direction
theta_idx = int((angle + math.pi/8) / (math.pi/4)) % 8
return theta_idx
def _find_open_positions(center_x, center_y, dir_x, dir_y, layer_idx, setback,
label, layer_names, spacing_mm, config, obstacles,
connector_obstacles, coord, neighbor_stubs):
"""Find open position for setback, preferring 0° but angling away from nearby stubs if needed.
Only angles away from 0° if the nearest unrouted stub is too close (within
required diff pair clearance). Returns list with best candidate first.
Each candidate is (gx, gy, dx, dy, angle_deg, dist_to_nearest_stub).
"""
current_layer = layer_names[layer_idx]
# Required clearance from centerline to neighboring stub
# P/N tracks are at ±spacing_mm from centerline, need config.clearance to other stub
# Add factor of 2 for extra margin to ensure future routes have room
required_clearance = 2 * (spacing_mm + config.clearance)
# Generate angles: 0, then ±max/4, ±max/2, ±3*max/4, ±max
max_angle = config.max_setback_angle
angles_deg = [0,
max_angle / 4, -max_angle / 4,
max_angle / 2, -max_angle / 2,
3 * max_angle / 4, -3 * max_angle / 4,
max_angle, -max_angle]
def check_angle_valid(angle_deg):
"""Check if angle is valid (not blocked). Returns (gx, gy, dx, dy, x, y) or None."""
angle_rad = math.radians(angle_deg)
cos_a = math.cos(angle_rad)
sin_a = math.sin(angle_rad)
dx = dir_x * cos_a - dir_y * sin_a
dy = dir_x * sin_a + dir_y * cos_a
x = center_x + dx * setback
y = center_y + dy * setback
gx, gy = coord.to_grid(x, y)
if obstacles.is_blocked(gx, gy, layer_idx):
return None
if not check_line_clearance(connector_obstacles, center_x, center_y, x, y, layer_idx, config):
return None
# Probe ahead
probe_dist = config.grid_step * 3
probe_x = x + dx * probe_dist
probe_y = y + dy * probe_dist
probe_gx, probe_gy = coord.to_grid(probe_x, probe_y)
if obstacles.is_blocked(probe_gx, probe_gy, layer_idx):
return None
return (gx, gy, dx, dy, x, y)
def find_nearest_stub(x, y):
"""Find nearest same-layer stub from position (x, y). Returns (dist, stub_x, stub_y) or (inf, None, None)."""
min_dist = float('inf')
closest = (None, None)
if neighbor_stubs:
for stub_x, stub_y, stub_layer in neighbor_stubs:
if stub_layer != current_layer:
continue
dist = math.sqrt((x - stub_x)**2 + (y - stub_y)**2)
if dist < min_dist:
min_dist = dist
closest = (stub_x, stub_y)
return min_dist, closest[0], closest[1]
# Check 0° first
zero_result = check_angle_valid(0)
if zero_result:
gx, gy, dx, dy, x, y = zero_result
dist, stub_x, stub_y = find_nearest_stub(x, y)
# Collect all valid angles as fallbacks (sorted by angle magnitude)
other_candidates = []
for angle_deg in sorted(angles_deg, key=abs):
if angle_deg == 0:
continue
result = check_angle_valid(angle_deg)
if result:
ax, ay, adx, ady, ax_pos, ay_pos = result
a_dist, _, _ = find_nearest_stub(ax_pos, ay_pos)
other_candidates.append((ax, ay, adx, ady, angle_deg, a_dist))
if dist >= required_clearance:
# 0° is valid and has enough clearance - use it as primary
if config.verbose:
if stub_x is not None:
print(f" {label} 0.0°: OK (nearest stub at ({stub_x:.1f},{stub_y:.1f}) dist={dist:.2f}mm >= {required_clearance:.2f}mm)")
else:
print(f" {label} 0.0°: OK (no nearby stubs on {current_layer})")
return [(gx, gy, dx, dy, 0.0, dist)] + other_candidates
# 0° is valid but too close to stub - need to angle away
if config.verbose:
print(f" {label} 0.0°: too close to stub at ({stub_x:.1f},{stub_y:.1f}) dist={dist:.2f}mm < {required_clearance:.2f}mm")
# Determine which direction to angle based on stub position
# Cross product: positive means stub is on left (+angle side)
stub_vec_x = stub_x - center_x
stub_vec_y = stub_y - center_y
cross = dir_x * stub_vec_y - dir_y * stub_vec_x
# Angle away from stub: if stub on left (cross > 0), go negative angle
preferred_sign = -1 if cross > 0 else 1
# Find the best angle that clears
best_clearing_angle = None
for cand in other_candidates:
if cand[4] * preferred_sign > 0 and cand[5] >= required_clearance:
best_clearing_angle = cand
if config.verbose:
print(f" {label} {cand[4]:+.1f}°: OK (cleared to {cand[5]:.2f}mm)")
break
if best_clearing_angle:
# Put clearing angle first, then 0°, then others
remaining = [c for c in other_candidates if c != best_clearing_angle]
return [best_clearing_angle, (gx, gy, dx, dy, 0.0, dist)] + remaining
else:
# No angle clears - use 0° as primary anyway
if config.verbose:
print(f" {label} using 0.0° (no angle clears {required_clearance:.2f}mm)")
return [(gx, gy, dx, dy, 0.0, dist)] + other_candidates
# 0° is blocked - find any valid angle, prefer smaller angles
if config.verbose:
print(f" {label} 0.0°: blocked")
valid_candidates = []
for angle_deg in sorted(angles_deg, key=abs):
if angle_deg == 0:
continue
result = check_angle_valid(angle_deg)
if result:
gx, gy, dx, dy, x, y = result
dist, _, _ = find_nearest_stub(x, y)
valid_candidates.append((gx, gy, dx, dy, angle_deg, dist))
if config.verbose:
print(f" {label} {angle_deg:+.1f}°: OK (dist={dist:.2f}mm)")
if not valid_candidates:
print(f" Error: {label} - no valid position at setback={setback:.2f}mm (all angles blocked)")
return []
# Sort by clearance (larger better), then by angle magnitude (smaller better)
valid_candidates.sort(key=lambda c: (c[5], -abs(c[4])), reverse=True)
return valid_candidates
def _collect_setback_blocked_cells(center_x, center_y, dir_x, dir_y, layer_idx, setback,
config, obstacles, connector_obstacles, coord):
"""Collect blocked cells at setback positions for rip-up analysis.
Called only after _find_open_positions returns empty list.
"""
max_angle = config.max_setback_angle
angles_deg = [0,
max_angle / 4, -max_angle / 4,
max_angle / 2, -max_angle / 2,
3 * max_angle / 4, -3 * max_angle / 4,
max_angle, -max_angle]
blocked = []
step = config.grid_step / 2
for angle_deg in angles_deg:
angle_rad = math.radians(angle_deg)
cos_a = math.cos(angle_rad)
sin_a = math.sin(angle_rad)
dx = dir_x * cos_a - dir_y * sin_a
dy = dir_x * sin_a + dir_y * cos_a
x = center_x + dx * setback
y = center_y + dy * setback
gx, gy = coord.to_grid(x, y)
# Collect blocked setback position
if obstacles.is_blocked(gx, gy, layer_idx):
if (gx, gy, layer_idx) not in blocked:
blocked.append((gx, gy, layer_idx))
# Collect blocked cells along connector path
length = math.sqrt((x - center_x)**2 + (y - center_y)**2)
if length > 0:
path_dx = (x - center_x) / length
path_dy = (y - center_y) / length
dist = 0.0
while dist <= length:
px = center_x + path_dx * dist
py = center_y + path_dy * dist
pgx, pgy = coord.to_grid(px, py)
if connector_obstacles.is_blocked(pgx, pgy, layer_idx):
if (pgx, pgy, layer_idx) not in blocked:
blocked.append((pgx, pgy, layer_idx))
dist += step
# Also collect "probe ahead" blocked cells (3 grid cells ahead of setback)
# This catches cases where setback and connector are clear but routing direction is blocked
probe_dist = config.grid_step * 3
probe_x = x + dx * probe_dist
probe_y = y + dy * probe_dist
probe_gx, probe_gy = coord.to_grid(probe_x, probe_y)
if obstacles.is_blocked(probe_gx, probe_gy, layer_idx):
if (probe_gx, probe_gy, layer_idx) not in blocked:
blocked.append((probe_gx, probe_gy, layer_idx))
return blocked
def _detect_polarity(simplified_path, coord,
p_src_x, p_src_y, n_src_x, n_src_y,
p_tgt_x, p_tgt_y, n_tgt_x, n_tgt_y,
config):
"""
Detect which side of the centerline P should be on and whether polarity swap is needed.
Args:
simplified_path: List of (gx, gy, layer) representing simplified centerline
coord: GridCoord for coordinate conversion
p_src_x, p_src_y: P source position in mm
n_src_x, n_src_y: N source position in mm
p_tgt_x, p_tgt_y: P target position in mm
n_tgt_x, n_tgt_y: N target position in mm
config: Routing config (for fix_polarity flag)
Returns:
(p_sign, polarity_fixed, polarity_swap_needed, has_layer_change)
- p_sign: +1 or -1, which perpendicular side P should be offset to
- polarity_fixed: True if we'll swap target pads in output
- polarity_swap_needed: True if source and target polarities differ
- has_layer_change: True if path has vias (layer changes)
"""
# Determine which side of the centerline P is on
# Use the first segment direction of the simplified path
if len(simplified_path) >= 2:
first_gx, first_gy, _ = simplified_path[0]
second_gx, second_gy, _ = simplified_path[1]
first_x, first_y = coord.to_float(first_gx, first_gy)
second_x, second_y = coord.to_float(second_gx, second_gy)
path_dir_x = second_x - first_x
path_dir_y = second_y - first_y
else:
path_dir_x, path_dir_y = 1.0, 0.0
# Vector from source midpoint to P source position
src_midpoint_x = (p_src_x + n_src_x) / 2
src_midpoint_y = (p_src_y + n_src_y) / 2
to_p_dx = p_src_x - src_midpoint_x
to_p_dy = p_src_y - src_midpoint_y
# Cross product: determines which side of the path direction P is on at source
src_cross = path_dir_x * to_p_dy - path_dir_y * to_p_dx
src_p_sign = +1 if src_cross >= 0 else -1
# Calculate target polarity using path direction at target end
# Path arrives at target, so use negative of last segment direction
if len(simplified_path) >= 2:
last_gx1, last_gy1, _ = simplified_path[-2]
last_gx2, last_gy2, _ = simplified_path[-1]
last_cx1, last_cy1 = coord.to_float(last_gx1, last_gy1)
last_cx2, last_cy2 = coord.to_float(last_gx2, last_gy2)
last_len = math.sqrt((last_cx2 - last_cx1)**2 + (last_cy2 - last_cy1)**2)
if last_len > 0.001:
tgt_path_dir_x = (last_cx2 - last_cx1) / last_len
tgt_path_dir_y = (last_cy2 - last_cy1) / last_len
else:
tgt_path_dir_x, tgt_path_dir_y = path_dir_x, path_dir_y
else:
tgt_path_dir_x, tgt_path_dir_y = path_dir_x, path_dir_y
# Vector from target midpoint to P target position
tgt_midpoint_x = (p_tgt_x + n_tgt_x) / 2
tgt_midpoint_y = (p_tgt_y + n_tgt_y) / 2
tgt_to_p_dx = p_tgt_x - tgt_midpoint_x
tgt_to_p_dy = p_tgt_y - tgt_midpoint_y
# Cross product: determines which side of the path direction P is on at target
tgt_cross = tgt_path_dir_x * tgt_to_p_dy - tgt_path_dir_y * tgt_to_p_dx
tgt_p_sign = +1 if tgt_cross >= 0 else -1
# Check if polarity differs between source and target
polarity_swap_needed = (src_p_sign != tgt_p_sign)
# Check if path has layer changes (vias)
has_layer_change = False
for i in range(len(simplified_path) - 1):
if simplified_path[i][2] != simplified_path[i + 1][2]:
has_layer_change = True
break
# Handle polarity fix - mark for pad/stub net swap in output file
# We DON'T swap coordinates here - instead we'll swap target pad and stub nets
# This preserves the P→P, N→N geometry and fixes polarity at the schematic level
polarity_fixed = False
if polarity_swap_needed and config.fix_polarity:
print(f" Polarity swap needed - will swap target pad and stub nets in output")
polarity_fixed = True
# Always use source polarity
p_sign = src_p_sign
return p_sign, polarity_fixed, polarity_swap_needed, has_layer_change
def _calculate_parallel_extension(p_stub, n_stub, p_route, n_route, stub_dir, p_sign):
"""Calculate extensions for P and N tracks to make their connectors parallel.
The key insight: for connectors to be parallel, the extending track must
extend along the stub direction until its connector is parallel to the
non-extended track's connector.
Formula derivation:
- V_p = R_p - S_p (direct connector for P)
- V_n = R_n - S_n (direct connector for N)
- For P extended by E: V_p' = V_p - E*D
- For V_p' || V_n: (V_p - E*D) × V_n = 0
- E = (V_p × V_n) / (D × V_n)
Returns (p_extension, n_extension) where one will be positive, the other 0.
"""
dx, dy = stub_dir
# Direct connector vectors
v_p = (p_route[0] - p_stub[0], p_route[1] - p_stub[1])
v_n = (n_route[0] - n_stub[0], n_route[1] - n_stub[1])
# Cross product of connector vectors: tells us if connectors are already parallel
# and which direction the divergence is
v_cross = v_p[0] * v_n[1] - v_p[1] * v_n[0]
# If connectors are nearly parallel, no extension needed
if abs(v_cross) < 0.0001:
return 0.0, 0.0
# Cross product D × V_n (for extending P)
d_cross_vn = dx * v_n[1] - dy * v_n[0]
# Cross product D × V_p (for extending N)
d_cross_vp = dx * v_p[1] - dy * v_p[0]
# Calculate extensions for both tracks
# E_p = (V_p × V_n) / (D × V_n) makes V_p' parallel to V_n
# E_n = (V_n × V_p) / (D × V_p) = -v_cross / d_cross_vp makes V_n' parallel to V_p
p_ext = v_cross / d_cross_vn if abs(d_cross_vn) > 0.0001 else 0.0
n_ext = -v_cross / d_cross_vp if abs(d_cross_vp) > 0.0001 else 0.0
# Use whichever extension is positive (extending in stub direction)
# If both are positive, prefer the one for the "outside" track
if p_ext > 0.001 and n_ext > 0.001:
# Both positive - use the outside track based on geometry
is_p_outside = (v_cross > 0 and p_sign < 0) or (v_cross < 0 and p_sign > 0)
if is_p_outside:
return p_ext, 0.0
else:
return 0.0, n_ext
elif p_ext > 0.001:
return p_ext, 0.0
elif n_ext > 0.001:
return 0.0, n_ext
return 0.0, 0.0
def _create_gnd_vias(simplified_path, coord, config, layer_names, spacing_mm, gnd_net_id, gnd_via_dirs):
"""Create GND vias at layer changes in the centerline path.
Args:
simplified_path: List of (gx, gy, layer_idx) grid points
coord: GridCoord for conversions
config: GridRouteConfig
layer_names: List of layer names
spacing_mm: P/N offset from centerline
gnd_net_id: Net ID for GND vias
gnd_via_dirs: List of directions (+1=ahead, -1=behind) from Rust router
Returns:
List of Via objects for GND connections
"""
gnd_vias = []
if gnd_net_id is None or len(simplified_path) < 2:
return gnd_vias
# Calculate GND via perpendicular offset: track edge + clearance + via radius
# Use max track width for clearance since track width varies by layer
max_track_width = config.get_max_track_width()
gnd_via_perp_mm = spacing_mm + max_track_width/2 + config.clearance + config.via_size/2
via_via_dist_mm = config.via_size + config.clearance
# Track which layer change we're processing to get direction from gnd_via_dirs
via_idx = 0
# Find layer changes in centerline path
for i in range(len(simplified_path) - 1):
gx1, gy1, layer1 = simplified_path[i]
gx2, gy2, layer2 = simplified_path[i + 1]
if layer1 != layer2:
# Layer change - calculate centerline position and direction
cx, cy = coord.to_float(gx1, gy1)
# Get heading direction (from via to next point)
next_cx, next_cy = coord.to_float(gx2, gy2)
dx = next_cx - cx
dy = next_cy - cy
length = math.sqrt(dx*dx + dy*dy)
if length > 0.001:
dx /= length
dy /= length
else:
# Fallback: use direction from previous point
if i > 0:
prev_gx, prev_gy, _ = simplified_path[i - 1]
prev_cx, prev_cy = coord.to_float(prev_gx, prev_gy)
dx = cx - prev_cx
dy = cy - prev_cy
length = math.sqrt(dx*dx + dy*dy)
if length > 0.001:
dx /= length
dy /= length
else:
dx, dy = 1.0, 0.0
else:
dx, dy = 1.0, 0.0
# Perpendicular direction: rotate 90° -> (-dy, dx)
perp_x = -dy
perp_y = dx
# Get GND via direction from Rust router (1=ahead, -1=behind)
gnd_dir = gnd_via_dirs[via_idx] if via_idx < len(gnd_via_dirs) else 1
via_idx += 1
# GND via positions: perpendicular offset + along-heading offset
gnd_p_x = cx + perp_x * gnd_via_perp_mm + dx * via_via_dist_mm * gnd_dir
gnd_p_y = cy + perp_y * gnd_via_perp_mm + dy * via_via_dist_mm * gnd_dir
gnd_n_x = cx - perp_x * gnd_via_perp_mm + dx * via_via_dist_mm * gnd_dir
gnd_n_y = cy - perp_y * gnd_via_perp_mm + dy * via_via_dist_mm * gnd_dir
# Create GND vias (free=True prevents KiCad auto-assigning net)
gnd_vias.append(Via(
x=gnd_p_x, y=gnd_p_y,
size=config.via_size,
drill=config.via_drill,
layers=["F.Cu", "B.Cu"], # Always through-hole
net_id=gnd_net_id,
free=True
))
gnd_vias.append(Via(
x=gnd_n_x, y=gnd_n_y,
size=config.via_size,
drill=config.via_drill,
layers=["F.Cu", "B.Cu"], # Always through-hole
net_id=gnd_net_id,
free=True
))
return gnd_vias
def _make_route_data(pose_path, p_src_x, p_src_y, n_src_x, n_src_y,
p_tgt_x, p_tgt_y, n_tgt_x, n_tgt_y,
src_dir_x, src_dir_y, tgt_dir_x, tgt_dir_y,
src_actual_dir, tgt_actual_dir,
center_src_x, center_src_y, center_tgt_x, center_tgt_y,
via_spacing, src_angle, tgt_angle, gnd_via_dirs=None):
"""Build route_data dictionary with all routing result info."""
return {
'pose_path': pose_path,
'p_src_x': p_src_x, 'p_src_y': p_src_y,
'n_src_x': n_src_x, 'n_src_y': n_src_y,
'p_tgt_x': p_tgt_x, 'p_tgt_y': p_tgt_y,
'n_tgt_x': n_tgt_x, 'n_tgt_y': n_tgt_y,
'src_dir_x': src_dir_x, 'src_dir_y': src_dir_y,
'tgt_dir_x': tgt_dir_x, 'tgt_dir_y': tgt_dir_y,
'src_actual_dir_x': src_actual_dir[0], 'src_actual_dir_y': src_actual_dir[1],
'tgt_actual_dir_x': tgt_actual_dir[0], 'tgt_actual_dir_y': tgt_actual_dir[1],
'center_src_x': center_src_x, 'center_src_y': center_src_y,
'center_tgt_x': center_tgt_x, 'center_tgt_y': center_tgt_y,
'via_spacing': via_spacing,
'best_src_angle': src_angle, 'best_tgt_angle': tgt_angle,
'gnd_via_dirs': gnd_via_dirs if gnd_via_dirs is not None else [],
}
def _generate_debug_arrows(center_src_x, center_src_y, src_dir_x, src_dir_y,
center_tgt_x, center_tgt_y, tgt_dir_x, tgt_dir_y):
"""Generate stub direction arrows for debug visualization (User.4 layer).
Returns list of ((start_x, start_y), (end_x, end_y)) line segments.
"""
arrows = []
arrow_length = 1.0 # mm
head_length = 0.2 # mm
head_angle = 0.5 # radians (~30 degrees)
for mid_x, mid_y, dir_x, dir_y in [
(center_src_x, center_src_y, src_dir_x, src_dir_y),
(center_tgt_x, center_tgt_y, tgt_dir_x, tgt_dir_y)
]:
# Arrow shaft
tip_x = mid_x + dir_x * arrow_length
tip_y = mid_y + dir_y * arrow_length
arrows.append(((mid_x, mid_y), (tip_x, tip_y)))
# Arrowhead lines (two lines from tip, angled back)
cos_a = math.cos(head_angle)
sin_a = math.sin(head_angle)
for sign in [1, -1]:
rot_x = dir_x * cos_a - sign * dir_y * sin_a
rot_y = sign * dir_x * sin_a + dir_y * cos_a
head_end_x = tip_x - rot_x * head_length
head_end_y = tip_y - rot_y * head_length
arrows.append(((tip_x, tip_y), (head_end_x, head_end_y)))
return arrows
def _float_path_to_geometry(float_path, net_id, original_start, original_end, sign,
src_stub_dir, tgt_stub_dir, src_extension, tgt_extension,
config, layer_names):
"""Convert floating-point path (x, y, layer) to segments and vias.
Adds extension segments to ensure P and N connectors are parallel.
Args:
float_path: List of (x, y, layer_idx) tuples
net_id: Network ID for the segments
original_start: (x, y) start position or None
original_end: (x, y) end position or None
sign: +1 or -1 indicating which side of centerline this track is on
src_stub_dir: (dx, dy) stub direction at source (pointing into route area)
tgt_stub_dir: (dx, dy) stub direction at target (pointing into route area)
src_extension: pre-calculated extension length at source end
tgt_extension: pre-calculated extension length at target end
config: GridRouteConfig with track_width, via_size, via_drill, debug_lines
layer_names: List of layer names indexed by layer_idx
Returns:
(segments, vias, connector_lines) tuple
"""
segs = []
vias = []
connector_lines = [] # Debug lines for connectors
num_segments = len(float_path) - 1
# Add connecting segment from original start if needed
if original_start and len(float_path) > 0:
first_x, first_y, first_layer = float_path[0]
orig_x, orig_y = original_start
if abs(orig_x - first_x) > 0.001 or abs(orig_y - first_y) > 0.001:
# Use pre-calculated extension to make P and N connectors parallel
# But skip extension if route start is between stub and extension point
# (otherwise we'd create a U-turn that could cross the other net)
use_extension = False
if src_extension > 0.001:
# Check where route start is relative to stub in stub direction
to_route_x = first_x - orig_x
to_route_y = first_y - orig_y
dot = to_route_x * src_stub_dir[0] + to_route_y * src_stub_dir[1]
# U-turn zone: route is between stub (0) and extension point (src_extension)
# Only use extension if route is NOT in U-turn zone
if dot <= 0.001 or dot >= src_extension - 0.001:
use_extension = True
# Use basic track_width for stub connectors to match stub spacing
first_layer_name = layer_names[first_layer]
if use_extension:
# Add extension segment in stub direction
ext_x = orig_x + src_stub_dir[0] * src_extension
ext_y = orig_y + src_stub_dir[1] * src_extension
segs.append(Segment(
start_x=orig_x, start_y=orig_y,
end_x=ext_x, end_y=ext_y,
width=config.track_width,
layer=first_layer_name,
net_id=net_id
))
# Connector from extension to route
segs.append(Segment(
start_x=ext_x, start_y=ext_y,
end_x=first_x, end_y=first_y,
width=config.track_width,
layer=first_layer_name,
net_id=net_id
))
if config.debug_lines:
connector_lines.append(((orig_x, orig_y), (ext_x, ext_y)))
connector_lines.append(((ext_x, ext_y), (first_x, first_y)))
else:
# No extension needed, direct connector
segs.append(Segment(
start_x=orig_x, start_y=orig_y,
end_x=first_x, end_y=first_y,
width=config.track_width,
layer=first_layer_name,
net_id=net_id
))
if config.debug_lines:
connector_lines.append(((orig_x, orig_y), (first_x, first_y)))
# Convert path segments
for i in range(num_segments):
x1, y1, layer1 = float_path[i]
x2, y2, layer2 = float_path[i + 1]
if layer1 != layer2:
# Layer change - add via
vias.append(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
))
elif abs(x1 - x2) > 0.001 or abs(y1 - y2) > 0.001:
# Always use actual layer for segment
layer_name = layer_names[layer1]
segs.append(Segment(
start_x=x1, start_y=y1,
end_x=x2, end_y=y2,
width=config.get_track_width(layer_name),
layer=layer_name,
net_id=net_id
))
# Add connecting segment to original end if needed
if original_end and len(float_path) > 0:
last_x, last_y, last_layer = float_path[-1]
orig_x, orig_y = original_end
if abs(orig_x - last_x) > 0.001 or abs(orig_y - last_y) > 0.001:
# Use pre-calculated extension to make P and N connectors parallel
# But skip extension if route end is between stub and extension point
# (otherwise we'd create a U-turn that could cross the other net)
use_extension = False
if tgt_extension > 0.001:
# Check where route end is relative to stub in stub direction
# Vector from stub to route end
to_route_x = last_x - orig_x
to_route_y = last_y - orig_y
# Dot product with stub direction - positive means route is in stub direction
dot = to_route_x * tgt_stub_dir[0] + to_route_y * tgt_stub_dir[1]
# U-turn zone: route is between stub (0) and extension point (tgt_extension)
# Only use extension if route is NOT in U-turn zone
# i.e., route is on pad side of stub (dot <= 0) or past extension (dot >= extension)
if dot <= 0.001 or dot >= tgt_extension - 0.001:
use_extension = True
# Use basic track_width for stub connectors to match stub spacing
last_layer_name = layer_names[last_layer]
if use_extension:
# Extend along stub direction (toward route area)
ext_x = orig_x + tgt_stub_dir[0] * tgt_extension
ext_y = orig_y + tgt_stub_dir[1] * tgt_extension
# Connector from route to extension point
segs.append(Segment(
start_x=last_x, start_y=last_y,
end_x=ext_x, end_y=ext_y,
width=config.track_width,
layer=last_layer_name,
net_id=net_id
))
# Extension back to stub endpoint
segs.append(Segment(
start_x=ext_x, start_y=ext_y,
end_x=orig_x, end_y=orig_y,
width=config.track_width,
layer=last_layer_name,
net_id=net_id
))
if config.debug_lines:
connector_lines.append(((last_x, last_y), (ext_x, ext_y)))
connector_lines.append(((ext_x, ext_y), (orig_x, orig_y)))
else:
# No extension needed, direct connector
segs.append(Segment(
start_x=last_x, start_y=last_y,
end_x=orig_x, end_y=orig_y,
width=config.track_width,
layer=last_layer_name,
net_id=net_id
))
if config.debug_lines:
connector_lines.append(((last_x, last_y), (orig_x, orig_y)))
return segs, vias, connector_lines
def get_diff_pair_endpoints(pcb_data: PCBData, p_net_id: int, n_net_id: int,
config: GridRouteConfig) -> Tuple[List, List, str]:
"""
Find source and target endpoints for a differential pair.
Returns:
(sources, targets, error_message)
- sources: List of (p_gx, p_gy, n_gx, n_gy, layer_idx)
- targets: List of (p_gx, p_gy, n_gx, n_gy, layer_idx)
- error_message: None if successful, otherwise describes why routing can't proceed
"""
coord = GridCoord(config.grid_step)
layer_map = build_layer_map(config.layers)
# Get endpoints for P and N nets separately
# Use stub free ends for diff pairs to get the actual stub tips
p_sources, p_targets, p_error = get_net_endpoints(pcb_data, p_net_id, config, use_stub_free_ends=True)
n_sources, n_targets, n_error = get_net_endpoints(pcb_data, n_net_id, config, use_stub_free_ends=True)
if p_error:
return [], [], f"P net: {p_error}"
if n_error:
return [], [], f"N net: {n_error}"
if not p_sources or not p_targets:
return [], [], "P net has no valid source/target endpoints"
if not n_sources or not n_targets:
return [], [], "N net has no valid source/target endpoints"
# Determine source vs target based on proximity between P and N endpoints.
# The "source" side is where P and N endpoints are closest together,
# and "target" side is where the other P and N endpoints are closest.
# This ensures P and N agree on which end is source vs target.
# Combine all P endpoints and all N endpoints (ignoring the source/target
# classification from get_net_endpoints since it may differ between P and N)
p_all = p_sources + p_targets
n_all = n_sources + n_targets
def find_closest_pair(p_endpoints, n_endpoints):
"""Find the P and N endpoints that are closest to each other on same layer."""
best_p, best_n = None, None
best_dist = float('inf')
for p in p_endpoints:
p_gx, p_gy, p_layer = p[0], p[1], p[2]
for n in n_endpoints:
n_gx, n_gy, n_layer = n[0], n[1], n[2]
if n_layer != p_layer:
continue
dist = abs(p_gx - n_gx) + abs(p_gy - n_gy)
if dist < best_dist:
best_dist = dist
best_p, best_n = p, n
return best_p, best_n, best_dist
# Find the closest P-N pair - this becomes one end (we'll call it "source")
p_src, n_src, src_dist = find_closest_pair(p_all, n_all)
if p_src is None or n_src is None:
return [], [], "Could not find matching P and N endpoints on same layer"
# Remove the matched endpoints from consideration
p_remaining = [p for p in p_all if p != p_src]
n_remaining = [n for n in n_all if n != n_src]
if not p_remaining or not n_remaining:
return [], [], "Not enough endpoints for source and target"
# Find the closest P-N pair from remaining - this becomes the other end ("target")
p_tgt, n_tgt, tgt_dist = find_closest_pair(p_remaining, n_remaining)
if p_tgt is None or n_tgt is None:
return [], [], "Could not find matching P and N target endpoints on same layer"
# Build the paired source and target tuples
paired_sources = [(
p_src[0], p_src[1], # P grid coords
n_src[0], n_src[1], # N grid coords
p_src[2], # layer
p_src[3], p_src[4], # P original coords
n_src[3], n_src[4] # N original coords
)]
paired_targets = [(
p_tgt[0], p_tgt[1], # P grid coords
n_tgt[0], n_tgt[1], # N grid coords
p_tgt[2], # layer
p_tgt[3], p_tgt[4], # P original coords
n_tgt[3], n_tgt[4] # N original coords
)]
return paired_sources, paired_targets, None
def create_parallel_path_float(centerline_path, coord, sign, spacing_mm=0.1, start_dir=None, end_dir=None):
"""
Create a path parallel to centerline using floating-point perpendicular offsets.
Uses bisector-based offsets at corners for smooth parallel paths.
Args:
centerline_path: List of (gx, gy, layer) grid coordinates
coord: GridCoord converter for grid<->float
sign: +1 for one track, -1 for the other
spacing_mm: Distance from centerline in mm
start_dir: Optional (dx, dy) direction to use at start point for perpendicular calc
end_dir: Optional (dx, dy) direction to use at end point for perpendicular calc
Returns:
List of (x, y, layer) floating-point coordinates
"""
if len(centerline_path) < 2:
return [(coord.to_float(p[0], p[1])[0], coord.to_float(p[0], p[1])[1], p[2])
for p in centerline_path]
result = []
for i in range(len(centerline_path)):
gx, gy, layer = centerline_path[i]
x, y = coord.to_float(gx, gy)
use_corner_scale = True # Only apply corner scaling for bisector calculations
if i == 0:
# First point: bisector between start_dir (if provided) and first segment
next_x, next_y = coord.to_float(centerline_path[1][0], centerline_path[1][1])
seg_dx, seg_dy = next_x - x, next_y - y
seg_len = math.sqrt(seg_dx*seg_dx + seg_dy*seg_dy) or 1
seg_dx, seg_dy = seg_dx/seg_len, seg_dy/seg_len
if start_dir is not None:
# Normalize start_dir
dir_len = math.sqrt(start_dir[0]**2 + start_dir[1]**2) or 1
norm_start_dx = start_dir[0] / dir_len
norm_start_dy = start_dir[1] / dir_len
# Bisector between start_dir and first segment direction
dx = norm_start_dx + seg_dx
dy = norm_start_dy + seg_dy
use_corner_scale = True # Apply corner scaling at junction
else:
dx, dy = seg_dx, seg_dy
use_corner_scale = False # Single segment, no corner scaling
elif i == len(centerline_path) - 1:
# Last point: bisector between last segment and end_dir (if provided)
prev_x, prev_y = coord.to_float(centerline_path[i-1][0], centerline_path[i-1][1])
seg_dx, seg_dy = x - prev_x, y - prev_y
seg_len = math.sqrt(seg_dx*seg_dx + seg_dy*seg_dy) or 1
seg_dx, seg_dy = seg_dx/seg_len, seg_dy/seg_len
if end_dir is not None:
# Normalize end_dir
dir_len = math.sqrt(end_dir[0]**2 + end_dir[1]**2) or 1
norm_end_dx = end_dir[0] / dir_len
norm_end_dy = end_dir[1] / dir_len
# Bisector between last segment direction and end_dir
dx = seg_dx + norm_end_dx
dy = seg_dy + norm_end_dy
use_corner_scale = True # Apply corner scaling at junction
else:
dx, dy = seg_dx, seg_dy
use_corner_scale = False # Single segment, no corner scaling
else:
# Corner: use bisector of incoming and outgoing directions
prev = centerline_path[i-1]
next_pt = centerline_path[i+1]
if prev[2] != layer or next_pt[2] != layer:
# Layer change - use incoming direction
prev_x, prev_y = coord.to_float(prev[0], prev[1])
dx, dy = x - prev_x, y - prev_y
else:
prev_x, prev_y = coord.to_float(prev[0], prev[1])
next_x, next_y = coord.to_float(next_pt[0], next_pt[1])
dx_in, dy_in = x - prev_x, y - prev_y
dx_out, dy_out = next_x - x, next_y - y
len_in = math.sqrt(dx_in*dx_in + dy_in*dy_in) or 1
len_out = math.sqrt(dx_out*dx_out + dy_out*dy_out) or 1
# Bisector direction (sum of unit vectors)
dx = dx_in/len_in + dx_out/len_out
dy = dy_in/len_in + dy_out/len_out
if abs(dx) < 0.01 and abs(dy) < 0.01:
dx, dy = dx_in, dy_in
# Normalize and compute perpendicular offset
length = math.sqrt(dx*dx + dy*dy) or 1
ndx, ndy = dx/length, dy/length
# Corner compensation: scale offset by 2/length to maintain perpendicular distance
# When summing two unit vectors, length = 2*cos(theta/2) where theta is angle between them
# To maintain spacing_mm perpendicular to each segment, multiply by 2/length
# Cap the scaling to avoid extreme miter extensions at very sharp corners (>135 deg turn)
# Only apply at actual corners (bisector calculations), not at endpoints
if use_corner_scale:
corner_scale = min(2.0 / length, 3.0) if length > 0.1 else 1.0
else:
corner_scale = 1.0
perp_x = -ndy * sign * spacing_mm * corner_scale
perp_y = ndx * sign * spacing_mm * corner_scale
result.append((x + perp_x, y + perp_y, layer))
return result
def create_parallel_path_from_float(centerline_path, sign, spacing_mm=0.1, start_dir=None, end_dir=None):
"""
Create a path parallel to centerline from float coordinates (no grid conversion).
Uses bisector-based offsets at corners for smooth parallel paths.
Args:
centerline_path: List of (x, y, layer) floating-point coordinates
sign: +1 for one track, -1 for the other
spacing_mm: Distance from centerline in mm
start_dir: Optional (dx, dy) direction to use at start point for perpendicular calc
end_dir: Optional (dx, dy) direction to use at end point for perpendicular calc
Returns:
List of (x, y, layer) floating-point coordinates
"""
if len(centerline_path) < 2:
return list(centerline_path)
result = []
for i in range(len(centerline_path)):
x, y, layer = centerline_path[i]
use_corner_scale = True # Only apply corner scaling for bisector calculations
if i == 0:
# First point: bisector between start_dir (if provided) and first segment
next_x, next_y, _ = centerline_path[1]
seg_dx, seg_dy = next_x - x, next_y - y
seg_len = math.sqrt(seg_dx*seg_dx + seg_dy*seg_dy) or 1
seg_dx, seg_dy = seg_dx/seg_len, seg_dy/seg_len
if start_dir is not None:
# Normalize start_dir
dir_len = math.sqrt(start_dir[0]**2 + start_dir[1]**2) or 1
norm_start_dx = start_dir[0] / dir_len
norm_start_dy = start_dir[1] / dir_len
# Bisector between start_dir and first segment direction
dx = norm_start_dx + seg_dx
dy = norm_start_dy + seg_dy
use_corner_scale = True # Apply corner scaling at junction
else: