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
|
"""Routing strategies on top of pcbroute: plane drops, tree routing, component joining.
Typical use (see knowledge/tooling/router.md):
R = Router("board.json") # from dump_board.py
R.route_plane_net("GND") # every SMD ground pad gets its own via to the plane
R.connect("/Comms ETH/XI") # join all copper of a net
R.save("routes.json") # for write_board.py
"""
import sys, time, math, json
import numpy as np
from shapely.geometry import Point, LineString
import pcbroute as P
from pcbroute import Item, Board, cell_xy, xy_cell, RES, CLR, M
# Filled in by Router() from the board dump: net -> class, class -> width / via size.
NETCLASS, WIDTH, VIA, DOMAINS = {}, {"Default": 0.2}, {}, {}
PLANE_NETS = ["GND"]
def pad_minor(poly):
r = poly.minimum_rotated_rectangle
xs, ys = r.exterior.coords.xy
e = [math.hypot(xs[i+1]-xs[i], ys[i+1]-ys[i]) for i in range(2)]
return min(e)
class Router:
def __init__(self, board_json, seeds=(), plane_nets=("GND",), domains=None):
d = json.load(open(board_json)) if isinstance(board_json, str) else board_json
P.setup(*d["bounds"])
NETCLASS.clear(); NETCLASS.update(d.get("netclass", {}))
WIDTH.update({k: v["track"] for k, v in d.get("classes", {}).items()})
VIA.update({k: v["via"] for k, v in d.get("classes", {}).items() if v["via"] != 0.6})
PLANE_NETS[:] = list(plane_nets)
DOMAINS.clear(); DOMAINS.update(domains or {})
self.B = Board(d, NETCLASS, DOMAINS, plane_nets=plane_nets)
self.B.build_static(domain_seeds=seeds)
self.log = []
self.net_items = {} # net -> list of committed items
self.connected = {} # net -> set of pad indexes connected to the main tree
self.failed = []
self.pads_by_net = {}
for k, p in enumerate(self.B.pads):
if p["net"] >= 0: self.pads_by_net.setdefault(p["net"], []).append(k)
def nid(self, name): return self.B.netid[name]
def cls(self, name): return NETCLASS.get(name, "Default")
# ----- congestion estimate (RUDY over MST edges of signal nets) -----
def build_rudy(self, weight=8.0, exclude=()):
B = self.B
R = np.zeros((P.NY, P.NX), np.float32)
for net, idx in self.pads_by_net.items():
name = B.netname[net]
if name in PLANE_NETS or name in exclude: continue
pts = [(B.pads[k]["x"], B.pads[k]["y"]) for k in idx]
for (a, b) in mst(pts):
x0, x1 = sorted((a[0], b[0])); y0, y1 = sorted((a[1], b[1]))
x0 -= 0.4; x1 += 0.4; y0 -= 0.4; y1 += 0.4
dens = ((x1 - x0) + (y1 - y0)) / ((x1 - x0) * (y1 - y0)) * 0.25
i0, j0 = xy_cell(x0, y0); i1, j1 = xy_cell(x1, y1)
R[max(j0,0):j1+1, max(i0,0):i1+1] += dens
self.rudy = R
return R
def set_cost(self, F=None, Bc=None):
self.B.cost[0] = 0 if F is None else F
self.B.cost[1] = 0 if Bc is None else Bc
# ----- helpers -----
def item_containing(self, items, xy, L):
best = None
for it in items:
if L not in it.layers: continue
if it.kind == "pad":
if it.geom.contains(Point(xy)) or it.geom.distance(Point(xy)) < 1e-6: return it
else:
d = it.dist(np.array([xy[0]]), np.array([xy[1]]))[0]
if d <= 1e-6: best = it
return best
def end_stub(self, it, xy, L, w):
if it is None: return None
if it.kind == "pad":
c = it.geom.centroid
if math.hypot(c.x - xy[0], c.y - xy[1]) < 1e-6: return None
wd = min(w, pad_minor(it.geom))
return (L, xy, (c.x, c.y), wd)
if it.kind == "via":
if it.owner and it.owner[0] == "wp": return None
x, y = it.geom
if math.hypot(x - xy[0], y - xy[1]) < 1e-6: return None
return (L, xy, (x, y), min(w, it.w))
if it.kind == "seg":
(x1, y1), (x2, y2) = it.geom
ls = LineString([(x1, y1), (x2, y2)])
q = ls.interpolate(ls.project(Point(xy)))
if math.hypot(q.x - xy[0], q.y - xy[1]) < 1e-6: return None
return (L, xy, (q.x, q.y), min(w, it.w))
def do_route(self, net, src_items, tgt_items, w, wneck, via_d, goal_layer1=False, extra_tgt=None, tag=None, **kw):
B = self.B
neck_items = [it for it in list(tgt_items or []) + list(src_items) if it.kind == "pad"][:60]
r = B.route(net, src_items, tgt_items, goal_layer1=goal_layer1, w=w, wneck=wneck, via_d=via_d,
neck_items=neck_items, extra_tgt_cells=extra_tgt, **kw)
if r is None: return None
path, neck = r
segs, vias = B.path_to_geom(net, path, neck, w, wneck, via_d)
# stubs at both ends
s0 = int(path[0]); s1 = int(path[-1])
L0, c0 = s0 // P.N, s0 % P.N; L1, c1 = s1 // P.N, s1 % P.N
xy0 = cell_xy(c0 % P.NX, c0 // P.NX); xy1 = cell_xy(c1 % P.NX, c1 // P.NX)
w0 = wneck if (wneck and neck[0]) else w
w1 = wneck if (wneck and neck[-1]) else w
st = []
a = self.end_stub(self.item_containing(src_items, xy0, L0), xy0, L0, w0)
a = self.safe_stub(net, a)
if a: st.append(a)
tl = list(tgt_items or []) + [it for it in self.net_items.get(net, [])]
b = self.end_stub(self.item_containing(tl, xy1, L1), xy1, L1, w1)
b = self.safe_stub(net, b)
if b: st.append(b)
items = B.commit(net, segs + st, vias, via_d, tag)
self.net_items.setdefault(net, []).extend(items)
return items
# ----- plane nets: drop each top SMD pad to the bottom plane -----
def route_plane_net(self, name, w=0.4, wneck=0.25, via_cost=12.0, via_cmult=2.0, order=None, only=None, skip=(), extra_planed=()):
B = self.B; net = self.nid(name)
idx = self.pads_by_net[net]
smd = [k for k in idx if not B.pads[k]["tht"] and (only is None or (B.pads[k]["ref"], B.pads[k]["num"]) in only)
and (B.pads[k]["ref"], B.pads[k]["num"]) not in skip]
# big pads (exposed pads) first
smd.sort(key=lambda k: -B.pads[k]["poly"].area)
planed = [B.pads[k]["item"] for k in idx if B.pads[k]["tht"]] + [it for it in self.net_items.get(net, []) if it.kind == "via"] + list(extra_planed)
nf = 0
for k in smd:
p = B.pads[k]
if self.touches(p["item"], planed):
continue
bb = p["poly"].bounds
if bb[2] - bb[0] > 2.5 and bb[3] - bb[1] > 2.5:
c = p["poly"].centroid
items = B.commit(net, [], [(round((c.x - P.X0) / RES) * RES + P.X0, round((c.y - P.Y0) / RES) * RES + P.Y0)], 0.6, ("plane", name))
self.net_items.setdefault(net, []).extend(items)
planed += items + [p["item"]]
continue
tgt_cells = B.cells_of(planed, layers=(0,)) if planed else None
items = self.do_route(net, [p["item"]], [], w, wneck, 0.6, goal_layer1=True, extra_tgt=tgt_cells,
via_cost=via_cost, via_cmult=via_cmult, bmult=50.0, turn=2.0, tag=("plane", name))
if items is None:
self.failed.append((name, p["ref"], p["num"])); nf += 1; continue
planed += items + [p["item"]]
self.log.append((name, "plane pads", len(smd), "failed", nf))
def safe_stub(self, net, st):
"""Keep a stub only where its copper clears every foreign item exactly; narrow it if needed."""
if st is None: return None
L, a, b, w = st
line = LineString([a, b])
x0, y0, x1, y1 = line.bounds
foreign = [it for it in self.B.items if it.net != net and L in it.layers and
it.bbox[0] < x1 + 1 and it.bbox[2] > x0 - 1 and it.bbox[1] < y1 + 1 and it.bbox[3] > y0 - 1]
shapes = [item_shape(it) for it in foreign]
for wd in (w, 0.25, 0.2):
if wd > w: continue
if all(line.distance(sh) >= wd / 2 + CLR + 0.005 for sh in shapes):
return (L, a, b, wd)
return None
def touches(self, it, items):
for o in items:
if o.kind == "pad" and it.kind == "pad":
if it.geom.distance(o.geom) < 1e-6: return True
return False
# ----- tree routing for an ordinary net -----
def route_tree(self, name, root=None, w=None, wneck=None, via_d=None, **kw):
B = self.B; net = self.nid(name)
c = self.cls(name)
w = w or WIDTH[c]
if wneck is None: wneck = 0.2 if w > 0.2 else 0.0
via_d = via_d or VIA.get(c, 0.6)
idx = list(self.pads_by_net[net])
if root is None:
root = idx[0]
else:
root = [k for k in idx if (B.pads[k]["ref"], B.pads[k]["num"]) == root][0]
tree_pads = {root}
tree_items = [B.pads[root]["item"]]
# pads that physically overlap tree copper are already connected
def absorb():
changed = True
while changed:
changed = False
for k in idx:
if k in tree_pads: continue
pi = B.pads[k]["item"]
for it in tree_items:
if set(it.layers) & set(pi.layers) and (pi.geom.distance(Point(it.geom) if it.kind == "via" else (LineString(it.geom) if it.kind == "seg" else it.geom)) <= (it.w / 2 if it.kind != "pad" else 0) + 1e-6):
tree_pads.add(k); tree_items.append(pi); changed = True; break
absorb()
tries = {}
nfail = 0
while len(tree_pads) < len(idx):
# nearest unconnected pad to the tree
best = None
for k in idx:
if k in tree_pads or tries.get(k, 0) >= 1: continue
p = B.pads[k]
dmin = min(math.hypot(p["x"] - B.pads[t]["x"], p["y"] - B.pads[t]["y"]) for t in tree_pads)
if best is None or dmin < best[0]: best = (dmin, k)
if best is None: break
k = best[1]; tries[k] = tries.get(k, 0) + 1
items = self.do_route(net, tree_items, [B.pads[k]["item"]], w, wneck, via_d, tag=("tree", name), **kw)
if items is None:
nfail += 1; self.failed.append((name, B.pads[k]["ref"], B.pads[k]["num"]))
continue
tree_items.extend(items)
tree_pads.add(k); tree_items.append(B.pads[k]["item"])
absorb()
self.log.append((name, "pads", len(idx), "unrouted", len(idx) - len(tree_pads)))
return len(idx) - len(tree_pads)
def rip_net(self, name):
"""Remove the router's copper of a net (kept existing copper stays)."""
net = self.nid(name)
items = self.net_items.pop(net, [])
keep = [it for it in items if it.owner and it.owner[0] == "existing"]
self.B.remove_items([it for it in items if not (it.owner and it.owner[0] == "existing")])
if keep:
self.net_items[net] = keep
self.failed = [f for f in self.failed if f[0] != name]
# ----- export -----
def geometry(self):
segs, vias = [], []
for net, items in self.net_items.items():
name = self.B.netname[net]
for it in items:
if it.kind == "seg":
(a, b) = it.geom
segs.append(dict(net=name, layer="F.Cu" if it.layers[0] == 0 else "B.Cu", x1=a[0], y1=a[1], x2=b[0], y2=b[1], w=it.w))
elif it.kind == "via":
vias.append(dict(net=name, x=it.geom[0], y=it.geom[1], d=it.w, drill=0.4 if it.w >= 0.8 else 0.3))
return segs, vias
def save(self, path):
segs, vias = self.geometry()
json.dump(dict(segs=segs, vias=vias, failed=self.failed, log=self.log), open(path, "w"), indent=0)
def load(self, path):
d = json.load(open(path))
B = self.B
for s in d["segs"]:
net = self.nid(s["net"])
it = Item("seg", net, (0 if s["layer"] == "F.Cu" else 1,), ((s["x1"], s["y1"]), (s["x2"], s["y2"])), w=s["w"], owner=("load",))
B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it)
for v in d["vias"]:
net = self.nid(v["net"])
it = Item("via", net, (0, 1), (v["x"], v["y"]), w=v["d"], owner=("load",))
B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it)
self.failed = [tuple(f) for f in d["failed"]]
def load_existing(self, d, keep=lambda t: True):
"""Add tracks/vias from a board dump as fixed copper (they are saved with the result)."""
B = self.B
for s in d.get("tracks", []):
if s["net"] not in B.netid or not keep(s): continue
net = self.nid(s["net"])
it = Item("seg", net, (0 if s["layer"] == "F.Cu" else 1,), ((s["x1"], s["y1"]), (s["x2"], s["y2"])), w=s["w"], owner=("existing",))
B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it)
for v in d.get("vias", []):
if v["net"] not in B.netid or not keep(v): continue
net = self.nid(v["net"])
it = Item("via", net, (0, 1), (v["x"], v["y"]), w=v["d"], owner=("existing",))
B.items.append(it); B.insert(it); self.net_items.setdefault(net, []).append(it)
Router.load_existing = load_existing
def mst(pts):
n = len(pts)
if n < 2: return []
inT = [False] * n; inT[0] = True
dist = [math.hypot(pts[i][0] - pts[0][0], pts[i][1] - pts[0][1]) for i in range(n)]
par = [0] * n; edges = []
for _ in range(n - 1):
k = min((i for i in range(n) if not inT[i]), key=lambda i: dist[i])
inT[k] = True; edges.append((pts[par[k]], pts[k]))
for i in range(n):
if not inT[i]:
d = math.hypot(pts[i][0] - pts[k][0], pts[i][1] - pts[k][1])
if d < dist[i]: dist[i] = d; par[i] = k
return edges
def _wp(net, x, y, L):
return Item("via", net, (L,), (x, y), w=0.12, owner=("wp",))
def route_waypoints(self, name, root, wps, w, wneck, via_d, **kw):
"""Route a trunk from the root pad through waypoints [(x, y, layer)]; returns tree items."""
B = self.B; net = self.nid(name)
idx = self.pads_by_net[net]
rk = [k for k in idx if (B.pads[k]["ref"], B.pads[k]["num"]) == root][0]
tree = [B.pads[rk]["item"]] + list(self.net_items.get(net, []))
for (x, y, L) in wps:
wp = _wp(net, x, y, L)
items = self.do_route(net, tree, [wp], w, wneck, via_d, tag=("trunk", name), **kw)
if items is None:
print("waypoint failed", name, x, y); return None
tree += items
return tree
Router.route_waypoints = route_waypoints
def route_tree_from(self, name, tree_items, w=None, wneck=None, via_d=None, skip=(), **kw):
"""Prim-style completion of a net from existing tree items."""
B = self.B; net = self.nid(name)
c = self.cls(name)
w = w or WIDTH[c]
if wneck is None: wneck = 0.2 if w > 0.2 else 0.0
via_d = via_d or VIA.get(c, 0.6)
idx = [k for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) not in skip]
tree_items = list(tree_items)
tree_pads = set()
def absorb():
changed = True
while changed:
changed = False
for k in idx:
if k in tree_pads: continue
pi = B.pads[k]["item"]
for it in tree_items:
if it is pi: tree_pads.add(k); changed = True; break
if not (set(it.layers) & set(pi.layers)): continue
g = Point(it.geom) if it.kind == "via" else (LineString(it.geom) if it.kind == "seg" else it.geom)
if pi.geom.distance(g) <= (it.w / 2 if it.kind != "pad" else 0) + 1e-6:
tree_pads.add(k); tree_items.append(pi); changed = True; break
absorb()
pts = []
for it in tree_items:
if it.kind == "seg": pts += list(it.geom)
elif it.kind == "via": pts.append(it.geom)
else: c0 = it.geom.centroid; pts.append((c0.x, c0.y))
tries = set()
while True:
cand = [k for k in idx if k not in tree_pads and k not in tries]
if not cand: break
P = np.array(pts)
best = min(cand, key=lambda k: np.min(np.hypot(P[:, 0] - B.pads[k]["x"], P[:, 1] - B.pads[k]["y"])))
tries.add(best)
items = self.do_route(net, tree_items, [B.pads[best]["item"]], w, wneck, via_d, tag=("tree", name), **kw)
if items is None:
self.failed.append((name, B.pads[best]["ref"], B.pads[best]["num"])); continue
tree_items.extend(items); tree_items.append(B.pads[best]["item"]); tree_pads.add(best)
for it in items:
if it.kind == "seg": pts += list(it.geom)
elif it.kind == "via": pts.append(it.geom)
c0 = B.pads[best]["item"].geom.centroid; pts.append((c0.x, c0.y))
absorb()
un = len(idx) - len(tree_pads)
self.log.append((name, "pads", len(idx), "unrouted", un))
return tree_items
Router.route_tree_from = route_tree_from
# ---------------- component-based net completion ----------------
from shapely.strtree import STRtree
def item_shape(it):
if it.kind == "pad": return it.geom
if it.kind == "seg": return LineString(it.geom).buffer(it.w / 2, quad_segs=4)
return Point(it.geom).buffer(it.w / 2, quad_segs=4)
def components(items):
shapes = [item_shape(i) for i in items]
tree = STRtree(shapes)
par = list(range(len(items)))
def f(a):
while par[a] != a: par[a] = par[par[a]]; a = par[a]
return a
for i, s in enumerate(shapes):
for j in tree.query(s.buffer(1e-4)):
j = int(j)
if j <= i: continue
if not (set(items[i].layers) & set(items[j].layers)): continue
if s.distance(shapes[j]) <= 1e-4:
a, b = f(i), f(j)
if a != b: par[a] = b
groups = {}
for i in range(len(items)): groups.setdefault(f(i), []).append(items[i])
return list(groups.values())
def net_items_all(self, net, pads_only_subset=None):
B = self.B
pads = [B.pads[k]["item"] for k in self.pads_by_net[net]]
return pads + list(self.net_items.get(net, []))
def comp_pts(comp):
pts = []
for it in comp:
if it.kind == "seg": pts += list(it.geom)
elif it.kind == "via": pts.append(it.geom)
else:
c = it.geom.centroid; pts.append((c.x, c.y))
return np.array(pts)
def connect(self, name, root=None, pads=None, w=None, wneck=None, via_d=None, max_tries=2, **kw):
"""Join all copper of a net (or only the components containing `pads`) into one."""
B = self.B; net = self.nid(name)
c = self.cls(name)
w = w or WIDTH[c]
if wneck is None: wneck = 0.2 if w > 0.2 else 0.0
via_d = via_d or VIA.get(c, 0.6)
def padit(rn):
return [B.pads[k]["item"] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(rn)][0]
tries = {}
while True:
comps = components(net_items_all(self, net))
if pads is not None:
want = [padit(p) for p in pads]
comps = [cp for cp in comps if any(any(x is it for x in cp) for it in want)]
if len(comps) <= 1: break
if root is not None:
ri = padit(root)
main = [cp for cp in comps if any(x is ri for x in cp)][0]
else:
main = max(comps, key=len)
others = [cp for cp in comps if cp is not main and tries.get(id(cp[0]), 0) < max_tries]
if not others: break
P = comp_pts(main)
def dist(cp):
Q = comp_pts(cp)
return np.min(np.hypot(P[:, None, 0] - Q[None, :, 0], P[:, None, 1] - Q[None, :, 1]))
tgt = min(others, key=dist)
tries[id(tgt[0])] = tries.get(id(tgt[0]), 0) + 1
# heuristic point: nearest point of target to main
Q = comp_pts(tgt)
dd = np.min(np.hypot(Q[:, None, 0] - P[None, :, 0], Q[:, None, 1] - P[None, :, 1]), axis=1)
q = Q[int(np.argmin(dd))]
items = self.do_route(net, main, tgt, w, wneck, via_d, tag=("conn", name), hxy=(q[0], q[1]), **kw)
if items is None:
tp = [it for it in tgt if it.kind == "pad"]
lab = tp[0].owner[1:] if tp else ("copper",)
self.failed.append((name,) + tuple(lab))
comps = components(net_items_all(self, net))
self.log.append((name, "components", len(comps)))
return len(comps)
Router.connect = connect
def place_via(self, name, x, y, d=0.6):
B = self.B; net = self.nid(name)
i, j = xy_cell(x, y); x, y = cell_xy(i, j)
for L in (0, 1):
s = L * P.N + j * P.NX + i
fd = B.d2.ravel()[s] if B.n1.ravel()[s] == net else B.d1.ravel()[s]
if fd < d / 2 + CLR + M:
print("via blocked", name, x, y, fd); return None
items = B.commit(net, [], [(x, y)], d, ("via", name))
self.net_items.setdefault(net, []).extend(items)
return items[0]
Router.place_via = place_via
def cap_value_uf(v):
import re
m = re.match(r"\s*([\d.]+)\s*([pnuµm]?)F?", v or "")
if not m:
return 0.0
return float(m.group(1)) * {"p": 1e-6, "n": 1e-3, "u": 1, "µ": 1, "m": 1e3, "": 1}[m.group(2)]
def connect_decaps(self, name, **kw):
"""Join each decoupling cap on net `name` to its nearest IC pin before the rest of the net.
A cap is a 2-pad C* part with its other pad on a plane net. Candidates are pins of parts
with >= 4 pads; bulk caps (>= 4.7 uF) may also go to an inductor or ferrite (L*, FB*).
"""
B = self.B; net = self.nid(name)
pads = [B.pads[k] for k in self.pads_by_net[net]]
for p in pads:
f = B.fps[p["ref"]]
if not p["ref"].startswith("C"):
continue
other = [q for q in B.pads if q["ref"] == p["ref"] and q is not p]
if len(other) != 1 or other[0]["net"] < 0 or B.netname[other[0]["net"]] not in PLANE_NETS:
continue
nfp = {}
for q in B.pads:
nfp[q["ref"]] = nfp.get(q["ref"], 0) + 1
bulk = cap_value_uf(f["value"]) >= 4.7
cand = [q for q in pads if q["ref"] != p["ref"] and (nfp[q["ref"]] >= 4 and not q["ref"].startswith(("J", "TP"))
or (bulk and q["ref"].startswith(("L", "FB"))))]
if not cand:
continue
q = min(cand, key=lambda q: math.hypot(q["x"] - p["x"], q["y"] - p["y"]))
self.route_pair(name, (p["ref"], p["num"]), (q["ref"], q["num"]), **kw)
Router.connect_decaps = connect_decaps
def route_pair(self, name, a, b, w=None, wneck=None, via_d=None, **kw):
"""Route pad a to pad b directly (connect() would join to the nearest copper of the net)."""
B = self.B; net = self.nid(name)
c = self.cls(name)
w = w or WIDTH.get(c, 0.2)
if wneck is None: wneck = 0.2 if w > 0.2 else 0.0
via_d = via_d or VIA.get(c, 0.6)
pa = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(a)][0]
pb = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(b)][0]
if any(x is pb["item"] for cp in components(net_items_all(self, net)) if any(y is pa["item"] for y in cp) for x in cp):
return True
items = self.do_route(net, [pa["item"]], [pb["item"]], w, wneck, via_d, tag=("pair", name), **kw)
if items is None:
self.failed.append((name,) + tuple(b))
return False
return True
Router.route_pair = route_pair
def stitch(self, name, pitch=5.0, d=0.6, box=None):
"""Stitching vias on a grid wherever a via of net `name` clears all foreign copper,
keep-outs and the board edge on both layers, and does not land in a pad."""
B = self.B; net = self.nid(name)
x0, y0, x1, y1 = box or (P.X0, P.Y0, P.X1, P.Y1)
placed = []
r = d / 2 + CLR + M
y = y0 + pitch / 2
while y < y1:
x = x0 + pitch / 2
while x < x1:
i, j = xy_cell(x, y)
ok = True
for L in (0, 1):
s = L * P.N + j * P.NX + i
fd = B.d2.ravel()[s] if B.n1.ravel()[s] == net else B.d1.ravel()[s]
if fd < r or B.padd.ravel()[s] < d / 2 + 0.05 or B.n1.ravel()[s] == net and B.d1.ravel()[s] < d / 2 + 0.3:
ok = False
if ok:
placed += B.commit(net, [], [cell_xy(i, j)], d, ("stitch", name))
x += pitch
y += pitch
self.net_items.setdefault(net, []).extend(placed)
self.log.append((name, "stitching vias", len(placed)))
return placed
Router.stitch = stitch
def tie(self, name, pad, xy, w=None, d=0.6, **kw):
"""Tie a pad to a new via at xy (e.g. a THT ground pad that pours may not reach once
tracks close in around it). Run it before the tracks that would close it in."""
B = self.B; net = self.nid(name)
v = self.place_via(name, xy[0], xy[1], d)
if v is None:
self.failed.append((name,) + tuple(pad)); return False
p = [B.pads[k] for k in self.pads_by_net[net] if (B.pads[k]["ref"], B.pads[k]["num"]) == tuple(pad)][0]
items = self.do_route(net, [p["item"]], [v], w or WIDTH.get(self.cls(name), 0.2), 0.0, d, tag=("tie", name), **kw)
if items is None:
self.failed.append((name,) + tuple(pad)); return False
return True
Router.tie = tie
# ---------------- rip-up and reroute ----------------
def route_net(self, name, cost=None, pads=None, **kw):
"""connect() that remembers its cost maps and arguments, so repair() can redo it."""
self.registry = getattr(self, "registry", {})
self.registry.setdefault(name, []).append((cost, pads, kw))
if cost is not None:
self.set_cost(**cost)
return self.connect(name, pads=pads, **kw)
Router.route_net = route_net
def _redo(self, name):
for cost, pads, kw in self.registry.get(name, [(None, None, {})]):
if cost is not None:
self.set_cost(**cost)
self.connect(name, pads=pads, **kw)
def split_nets(self, skip=()):
"""Nets (by name) whose copper is still in more than one piece."""
out = []
for net, idx in self.pads_by_net.items():
name = self.B.netname[net]
if name in skip or len(idx) < 2:
continue
if len(components(net_items_all(self, net))) > 1:
out.append(name)
return out
Router.split_nets = split_nets
def repair(self, rounds=4, radius=1.2, protect=(), skip=("GND",)):
"""Rip-up and reroute: for each split net, remove the nets with copper within `radius`
of its unconnected pieces, route it first, then route the removed nets again.
Only nets routed through route_net() are ripped; `protect` nets are never ripped."""
B = self.B
for rnd in range(rounds):
bad = self.split_nets(skip)
self.log.append(("repair", rnd, "split", bad))
if not bad:
return []
for name in bad:
net = self.nid(name)
comps = components(net_items_all(self, net))
if len(comps) <= 1:
continue
main = max(comps, key=len)
shapes = [item_shape(it).buffer(radius) for cp in comps if cp is not main for it in cp if it.kind == "pad"]
if not shapes:
continue
victims = set()
for it in B.items:
if it.net < 0 or it.net == net or it.kind == "pad":
continue
vn = B.netname[it.net]
if vn in protect or vn in skip or vn not in self.registry:
continue
g = item_shape(it)
if any(g.intersects(s) for s in shapes):
victims.add(vn)
for vn in [name] + sorted(victims):
self.rip_net(vn)
_redo(self, name)
for vn in sorted(victims):
_redo(self, vn)
return self.split_nets(skip)
Router.repair = repair
|