aboutsummaryrefslogtreecommitdiff
path: root/tools/router/pipeline.py
diff options
context:
space:
mode:
authorLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
committerLouis <louis@dnge.de>2026-11-11 10:32:51 +0100
commita59e8e99243a895197a30d6cd6dd8d744dd606de (patch)
tree8910cc7476ff1317932257dfc8497a0f9ffc29f7 /tools/router/pipeline.py
parent6f2bbe1f94e4321c329f92ec3420f6d32fd7b26d (diff)
downloadhw-toolchain-a59e8e99243a895197a30d6cd6dd8d744dd606de.tar.gz
Keep only the current router: drop the Python router, router-rs -> routerHEADmain
The sequential Python/C router (pcbroute.py, pipeline.py, astar.c) is gone. The Rust crate takes its place at tools/router/, next to the KiCad I/O scripts it uses (dump_board.py, write_board.py, plot_routes.py). knowledge/tooling/router.md is now the Rust router's reference; the small Python venv for plots and 3D checks moves to tools/.venv (tools/requirements.txt). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/router/pipeline.py')
-rw-r--r--tools/router/pipeline.py638
1 files changed, 0 insertions, 638 deletions
diff --git a/tools/router/pipeline.py b/tools/router/pipeline.py
deleted file mode 100644
index f7783d3..0000000
--- a/tools/router/pipeline.py
+++ /dev/null
@@ -1,638 +0,0 @@
-"""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