diff options
| author | Louis <louis@dnge.de> | 2026-11-11 10:32:51 +0100 |
|---|---|---|
| committer | Louis <louis@dnge.de> | 2026-11-11 10:32:51 +0100 |
| commit | a59e8e99243a895197a30d6cd6dd8d744dd606de (patch) | |
| tree | 8910cc7476ff1317932257dfc8497a0f9ffc29f7 /tools | |
| parent | 6f2bbe1f94e4321c329f92ec3420f6d32fd7b26d (diff) | |
| download | hw-toolchain-main.tar.gz | |
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')
| -rw-r--r-- | tools/height_check.py | 2 | ||||
| -rw-r--r-- | tools/housing_inputs.py | 2 | ||||
| -rw-r--r-- | tools/placer/Cargo.toml | 2 | ||||
| -rw-r--r-- | tools/placer/src/main.rs | 2 | ||||
| -rw-r--r-- | tools/pnr.sh | 2 | ||||
| -rw-r--r-- | tools/pnr_eval.sh | 2 | ||||
| -rw-r--r-- | tools/requirements.txt (renamed from tools/router/requirements.txt) | 2 | ||||
| -rw-r--r-- | tools/router-rs/README.md | 13 | ||||
| -rw-r--r-- | tools/router/Cargo.lock (renamed from tools/router-rs/Cargo.lock) | 0 | ||||
| -rw-r--r-- | tools/router/Cargo.toml (renamed from tools/router-rs/Cargo.toml) | 2 | ||||
| -rw-r--r-- | tools/router/README.md | 20 | ||||
| -rw-r--r-- | tools/router/astar.c | 136 | ||||
| -rw-r--r-- | tools/router/pcbroute.py | 356 | ||||
| -rw-r--r-- | tools/router/pipeline.py | 638 | ||||
| -rw-r--r-- | tools/router/plot_routes.py | 2 | ||||
| -rw-r--r-- | tools/router/src/astar.rs (renamed from tools/router-rs/src/astar.rs) | 2 | ||||
| -rw-r--r-- | tools/router/src/board.rs (renamed from tools/router-rs/src/board.rs) | 4 | ||||
| -rw-r--r-- | tools/router/src/cleanup.rs (renamed from tools/router-rs/src/cleanup.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/config.rs (renamed from tools/router-rs/src/config.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/geom.rs (renamed from tools/router-rs/src/geom.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/io.rs (renamed from tools/router-rs/src/io.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/lib.rs (renamed from tools/router-rs/src/lib.rs) | 2 | ||||
| -rw-r--r-- | tools/router/src/main.rs (renamed from tools/router-rs/src/main.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/placement.rs (renamed from tools/router-rs/src/placement.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/pour.rs (renamed from tools/router-rs/src/pour.rs) | 0 | ||||
| -rw-r--r-- | tools/router/src/router.rs (renamed from tools/router-rs/src/router.rs) | 2 | ||||
| -rw-r--r-- | tools/router/src/run.rs (renamed from tools/router-rs/src/run.rs) | 0 | ||||
| -rw-r--r-- | tools/thermal_vias.py | 2 |
28 files changed, 27 insertions, 1166 deletions
diff --git a/tools/height_check.py b/tools/height_check.py index fa1e6e8..ad0c039 100644 --- a/tools/height_check.py +++ b/tools/height_check.py @@ -1,6 +1,6 @@ """Check part heights on a DIN-rail board against the printed housing. - tools/router/.venv/bin/python tools/height_check.py projects/<name>/kicad/<name>.kicad_pcb + tools/.venv/bin/python tools/height_check.py projects/<name>/kicad/<name>.kicad_pcb Finds the HW:DIN_Housing_<k>TE footprint (its position is the housing centre), loads every top-side footprint's 3D model (STEP vertices, transformed like KiCad does) and compares each diff --git a/tools/housing_inputs.py b/tools/housing_inputs.py index c6361db..1080c79 100644 --- a/tools/housing_inputs.py +++ b/tools/housing_inputs.py @@ -1,6 +1,6 @@ """Numbers for a project's DIN-rail housing: notches, pockets, spacer-frame tongues and pin cutouts. - tools/router/.venv/bin/python tools/housing_inputs.py projects/<name>/kicad/<name>.kicad_pcb + tools/.venv/bin/python tools/housing_inputs.py projects/<name>/kicad/<name>.kicad_pcb Prints, in housing coordinates (X along the rail, Y up = board -y, origin at the HW:DIN_Housing_<k>TE footprint), what the per-project changes of the DIN housing model need: diff --git a/tools/placer/Cargo.toml b/tools/placer/Cargo.toml index 64ddf81..0d8424a 100644 --- a/tools/placer/Cargo.toml +++ b/tools/placer/Cargo.toml @@ -8,7 +8,7 @@ description = "Simulated-annealing component placer for KiCad boards (see knowle anyhow = "1" rand = { version = "0.8", features = ["small_rng"] } rayon = "1" -router = { path = "../router-rs" } +router = { path = "../router" } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1" diff --git a/tools/placer/src/main.rs b/tools/placer/src/main.rs index c94f865..5218bf7 100644 --- a/tools/placer/src/main.rs +++ b/tools/placer/src/main.rs @@ -14,7 +14,7 @@ //! OUT_DIR/runs.tsv. A placement file maps ref -> [x, y, rotation in degrees], either at the //! top level or under "placement". //! -//! `--route` routes the best K placements in-process with tools/router-rs (BOARD.json is any +//! `--route` routes the best K placements in-process with tools/router (BOARD.json is any //! dump of the board from tools/router/dump_board.py; parts are moved to each placement) and //! ranks them by the router's result (split nets, failed connections, pour islands, then the //! route.toml's [rank] score of length, vias, necked and B.Cu length): OUT_DIR/routed.tsv, diff --git a/tools/pnr.sh b/tools/pnr.sh index b21bde5..48292ba 100644 --- a/tools/pnr.sh +++ b/tools/pnr.sh @@ -1,5 +1,5 @@ #!/bin/sh -# Place and route a board with tools/placer + tools/router-rs, check the best candidates with +# Place and route a board with tools/placer + tools/router, check the best candidates with # KiCad's DRC, and install one. See knowledge/tooling/pnr.md. # # sh tools/pnr.sh run BOARD_DIR [TOP] # 32 placements, all routed; DRC of the TOP (6) best diff --git a/tools/pnr_eval.sh b/tools/pnr_eval.sh index ed73828..04f290a 100644 --- a/tools/pnr_eval.sh +++ b/tools/pnr_eval.sh @@ -11,7 +11,7 @@ T=$(cd "$(dirname "$0")" && pwd) . "$T/kicad_env.sh" : "${E:?set E to the board directory}" "${BOARD:?set BOARD to the board name}" -ROUTER=${ROUTER:-$T/router-rs/target/release/router} +ROUTER=${ROUTER:-$T/router/target/release/router} TOML=${TOML:-$E/route.toml} PLANE=${PLANE:-GND} # the plane net whose dangling vias write_board.py prunes export E BOARD ROUTER TOML PLANE diff --git a/tools/router/requirements.txt b/tools/requirements.txt index 3f89b23..aa094d9 100644 --- a/tools/router/requirements.txt +++ b/tools/requirements.txt @@ -1,4 +1,2 @@ numpy -shapely -scipy matplotlib diff --git a/tools/router-rs/README.md b/tools/router-rs/README.md deleted file mode 100644 index 969c415..0000000 --- a/tools/router-rs/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Router (Rust) - -Grid router for 2-layer KiCad boards with negotiated congestion (all nets at once, ground drops -optionally included), cleanup passes, a pour-connectivity check and a sequential mode that runs -the old route scripts' order from a `route.toml`. Footprint copper such as net-tie bridges is -respected; `area = "pours"` in route.toml keeps all copper inside the plane pours (a design block's area). -Reads board.json from `tools/router/dump_board.py`, writes routes.json for -`tools/router/write_board.py`; the placer links it to route its candidates. -Documentation and lessons: [knowledge/tooling/rust-router.md](../../knowledge/tooling/rust-router.md); end to end on your board: [knowledge/tooling/pnr.md](../../knowledge/tooling/pnr.md). - - cargo build --release - target/release/router route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL] - target/release/router place board.json placement.json moved.json diff --git a/tools/router-rs/Cargo.lock b/tools/router/Cargo.lock index 04eead0..04eead0 100644 --- a/tools/router-rs/Cargo.lock +++ b/tools/router/Cargo.lock diff --git a/tools/router-rs/Cargo.toml b/tools/router/Cargo.toml index c7ff51a..12d5a17 100644 --- a/tools/router-rs/Cargo.toml +++ b/tools/router/Cargo.toml @@ -2,7 +2,7 @@ name = "router" version = "0.1.0" edition = "2021" -description = "Grid maze router for 2-layer KiCad boards (see knowledge/tooling/rust-router.md)" +description = "Grid maze router for 2-layer KiCad boards (see knowledge/tooling/router.md)" [lib] name = "router" diff --git a/tools/router/README.md b/tools/router/README.md index a3f594e..847ed25 100644 --- a/tools/router/README.md +++ b/tools/router/README.md @@ -1,12 +1,18 @@ # 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). +Grid router for 2-layer KiCad boards with negotiated congestion (all nets at once, plane-net +drops optionally included), cleanup passes, a pour-connectivity check and ordered steps, all +configured per board in a `route.toml`. Footprint copper such as net-tie bridges is respected; +`area = "pours"` keeps all copper inside the plane pours (a design block's area). The placer +links the crate to route its candidates. -Setup once: +KiCad I/O (run with KiCad's Python, see `../kicad_env.sh`): `dump_board.py` writes board.json, +`write_board.py` writes routes.json back into a board. `plot_routes.py` draws a route (plain +Python with `../requirements.txt`). - python3 -m venv tools/router/.venv - tools/router/.venv/bin/pip install -r tools/router/requirements.txt +Documentation and lessons: [knowledge/tooling/router.md](../../knowledge/tooling/router.md); +end to end on your board: [knowledge/tooling/pnr.md](../../knowledge/tooling/pnr.md). -The C core compiles itself (`cc`) on first import. + cargo build --release + target/release/router route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL] + target/release/router place board.json placement.json moved.json diff --git a/tools/router/astar.c b/tools/router/astar.c deleted file mode 100644 index 3b3ccb5..0000000 --- a/tools/router/astar.c +++ /dev/null @@ -1,136 +0,0 @@ -// 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/pcbroute.py b/tools/router/pcbroute.py deleted file mode 100644 index 24f932e..0000000 --- a/tools/router/pcbroute.py +++ /dev/null @@ -1,356 +0,0 @@ -"""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 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 diff --git a/tools/router/plot_routes.py b/tools/router/plot_routes.py index f7b3976..81b11c2 100644 --- a/tools/router/plot_routes.py +++ b/tools/router/plot_routes.py @@ -1,6 +1,6 @@ """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] + tools/.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 diff --git a/tools/router-rs/src/astar.rs b/tools/router/src/astar.rs index 2be7595..0a91f7a 100644 --- a/tools/router-rs/src/astar.rs +++ b/tools/router/src/astar.rs @@ -1,4 +1,4 @@ -//! Grid A* core, 2 layers (port of tools/router/astar.c with the same arithmetic in f32; +//! Grid A* core, 2 layers (port of an earlier C core with the same arithmetic in f32; //! a radix heap replaces the binary heap, so ties break differently). //! //! States are cell * 2 + layer, so both layers of a cell share a cache line. Foreign distance for net X: n1 == X ? d2 : d1. diff --git a/tools/router-rs/src/board.rs b/tools/router/src/board.rs index 137b4fa..730d90e 100644 --- a/tools/router-rs/src/board.rs +++ b/tools/router/src/board.rs @@ -1,4 +1,4 @@ -//! Board model and clearance fields (port of tools/router/pcbroute.py). +//! Board model and clearance fields (port of an earlier Python router). //! //! The board is a 0.05 mm grid on two layers (0 = F.Cu, 1 = B.Cu), with its origin on a //! multiple of 0.05 mm, so that parts placed on the placer's 0.05 mm grid have their pads on @@ -95,7 +95,7 @@ pub struct Pad { pub item: usize, } -/// Search settings of one connection (pcbroute.Board.route keyword arguments). +/// Search settings of one connection (per step or per net in route.toml). #[derive(Clone, Copy, Debug)] pub struct SearchOpts { pub via_cost: f64, diff --git a/tools/router-rs/src/cleanup.rs b/tools/router/src/cleanup.rs index d3ed3bc..d3ed3bc 100644 --- a/tools/router-rs/src/cleanup.rs +++ b/tools/router/src/cleanup.rs diff --git a/tools/router-rs/src/config.rs b/tools/router/src/config.rs index 090d999..090d999 100644 --- a/tools/router-rs/src/config.rs +++ b/tools/router/src/config.rs diff --git a/tools/router-rs/src/geom.rs b/tools/router/src/geom.rs index f176e39..f176e39 100644 --- a/tools/router-rs/src/geom.rs +++ b/tools/router/src/geom.rs diff --git a/tools/router-rs/src/io.rs b/tools/router/src/io.rs index be51147..be51147 100644 --- a/tools/router-rs/src/io.rs +++ b/tools/router/src/io.rs diff --git a/tools/router-rs/src/lib.rs b/tools/router/src/lib.rs index 925b1af..5156e0b 100644 --- a/tools/router-rs/src/lib.rs +++ b/tools/router/src/lib.rs @@ -1,4 +1,4 @@ -//! Grid maze router for 2-layer KiCad boards (see knowledge/tooling/rust-router.md). +//! Grid maze router for 2-layer KiCad boards (see knowledge/tooling/router.md). //! //! Reads board.json from tools/router/dump_board.py and the board's route.toml, writes //! routes.json for tools/router/write_board.py. diff --git a/tools/router-rs/src/main.rs b/tools/router/src/main.rs index 85802ce..85802ce 100644 --- a/tools/router-rs/src/main.rs +++ b/tools/router/src/main.rs diff --git a/tools/router-rs/src/placement.rs b/tools/router/src/placement.rs index 9409742..9409742 100644 --- a/tools/router-rs/src/placement.rs +++ b/tools/router/src/placement.rs diff --git a/tools/router-rs/src/pour.rs b/tools/router/src/pour.rs index b7aaab4..b7aaab4 100644 --- a/tools/router-rs/src/pour.rs +++ b/tools/router/src/pour.rs diff --git a/tools/router-rs/src/router.rs b/tools/router/src/router.rs index b22b78a..e829fe8 100644 --- a/tools/router-rs/src/router.rs +++ b/tools/router/src/router.rs @@ -1,4 +1,4 @@ -//! Routing strategies on top of the board fields (port of tools/router/pipeline.py): +//! Routing strategies on top of the board fields (port of an earlier Python router): //! plane drops, component joining, pad pairs, decoupling caps, rip-up and reroute. use crate::board::{Board, Item, Owner, SearchOpts, Seg, Shape, CLR, CU_STEP, M, RDIAG, RES}; diff --git a/tools/router-rs/src/run.rs b/tools/router/src/run.rs index 8de3e65..8de3e65 100644 --- a/tools/router-rs/src/run.rs +++ b/tools/router/src/run.rs diff --git a/tools/thermal_vias.py b/tools/thermal_vias.py index 744d0d6..d2e7425 100644 --- a/tools/thermal_vias.py +++ b/tools/thermal_vias.py @@ -1,6 +1,6 @@ """Add a grid of thermal vias to the exposed pads of the given footprints, after routing. -The routers (tools/router-rs, tools/placer) refuse footprints with bottom-side pads, so the +The routers (tools/router, tools/placer) refuse footprints with bottom-side pads, so the KiCad "_ThermalVias" footprint variants cannot be used. Use the plain exposed-pad footprint, keep B.Cu clear under the pad with a router cost zone (route.toml), and run this on the routed board. Each via takes the pad's net; a via is skipped where it would come within the clearance |
