Add MVP grid maze router and DSN->SES routing pipeline
Implements a working autorouter and the Java-free replacement for the freerouting.jar step: dsn_text -> parse_dsn -> build_board -> route -> write_ses. GridRouter is a single-layer A* maze search over a uniform occupancy grid: a cell is blocked by another net's pad (inflated by clearance + half trace width) or a keepout; each net's ratsnest is connected pin to pin; a routed trace then blocks other nets. The cell path becomes a trace polyline whose endpoints are the exact pin locations. Board-unit paths are converted back to DSN units for the SES (wire (path ...)) scopes. This is an MVP, not a port of FreeRouting's expansion-room maze: free-space rooms, rip-up-and-retry, multi-layer via search, and shove are deferred (they raise quality/coverage, not the connectivity milestone). It reaches connectivity on boards whose nets route on one layer without crossing. Adds tests/dsn/fixtures/simple_2net.dsn (a guaranteed-routable 2-net board). Invariant tests: both nets route, the emitted SES parses, every trace stays on a valid layer and within the board outline, and every routed net's trace endpoints sit exactly on its two pads. An oracle-gated test asserts connectivity parity with the reference FreeRouting JAR on the simple board.
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
"""A grid-based maze router (MVP).
|
||||
|
||||
This is an *MVP* autorouter, not a port of FreeRouting's expansion-room maze.
|
||||
Per the phase brief the milestone is connectivity parity with the reference JAR
|
||||
on a simple board, not FreeRouting-quality optimization. It routes on a single
|
||||
signal layer with an A* search over a uniform occupancy grid:
|
||||
|
||||
* a cell is blocked if it overlaps another net's pad or a keepout, inflated by
|
||||
``clearance + half trace width``;
|
||||
* each net's ratsnest is connected pin-to-pin; a routed trace's cells then block
|
||||
other nets (so routes do not overlap);
|
||||
* the resulting cell path is turned into a trace polyline whose endpoints are the
|
||||
exact pin locations.
|
||||
|
||||
Deferred (router phase, exact-geometry track): FreeRouting's free-space
|
||||
expansion rooms, rip-up-and-retry, multi-layer via search, and shove. Those
|
||||
raise quality/completeness; this reaches connectivity on boards whose nets route
|
||||
on one layer without crossing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import heapq
|
||||
import math
|
||||
|
||||
from freeroute.board.board import BasicBoard
|
||||
from freeroute.board.items import ObstacleArea, Pin
|
||||
from freeroute.geometry import IntPoint
|
||||
|
||||
__all__ = ["GridRouter", "RouteResult", "route_board"]
|
||||
|
||||
# 8-connected neighbourhood (orthogonal + diagonal) for 45-degree routing.
|
||||
_NEIGHBOURS = [
|
||||
(1, 0),
|
||||
(-1, 0),
|
||||
(0, 1),
|
||||
(0, -1),
|
||||
(1, 1),
|
||||
(1, -1),
|
||||
(-1, 1),
|
||||
(-1, -1),
|
||||
]
|
||||
|
||||
|
||||
class RouteResult:
|
||||
"""Per-net routing outcome in *board* units.
|
||||
|
||||
``wires`` maps a net number to a list of trace paths (each a list of
|
||||
:class:`IntPoint`). ``routed_net_numbers`` are the nets that got >= 1 trace.
|
||||
"""
|
||||
|
||||
__slots__ = ("wires", "half_width", "layer")
|
||||
|
||||
def __init__(self, half_width: int, layer: int) -> None:
|
||||
self.wires: dict[int, list[list[IntPoint]]] = {}
|
||||
self.half_width = half_width
|
||||
self.layer = layer
|
||||
|
||||
def add(self, net_no: int, path: list[IntPoint]) -> None:
|
||||
self.wires.setdefault(net_no, []).append(path)
|
||||
|
||||
@property
|
||||
def routed_net_numbers(self) -> set[int]:
|
||||
return {n for n, paths in self.wires.items() if paths}
|
||||
|
||||
|
||||
class GridRouter:
|
||||
"""Routes a :class:`BasicBoard` on one layer with a uniform-grid A* search."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
board: BasicBoard,
|
||||
*,
|
||||
trace_width: int,
|
||||
clearance: int,
|
||||
layer: int = 0,
|
||||
) -> None:
|
||||
self.board = board
|
||||
self.trace_width = max(trace_width, 1)
|
||||
self.clearance = max(clearance, 0)
|
||||
self.layer = layer
|
||||
self.half_width = self.trace_width // 2
|
||||
# cell size must fit a trace plus its clearance to a neighbouring trace
|
||||
self.step = max(self.trace_width + self.clearance, 1)
|
||||
|
||||
box = board.bounding_box
|
||||
self.origin_x = box.ll.x
|
||||
self.origin_y = box.ll.y
|
||||
self.cols = max(1, math.ceil((box.ur.x - box.ll.x) / self.step) + 1)
|
||||
self.rows = max(1, math.ceil((box.ur.y - box.ll.y) / self.step) + 1)
|
||||
|
||||
# cell -> set of net numbers whose pad blocks it; keepout cells; trace cells
|
||||
self._pad_block: dict[tuple[int, int], set[int]] = {}
|
||||
self._keepout: set[tuple[int, int]] = set()
|
||||
self._trace_block: dict[tuple[int, int], int] = {}
|
||||
self._rasterize_obstacles()
|
||||
|
||||
# --- grid helpers -------------------------------------------------------
|
||||
|
||||
def _cell_of(self, point: IntPoint) -> tuple[int, int]:
|
||||
gx = round((point.x - self.origin_x) / self.step)
|
||||
gy = round((point.y - self.origin_y) / self.step)
|
||||
gx = min(max(gx, 0), self.cols - 1)
|
||||
gy = min(max(gy, 0), self.rows - 1)
|
||||
return gx, gy
|
||||
|
||||
def _cell_center(self, gx: int, gy: int) -> IntPoint:
|
||||
return IntPoint(self.origin_x + gx * self.step, self.origin_y + gy * self.step)
|
||||
|
||||
def _cells_in_box(self, box, margin: int):
|
||||
lo_x = round((box.ll.x - margin - self.origin_x) / self.step)
|
||||
hi_x = round((box.ur.x + margin - self.origin_x) / self.step)
|
||||
lo_y = round((box.ll.y - margin - self.origin_y) / self.step)
|
||||
hi_y = round((box.ur.y + margin - self.origin_y) / self.step)
|
||||
for gx in range(max(lo_x, 0), min(hi_x, self.cols - 1) + 1):
|
||||
for gy in range(max(lo_y, 0), min(hi_y, self.rows - 1) + 1):
|
||||
yield gx, gy
|
||||
|
||||
def _rasterize_obstacles(self) -> None:
|
||||
margin = self.clearance + self.half_width
|
||||
for item in self.board.get_items():
|
||||
if isinstance(item, Pin):
|
||||
if self.layer not in item.layers:
|
||||
continue
|
||||
box = item.shape.bounding_box() if item.shape is not None else None
|
||||
if box is None or box.is_empty():
|
||||
continue
|
||||
net = item.net_nos[0] if item.net_nos else 0
|
||||
for cell in self._cells_in_box(box, margin):
|
||||
self._pad_block.setdefault(cell, set()).add(net)
|
||||
elif isinstance(item, ObstacleArea):
|
||||
if item.layer != self.layer:
|
||||
continue
|
||||
box = item.bounding_box()
|
||||
if box.is_empty():
|
||||
continue
|
||||
for cell in self._cells_in_box(box, self.clearance):
|
||||
self._keepout.add(cell)
|
||||
|
||||
def _blocked(self, cell: tuple[int, int], net_no: int) -> bool:
|
||||
if cell in self._keepout:
|
||||
return True
|
||||
pads = self._pad_block.get(cell)
|
||||
if pads and any(n != net_no for n in pads):
|
||||
return True
|
||||
trace = self._trace_block.get(cell)
|
||||
return trace is not None and trace != net_no
|
||||
|
||||
# --- A* search ----------------------------------------------------------
|
||||
|
||||
def _search(
|
||||
self, start: tuple[int, int], goal: tuple[int, int], net_no: int
|
||||
) -> list[tuple[int, int]] | None:
|
||||
if start == goal:
|
||||
return [start]
|
||||
open_heap: list[tuple[float, tuple[int, int]]] = []
|
||||
heapq.heappush(open_heap, (0.0, start))
|
||||
came_from: dict[tuple[int, int], tuple[int, int]] = {}
|
||||
g_score: dict[tuple[int, int], float] = {start: 0.0}
|
||||
|
||||
def h(cell):
|
||||
return math.hypot(cell[0] - goal[0], cell[1] - goal[1])
|
||||
|
||||
while open_heap:
|
||||
_, current = heapq.heappop(open_heap)
|
||||
if current == goal:
|
||||
return _reconstruct(came_from, current)
|
||||
cx, cy = current
|
||||
for dx, dy in _NEIGHBOURS:
|
||||
nxt = (cx + dx, cy + dy)
|
||||
if not (0 <= nxt[0] < self.cols and 0 <= nxt[1] < self.rows):
|
||||
continue
|
||||
# the goal cell may be blocked by its own pad's net-agnostic
|
||||
# rasterization; always allow stepping onto the goal
|
||||
if nxt != goal and self._blocked(nxt, net_no):
|
||||
continue
|
||||
step_cost = 1.0 if dx == 0 or dy == 0 else math.sqrt(2)
|
||||
tentative = g_score[current] + step_cost
|
||||
if tentative < g_score.get(nxt, math.inf):
|
||||
came_from[nxt] = current
|
||||
g_score[nxt] = tentative
|
||||
heapq.heappush(open_heap, (tentative + h(nxt), nxt))
|
||||
return None
|
||||
|
||||
def _mark_trace(self, cells: list[tuple[int, int]], net_no: int) -> None:
|
||||
for cell in cells:
|
||||
self._trace_block[cell] = net_no
|
||||
|
||||
# --- public routing -----------------------------------------------------
|
||||
|
||||
def route(self) -> RouteResult:
|
||||
"""Route every net with >= 2 pins on this router's layer."""
|
||||
result = RouteResult(self.half_width, self.layer)
|
||||
pins_by_net = self._pins_by_net()
|
||||
# route nets with fewer pins first (usually easier / shorter)
|
||||
for net_no in sorted(pins_by_net, key=lambda n: len(pins_by_net[n])):
|
||||
pins = pins_by_net[net_no]
|
||||
if len(pins) < 2:
|
||||
continue
|
||||
for a, b in zip(pins, pins[1:], strict=False):
|
||||
path = self._route_connection(a, b, net_no)
|
||||
if path is not None:
|
||||
result.add(net_no, path)
|
||||
return result
|
||||
|
||||
def _pins_by_net(self) -> dict[int, list[Pin]]:
|
||||
by_net: dict[int, list[Pin]] = {}
|
||||
for pin in self.board.get_pins():
|
||||
if self.layer not in pin.layers:
|
||||
continue
|
||||
for net_no in pin.net_nos:
|
||||
by_net.setdefault(net_no, []).append(pin)
|
||||
return by_net
|
||||
|
||||
def _route_connection(self, a: Pin, b: Pin, net_no: int) -> list[IntPoint] | None:
|
||||
start = self._cell_of(a.location)
|
||||
goal = self._cell_of(b.location)
|
||||
cells = self._search(start, goal, net_no)
|
||||
if cells is None:
|
||||
return None
|
||||
self._mark_trace(cells, net_no)
|
||||
# cell centres, with exact pad locations as the true endpoints
|
||||
points = [a.location]
|
||||
points.extend(self._cell_center(gx, gy) for gx, gy in cells)
|
||||
points.append(b.location)
|
||||
return _simplify(points)
|
||||
|
||||
|
||||
def _reconstruct(came_from, current):
|
||||
path = [current]
|
||||
while current in came_from:
|
||||
current = came_from[current]
|
||||
path.append(current)
|
||||
path.reverse()
|
||||
return path
|
||||
|
||||
|
||||
def _simplify(points: list[IntPoint]) -> list[IntPoint]:
|
||||
"""Drop duplicate and collinear points from a polyline."""
|
||||
out: list[IntPoint] = []
|
||||
for p in points:
|
||||
if out and out[-1].x == p.x and out[-1].y == p.y:
|
||||
continue
|
||||
if len(out) >= 2:
|
||||
a, b = out[-2], out[-1]
|
||||
# collinear if cross product of (b-a) and (p-a) is zero
|
||||
if (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x) == 0:
|
||||
out[-1] = p
|
||||
continue
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
|
||||
def route_board(
|
||||
board: BasicBoard, *, trace_width: int, clearance: int, layer: int = 0
|
||||
) -> RouteResult:
|
||||
"""Convenience wrapper: build a :class:`GridRouter` and route the board."""
|
||||
router = GridRouter(board, trace_width=trace_width, clearance=clearance, layer=layer)
|
||||
return router.route()
|
||||
Reference in New Issue
Block a user