Compare commits

..
Author SHA1 Message Date
rsp2k fa20dc5623 Merge main into feat/reduce-vias 2026-10-07 20:54:02 -06:00
rsp2k b9fed0fc4d Merge feat/verify-output: check grid and room output on exact shapes, --strict 2026-10-07 20:12:51 -06:00
rsp2k 8cb7a627f0 Add --reduce-vias and --via-cost to the exact engine
--reduce-vias is a last stage: each net that has vias is routed again on
its own with vias made eight times dearer, everything else held as fixed
copper (the window stage's board), and its new copper is kept only if the
net fails nothing new and has fewer vias; the nets with the most vias go
first, within a share of the routing's own time. --via-cost exposes the
search's layer-change price (default 10 grid steps). bench.py records
each run's via count and prints via totals per variant.
2026-10-07 20:06:00 -06:00
rsp2k 74d97b601c Check grid and room output on exact shapes and report shorts
The grid and room engines write copper they never check. After a grid or
room run the result is now put through the exact engine's geometry (its
pads, fixed copper and keepouts; wires as boxes or slanted slabs; vias as
their pads) and the report gives the shorts and clearance violations, with
examples, instead of a blanket warning. --strict exits 3 when there are any;
by default the exit status stays 0 so the JAR drop-in contract holds.

