Initial buildout

This commit is contained in:
Jan Petykiewicz 2026-03-07 08:26:29 -08:00
commit 84b76d0f6a

View file

@ -0,0 +1,144 @@
"""Route and plot the advanced layouts with Inire's public API."""
from __future__ import annotations
import os
from argparse import ArgumentParser
from json import loads
from math import cos, radians, sin
from pathlib import Path
from typing import TYPE_CHECKING
import matplotlib
from shapely import from_wkt, union_all
from shapely.geometry import box
from shapely.plotting import plot_polygon
from inire import NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
if "MPLBACKEND" not in os.environ:
matplotlib.use("Agg")
from matplotlib import pyplot as plt # noqa: E402
from matplotlib.lines import Line2D # noqa: E402
if TYPE_CHECKING:
from collections.abc import Iterable
from matplotlib.axes import Axes
from inire import RoutingRunResult
INPUTS = Path(__file__).with_name("advanced-layouts.json")
COMPLEX_EXAMPLE = "complex-routing-example-1"
COMPLEX_EXAMPLE_POINTS = f"{COMPLEX_EXAMPLE}-point-terminals"
_CASE_ALIASES = {"terminal-bench": COMPLEX_EXAMPLE, "terminal-bench-point-terminals": COMPLEX_EXAMPLE_POINTS}
COLORS = ("#007189", "#af511b", "#654a99", "#427326", "#b73c62", "#975b2d", "#2f569a", "#734359", "#328179")
def build_problem(layout: dict) -> tuple[RoutingProblem, RoutingOptions]:
"""Create the board, connections, and geometry options from a layout entry."""
problem = RoutingProblem(
bounds=tuple(layout["bounds"]),
static_obstacles=tuple(from_wkt(shape) for shape in layout["keepouts"]),
nets=tuple(NetSpec(name, Port(*start), Port(*target), width) for name, start, target, width in layout["nets"]),
clearance=layout["clearance"],
)
options = RoutingOptions(
search=SearchOptions(bend_radii=tuple(layout["bend_radii"]), sbend_radii=tuple(layout["sbend_radii"])),
topology=TopologyOptions(infer_terminal_headings=layout["infer_terminal_headings"]),
)
return problem, options
def _draw_board(ax: Axes, problem: RoutingProblem) -> None:
x0, y0, x1, y1 = problem.bounds
margin = (x1 - x0) * 0.025
ax.set(xlim=(x0 - margin, x1 + margin), ylim=(y0 - margin, y1 + margin), aspect="equal")
ax.set_axis_off()
plot_polygon(box(*problem.bounds), ax=ax, add_points=False, facecolor="#fbfcfd", edgecolor="#9caeb6", linewidth=0.8)
for shape in problem.static_obstacles:
plot_polygon(shape, ax=ax, add_points=False, facecolor="#d4dde2", edgecolor="#758892", linewidth=0.8)
def _draw_ports(ax: Axes, start: Port, target: Port, color: str, arrow_length: float) -> None:
if arrow_length:
ports = (start, target)
ax.quiver(
[p.x for p in ports], [p.y for p in ports],
[arrow_length * cos(radians(p.r)) for p in ports], [arrow_length * sin(radians(p.r)) for p in ports],
color=color, scale=1, scale_units="xy", angles="xy", width=0.0025, zorder=4,
)
ax.scatter(start.x, start.y, s=19, marker="o", facecolors="white", edgecolors=color, linewidths=1.0, zorder=5)
ax.scatter(target.x, target.y, s=16, marker="s", color=color, linewidths=0.6, zorder=5)
def _plot_case(problem: RoutingProblem, options: RoutingOptions, run: RoutingRunResult, output: Path) -> None:
ratio = (problem.bounds[3] - problem.bounds[1]) / (problem.bounds[2] - problem.bounds[0])
stacked = ratio < 0.45
fig, (setup, result) = plt.subplots(
2 if stacked else 1, 1 if stacked else 2,
figsize=(9.6, (19.2 if stacked else 4.8) * ratio + 1.2),
layout="constrained",
)
for panel in (setup, result):
_draw_board(panel, problem)
verified = sum(route_result.is_valid for route_result in run.results_by_net.values())
setup.set_title("Setup", loc="left", fontsize=13, color="#193447", fontweight="bold")
result.set_title(f"Result · {verified}/{len(problem.nets)} verified", loc="left", fontsize=13, color="#193447", fontweight="bold")
inferred = options.topology.infer_terminal_headings
arrow_length = (problem.bounds[2] - problem.bounds[0]) * 0.025
legend = []
for index, net in enumerate(problem.nets):
color = COLORS[index % len(COLORS)]
legend.append(Line2D([], [], color=color, linewidth=2, label=net.net_id))
routed = run.results_by_net[net.net_id]
_draw_ports(setup, net.start, net.target, color, 0 if inferred else arrow_length)
if routed.path:
plot_polygon(
union_all(routed.locked_geometry), ax=result, add_points=False, facecolor=color, edgecolor=color,
linewidth=0.55, linestyle="-" if routed.is_valid else "--", alpha=1 if routed.is_valid else 0.35, zorder=3,
)
start, target = (routed.path[0].start_port, routed.path[-1].end_port) if inferred and routed.is_valid else (net.start, net.target)
_draw_ports(result, start, target, color, arrow_length if not inferred or routed.is_valid else 0)
columns = 5 if stacked else 4
fig.legend(handles=legend, loc="outside lower center", ncols=columns, fontsize=8.5, frameon=False)
fig.savefig(output, dpi=150, facecolor="white")
plt.close(fig)
def render_layouts(layouts: dict, output_dir: Path, *, cases: Iterable[str] | None = None) -> int:
"""Render selected gallery layouts and report whether all routes verified."""
output_dir.mkdir(parents=True, exist_ok=True)
all_verified = True
for name in dict.fromkeys(cases or layouts):
problem, options = build_problem(layouts[name])
run = route(problem, options=options)
valid = sum(result.is_valid for result in run.results_by_net.values())
print(f"{name}: {valid}/{len(problem.nets)} verified")
if valid != len(problem.nets):
all_verified = False
print(" " + ", ".join(f"{res.net_id}: {res.outcome}" for res in run.results_by_net.values() if not res.is_valid))
_plot_case(problem, options, run, output_dir / f"example-{name}.png")
return 0 if all_verified else 1
def main() -> int:
layouts = loads(INPUTS.read_text(encoding="utf-8"))
parser = ArgumentParser(description=__doc__)
parser.add_argument(
"--case", action="append", choices=layouts, type=lambda name: _CASE_ALIASES.get(name, name),
help="Layout to route. Repeat to select several. Defaults to all.",
)
parser.add_argument("--output-dir", type=Path, default=INPUTS.parent, help="Directory for the setup and result PNGs.")
args = parser.parse_args()
return render_layouts(layouts, args.output_dir, cases=args.case)
if __name__ == "__main__":
raise SystemExit(main())