From a59e8e99243a895197a30d6cd6dd8d744dd606de Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 11 Nov 2026 10:32:51 +0100 Subject: Keep only the current router: drop the Python router, router-rs -> router 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 --- knowledge/tooling/router.md | 222 +++++++++++++++++++++++++++----------------- 1 file changed, 139 insertions(+), 83 deletions(-) (limited to 'knowledge/tooling/router.md') diff --git a/knowledge/tooling/router.md b/knowledge/tooling/router.md index 136f1e8..c6c615f 100644 --- a/knowledge/tooling/router.md +++ b/knowledge/tooling/router.md @@ -1,95 +1,151 @@ -# Router (Python) +# Router -`tools/router/` is the scripted grid maze router that came before the [Rust router](rust-router.md). It routes one net at a time, in an order the board's own `route.py` script sets. New boards should use the Rust router, with a `route.toml` instead of a `route.py`. This router stays for existing scripts. Its board I/O (`dump_board.py`, `write_board.py`, `plot_routes.py`) is shared by both. +`tools/router/` routes 2-layer KiCad boards on a 0.05 mm grid with **negotiated congestion** (PathFinder): all nets at once, so there is no net order to get wrong. The Rust crate sits next to its KiCad I/O scripts: `dump_board.py` exports the board, `write_board.py` writes the routes back, and `plot_routes.py` draws them (each net in its own colour, B.Cu dashed, failed pins crossed). It is also a library: the [Placer](placer.md) links it to route its candidates in-process. KiCad's DRC stays the judge. -## Setup +For the end-to-end flow on your own board, start with [Place and route your own board](pnr.md). -``` sh -python3 -m venv tools/router/.venv -tools/router/.venv/bin/pip install -r tools/router/requirements.txt # numpy, shapely, scipy, matplotlib -``` - -The C core (`astar.c`) compiles itself with `cc` on first import. - -## How it works - -- **Grid:** 0.05 mm cells on F.Cu and B.Cu. - - Exact distance fields hold, for every cell, the distance to the nearest copper and to the nearest copper of another net. - - A track of width w fits where foreign copper is at least w/2 + 0.2 mm away. - - Near pads it may neck down (e.g. 0.5 mm power to 0.2 mm), so fine-pitch pins can be entered. -- **Search** (`astar.c`): 8-direction A* with costs for vias (default 40 cells), turns and B.Cu (`bmult`, default 3), plus optional cost maps per layer. No via lands in a pad. -- **Strategies** (`pipeline.py`): - - `route_plane_net("GND")`: each SMD ground pad gets its own via to the B.Cu plane; - - `connect(net)`: joins all copper of a net, nearest piece first; - - `route_pair(net, a, b)`: pad to pad; - - `connect_decaps(net)`: each decoupling cap to its own nearest IC pin, before the rest of the net; - - `tie(net, pad, xy)`: pad to a new via; - - `route_waypoints(...)`: a trunk through fixed points; - - `stitch("GND", pitch)`: stitching vias wherever they fit (finished boards only); - - `load_existing(dump)`: fixed copper, e.g. a planned bus, loaded before anything else; - - `route_net(...)` + `repair()`: rip-up and reroute. -- **Board I/O** (KiCad's Python): - - `dump_board.py` writes pads, net classes and widths, keep-outs, zones and existing copper to JSON. The output is sorted, so the same placement always gives the same dump. KiCad orders footprints by UUID, which a regenerated board draws anew, and the router's result depends on pad order. - - `write_board.py` writes tracks, vias and pours (`--replace`, `--diff`, `--zones`, `--prune-vias GND`). `--diff` changes only the items that differ, so untouched copper keeps its exact drill and width. Every mode restores the `.kicad_pro` that `SaveBoard` resets ([KiCad notes](kicad.md)). -- **Debugging:** `plot_routes.py board.json routes.json out.png [x0 y0 x1 y1]` draws each net in its own colour with its name, B.Cu dashed and failed pins crossed. KiCad's SVG export cannot show which net blocks which; this can. - -## Workflow +## Use ``` sh +cargo build --release --manifest-path tools/router/Cargo.toml . tools/kicad_env.sh # KPY, KC -VPY=tools/router/.venv/bin/python -$KPY tools/router/dump_board.py board.kicad_pcb /tmp/board.json -$VPY my_board/route.py /tmp/board.json /tmp/routes.json # the board's own script -$VPY tools/router/plot_routes.py /tmp/board.json /tmp/routes.json /tmp/z.png 110 90 130 110 -$KPY tools/router/write_board.py board.kicad_pcb /tmp/routes.json board.kicad_pcb --replace --prune-vias GND -$KC pcb drc --refill-zones --schematic-parity board.kicad_pcb -$KPY tools/silk_refs.py board.kicad_pcb # references off pads and each other +R=tools/router/target/release/router +$KPY tools/router/dump_board.py board.kicad_pcb board.json +$R route board.json route.toml routes.json [--fixed NAME=FILE]... [--stop LABEL] +$R place board.json placement.json moved.json # move parts to a placer result, without KiCad +$KPY tools/router/write_board.py board.kicad_pcb routes.json out.kicad_pcb --replace [--zones zones.json] --prune-vias GND +$KC pcb drc --refill-zones out.kicad_pcb ``` -`silk_refs.py` keeps each reference 0.5 mm inside the real board outline, clear of pads, vias and other silk. - -Close the board in KiCad and check for its `~*.lck` file before writing. Run with `PYTHONHASHSEED=0` so a rebuild gives the same board. - -To take parts off a routed board, use `tools/prune_copper.py board.kicad_pcb --remove J3 [--clip X0,Y0,X1,Y1] [--netlist board.net]`. It does four things: - -1. deletes the footprints; -2. optionally cuts the outline down, clipping zones and deleting copper outside; -3. renames nets to the schematic's names; -4. deletes whatever DRC would call dangling, repeating until nothing is left (KiCad's own `TestTrackEndpointDangling`). - -## Order that works (sequential routing) +The last line of `route` is: -1. **Keep hand routing** of nets whose parts did not move (`load_existing`). Those nets are protected from rip-up. -2. **Ground:** fixed vias under a QFP without an exposed pad, its GND pins to those vias, then every other SMD ground pad to its own via. If signal lines will close in THT ground pads, tie them to their own via now. -3. **The fine-pitch IC's own pins first:** crystal, regulator caps, bias resistor. Join analog supply pins inside the pad ring, then the PHY pairs, then control and bus lines. -4. **Supplies after the signals:** decaps pad to pad, then the rest of each rail. Wide power trunks go around signals easily; signals cannot get past an early trunk. -5. **Other signals, shortest first.** -6. `repair()`, then pours, then DRC. - -**Buses between two ICs:** do not leave them to a one-net-at-a-time router; a six-line bus took 37 vias that way. Instead: - -1. Work out the crossings from the pin orders on both ends. -2. Give each layer an order that needs no crossings. -3. Write the geometry as fixed copper and route the rest around it. - -That took 8 vias. The Rust router's negotiation makes this mostly unnecessary. - -## Cost zones - -- **F.Cu under a module** with pads underneath, and **inside a QFP pad ring** (reserved for its ground vias): cost 200 per cell. That is effectively forbidden, but not a hard keep-out, so GND drops can still use it. -- **Block tile:** make the board outline the tile plus the copper-to-edge clearance on the sides that face other blocks. The router and DRC then keep all copper inside the tile. -- **Quiet zone on B.Cu** under a crystal, PHY or Ethernet IC: +10 per cell for signals, which keeps the ground plane whole where it matters. -- **A failure within 0.4 s** means a pin is enclosed, not that the search budget ran out. Test the net alone on the empty board, and after each phase, to find which phase encloses it. - -## Rip-up and reroute - -`route_net(name, cost=..., **kw)` records each connection's cost map and settings. `repair(rounds, protect=kept_nets)` works in four steps: +``` +RESULT split= failed= islands= + vias= length= bcu= neck= score=<[rank]> time= +``` -1. finds nets still in several pieces; -2. removes the nets with copper within 1.2 mm of the unconnected pieces; -3. routes the failed net first; -4. routes the removed nets again with their recorded settings. +`ROUTER_TIMES=1` prints each step's time. `ROUTER_TRACE=1` prints each search and the conflicts left after the last negotiation round. + +`write_board.py` options: + +- `--replace` deletes the board's tracks and vias first. +- `--diff` changes only what differs from the board. Use it when `routes.json` also holds the board's own copper, for example a `[[fixed]]` dump, so that untouched copper keeps its exact drill and width. +- `--prune-vias NET` removes that net's vias that connect nothing. +- `--zones` adds pours from a JSON file. + +All three restore the `.kicad_pro` that pcbnew's `SaveBoard` would reset. + +## route.toml + +The doc comment of `src/config.rs` is the full reference. In short: + +### Board-wide + +- `prefix`: a sheet path such as `"/My Sheet/"` that net names in the file may leave out. +- `plane_nets`: nets that reach their pads through pours and drop vias, usually `["GND"]`. With `area = "pours"`, give a sheet-local plane its full name (e.g. `/Iso/GND_ISO`). Zones are matched literally, and a missing pour silently shrinks the area. +- `area`: limits where copper may go. + - `"pours"` keeps all copper inside the plane nets' pours, e.g. a design block that will be pasted onto a larger board. + - `[[x, y], ...]` gives a polygon instead. + - `area_margin` (mm) keeps copper that far inside. +- `[[bundle]] nets = [...]`: pairs and buses that should run side by side. A step that does not hug a partner's copper costs `attract` more. Set `attract` on the negotiate step (0.5 works well); the cleanup step defaults to 0.5. It is soft attraction, not coupled routing. +- `[[fixed]]`: copper loaded before the steps. + - `name` + `--fixed NAME=FILE`, or `path` relative to the toml. + - A JSON of tracks and vias, or a board dump with `unmoved = true` (keep the copper of nets whose parts did not move). + - `done = true` marks its nets complete. `protect = true` protects it from rip-up. + - `exclude = [...]`, `optional = true`. +- `[costs.NAME]`: cost maps. + - `zones = [{ layer = "F"|"B", fp = "U1", rect = [x0, y0, x1, y1], cost = 200 }]`. Rectangles are relative to the footprint origin and do not turn with it. Without `fp` they are absolute. Zones add up. + - `rudy = { scale, max }`: RUDY congestion of the pads' MSTs. + - `none` is empty. A step's `cost` stays set for the following steps. +- `[nets.NAME]`: per-net settings. + - `w` (width) and `wneck` (neck width). + - `neck_zone`: how far from a pad a track may neck; default 1 mm. + - `root` (`"U1:19"`, where the net's tree grows from) and `decaps` (each decoupling cap to its pin first). + - `priority` (higher routes first), `cost`, `bmult` (B.Cu multiplier) and `via_cost`. + - `[[nets.NAME.join]]` pad pairs routed first: `{ a = "U1:4", b = "U1:8", w, wneck, cost, allow_via }`. +- `[[escape]]`: reserves a way out for nets that leave a block, such as a module's interface lines with one pad each. + - Keys: `nets = [...]`, `from = [x, y]`, `to = [x, y]`, `size` (default 0.25), `w`, `keep`. + - It adds one virtual pad per net, evenly spaced from `from` to `to` and snapped to the grid, and routes them in the same negotiation. + - Their copper is left out of `routes.json` unless `keep = true`. + - A board only counts as complete if every interface line can still reach the edge. +- `[rank]`: how routed boards compare (used by `placer --route` and `pnr.sh`). + - First: split nets, failed connections, pour islands. + - Then a score: Σ length × net weight (`nets = [{ match = "*/ETH_*", weight = 2 }]`, `*` globs) + `via_mm` (2) × vias + `neck_mm` (2) × necked mm + `bcu_mm` (0) × B.Cu mm. + +### Steps (`[[step]] do = ...`, in order) + +| Step | What it does | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `negotiate` | routes every net still in pieces at once. `planes = true` negotiates the plane nets' pad drops too, so they give way to signals. Also: `cost`, `rounds`, `pres`, `pres_mult`, `hist`, `margin` (search window around each connection, default 1.5 mm), `attract` | +| `repair` | rips up what lies around failures and routes again (`rounds`) | +| `cleanup` | reroutes each net once with the rest fixed: shorter, fewer vias, tighter octilinear shortcuts, necks widened (`neck`, default 4) | +| `pour` | models the plane net's pour fill, finds islands that leave pads apart and joins them with vias (`fix`, default true; `d` via size) | +| `via` | fixed vias, e.g. ground vias inside a QFP pad ring | +| `plane` | each SMD pad of a plane net drops to its own via before the negotiation (`only`, `skip`) | +| `connect`, `pair`, `decaps`, `rest`, `tie`, `stitch` | ordered steps (outside the negotiation): nets in a given order, pad to pad, caps to pins, everything left, pad to a new via, stitching vias (finished boards only) | + +`label = "x"` on a step and `--stop x` end the run after that step. + +Two typical recipes: + +- `negotiate` (with `planes = true`) → `repair` → `cleanup` → `pour`. +- `via` + `plane` for ground first, then `negotiate` → `repair` → `cleanup`. -It cannot fix placement. If a net fails alone on the empty board, or fails again after repair, change the placement ([Placement for routing](../topics/placement-for-routing.md)). +## How it works -Related: [Placement check](placement-check.md), [Net classes](../topics/netclasses.md). +- **Grid**: 0.05 mm, origin snapped to a multiple of 0.05 mm (the edge clearance uses the true outline), so pads of parts on the placer's grid sit on cell centres. +- **Fields** (`board.rs`): + - Per cell and layer: the distance to and net of the nearest copper, and the distance to the nearest copper of another net. + - Board edge, NPTH and keep-outs are static no-net copper. + - Footprint copper that is not a pad (a net tie's bridge) is static too, sampled every 0.025 mm. + - A track of width w fits where foreign copper is at least w/2 + clearance away. It may neck to `wneck` only within `neck_zone` of the pads it joins. + - Separate fields keep vias out of SMD pads and drill edges 0.25 mm apart (KiCad's `min_hole_to_hole`). +- **Search** (`astar.rs`): 8-direction A* with turn cost (no turns over 90°), via cost, B.Cu multiplier (3) and cost maps. It uses a radix heap, which works because the octile heuristic is consistent. +- **Negotiation** (`router.rs`): + - Every net in pieces is a job. Tracks routed in negotiation are soft. + - A step onto other nets' soft copper costs (base + history) × (1 + present factor). + - After each round only the conflicting connections are rerouted. A net that stays in conflict for three rounds is rerouted whole with a wider window. + - Present factor 4, × 1.5 per round, up to 30 rounds. + - Whatever still conflicts is routed with soft copper made hard, trying every order of up to four such nets. Then all copper is hardened and dangling remnants are pruned. +- **Cleanup** (`cleanup.rs`): + - Each net is rerouted with the rest fixed. Steps that hug other copper are cheaper, so lines bundle. + - A reroute is kept if it is at most 2 % worse (length + 2 mm per via + 2 × necked mm) and splits nothing. + - Vias that are not needed go. + - Same-layer chains are pulled tight to octilinear shortcuts, and necked tracks widen wherever clearance allows. +- **Pours** (`pour.rs`): + - A plane net's pours fill where foreign copper is at least clearance + half the minimum fill width away. + - The net's copper joins an island where tracks and vias touch it, and where pads are within thermal-gap + spoke distance. + - Pad groups left apart get a via or a short track to the main island. Whatever stays apart is reported as `islands`. +- **Placer link**: + - `placer run ... --route board.json route.toml --route-top K` routes the best K placements in parallel and ranks them. + - `placer route PROBLEM CONFIG board.json route.toml OUT PLACEMENT...` does the same for existing placement files. + - Memory: about 160 MB per board routed at once. + +## Lessons from real boards + +- **Net order was the limit, and negotiation removes it.** With the same grid, costs and A*, a one-net-at-a-time router completed 5 of 32 placer candidates on a dense ESP32 + Ethernet board. Negotiation completed 20, and later 26 with bundle attraction. +- **PathFinder's multiplicative form matters.** With additive costs (step + present + history), the present factor swamps history, and two nets keep trading the same crossing. (base + history) × (1 + present) converged in about 12 rounds. +- **Hard pre-routes can box in pins** that negotiation cannot free later. Prefer `planes = true` over `plane` steps when ground drops wall in signal pins. +- **Interface escapes in a block.** Without `[[escape]]`, "complete" boards walled in an MCU's interface pins with supply and crystal tracks. + - Don't put cost zones on the escape channels. They price the layer for the escape lines too, which then drop to B.Cu with a via at each fine-pitch pin. + - Space escape pads at least 0.5 mm apart for 0.2 mm lines. Lines need 0.415 mm, and at 0.45 mm the slack is less than one grid step. + - Choose `from`/`to` so that the pitch is a multiple of 0.05 mm. + - Keep the escape corridor free of parts. Covering the whole pin side with a footprint rule area works. +- **Fine-pitch parts must sit on the 0.05 mm grid.** A QFN 0.01 mm off the cells failed random pins on every placement. Put fixed parts' origins on multiples of 0.05 mm. The placer keeps its own parts on the grid. +- **0.4 mm QFN vs 0.5 mm LQFP**: two 0.2 mm tracks cannot leave neighbouring 0.4 mm-pitch pins side by side. If nearly every pin is used, all lines must neck (`wneck = 0.15`, `neck_zone = 2`). When a fine-pitch MCU has many consecutive pins in use, compare packages before tuning the router: the LQFP routed every time, the QFN never. +- **Routing a base board between fixed blocks**: + - Load the whole board dump as `[[fixed]] unmoved = true, protect = true` and route only what is still apart. + - Raise `margin` on the negotiate step (e.g. 20). Otherwise the 1.5 mm window never reaches the free channel between blocks, and lines cut through them. + - Write the result with `write_board.py --diff`. +- **Rerouting a few nets on a finished board**: strip those nets' copper from a copy, dump it, and load the dump as `[[fixed]] unmoved = true` **without** `done = true`. With `done = true` the stripped nets count as done too, and negotiate gets no jobs. +- **Starved thermal spokes**: the router does not model thermal-relief spokes. Through-hole plane pads next to signal pins can end with one spoke (KiCad DRC `starved_thermal`). On small pours, solid zone connections for those pads fix it. +- **Bundle attraction only works in the negotiation.** In the cleanup the space beside a partner is already taken. With `attract = 0.5` on negotiate, pair coupling went from about 2–9 % to about 30 %, with fewer vias. Too strong (2) pulls nets off their short paths. +- **Placement measures do not predict routability.** Spearman |ρ| ≤ 0.3 between unconnected pins and placer cost, crossings, RUDY or a coarse global route. Rank by routing instead (`--route`). +- A weighted A* heuristic (1.5–2) made negotiation slower and worse. Search windows and partial reroutes were what helped. + +## Limits + +- Two layers only. Footprints with bottom-side pads are refused: use the plain exposed-pad footprint, then [Thermal vias](thermal-vias.md) after routing. +- Differential pairs are routed as single nets; bundles only attract. +- No thermal-spoke check in the pour model. +- Negotiated boards take 4–15 s each on a 50-part board, single-threaded per board. -- cgit v1.3