The exact engine's static-copper setup moves into insert_static_copper so
both use it; exact runs are byte-identical before and after.
2026-10-07 20:04:04 -06:00
rsp2k 1852df3d53 Merge fix/default-exact: exact engine by default, warn on unchecked engines 2026-10-07 18:52:10 -06:00
10 changed files with 653 additions and 43 deletions
+16 -1
View File
@@ -100,13 +100,18 @@ def run_one(board, variant, seed: int, timeout: float) -> dict:
)
rss_mb = round(usage.ru_maxrss / 1024)
secs = round(time.monotonic() - start, 1)
try:
with open(f"{tmp}/out.ses", encoding="utf-8") as f:
vias = f.read().count("(via ")
except OSError:
vias = None
missing = NOT_ROUTED.search(err)
zone = TO_ZONE.search(err)
return {
"board": name, "variant": vname, "seed": seed, "status": status,
"unrouted": int(missing.group(1)) if missing else 0,
"to_zone": int(zone.group(1)) if zone else 0,
"secs": secs, "rss_mb": rss_mb,
"secs": secs, "rss_mb": rss_mb, "vias": vias,
"tail": err.strip().splitlines()[-1] if status != "ok" and err.strip() else "",
}
@@ -147,6 +152,16 @@ def report(rows: list[dict], boards, variants) -> None:
line += (f" {dm:+.1f} ± {se:.1f} ({better} better, {worse} worse,"
f" {len(diffs) - better - worse} same) {verdict}")
print(line)
# vias, where the runs recorded them (older result files did not)
print("\nvias per variant, summed over boards (mean over seeds per board)\n")
for vname, _, _ in variants:
total, boards_counted = 0.0, 0
for bname, _, _ in boards:
vs = [r["vias"] for k, r in ok.items() if k[:2] == (bname, vname) and r.get("vias") is not None]
if vs:
total += sum(vs) / len(vs)
boards_counted += 1
print(f"{vname:14} {total:8.1f} vias over {boards_counted} boards")
failed = [r for r in rows if r["status"] != "ok"]
for r in failed:
print(f"FAILED {r['board']} {r['variant']} seed {r['seed']}: {r['status']} {r['tail']}")
+33
View File
@@ -237,3 +237,36 @@ class ShapeSearchTree:
if overlaps_2d(grown, other_tile):
return shape
return None
def violation_pairs(self, clearance: int) -> list[tuple[TreeShape, TreeShape, bool]]:
"""Every different-net pair sharing a layer, at least one of them
routed, whose coppers come closer than ``clearance``: ``(routed tile,
other tile, touching)``. ``touching`` is True when the coppers
themselves overlap (a short, or copper inside a keepout); False for a
clearance violation. Each pair of tiles is reported once.
:meth:`has_violation` asks whether there is one; this lists them all,
for a report on copper that no engine has checked.
"""
pairs: list[tuple[TreeShape, TreeShape, bool]] = []
seen: set[tuple[int, int]] = set()
for shape in self.all_shapes():
if not shape.routed:
continue
mine = shape.exact if shape.exact is not None else shape.tile
grown = shape.clearance_region(clearance)
for other in self.overlapping(grown.bounding_box()):
if other is shape or other.net_no == shape.net_no:
continue
if not (shape.layers & other.layers):
continue
key = (min(id(shape), id(other)), max(id(shape), id(other)))
if key in seen:
continue
theirs = other.exact if other.exact is not None else other.tile
touching = overlaps_2d(mine, theirs)
if not touching and (not other.clearance or not overlaps_2d(grown, theirs)):
continue # a rule area only counts an overlap
seen.add(key)
pairs.append((shape, other, touching))
return pairs
+74 -8
View File
@@ -25,15 +25,19 @@ from rpmroute.route.pipeline import (
build_rooms_routing_result,
build_routing_result,
)
from rpmroute.route.verify import verify_result
from rpmroute.ses import write_ses
#: which optional flags each engine actually implements. Anything not listed for
#: an engine is rejected by :func:`_validate` rather than quietly ignored.
ENGINE_OPTIONS: dict[str, frozenset[str]] = {
"grid": frozenset({"rip_up", "max_passes", "seed", "orders", "promote", "access", "negotiate", "rollback", "tree"}),
"grid": frozenset({
"rip_up", "max_passes", "seed", "orders", "promote", "access", "negotiate", "rollback",
"tree", "via_cost",
}),
"exact": frozenset({
"shove", "diagonal", "rip_up", "max_passes", "seed", "orders", "promote", "access",
"negotiate", "rollback", "tree", "window",
"negotiate", "rollback", "tree", "window", "vias", "via_cost",
}),
"room": frozenset({"shove", "pack"}),
}
@@ -53,6 +57,8 @@ _FLAG_NAMES = {
"rollback": "--no-rollback",
"tree": "--no-tree",
"window": "--window-reroute",
"vias": "--reduce-vias",
"via_cost": "--via-cost",
}
@@ -237,6 +243,37 @@ def build_parser() -> argparse.ArgumentParser:
metavar="MM",
help="the first round's window margin around the stuck connection's pins (default 1.5)",
)
parser.add_argument(
"--via-cost",
type=float,
default=None,
metavar="C",
help="grid and exact engines: what a layer change costs the search, in grid "
"steps of track (default 10)",
)
parser.add_argument(
"--reduce-vias",
action="store_true",
default=None,
help="exact engine: after routing, route each net that has vias again on its own "
"with vias made dearer, everything else held fixed; its new copper is kept only "
"if it fails nothing new and has fewer vias",
)
parser.add_argument(
"--reduce-vias-budget",
type=float,
default=0.5,
metavar="F",
help="via reduction stops starting nets once it has spent this share of the "
"routing's own time (default 0.5)",
)
parser.add_argument(
"--reduce-vias-margin",
type=float,
default=2.0,
metavar="MM",
help="how far past its pins and copper a net may go when routed again (default 2.0)",
)
parser.add_argument(
"--hole-to-hole",
type=float,
@@ -251,6 +288,15 @@ def build_parser() -> argparse.ArgumentParser:
metavar="J",
help="processes for --orders (default: one per order, up to the CPU count)",
)
parser.add_argument(
"--strict",
action="store_true",
help=(
"exit with status 3 when the routed copper has shorts or clearance "
"violations (grid and room output is checked after routing; the "
"session file is still written)"
),
)
return parser
@@ -278,6 +324,8 @@ def main(argv: list[str] | None = None) -> int:
("rollback", not args.rollback),
("tree", not args.tree_nets),
("window", args.window_reroute is not None),
("vias", args.reduce_vias is not None),
("via_cost", args.via_cost is not None),
)
if asked
]
@@ -321,7 +369,12 @@ def main(argv: list[str] | None = None) -> int:
"window_margin_mm": args.window_margin,
"window_budget": args.window_budget,
"window_cap": args.window_cap,
"reduce_vias": bool(args.reduce_vias),
"reduce_vias_budget": args.reduce_vias_budget,
"reduce_vias_margin_mm": args.reduce_vias_margin,
}
if args.via_cost is not None:
options["via_cost"] = args.via_cost
elif args.engine == "grid":
options = {
"layers": layers,
@@ -335,6 +388,8 @@ def main(argv: list[str] | None = None) -> int:
"rollback": args.rollback,
"tree_nets": args.tree_nets,
}
if args.via_cost is not None:
options["via_cost"] = args.via_cost
if args.engine == "room":
result = build_rooms_routing_result(
dsn, layers=layers, shove=args.shove, pack=args.pack,
@@ -387,23 +442,34 @@ def main(argv: list[str] | None = None) -> int:
for net, a, b, zone in in_zone:
print(f" {net}: {a} to {b} (both in zone {zone})", file=sys.stderr)
flawed = False
if args.engine != "exact":
# These engines route on approximations and do not check the copper
# they write against exact shapes: a board can come out with shorts
# that this report would otherwise never mention.
# they write: check it now against the exact shapes the exact engine
# uses, so shorts are reported rather than shipped.
check = verify_result(dsn, result)
flawed = not check.clean
print(
f"rpmroute: WARNING: the {args.engine} engine does not check its copper for "
"clearance or shorts; run KiCad's DRC on the result, or route with "
"--engine exact (the default)",
f"rpmroute: {args.engine} output checked on exact shapes: "
f"{check.shorts} short(s), {check.clearance} clearance violation(s)",
file=sys.stderr,
)
for kind, examples in (("short", check.short_examples), ("clearance", check.clearance_examples)):
for found in examples:
print(f" {kind}: {found}", file=sys.stderr)
if flawed:
print(
f"rpmroute: WARNING: this {args.engine} routing is not DRC-clean; fix it in "
"KiCad or route with --engine exact (the default)",
file=sys.stderr,
)
if args.output:
with open(args.output, "w", encoding="utf-8") as f:
f.write(ses_text)
else:
sys.stdout.write(ses_text)
return 0
return 3 if (flawed and args.strict) else 0
if __name__ == "__main__":
+38 -32
View File
@@ -155,38 +155,7 @@ def route_board_exact(
owner = _counter()
# static items: pad and keepout copper (routed=False)
for pin in board.get_pins():
if pin.shape is None:
continue
box = pin.shape.bounding_box()
if box.is_empty():
continue
net = pin.net_nos[0] if pin.net_nos else -1
pin_layers = frozenset(layer for layer in pin.layers if layer in signal_layers)
if pin_layers:
# a rotated pad is checked against its outline, not its box
exact = pin.shape if _is_rotated(pin.shape) else None
tree.insert(TreeShape(next(owner), net, pin_layers, box, exact=exact))
for net, copper_layers, box in board.get_fixed_copper():
on = frozenset(layer for layer in copper_layers if layer in signal_layers)
if on and not box.is_empty():
tree.insert(TreeShape(next(owner), net, on, box))
for obstacle in board.get_obstacle_areas():
if obstacle.layer not in signal_layers:
continue
blocks = (
"all" if obstacle.blocks_wires and obstacle.blocks_vias
else "wires" if obstacle.blocks_wires else "vias"
)
for tile in obstacle.tiles:
box = tile.bounding_box()
if not box.is_empty():
tree.insert(
TreeShape(
next(owner), -1, frozenset({obstacle.layer}), box,
blocks=blocks, clearance=obstacle.clearance,
)
)
insert_static_copper(tree, board, signal_layers, owner)
via_layers = frozenset(signal_layers)
accepted: dict[int, _Accepted] = {}
@@ -325,6 +294,43 @@ def route_board_exact(
# --- 45-degree (diagonal) recovery -------------------------------------------
def insert_static_copper(tree: ShapeSearchTree, board: BasicBoard, signal_layers, owner) -> None:
"""Index the board's pads, fixed copper and keepouts (``routed=False``) on
``signal_layers``: what routed copper is checked against."""
for pin in board.get_pins():
if pin.shape is None:
continue
box = pin.shape.bounding_box()
if box.is_empty():
continue
net = pin.net_nos[0] if pin.net_nos else -1
pin_layers = frozenset(layer for layer in pin.layers if layer in signal_layers)
if pin_layers:
# a rotated pad is checked against its outline, not its box
exact = pin.shape if _is_rotated(pin.shape) else None
tree.insert(TreeShape(next(owner), net, pin_layers, box, exact=exact))
for net, copper_layers, box in board.get_fixed_copper():
on = frozenset(layer for layer in copper_layers if layer in signal_layers)
if on and not box.is_empty():
tree.insert(TreeShape(next(owner), net, on, box))
for obstacle in board.get_obstacle_areas():
if obstacle.layer not in signal_layers:
continue
blocks = (
"all" if obstacle.blocks_wires and obstacle.blocks_vias
else "wires" if obstacle.blocks_wires else "vias"
)
for tile in obstacle.tiles:
box = tile.bounding_box()
if not box.is_empty():
tree.insert(
TreeShape(
next(owner), -1, frozenset({obstacle.layer}), box,
blocks=blocks, clearance=obstacle.clearance,
)
)
def _octilinear_candidates(a: IntPoint, b: IntPoint) -> list[list[IntPoint]]:
"""Octilinear (0/45/90/135-degree) polylines from ``a`` to ``b``.
+30
View File
@@ -22,6 +22,7 @@ from rpmroute.ses import RoutedVia, RoutedWire, RoutingResult, write_ses
from .exact_router import ExactRouteResult, route_board_exact
from .grid_router import RouteResult, route_board
from .room_router import route_board_rooms
from .vias import reduce_vias as reduce_vias_stage
from .window import window_reroute as window_reroute_stage
__all__ = ["route", "route_dsn_board", "build_routing_result"]
@@ -124,6 +125,7 @@ def route_dsn_board(
hole_to_hole_mm: float = 0.25,
rollback: bool = True,
tree_nets: bool = True,
via_cost: float = 10.0,
) -> tuple[RouteResult, int, list[str]]:
"""Route a parsed :class:`DsnBoard`; return the board-unit result, the scale,
and the layer names. ``layers`` restricts routing to those signal-layer
@@ -153,6 +155,7 @@ def route_dsn_board(
net_widths=_net_widths_board(dsn, scale),
via_drill=_via_drill_board(dsn, scale),
hole_to_hole=_mm_to_board(dsn, scale, hole_to_hole_mm) or 0,
via_cost=via_cost,
)
return result, scale, [layer.name for layer in dsn.layers]
@@ -206,6 +209,7 @@ def build_routing_result(
hole_to_hole_mm: float = 0.25,
rollback: bool = True,
tree_nets: bool = True,
via_cost: float = 10.0,
) -> RoutingResult:
"""Route ``dsn`` (grid track) and convert to a DSN-unit RoutingResult."""
route, scale, layer_names = route_dsn_board(
@@ -217,6 +221,7 @@ def build_routing_result(
hole_to_hole_mm=hole_to_hole_mm,
rollback=rollback,
tree_nets=tree_nets,
via_cost=via_cost,
)
return _to_routing_result(route, dsn, scale, layer_names)
@@ -244,6 +249,10 @@ def route_dsn_board_exact(
window_margin_mm: float = 1.5,
window_budget: float = 0.25,
window_cap: int = 40,
reduce_vias: bool = False,
reduce_vias_budget: float = 0.5,
reduce_vias_margin_mm: float = 2.0,
via_cost: float = 10.0,
) -> tuple[ExactRouteResult, int, list[str]]:
"""Route a parsed :class:`DsnBoard` with the exact-geometry (orthogonal,
DRC-verified) track; return the exact result, the scale, and layer names.
@@ -272,6 +281,7 @@ def route_dsn_board_exact(
"net_widths": _net_widths_board(dsn, scale),
"via_drill": _via_drill_board(dsn, scale),
"hole_to_hole": _mm_to_board(dsn, scale, hole_to_hole_mm) or 0,
"via_cost": via_cost,
}
started = time.monotonic()
exact = route_board_exact(
@@ -297,6 +307,18 @@ def route_dsn_board_exact(
budget_s=max(float(window_budget), 0.0) * (time.monotonic() - started),
max_windows=window_cap,
)
if reduce_vias:
via_half = common["via_half"] or max(width_board // 2, 1)
exact.result = reduce_vias_stage(
dsn, exact.result, common,
resolution=resolution,
margin=_mm_to_board(dsn, scale, reduce_vias_margin_mm) or 0,
via_half=via_half,
via_drill=common["via_drill"] or 2 * via_half,
via_name=_via_padstack(dsn),
# a share of what the routing itself took
budget_s=max(float(reduce_vias_budget), 0.0) * (time.monotonic() - started),
)
return exact, scale, [layer.name for layer in dsn.layers]
@@ -323,6 +345,10 @@ def build_exact_routing_result(
window_margin_mm: float = 1.5,
window_budget: float = 0.25,
window_cap: int = 40,
reduce_vias: bool = False,
reduce_vias_budget: float = 0.5,
reduce_vias_margin_mm: float = 2.0,
via_cost: float = 10.0,
) -> RoutingResult:
"""Route ``dsn`` (exact track) and convert to a DSN-unit RoutingResult."""
exact, scale, layer_names = route_dsn_board_exact(
@@ -347,6 +373,10 @@ def build_exact_routing_result(
window_margin_mm=window_margin_mm,
window_budget=window_budget,
window_cap=window_cap,
reduce_vias=reduce_vias,
reduce_vias_budget=reduce_vias_budget,
reduce_vias_margin_mm=reduce_vias_margin_mm,
via_cost=via_cost,
)
return _to_routing_result(exact.result, dsn, scale, layer_names)
+151
View File
@@ -0,0 +1,151 @@
"""Check routed copper that no engine has checked.
The exact engine verifies every connection against exact pad and copper
shapes before it accepts it. The grid and room engines do not: they route on
approximations, and their output can short or crowd another net with nothing
in their report to say so. :func:`verify_result` puts a finished
:class:`RoutingResult` through the same exact geometry the exact engine uses
(its pads, fixed copper and keepouts, wires as boxes or slanted slabs, vias as
their pads) and lists what it finds.
A violation is a pair of different-net coppers on a shared layer, at least one
of them routed, closer than the board's clearance rule. It is a short when the
coppers themselves overlap (or routed copper sits inside a keepout), else a
clearance violation. Pairs are counted per routed segment or via, as KiCad's
DRC counts per item pair; pads already too close to each other in the design
are not the router's and are not counted.
"""
from __future__ import annotations
from dataclasses import dataclass, field
import itertools
from rpmroute.board import build_board
from rpmroute.board.search_tree import ShapeSearchTree, TreeShape
from rpmroute.dsn.model import DsnBoard
from rpmroute.geometry import IntBox, IntPoint, segment_box, segment_slab
from rpmroute.geometry.polyline import corner_box
from rpmroute.ses.model import RoutingResult
from .exact_router import insert_static_copper
from .pipeline import _dsn_units_per_um, _rule_clearance_dsn, _via_half_board
# examples kept per kind; the counts are always complete
MAX_EXAMPLES = 5
@dataclass
class Violation:
"""One offending pair: the routed copper's net, what it came too close
to, the layer, and roughly where (mm, DSN coordinates)."""
net: str
other: str
layer: str
x_mm: float
y_mm: float
def __str__(self) -> str:
return f"{self.net} x {self.other} on {self.layer} at ({self.x_mm:.2f}, {self.y_mm:.2f}) mm"
@dataclass
class VerifyReport:
shorts: int = 0
clearance: int = 0
short_examples: list[Violation] = field(default_factory=list)
clearance_examples: list[Violation] = field(default_factory=list)
@property
def clean(self) -> bool:
return not (self.shorts or self.clearance)
def verify_result(dsn: DsnBoard, result: RoutingResult) -> VerifyReport:
"""Check ``result``'s copper against ``dsn``'s pads, keepouts and each
other, with the board's clearance rule."""
board = build_board(dsn)
scale = max(dsn.resolution.value, 1)
clearance = round(_rule_clearance_dsn(dsn) * scale)
signal_layers = [i for i, layer in enumerate(dsn.layers) if layer.is_signal]
layer_index = {layer.name: i for i, layer in enumerate(dsn.layers)}
via_layers = frozenset(signal_layers)
net_numbers = {n.name: i + 1 for i, n in enumerate(dsn.nets)}
names = {number: name for name, number in net_numbers.items()}
tree = ShapeSearchTree()
owner = itertools.count(1)
insert_static_copper(tree, board, signal_layers, owner)
static_names: dict[int, str] = {}
for shape in tree.all_shapes():
static_names[shape.owner] = "keepout" if shape.net_no == -1 else f"pad of {names.get(shape.net_no, '?')}"
via_default = _via_half_board(dsn, scale)
for net in result.nets:
net_no = net_numbers.get(net.name)
if net_no is None:
continue
for wire in net.wires:
layer = layer_index.get(wire.layer)
if layer is None or layer not in signal_layers:
continue
half = max(round(wire.width * scale / 2), 1)
pts = [
IntPoint(round(wire.coords[i] * scale), round(wire.coords[i + 1] * scale))
for i in range(0, len(wire.coords) - 1, 2)
]
on = frozenset({layer})
for a, b in zip(pts, pts[1:], strict=False):
oid = next(owner)
if a.x == b.x or a.y == b.y:
tree.insert(TreeShape(oid, net_no, on, segment_box(a, b, half), routed=True))
else: # a 45-degree or slanted segment, on its exact copper
slab = segment_slab(a, b, half)
tree.insert(TreeShape(
oid, net_no, on, slab.bounding_box(), routed=True,
exact=slab, seg=("slab", a, b, half),
))
# the round end where it meets the next segment, with this one
tree.insert(TreeShape(oid, net_no, on, corner_box(b, half), routed=True))
for via in net.vias:
half = via_default or max(round(_wire_width(net) * scale / 2), 1)
x, y = round(via.x * scale), round(via.y * scale)
tree.insert(TreeShape(
next(owner), net_no, via_layers, IntBox(x - half, y - half, x + half, y + half), routed=True,
))
mm_per_unit = 1 / (_dsn_units_per_um(dsn) * 1000 * scale)
# one entry per pair of items, however many of their tiles meet; a short
# if any of them overlap
by_pair: dict[tuple[int, int], tuple[TreeShape, TreeShape, bool]] = {}
for shape, other, touching in tree.violation_pairs(clearance):
key = (min(shape.owner, other.owner), max(shape.owner, other.owner))
seen = by_pair.get(key)
if seen is None or (touching and not seen[2]):
by_pair[key] = (shape, other, touching)
report = VerifyReport()
for shape, other, touching in by_pair.values():
layer = min(shape.layers & other.layers)
box = shape.tile.intersection(other.tile.offset(clearance))
if box.is_empty():
box = shape.tile
what = names.get(other.net_no, "?") if other.routed else static_names.get(other.owner, "?")
found = Violation(
names.get(shape.net_no, "?"), what, dsn.layers[layer].name,
(box.ll.x + box.ur.x) / 2 * mm_per_unit, (box.ll.y + box.ur.y) / 2 * mm_per_unit,
)
if touching:
report.shorts += 1
if len(report.short_examples) < MAX_EXAMPLES:
report.short_examples.append(found)
else:
report.clearance += 1
if len(report.clearance_examples) < MAX_EXAMPLES:
report.clearance_examples.append(found)
return report
def _wire_width(net) -> float:
return max((w.width for w in net.wires), default=0.0)
+128
View File
@@ -0,0 +1,128 @@
"""Via reduction: a last stage that routes each net again with vias made dear.
The main search prices a layer change at a few millimetres of track, which
is right while the board is crowded and wrong once it is routed: a net that
hopped layers to slip past a route can often stay on one layer around it.
So each net that has vias is ripped and routed again on its own, everything
else held as fixed copper, with the via cost raised; the new copper is kept
only if the net loses no connection and ends with fewer vias.
It reuses the window stage's board: the net's own items and copper, and of
everything else only what lies near the box the net is routed in. The nets
with the most vias go first, and no new net starts once ``budget_s`` is
spent.
"""
from __future__ import annotations
import time
from typing import Any
from rpmroute.board import build_board
from rpmroute.dsn import DsnBoard
from rpmroute.geometry import IntBox
from .exact_router import route_board_exact
from .grid_router import RouteResult
from .window import Copper, _inside, _item_box, _open, _window_board
def _net_box(copper: Copper, pins: list, grow: int) -> IntBox | None:
wires, vias = copper
points = [p for _layer, path in wires for p in path] + list(vias) + pins
if not points:
return None
xs, ys = [p.x for p in points], [p.y for p in points]
return IntBox(min(xs) - grow, min(ys) - grow, max(xs) + grow, max(ys) + grow)
def reduce_vias(
dsn: DsnBoard,
result: RouteResult,
route_args: dict[str, Any],
*,
resolution: int,
margin: int,
via_half: int,
via_drill: int,
via_name: str,
via_cost_factor: float = 8.0,
budget_s: float | None = None,
) -> RouteResult:
"""Route each net with vias again with vias ``via_cost_factor`` times dearer;
keep a net's new copper only when it fails nothing new and has fewer vias.
``route_args`` are the exact engine's settings for the whole board.
``margin`` grows the box around the net's pins and copper that it is
routed in, so it may go round what it used to hop over."""
started = time.monotonic()
copper: dict[int, Copper] = {
net: (list(result.wires.get(net, [])), list(result.vias.get(net, [])))
for net in set(result.wires) | set(result.vias)
}
todo = sorted((n for n, c in copper.items() if c[1]), key=lambda n: -len(set(copper[n][1])))
if not todo:
return result
default_half = result.half_width
half = dict(result.net_half)
failed = list(result.failed)
base = build_board(dsn)
base_items = [(item, _item_box(item)) for item in base.get_items()]
layers = route_args.get("layers") or [
i for i, layer in enumerate(base.layer_structure.arr) if layer.is_signal
]
pins_of: dict[int, list] = {}
for pin in base.get_pins():
for net in pin.net_nos:
pins_of.setdefault(net, []).append(pin.location)
context = 2 * (route_args["trace_width"] + route_args["clearance"]) + 2 * via_half + (
route_args.get("edge_clearance") or 0
)
args = dict(route_args)
args["via_cost"] = float(route_args.get("via_cost", 10.0)) * via_cost_factor
changed = False
for net in todo:
if budget_s is not None and time.monotonic() - started >= budget_s:
break
old_vias = len(set(copper[net][1]))
window = _net_box(copper[net], pins_of.get(net, []), margin)
if window is None:
continue
before = _open(f for f in failed if f[0] == net)
view = IntBox(window.ll.x - context, window.ll.y - context,
window.ur.x + context, window.ur.y + context)
keep = set(copper) - {net}
board = _window_board(base, base_items, view, {net}, copper, keep, half,
default_half, via_half, via_drill, layers, via_name)
sub = route_board_exact(
board, **args, resolution=resolution, only_nets=frozenset({net}), bounds=window,
).result
after = _open(f for f in sub.failed if f[0] == net)
new = (sub.wires.get(net, []), sub.vias.get(net, []))
if len(after) > len(before) or len(set(new[1])) >= old_vias:
continue
# the board left out what lies away from the box, so copper reaching
# out of it was never checked against that
if (new[0] or new[1]) and not _inside(new, window):
continue
copper[net] = (list(new[0]), list(new[1]))
half.pop(net, None)
if net in sub.net_half:
half[net] = sub.net_half[net]
failed = [f for f in failed if f[0] != net] + [f for f in sub.failed if f[0] == net]
changed = True
if not changed:
return result
out = RouteResult(default_half)
for net, (wires, vias) in copper.items():
for layer, path in wires:
out.add_wire(net, layer, path)
for location in dict.fromkeys(vias):
out.add_via(net, location)
out.failed = failed
out.unrouted = len(_open(failed))
out.net_half = half
out.narrowed = list(result.narrowed)
return out
+123
View File
@@ -0,0 +1,123 @@
"""Via reduction: each net with vias is routed again with vias made dear,
kept only when it fails nothing new and has fewer vias."""
from __future__ import annotations
from rpmroute.board import build_board
from rpmroute.dsn import parse_dsn
from rpmroute.geometry import IntPoint
from rpmroute.route.grid_router import RouteResult
from rpmroute.route.pipeline import (
_rule_clearance_dsn,
_rule_width_dsn,
_via_half_board,
route_dsn_board_exact,
)
from rpmroute.route.vias import reduce_vias
VIA = "Via[0-1]_600:300_um"
def _board(second_on_bottom: bool = False) -> str:
"""Two pads 14 mm apart on an empty two-layer board; the second on the
bottom layer when ``second_on_bottom``."""
p2_stack = "Bot_Pad" if second_on_bottom else "Top_Pad"
return f"""(pcb "vias.dsn"
(parser (string_quote ") (space_in_quoted_tokens on) (host_cad "t") (host_version "1"))
(resolution um 10)
(unit um)
(structure
(layer F.Cu (type signal) (property (index 0)))
(layer B.Cu (type signal) (property (index 1)))
(boundary (path pcb 0 0 0 20000 0 20000 -10000 0 -10000 0 0))
(via "{VIA}")
(rule (width 200) (clearance 200))
)
(library
(padstack Top_Pad (shape (rect F.Cu -300 -300 300 300)) (attach off))
(padstack Bot_Pad (shape (rect B.Cu -300 -300 300 300)) (attach off))
(padstack "{VIA}" (shape (circle F.Cu 600)) (shape (circle B.Cu 600)) (attach off))
(image TOP (pin Top_Pad 1 0 0))
(image SECOND (pin {p2_stack} 1 0 0))
)
(placement
(component TOP (place P1 3000 -5000 front 0))
(component SECOND (place P2 17000 -5000 front 0))
)
(network
(net N (pins P1-1 P2-1))
(class default (rule (width 200) (clearance 200)))
)
(wiring)
)
"""
def _route_args(dsn) -> dict:
scale = max(dsn.resolution.value, 1)
return {
"heuristic_weight": 1.0,
"via_half": _via_half_board(dsn, scale),
"edge_clearance": None,
"trace_width": round(_rule_width_dsn(dsn) * scale),
"clearance": round(_rule_clearance_dsn(dsn) * scale),
"layers": None,
"max_passes": 10,
"rip_up": True,
"shove": False,
"diagonal": False,
"rollback": True,
"tree_nets": True,
"net_widths": {},
"via_drill": None,
"hole_to_hole": 0,
"via_cost": 10.0,
}
def _reduce(text: str, result: RouteResult) -> RouteResult:
dsn = parse_dsn(text)
args = _route_args(dsn)
return reduce_vias(
dsn, result, args, resolution=1, margin=20000,
via_half=args["via_half"], via_drill=2 * args["via_half"], via_name=VIA,
)
def _pins(text: str) -> tuple[IntPoint, IntPoint]:
pins = {p.component_ref: p.location for p in build_board(parse_dsn(text)).get_pins()}
return pins["P1"], pins["P2"]
def test_a_needless_via_pair_is_routed_out():
text = _board()
a, b = _pins(text)
# a detour: down to the bottom layer and back up, for no reason
v1, v2 = IntPoint(a.x + 40000, a.y), IntPoint(b.x - 40000, b.y)
detour = RouteResult(1000)
detour.add_wire(1, 0, [a, v1])
detour.add_via(1, v1)
detour.add_wire(1, 1, [v1, v2])
detour.add_via(1, v2)
detour.add_wire(1, 0, [v2, b])
out = _reduce(text, detour)
assert out.failed == []
assert sum(len(v) for v in out.vias.values()) == 0
assert out.wires.get(1)
def test_a_needed_via_stays():
text = _board(second_on_bottom=True)
exact, _scale, _layers = route_dsn_board_exact(parse_dsn(text), resolution=1)
routed = exact.result
assert routed.failed == []
vias_before = sum(len(set(v)) for v in routed.vias.values())
assert vias_before >= 1
out = _reduce(text, routed)
assert out.failed == []
assert sum(len(set(v)) for v in out.vias.values()) == vias_before
def test_the_flag_runs_the_stage_end_to_end():
exact, _scale, _layers = route_dsn_board_exact(parse_dsn(_board()), resolution=1, reduce_vias=True)
assert exact.result.failed == []
+42
View File
@@ -0,0 +1,42 @@
"""verify_result: copper no engine checked is checked on exact shapes."""
from pathlib import Path
from rpmroute.dsn import parse_dsn
from rpmroute.route.verify import verify_result
from rpmroute.ses.model import RoutedWire, RoutingResult
FIXTURE = Path(__file__).parents[1] / "dsn" / "fixtures" / "crossing_2net.dsn"
# rule: 2000 um wide traces, 2000 um clearance; NET_A runs along y = -40000
A = RoutedWire(layer="Top", width=2000, coords=[2000, -40000, 198000, -40000])
def _check(b_wire):
result = RoutingResult()
result.add_wire("NET_A", A)
result.add_wire("NET_B", b_wire)
return verify_result(parse_dsn(FIXTURE.read_text()), result)
def test_a_crossing_on_one_layer_is_a_short():
report = _check(RoutedWire(layer="Top", width=2000, coords=[100000, -15000, 100000, -65000]))
assert report.shorts == 1 and report.clearance == 0
found = report.short_examples[0]
assert {found.net, found.other} == {"NET_A", "NET_B"} and found.layer == "Top"
assert abs(found.x_mm - 100.0) < 1.5 and abs(found.y_mm + 40.0) < 1.5
def test_copper_closer_than_the_rule_is_a_clearance_violation():
# edges 1500 um apart against a 2000 um rule
report = _check(RoutedWire(layer="Top", width=2000, coords=[50000, -36500, 150000, -36500]))
assert report.shorts == 0 and report.clearance == 1
def test_exactly_the_clearance_apart_is_clean():
report = _check(RoutedWire(layer="Top", width=2000, coords=[50000, -36000, 150000, -36000]))
assert report.clean
def test_a_crossing_on_another_layer_is_clean():
report = _check(RoutedWire(layer="Bottom", width=2000, coords=[100000, -15000, 100000, -65000]))
assert report.clean
+18 -2
View File
@@ -82,9 +82,23 @@ def test_cli_default_engine_is_exact(tmp_path):
@pytest.mark.parametrize("engine", ["grid", "room"])
def test_unchecked_engines_say_so(tmp_path, capsys, engine):
def test_unchecked_engines_are_checked_after_routing(tmp_path, capsys, engine):
assert main([str(FIXTURE), "--engine", engine, "-do", str(tmp_path / "out.ses")]) == 0
assert "does not check its copper" in capsys.readouterr().err
assert f"{engine} output checked on exact shapes: 0 short(s), 0 clearance" in capsys.readouterr().err
def test_strict_fails_a_run_whose_copper_is_not_clean(tmp_path, monkeypatch, capsys):
from rpmroute import cli
from rpmroute.route.verify import VerifyReport, Violation
bad = VerifyReport(shorts=1, short_examples=[Violation("A", "B", "F.Cu", 1.0, 2.0)])
monkeypatch.setattr(cli, "verify_result", lambda dsn, result: bad)
out = tmp_path / "out.ses"
assert main([str(FIXTURE), "--engine", "grid", "-do", str(out)]) == 0
assert main([str(FIXTURE), "--engine", "grid", "--strict", "-do", str(out)]) == 3
assert out.exists() # the session is still written
err = capsys.readouterr().err
assert "short: A x B on F.Cu at (1.00, 2.00) mm" in err and "not DRC-clean" in err
def test_the_exact_engine_does_not_warn(tmp_path, capsys):
@@ -174,6 +188,8 @@ def test_cli_supported_combinations_are_accepted(tmp_path):
"rollback": ["--no-rollback"],
"tree": ["--no-tree"],
"window": ["--window-reroute", "1"],
"vias": ["--reduce-vias"],
"via_cost": ["--via-cost", "40"],
}
for engine, options in ENGINE_OPTIONS.items():
for option in options: