diff options
| author | Louis <louis@dnge.de> | 2026-11-11 10:08:41 +0100 |
|---|---|---|
| committer | Louis <louis@dnge.de> | 2026-11-11 10:08:41 +0100 |
| commit | 2e433fcd0d1afadd8ab786dd30d7d4546bdee43d (patch) | |
| tree | f2a5603703d56b08c1eaa672eaf529ec4b2cc3fa /tools/router | |
| download | hw-toolchain-2e433fcd0d1afadd8ab786dd30d7d4546bdee43d.tar.gz | |
hw-toolchain: placer, routers and KiCad helpers for agent-driven hardware work
Rust placer (simulated annealing) and negotiated-congestion router for
2-layer KiCad boards, pnr.sh to place, route, DRC-check and install
candidates, Python KiCad helpers, repo conventions (AGENTS.md) and the
tool documentation under knowledge/. Konnect (KiCad MCP, AGPL) as a
submodule.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'tools/router')
| -rw-r--r-- | tools/router/README.md | 12 | ||||
| -rw-r--r-- | tools/router/astar.c | 136 | ||||
| -rw-r--r-- | tools/router/dump_board.py | 105 | ||||
| -rw-r--r-- | tools/router/pcbroute.py | 356 | ||||
| -rw-r--r-- | tools/router/pipeline.py | 638 | ||||
| -rw-r--r-- | tools/router/plot_routes.py | 63 | ||||
| -rw-r--r-- | tools/router/requirements.txt | 4 | ||||
| -rw-r--r-- | tools/router/write_board.py | 131 |
8 files changed, 1445 insertions, 0 deletions
diff --git a/tools/router/README.md b/tools/router/README.md new file mode 100644 index 0000000..a3f594e --- /dev/null +++ b/tools/router/README.md @@ -0,0 +1,12 @@ +# Router + +Scripted 2-layer grid maze router (A* in `astar.c`, strategies in `pipeline.py`), the +predecessor of the Rust router in `../router-rs`. Documentation, workflow and lessons: +[knowledge/tooling/router.md](../../knowledge/tooling/router.md). + +Setup once: + + python3 -m venv tools/router/.venv + tools/router/.venv/bin/pip install -r tools/router/requirements.txt + +The C core compiles itself (`cc`) on first import. diff --git a/tools/router/astar.c b/tools/router/astar.c new file mode 100644 index 0000000..3b3ccb5 --- /dev/null +++ b/tools/router/astar.c @@ -0,0 +1,136 @@ +// Grid A* maze router core, 2 layers (0 = F.Cu, 1 = B.Cu). +// Clearance uses exact distance fields: d1/n1 = distance to and net of nearest copper, +// d2 = distance to nearest copper of a net other than n1. Foreign distance for net X: +// n1 == X ? d2 : d1. +#include <stdint.h> +#include <stdlib.h> +#include <string.h> +#include <math.h> + +static int NX, NY, N; +static float *G = 0; static int32_t *PAR = 0; static uint32_t *STAMP = 0; static uint8_t *DIR = 0; static uint8_t *CLOSED = 0; +static uint32_t CALL = 0; +static int32_t *HEAPI = 0; static float *HEAPF = 0; static int HN = 0, HCAP = 0; + +int init(int nx, int ny) { + NX = nx; NY = ny; N = nx * ny; + free(G); free(PAR); free(STAMP); free(DIR); free(CLOSED); free(HEAPI); free(HEAPF); + G = malloc(sizeof(float) * 2 * N); PAR = malloc(sizeof(int32_t) * 2 * N); + STAMP = calloc(2 * N, sizeof(uint32_t)); DIR = malloc(2 * N); CLOSED = malloc(2 * N); + HCAP = 1 << 22; HEAPI = malloc(sizeof(int32_t) * HCAP); HEAPF = malloc(sizeof(float) * HCAP); + CALL = 0; + return (G && PAR && STAMP && DIR && CLOSED && HEAPI && HEAPF) ? 0 : -1; +} + +static void hpush(float f, int32_t i) { + if (HN >= HCAP) { HCAP *= 2; HEAPI = realloc(HEAPI, sizeof(int32_t) * HCAP); HEAPF = realloc(HEAPF, sizeof(float) * HCAP); } + int k = HN++; + while (k > 0) { int p = (k - 1) >> 1; if (HEAPF[p] <= f) break; HEAPF[k] = HEAPF[p]; HEAPI[k] = HEAPI[p]; k = p; } + HEAPF[k] = f; HEAPI[k] = i; +} +static int32_t hpop(void) { + int32_t top = HEAPI[0]; float lf = HEAPF[--HN]; int32_t li = HEAPI[HN]; + int k = 0; + while (1) { int c = 2 * k + 1; if (c >= HN) break; if (c + 1 < HN && HEAPF[c + 1] < HEAPF[c]) c++; if (HEAPF[c] >= lf) break; HEAPF[k] = HEAPF[c]; HEAPI[k] = HEAPI[c]; k = c; } + HEAPF[k] = lf; HEAPI[k] = li; + return top; +} + +static const int DX[8] = {1, 1, 0, -1, -1, -1, 0, 1}; +static const int DY[8] = {0, 1, 1, 1, 0, -1, -1, -1}; + +static inline float fdist(const float *d1, const int32_t *n1, const float *d2, int32_t s, int net) { + return n1[s] == net ? d2[s] : d1[s]; +} +static inline float heur(int x, int y, int hx, int hy) { + int ax = abs(x - hx), ay = abs(y - hy); + return (ax > ay ? ax : ay) + 0.41421356f * (ax < ay ? ax : ay); +} + +// Returns path length (cells, target back to source) or -1. +// neck flag per output cell: 1 if only the neck radius passed. +int route(const float *d1, const int32_t *n1, const float *d2, const float *padd, const float *costmap, + int net, const int32_t *src, int nsrc, const uint8_t *tgt, int goal_layer1, + int hx, int hy, + float r_nom, float r_neck, float r_via, float r_vpad, float r_diag, + const int32_t *neckbox, int nbox, + float via_cost, float via_cmult, float bmult, float turn_cost, int allow_via, int max_expand, + int32_t *out, uint8_t *outneck, int maxout, int layer_mask) +{ + CALL++; + if (CALL == 0) { memset(STAMP, 0, sizeof(uint32_t) * 2 * N); CALL = 1; } + HN = 0; + for (int i = 0; i < nsrc; i++) { + int32_t s = src[i]; + int L = s / N; if (!((layer_mask >> L) & 1)) continue; + float sfd = fdist(d1, n1, d2, s, net); + if (sfd < (r_neck > 0 ? r_neck : r_nom)) continue; // a track must fit at its start cell + STAMP[s] = CALL; G[s] = 0; PAR[s] = -1; DIR[s] = 255; CLOSED[s] = 0; + int c = s % N; + hpush(goal_layer1 ? 0 : heur(c % NX, c / NX, hx, hy), s); + } + int expanded = 0, found = -1; + while (HN > 0) { + int32_t s = hpop(); + if (CLOSED[s]) continue; + CLOSED[s] = 1; + int L = s / N; int c = s % N; int x = c % NX, y = c / NX; + if ((tgt && tgt[s]) || (goal_layer1 && L == 1)) { found = s; break; } + if (++expanded > max_expand) break; + float gcur = G[s]; + int pd = DIR[s]; + for (int d = 0; d < 8; d++) { + int qx = x + DX[d], qy = y + DY[d]; + if (qx < 0 || qy < 0 || qx >= NX || qy >= NY) continue; + int nc = qy * NX + qx; int32_t ns = (int32_t)(L * N + nc); + float fd = fdist(d1, n1, d2, ns, net); + float need = r_nom + ((d & 1) ? r_diag : 0); + int neck = 0; + if (fd < need) { + if (r_neck <= 0) continue; + float needn = r_neck + ((d & 1) ? r_diag : 0); + if (fd < needn) continue; + int nb = 0; + for (int b = 0; b < nbox; b++) { if (qx >= neckbox[4*b] && qx <= neckbox[4*b+2] && qy >= neckbox[4*b+1] && qy <= neckbox[4*b+3]) { nb = 1; break; } } + if (!nb) continue; + neck = 1; + } + float step = (d & 1) ? 1.41421356f : 1.0f; + float cst = step * (L ? bmult : 1.0f) + (costmap ? costmap[(size_t)L * N + nc] * step : 0); + if (neck) cst += 0.3f * step; + if (pd != 255 && pd != d) { + int t = abs(pd - d); if (t > 4) t = 8 - t; + if (t >= 3) continue; + cst += turn_cost * t; + } + float ng = gcur + cst; + if (STAMP[ns] == CALL && (CLOSED[ns] || G[ns] <= ng)) continue; + STAMP[ns] = CALL; G[ns] = ng; PAR[ns] = s; DIR[ns] = (uint8_t)d; CLOSED[ns] = 0; + hpush(ng + (goal_layer1 ? 0 : heur(qx, qy, hx, hy)), ns); + } + if (allow_via && ((layer_mask & 3) == 3)) { + int32_t s0 = c, s1 = N + c; + if (fdist(d1, n1, d2, s0, net) >= r_via && fdist(d1, n1, d2, s1, net) >= r_via && + padd[s0] >= r_vpad && padd[s1] >= r_vpad) { + int32_t ns = (int32_t)((1 - L) * N + c); + float ng = gcur + via_cost + (costmap ? via_cmult * (costmap[c] + costmap[N + c]) : 0); + if (!(STAMP[ns] == CALL && (CLOSED[ns] || G[ns] <= ng))) { + STAMP[ns] = CALL; G[ns] = ng; PAR[ns] = s; DIR[ns] = 255; CLOSED[ns] = 0; + hpush(ng + (goal_layer1 ? 0 : heur(x, y, hx, hy)), ns); + } + } + } + } + if (found < 0) return -1; + int n = 0; int32_t s = found; + while (s >= 0 && n < maxout) { + int32_t p = PAR[s]; + float fd = fdist(d1, n1, d2, s, net); + // the same test the search used to enter the cell: a full-width track that barely + // fits (e.g. 0.5 mm beside a bus line) must not be drawn necked all along its run + int dd = DIR[s]; + outneck[n] = fd < r_nom + ((dd != 255 && (dd & 1)) ? r_diag : 0) ? 1 : 0; + out[n++] = s; s = p; + } + return n; +} diff --git a/tools/router/dump_board.py b/tools/router/dump_board.py new file mode 100644 index 0000000..33b4528 --- /dev/null +++ b/tools/router/dump_board.py @@ -0,0 +1,105 @@ +"""Export what the router needs from a saved .kicad_pcb into JSON. + +Run with KiCad's bundled Python (pcbnew); the board's .kicad_pro is read for net classes: + + $KPY tools/router/dump_board.py board.kicad_pcb board.json + +Output keys: + bounds [x0, y0, x1, y1] of Edge.Cuts (mm) + pads ref, num, net, x, y, drill, F / B (copper outline on that layer or null), npth + fps ref -> x, y, rot, value + netclass net -> class name; classes: name -> track width, via diameter, clearance + fpcopper footprint copper that is not a pad (ref, layer, poly) + keepouts polygons of rule areas that forbid tracks (board and footprint rule areas) + keepout_refs footprint reference owning each keepout ("" for board rule areas), parallel to keepouts + zones copper pours (not rule areas): net, layer, pts (outline), one entry per copper layer + tracks / vias existing copper, so a run can keep it (Router.load_existing) +""" +import json +import sys + +import pcbnew + +MM = 1e6 + + +def outline(ps): + if ps.OutlineCount() == 0: + return None + best = max(range(ps.OutlineCount()), key=lambda k: ps.Outline(k).Area()) + ol = ps.Outline(best) + return [[ol.CPoint(i).x / MM, ol.CPoint(i).y / MM] for i in range(ol.PointCount())] + + +def shape_poly(item, layer): + ps = pcbnew.SHAPE_POLY_SET() + item.TransformShapeToPolygon(ps, layer, 0, pcbnew.FromMM(0.005), pcbnew.ERROR_INSIDE) + return outline(ps) + + +def main(src, out): + b = pcbnew.LoadBoard(src) + bb = b.GetBoardEdgesBoundingBox() + d = dict(bounds=[bb.GetLeft() / MM, bb.GetTop() / MM, bb.GetRight() / MM, bb.GetBottom() / MM], + pads=[], fps={}, netclass={}, classes={}, fpcopper=[], keepouts=[], keepout_refs=[], zones=[], tracks=[], vias=[]) + for f in b.GetFootprints(): + ref = f.GetReference() + d["fps"][ref] = dict(x=f.GetPosition().x / MM, y=f.GetPosition().y / MM, rot=f.GetOrientationDegrees(), value=f.GetValue()) + for p in f.Pads(): + npth = p.GetAttribute() == pcbnew.PAD_ATTRIB_NPTH + drill = p.GetDrillSize().x / MM if p.HasHole() else 0.0 + cu = {} + for key, layer in (("F", pcbnew.F_Cu), ("B", pcbnew.B_Cu)): + cu[key] = None if npth or not p.IsOnLayer(layer) else shape_poly(p, layer) + d["pads"].append(dict(ref=ref, num=p.GetNumber(), net=p.GetNetname(), x=p.GetPosition().x / MM, + y=p.GetPosition().y / MM, drill=drill, npth=npth, **cu)) + for g in f.GraphicalItems(): + for key, layer in (("F", pcbnew.F_Cu), ("B", pcbnew.B_Cu)): + if g.GetLayer() == layer: + poly = shape_poly(g, layer) + if poly: + d["fpcopper"].append(dict(ref=ref, layer=key, poly=poly)) + for z in f.Zones(): + if z.GetIsRuleArea() and z.GetDoNotAllowTracks(): + d["keepouts"].append(outline(z.Outline())) + d["keepout_refs"].append(ref) + for z in b.Zones(): + if z.GetIsRuleArea() and z.GetDoNotAllowTracks(): + d["keepouts"].append(outline(z.Outline())) + d["keepout_refs"].append("") + for z in b.Zones(): + if z.GetIsRuleArea(): + continue + for key, layer in (("F.Cu", pcbnew.F_Cu), ("B.Cu", pcbnew.B_Cu)): + if z.IsOnLayer(layer): + d["zones"].append(dict(net=z.GetNetname(), layer=key, pts=outline(z.Outline()))) + for name, ni in b.GetNetInfo().NetsByName().items(): + name = str(name) + if name: + d["netclass"][name] = ni.GetNetClassName() + pro = json.load(open(src[:-len(".kicad_pcb")] + ".kicad_pro")) + for c in pro["net_settings"]["classes"]: + d["classes"][c["name"]] = dict(track=c["track_width"], via=c["via_diameter"], drill=c["via_drill"], clearance=c["clearance"]) + for t in b.GetTracks(): + if t.GetClass() == "PCB_VIA": + d["vias"].append(dict(net=t.GetNetname(), x=t.GetPosition().x / MM, y=t.GetPosition().y / MM, + d=t.GetWidth(pcbnew.F_Cu) / MM, drill=t.GetDrillValue() / MM)) + elif t.GetClass() == "PCB_TRACK": + d["tracks"].append(dict(net=t.GetNetname(), layer=b.GetLayerName(t.GetLayer()), x1=t.GetStart().x / MM, + y1=t.GetStart().y / MM, x2=t.GetEnd().x / MM, y2=t.GetEnd().y / MM, w=t.GetWidth() / MM)) + # KiCad orders footprints by UUID, which a regenerated board draws anew: sort, so the same + # placement always gives the same dump and the router (order-sensitive) the same result + d["pads"].sort(key=lambda p: (p["ref"], p["num"], p["x"], p["y"])) + d["fps"] = dict(sorted(d["fps"].items())) + for k in ("fpcopper", "zones", "tracks", "vias"): + d[k].sort(key=json.dumps) + pairs = sorted(zip(d["keepouts"], d["keepout_refs"]), key=lambda kr: json.dumps(kr[0])) + d["keepouts"] = [k for k, _ in pairs] + d["keepout_refs"] = [r for _, r in pairs] + json.dump(d, open(out, "w")) + print("pads %d, footprints %d, keepouts %d, fp copper %d, zones %d, tracks %d, vias %d, bounds %s" + % (len(d["pads"]), len(d["fps"]), len(d["keepouts"]), len(d["fpcopper"]), len(d["zones"]), len(d["tracks"]), len(d["vias"]), d["bounds"])) + + +if __name__ == "__main__": + main(*sys.argv[1:3]) diff --git a/tools/router/pcbroute.py b/tools/router/pcbroute.py new file mode 100644 index 0000000..24f932e --- /dev/null +++ b/tools/router/pcbroute.py @@ -0,0 +1,356 @@ +"""Grid maze router for 2-layer boards (Python side; the search runs in astar.c). + +The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu). Clearance uses exact +distance fields: for every cell the distance to the nearest copper (d1, its net n1) +and to the nearest copper of any other net (d2). A track of width w fits where the +distance to foreign copper is >= w/2 + CLR. Necks (narrower width) are allowed only +near pads, so fine-pitch pins can be entered. + + +Call setup(x0, y0, x1, y1) with the board extents before creating a Board. +""" +import ctypes, json, math, os, subprocess +import numpy as np +import shapely +from shapely.geometry import Polygon, Point, box, LineString +from scipy import ndimage + +HERE = os.path.dirname(os.path.abspath(__file__)) +_LIB = os.path.join(HERE, "libastar.dylib") +if not os.path.exists(_LIB) or os.path.getmtime(_LIB) < os.path.getmtime(os.path.join(HERE, "astar.c")): + subprocess.run(["cc", "-O3", "-shared", "-fPIC", "-o", _LIB, os.path.join(HERE, "astar.c")], check=True) +lib = ctypes.CDLL(_LIB) +fp = np.ctypeslib.ndpointer +lib.init.argtypes = [ctypes.c_int, ctypes.c_int] +lib.route.restype = ctypes.c_int +lib.route.argtypes = [fp(np.float32), fp(np.int32), fp(np.float32), fp(np.float32), fp(np.float32), + ctypes.c_int, fp(np.int32), ctypes.c_int, fp(np.uint8), ctypes.c_int, + ctypes.c_int, ctypes.c_int, + ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, + fp(np.int32), ctypes.c_int, + ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_float, ctypes.c_int, ctypes.c_int, + fp(np.int32), fp(np.uint8), ctypes.c_int, ctypes.c_int] + +RES = 0.05 +X0 = Y0 = X1 = Y1 = 0.0 +NX = NY = N = 0 + + +def setup(x0, y0, x1, y1): + """Set the grid to the board extents (mm). Call before Board().""" + global X0, Y0, X1, Y1, NX, NY, N + X0, Y0, X1, Y1 = x0, y0, x1, y1 + NX = int(round((X1 - X0) / RES)) + 1 + NY = int(round((Y1 - Y0) / RES)) + 1 + N = NX * NY +CAP = 1.5 +CLR = 0.2 +M = 0.015 # numeric margin on clearance checks +RDIAG = 0.02 # extra margin on diagonal steps +EDGE_CLR = 0.5 # copper to board edge +HOLE_CLR = 0.3 # copper to NPTH hole edge + +def cell_xy(i, j): return X0 + i * RES, Y0 + j * RES +def xy_cell(x, y): return int(round((x - X0) / RES)), int(round((y - Y0) / RES)) + +class Item: + __slots__ = ("kind", "net", "layers", "geom", "bbox", "w", "owner") + def __init__(self, kind, net, layers, geom, w=0.0, owner=None): + self.kind, self.net, self.layers, self.geom, self.w, self.owner = kind, net, layers, geom, w, owner + if kind == "pad": + self.bbox = geom.bounds + elif kind == "seg": + (x1, y1), (x2, y2) = geom + self.bbox = (min(x1, x2) - w / 2, min(y1, y2) - w / 2, max(x1, x2) + w / 2, max(y1, y2) + w / 2) + elif kind == "via": + x, y = geom; r = w / 2 + self.bbox = (x - r, y - r, x + r, y + r) + + def dist(self, X, Y): + if self.kind == "pad": + return shapely.distance(shapely.points(X, Y), self.geom).astype(np.float32) + if self.kind == "seg": + (x1, y1), (x2, y2) = self.geom + dx, dy = x2 - x1, y2 - y1 + L2 = dx * dx + dy * dy + if L2 == 0: t = np.zeros_like(X) + else: t = np.clip(((X - x1) * dx + (Y - y1) * dy) / L2, 0, 1) + return (np.hypot(X - (x1 + t * dx), Y - (y1 + t * dy)) - self.w / 2).astype(np.float32) + if self.kind == "via": + x, y = self.geom + return (np.hypot(X - x, Y - y) - self.w / 2).astype(np.float32) + + +class Board: + def __init__(self, board_json, netclass_of, domains, plane_nets=("GND",)): + d = json.load(open(board_json)) if isinstance(board_json, str) else board_json + self.plane_nets = set(plane_nets) + self.fpcopper = d.get("fpcopper", []) + self.keepouts = [Polygon(k) for k in d.get("keepouts", [])] + self.fps = d["fps"] + self.netid = {"": -1} + self.netname = {-1: ""} + self.pads = [] # dicts with poly, net id, layers, ref, num, center + for p in d["pads"]: + layers = tuple(L for L, k in ((0, "F"), (1, "B")) if p[k]) + if not layers: continue + name = p["net"] + if not name or name.startswith("unconnected"): + nid = -1 + else: + if name not in self.netid: + k = len(self.netid); self.netid[name] = k; self.netname[k] = name + nid = self.netid[name] + poly = Polygon(p["F"] or p["B"]) + self.pads.append(dict(ref=p["ref"], num=p["num"], net=nid, layers=layers, poly=poly, + x=p["x"], y=p["y"], drill=p["drill"], tht=len(layers) == 2)) + self.npth = [(p["x"], p["y"], p["drill"]) for p in d["pads"] if p.get("npth")] + self.netclass_of = netclass_of + self.domains = domains + self.items = [] + self.d1 = np.full((2, NY, NX), CAP, np.float32) + self.n1 = np.zeros((2, NY, NX), np.int32) + self.d2 = np.full((2, NY, NX), CAP, np.float32) + self.padd = np.full((2, NY, NX), CAP, np.float32) + self.cost = np.zeros((2, NY, NX), np.float32) + self.base = np.full((2, NY, NX), CAP, np.float32) + gx = X0 + np.arange(NX) * RES; gy = Y0 + np.arange(NY) * RES + self.GX, self.GY = np.meshgrid(gx, gy) + lib.init(NX, NY) + self.tgt = np.zeros(2 * N, np.uint8) + self.out = np.zeros(400000, np.int32); self.outneck = np.zeros(400000, np.uint8) + self.routes = {} # net id -> list of route records (segments/vias) + + # ---------- static obstacles ---------- + def build_static(self, keepouts=(), domain_seeds=()): + keepouts = list(keepouts) + self.keepouts + GX, GY = self.GX, self.GY + edge = np.minimum.reduce([GX - X0, X1 - GX, GY - Y0, Y1 - GY]) + base = edge - (EDGE_CLR - CLR) + for (x, y, dr) in self.npth: + r = dr / 2 + HOLE_CLR + base = np.minimum(base, np.hypot(GX - x, GY - y) - r + CLR) + for poly in keepouts: + dd = shapely.distance(shapely.points(GX.ravel(), GY.ravel()), poly).reshape(GX.shape) + base = np.minimum(base, dd + CLR) + # isolation domains (e.g. isolated RS485): voronoi to domain pad copper, eroded by + # 1.55 mm each side. Skipped when the board has none. + dom_ids = sorted(set(self.domains.values()) | {"LOGIC"}) + if len(dom_ids) == 1: + dom_ids = [] + dist_stack = [] + for dmn in dom_ids: + mask = np.zeros((NY, NX), bool) + for p in self.pads: + if p["net"] < 0: continue + if self.domains.get(self.netname[p["net"]], "LOGIC") != dmn: continue + b = p["poly"].bounds + i0, j0 = xy_cell(b[0], b[1]); i1, j1 = xy_cell(b[2], b[3]) + sub = shapely.contains_xy(p["poly"], GX[j0:j1+1, i0:i1+1], GY[j0:j1+1, i0:i1+1]) + mask[j0:j1+1, i0:i1+1] |= sub + ci, cj = xy_cell(p["x"], p["y"]); mask[cj, ci] = True + for (sd, sx, sy) in domain_seeds: + if sd == dmn: + ci, cj = xy_cell(sx, sy); mask[cj, ci] = True + dist_stack.append(ndimage.distance_transform_edt(~mask) * RES) + if dom_ids: + dist_stack = np.array(dist_stack) + owner = np.argmin(dist_stack, axis=0) + self.dom_owner = owner; self.dom_ids = dom_ids + allowed = np.zeros((NY, NX), bool) + for k in range(len(dom_ids)): + m = owner == k + dout = ndimage.distance_transform_edt(m) * RES # distance to nearest non-m cell + allowed |= m & (dout >= 1.55) + dforb = ndimage.distance_transform_edt(allowed) * RES # distance from allowed cell to forbidden + base = np.minimum(base, np.where(allowed, dforb + CLR - RES, -1.0)) + self.allowed = allowed + base = base.astype(np.float32) + self.base[0] = base; self.base[1] = base + self.reset_region(None) + # pad distance field for via-in-pad avoidance (SMD pads, not exposed pads) + for p in self.pads: + if p["tht"]: continue + b = p["poly"].bounds + if (b[2] - b[0]) > 2.5 and (b[3] - b[1]) > 2.5 and p["net"] >= 0 and self.netname[p["net"]] in self.plane_nets: + continue # exposed GND pad: vias allowed + sl, X, Y = self.window(b, 1.0) + dd = shapely.distance(shapely.points(X, Y), p["poly"]).astype(np.float32) + for L in p["layers"]: + v = self.padd[L][sl]; np.minimum(v, dd, out=v) + for p in self.pads: + it = Item("pad", p["net"], p["layers"], p["poly"], owner=("pad", p["ref"], p["num"])) + p["item"] = it + self.items.append(it) + self.insert(it) + if True: + # footprint copper that is not a pad (net-tie bridges, antenna graphics) + for g in self.fpcopper: + poly = Polygon(g["poly"]).buffer(0) + for p in self.pads: + if p["ref"] == g["ref"]: poly = poly.difference(p["poly"]) + if poly.is_empty: continue + # a net tie's bridge is GND copper (it joins the AGND pad to GND) + nid = self.netid.get("GND", -1) if g["ref"].startswith("NT") else -1 + it = Item("pad", nid, (0,) if g["layer"] == "F" else (1,), poly, owner=("fpcopper", g["ref"])) + self.items.append(it); self.insert(it) + # KiCad sees this graphic as net-less for hole clearance (0.3 mm to the via hole) + sl, X, Y = self.window(poly.bounds, 1.0) + dd = shapely.distance(shapely.points(X, Y), poly).astype(np.float32) - 0.1 + for L in (0, 1): + v = self.padd[L][sl]; np.minimum(v, dd, out=v) + + def window(self, b, pad): + i0 = max(0, int(math.floor((b[0] - pad - X0) / RES))); j0 = max(0, int(math.floor((b[1] - pad - Y0) / RES))) + i1 = min(NX - 1, int(math.ceil((b[2] + pad - X0) / RES))); j1 = min(NY - 1, int(math.ceil((b[3] + pad - Y0) / RES))) + sl = (slice(j0, j1 + 1), slice(i0, i1 + 1)) + return sl, self.GX[sl], self.GY[sl] + + def reset_region(self, b): + if b is None: + sl = (slice(None), slice(None)) + else: + sl, _, _ = self.window(b, 0) + for L in (0, 1): + bd = self.base[L][sl] + self.d1[L][sl] = np.minimum(bd, CAP) + self.n1[L][sl] = np.where(bd < CAP, -1, 0) + self.d2[L][sl] = CAP + + def insert(self, it, clip=None): + b = it.bbox + if clip is not None: + b2 = (max(b[0] - CAP, clip[0]), max(b[1] - CAP, clip[1]), min(b[2] + CAP, clip[2]), min(b[3] + CAP, clip[3])) + if b2[0] > b2[2] or b2[1] > b2[3]: return + sl, X, Y = self.window(b2, 0) + else: + sl, X, Y = self.window(b, CAP) + dd = it.dist(X, Y) + net = it.net + for L in it.layers: + d1 = self.d1[L][sl]; n1 = self.n1[L][sl]; d2 = self.d2[L][sl] + same = n1 == net + np.minimum(d1, dd, out=d1, where=same) + m = (~same) & (dd < d1) + d2[m] = d1[m]; d1[m] = dd[m]; n1[m] = net + o = (~same) & (~m) + np.minimum(d2, dd, out=d2, where=o) + + def remove_items(self, items): + if not items: return + ids = set(id(i) for i in items) + self.items = [i for i in self.items if id(i) not in ids] + for it in items: + b = (it.bbox[0] - CAP, it.bbox[1] - CAP, it.bbox[2] + CAP, it.bbox[3] + CAP) + self.reset_region(b) + for o in self.items: + ob = o.bbox + if ob[0] - CAP > b[2] or ob[2] + CAP < b[0] or ob[1] - CAP > b[3] or ob[3] + CAP < b[1]: continue + self.insert(o, clip=b) + + # ---------- routing ---------- + def cells_of(self, items, layers=(0, 1)): + out = [] + for it in items: + sl, X, Y = self.window(it.bbox, 0.05) + dd = it.dist(X, Y) + jj, ii = np.nonzero(dd <= 0.0) + j0, i0 = sl[0].start, sl[1].start + c = (jj + j0) * NX + (ii + i0) + for L in it.layers: + if L in layers: out.append(L * N + c) + if not out: return np.zeros(0, np.int32) + return np.unique(np.concatenate(out)).astype(np.int32) + + def route(self, net, src_items, tgt_items=None, goal_layer1=False, w=0.2, wneck=0.0, via_d=0.6, + via_cost=40.0, via_cmult=0.0, bmult=3.0, turn=4.0, allow_via=True, layer_mask=3, neck_items=(), max_expand=4000000, + hxy=None, extra_tgt_cells=None): + src = self.cells_of(src_items) + if len(src) == 0: return None + if tgt_items: + tc = self.cells_of(tgt_items) + else: + tc = np.zeros(0, np.int32) + if extra_tgt_cells is not None and len(extra_tgt_cells): + tc = np.concatenate([tc, extra_tgt_cells]).astype(np.int32) + self.tgt[tc] = 1 + if hxy is None: + if tgt_items: + g0 = tgt_items[0] + c = g0.geom.centroid if g0.kind == "pad" else (Point(g0.geom) if g0.kind == "via" else Point(g0.geom[0])) + hxy = (c.x, c.y) + else: + hxy = (X0, Y0) + hx, hy = xy_cell(*hxy) + boxes = [] + for it in neck_items: + b = it.bbox + i0, j0 = xy_cell(b[0] - 1.0, b[1] - 1.0); i1, j1 = xy_cell(b[2] + 1.0, b[3] + 1.0) + boxes += [i0, j0, i1, j1] + boxes = np.array(boxes or [0, 0, -1, -1], np.int32) + r_nom = w / 2 + CLR + M + r_neck = (wneck / 2 + CLR + M) if wneck else 0.0 + r_via = via_d / 2 + CLR + M + r_vpad = via_d / 2 + 0.05 + n = lib.route(self.d1.ravel(), self.n1.ravel(), self.d2.ravel(), self.padd.ravel(), self.cost.ravel(), + net, src, len(src), self.tgt, int(goal_layer1), hx, hy, + r_nom, r_neck, r_via, r_vpad, RDIAG, boxes, len(boxes) // 4, + via_cost, via_cmult, bmult, turn, int(allow_via), max_expand, + self.out, self.outneck, len(self.out), layer_mask) + self.tgt[tc] = 0 + if n < 0: return None + path = self.out[:n][::-1].copy(); neck = self.outneck[:n][::-1].copy() + return path, neck + + def path_to_geom(self, net, path, neck, w, wneck, via_d): + """Convert a cell path into segments and vias (lists).""" + pts = [] + for s, nk in zip(path, neck): + L = int(s // N); c = int(s % N) + pts.append((L, c % NX, c // NX, int(nk))) + segs, vias = [], [] + run = [pts[0]] + def flush(run): + if len(run) < 2: return + # widths per step + k = 0 + while k < len(run) - 1: + L, i, j, nk = run[k] + wd = wneck if (wneck and (run[k][3] or run[k + 1][3])) else w + # extend while direction and width constant + di, dj = run[k + 1][1] - i, run[k + 1][2] - j + m = k + 1 + while m < len(run) - 1: + w2 = wneck if (wneck and (run[m][3] or run[m + 1][3])) else w + if (run[m + 1][1] - run[m][1], run[m + 1][2] - run[m][2]) != (di, dj) or w2 != wd: break + m += 1 + segs.append((L, cell_xy(i, j), cell_xy(run[m][1], run[m][2]), wd)) + k = m + for p in pts[1:]: + if p[0] != run[-1][0]: + flush(run) + vias.append(cell_xy(p[1], p[2])) + run = [p] + else: + run.append(p) + flush(run) + return segs, vias + + def commit(self, net, segs, vias, via_d, tag): + items = [] + for (L, a, b, wd) in segs: + it = Item("seg", net, (L,), (a, b), w=wd, owner=tag) + items.append(it) + for v in vias: + items.append(Item("via", net, (0, 1), v, w=via_d, owner=tag)) + for it in items: + self.items.append(it); self.insert(it) + return items + + def stub(self, net, cell_xy_pt, L, target_item, w): + """Straight stub from a path end to the centre of the pad it ends in (if inside).""" + if target_item.kind != "pad": return None + c = target_item.geom.centroid + if target_item.geom.contains(Point(cell_xy_pt)) and (abs(c.x - cell_xy_pt[0]) > 1e-6 or abs(c.y - cell_xy_pt[1]) > 1e-6): + return (L, cell_xy_pt, (c.x, c.y), w) + return None diff --git a/tools/router/pipeline.py b/tools/router/pipeline.py new file mode 100644 index 0000000..f7783d3 --- /dev/null +++ b/tools/router/pipeline.py @@ -0,0 +1,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 diff --git a/tools/router/plot_routes.py b/tools/router/plot_routes.py new file mode 100644 index 0000000..f7b3976 --- /dev/null +++ b/tools/router/plot_routes.py @@ -0,0 +1,63 @@ +"""Plot router output over the board's pads, one colour per net, failed pins marked. + + tools/router/.venv/bin/python tools/router/plot_routes.py board.json routes.json out.png [x0 y0 x1 y1] + +Pads are grey (F.Cu darker, B.Cu-only lighter); F.Cu tracks solid, B.Cu tracks dashed; +vias are circles; every net is labelled at its longest segment; pins listed in +routes.json "failed" get a red cross. Use a window (mm) to zoom into a dense part. +""" +import json +import sys +import zlib + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +from matplotlib.patches import Circle, Polygon # noqa: E402 + +board, routes, out = sys.argv[1:4] +win = [float(v) for v in sys.argv[4:8]] if len(sys.argv) >= 8 else None +d = json.load(open(board)) +r = json.load(open(routes)) +x0, y0, x1, y1 = win or d["bounds"] +scale = 12 if win else 4 +fig = plt.figure(figsize=((x1 - x0) / 25.4 * scale, (y1 - y0) / 25.4 * scale), dpi=100) +ax = fig.add_axes([0, 0, 1, 1]) +ax.set_xlim(x0, x1) +ax.set_ylim(y1, y0) +ax.set_aspect("equal") +ax.axis("off") +cmap = plt.get_cmap("tab20") + + +def col(net): + return cmap(zlib.crc32(net.encode()) % 20) + + +for p in d["pads"]: + poly = p["F"] or p["B"] + if poly: + ax.add_patch(Polygon(poly, closed=True, fc="#9e9e9e" if p["F"] else "#d0d0d0", ec="none", zorder=1)) + if win and x0 <= p["x"] <= x1 and y0 <= p["y"] <= y1: + ax.text(p["x"], p["y"], "%s.%s" % (p["ref"], p["num"]), fontsize=4, ha="center", va="center", zorder=5) +longest = {} +for s in r["segs"]: + lw = s["w"] * 72 / 25.4 * scale * 1.0 + ax.plot([s["x1"], s["x2"]], [s["y1"], s["y2"]], color=col(s["net"]), lw=lw, solid_capstyle="round", + ls="-" if s["layer"] == "F.Cu" else (0, (2, 1)), alpha=0.85 if s["layer"] == "F.Cu" else 0.6, zorder=3) + L = abs(s["x2"] - s["x1"]) + abs(s["y2"] - s["y1"]) + if L > longest.get(s["net"], (0,))[0]: + longest[s["net"]] = (L, (s["x1"] + s["x2"]) / 2, (s["y1"] + s["y2"]) / 2) +for v in r["vias"]: + ax.add_patch(Circle((v["x"], v["y"]), v["d"] / 2, fc="white", ec=col(v["net"]), lw=1.5, zorder=4)) +for net, (L, x, y) in longest.items(): + if x0 <= x <= x1 and y0 <= y <= y1: + ax.text(x, y, net.split("/")[-1], fontsize=6 if win else 4, color="black", zorder=6, + bbox=dict(fc=col(net), ec="none", alpha=0.7, pad=0.5)) +pads = {(p["ref"], p["num"]): p for p in d["pads"]} +for f in r.get("failed", []): + p = pads.get((f[1], f[2])) if len(f) >= 3 else None + if p: + ax.plot([p["x"]], [p["y"]], marker="x", color="red", ms=14, mew=3, zorder=7) +fig.savefig(out) +print("wrote", out) diff --git a/tools/router/requirements.txt b/tools/router/requirements.txt new file mode 100644 index 0000000..3f89b23 --- /dev/null +++ b/tools/router/requirements.txt @@ -0,0 +1,4 @@ +numpy +shapely +scipy +matplotlib diff --git a/tools/router/write_board.py b/tools/router/write_board.py new file mode 100644 index 0000000..a4eaa6d --- /dev/null +++ b/tools/router/write_board.py @@ -0,0 +1,131 @@ +"""Write router output (tracks, vias) and copper pours into a board. + +Run with KiCad's bundled Python (pcbnew): + + $KPY tools/router/write_board.py src.kicad_pcb routes.json out.kicad_pcb [--zones zones.json] [--replace] + + --replace delete all existing tracks and vias first (routes.json then holds everything) + --diff routes.json holds everything (a route with the board's copper as [[fixed]]): only + tracks/vias that differ are touched; untouched copper keeps its exact drill and width + --zones zones.json: {"zones": [{net, layer, pts, priority, clearance?}]}; zones are filled + +pcbnew.SaveBoard rewrites the project file next to `out` with default net settings +(knowledge/tooling/kicad.md, pcbnew quirks), so an existing .kicad_pro is copied +before the save and written back afterwards. Close the board in KiCad before writing to +its own path; an open editor overwrites the file on its next save. +""" +import argparse +import json +import os + +import pcbnew + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src") + ap.add_argument("routes") + ap.add_argument("out") + ap.add_argument("--zones") + ap.add_argument("--replace", action="store_true") + ap.add_argument("--diff", action="store_true") + ap.add_argument("--prune-vias", metavar="NET", help="after filling, drop vias of NET that touch no track and do not sit in a fill on both layers (stitching vias that ended up isolated)") + a = ap.parse_args() + + mm = pcbnew.FromMM + b = pcbnew.LoadBoard(a.src) + nets = b.GetNetsByName() + if a.replace: + for t in list(b.GetTracks()): + b.Remove(t) + r = json.load(open(a.routes)) + if a.diff: + def skey(net, layer, x1, y1, x2, y2): + e = sorted([(round(x1, 3), round(y1, 3)), (round(x2, 3), round(y2, 3))]) + return (net, layer, e[0], e[1]) + want_s = {skey(t["net"], t["layer"], t["x1"], t["y1"], t["x2"], t["y2"]) for t in r["segs"]} + want_v = {(v["net"], round(v["x"], 3), round(v["y"], 3)) for v in r["vias"]} + have_s, have_v, gone = set(), set(), [] + for t in list(b.GetTracks()): + if t.GetClass() == "PCB_VIA": + k = (t.GetNetname(), round(t.GetPosition().x / 1e6, 3), round(t.GetPosition().y / 1e6, 3)) + if k in want_v: + have_v.add(k) + else: + gone.append(t) + elif t.GetClass() == "PCB_TRACK": + k = skey(t.GetNetname(), b.GetLayerName(t.GetLayer()), t.GetStart().x / 1e6, t.GetStart().y / 1e6, + t.GetEnd().x / 1e6, t.GetEnd().y / 1e6) + if k in want_s: + have_s.add(k) + else: + gone.append(t) + for t in gone: + b.Delete(t) + r["segs"] = [t for t in r["segs"] if skey(t["net"], t["layer"], t["x1"], t["y1"], t["x2"], t["y2"]) not in have_s] + r["vias"] = [v for v in r["vias"] if (v["net"], round(v["x"], 3), round(v["y"], 3)) not in have_v] + print("diff: %d tracks/vias removed" % len(gone)) + for s in r["segs"]: + t = pcbnew.PCB_TRACK(b) + t.SetStart(pcbnew.VECTOR2I(mm(s["x1"]), mm(s["y1"]))) + t.SetEnd(pcbnew.VECTOR2I(mm(s["x2"]), mm(s["y2"]))) + t.SetWidth(mm(s["w"])) + t.SetLayer(pcbnew.F_Cu if s["layer"] == "F.Cu" else pcbnew.B_Cu) + t.SetNet(nets[s["net"]]) + b.Add(t) + for v in r["vias"]: + t = pcbnew.PCB_VIA(b) + t.SetPosition(pcbnew.VECTOR2I(mm(v["x"]), mm(v["y"]))) + t.SetWidth(mm(v["d"])) + t.SetDrill(mm(v["drill"])) + t.SetViaType(pcbnew.VIATYPE_THROUGH) + t.SetNet(nets[v["net"]]) + b.Add(t) + if a.zones: + for zd in json.load(open(a.zones))["zones"]: + zn = pcbnew.ZONE(b) + zn.SetLayer(pcbnew.F_Cu if zd["layer"] == "F.Cu" else pcbnew.B_Cu) + zn.SetNet(nets[zd["net"]]) + zn.SetZoneName(zd.get("name", zd["net"] + " " + zd["layer"])) + o = zn.Outline() + o.NewOutline() + for (x, y) in zd["pts"]: + o.Append(mm(x), mm(y)) + zn.SetAssignedPriority(zd.get("priority", 0)) + zn.SetLocalClearance(mm(zd.get("clearance", 0.3))) + zn.SetMinThickness(mm(0.25)) + zn.SetPadConnection(pcbnew.ZONE_CONNECTION_THERMAL) + zn.SetThermalReliefGap(mm(0.3)) + zn.SetThermalReliefSpokeWidth(mm(0.4)) + zn.SetIslandRemovalMode(pcbnew.ISLAND_REMOVAL_MODE_ALWAYS) + b.Add(zn) + if b.Zones(): + pcbnew.ZONE_FILLER(b).Fill(b.Zones()) + if a.prune_vias and b.Zones(): + net = nets[a.prune_vias] + ends = [(t.GetStart(), t.GetEnd(), t.GetLayer()) for t in b.GetTracks() if t.GetClass() == "PCB_TRACK" and t.GetNetCode() == net.GetNetCode()] + zones = [z for z in b.Zones() if not z.GetIsRuleArea() and z.GetNetCode() == net.GetNetCode()] + dropped = 0 + for v in [t for t in b.GetTracks() if t.GetClass() == "PCB_VIA" and t.GetNetCode() == net.GetNetCode()]: + p, rad = v.GetPosition(), v.GetWidth(pcbnew.F_Cu) / 2 + if any((e - p).EuclideanNorm() <= rad for s_, e_, _ in ends for e in (s_, e_)): + continue + inF = any(z.IsOnLayer(pcbnew.F_Cu) and z.GetFilledPolysList(pcbnew.F_Cu).Contains(p) for z in zones) + inB = any(z.IsOnLayer(pcbnew.B_Cu) and z.GetFilledPolysList(pcbnew.B_Cu).Contains(p) for z in zones) + if not (inF and inB): + b.Remove(v) + dropped += 1 + if dropped: + pcbnew.ZONE_FILLER(b).Fill(b.Zones()) + print("pruned %d isolated %s vias" % (dropped, a.prune_vias)) + + pro = a.out[:-len(".kicad_pcb")] + ".kicad_pro" + keep = open(pro).read() if os.path.exists(pro) else None + pcbnew.SaveBoard(a.out, b) + if keep is not None: + open(pro, "w").write(keep) + print("saved %s: %d segments, %d vias added" % (a.out, len(r["segs"]), len(r["vias"]))) + + +if __name__ == "__main__": + main() |
