Generate the guide, walkthrough, and gallery figures from one command. Keep benchmark fixtures and attribution with the tests and fold the durable findings from completed plans into the guides.
519 lines
26 KiB
Python
519 lines
26 KiB
Python
"""Render the guide, walkthrough, and advanced example figures."""
|
||
|
||
from __future__ import annotations
|
||
|
||
from argparse import ArgumentParser
|
||
from dataclasses import replace
|
||
from itertools import pairwise
|
||
from json import loads
|
||
from math import floor
|
||
from pathlib import Path
|
||
from typing import TYPE_CHECKING
|
||
|
||
import matplotlib
|
||
import shapely
|
||
from shapely import get_parts, union_all
|
||
from shapely.geometry import box
|
||
|
||
from inire import CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
|
||
from inire.constants import TOLERANCE_LINEAR
|
||
from inire.geometry.intervals import open_intervals
|
||
from inire.router._bundle import _identify_layout, plan_ordered_bundle
|
||
from inire.router._seed_materialization import materialize_path_seed
|
||
from inire.router._stack import route_once
|
||
from inire.router._topology import HEADINGS, _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments
|
||
from inire.router._waypoints import export_waypoints
|
||
from inire.tests.routing_corpus import CASE_GROUPS, profile_options
|
||
|
||
matplotlib.use("Agg")
|
||
from matplotlib import pyplot as plt # noqa: E402
|
||
from matplotlib.lines import Line2D # noqa: E402
|
||
from matplotlib.patches import FancyBboxPatch # noqa: E402
|
||
from examples.advanced_layouts import COMPLEX_EXAMPLE, INPUTS, _draw_ports, build_problem, render_layouts # noqa: E402
|
||
from inire.utils.visualization import draw_polygon # noqa: E402
|
||
|
||
if TYPE_CHECKING:
|
||
from collections.abc import Mapping, Sequence
|
||
|
||
from matplotlib.axes import Axes
|
||
from matplotlib.figure import Figure
|
||
from shapely.geometry import Polygon
|
||
|
||
from inire import RoutingResult, RoutingRunResult
|
||
from inire.geometry.components import ComponentResult
|
||
|
||
PathMap = Mapping[str, Sequence[ComponentResult]]
|
||
|
||
|
||
INK = "#193447"
|
||
MUTED = "#4c6370"
|
||
ROUTE = "#00748b"
|
||
PARTIAL = "#a43a33"
|
||
PORTAL = "#a05221"
|
||
OBSTACLE = "#d9e1e4"
|
||
EDGE = "#738692"
|
||
LOWER = "#326a9b"
|
||
UPPER = "#26785e"
|
||
SHORT = "#725197"
|
||
RETURN = "#b34331"
|
||
|
||
|
||
def _save(fig: Figure, directory: Path, name: str) -> None:
|
||
fig.savefig(directory / name, dpi=160, bbox_inches="tight", pad_inches=0.16)
|
||
plt.close(fig)
|
||
|
||
|
||
def _polygon(ax: Axes, polygon: Polygon, *, fill: str, edge: str, **kwargs: object) -> None:
|
||
draw_polygon(ax, polygon, facecolor=fill, edgecolor=edge, **kwargs)
|
||
|
||
|
||
def _waveguide(ax: Axes, result: RoutingResult, *, color: str, linestyle: str = "-") -> None:
|
||
for polygon in shapely.get_parts(shapely.union_all(result.locked_geometry)):
|
||
_polygon(ax, polygon, fill=color if linestyle == "-" else "none", edge=color, linestyle=linestyle, linewidth=1.5, zorder=4)
|
||
|
||
|
||
def _heading(ax: Axes, port: Port, length: float) -> None:
|
||
dx, dy = HEADINGS[int(port.r) // 90]
|
||
position = (port.x, port.y)
|
||
ax.annotate(
|
||
"",
|
||
xy=(port.x + dx * length, port.y + dy * length),
|
||
xytext=position,
|
||
arrowprops={"arrowstyle": "-|>", "color": INK, "lw": 1.4},
|
||
zorder=6,
|
||
)
|
||
ax.scatter(*position, s=26, facecolor="white", edgecolor=INK, zorder=7)
|
||
|
||
|
||
def _board(ax: Axes, problem: RoutingProblem, *, grid: bool = False) -> None:
|
||
x0, y0, x1, y1 = problem.bounds
|
||
ax.set(xlim=(x0, x1), ylim=(y0, y1), aspect="equal")
|
||
if grid:
|
||
ax.set_axisbelow(True)
|
||
ax.grid(color="#e5ecee", linewidth=0.7)
|
||
else:
|
||
ax.set(xticks=[], yticks=[])
|
||
for spine in ax.spines.values():
|
||
spine.set_color("#b5c2c9")
|
||
for obstacle in problem.static_obstacles:
|
||
_polygon(ax, obstacle, fill=OBSTACLE, edge=EDGE, linewidth=0.8, zorder=2)
|
||
|
||
|
||
def _first_route(directory: Path) -> None:
|
||
# Match the public quick-start snippet in README.md.
|
||
net = NetSpec("input", Port(50, 100, 0), Port(250, 100, 0), width=2)
|
||
problem = RoutingProblem((0, 0, 1000, 1000), (net,), clearance=2)
|
||
result = route(problem).results_by_net[net.net_id]
|
||
assert result.is_valid
|
||
assert result.report.total_length == 200
|
||
|
||
fig, ax = plt.subplots(figsize=(6.9, 2.15), layout="constrained")
|
||
_board(ax, problem, grid=True)
|
||
ax.set(xlim=(20, 285), ylim=(68, 132), yticks=[100], xticks=[50, 100, 150, 200, 250])
|
||
ax.tick_params(labelsize=9, colors=MUTED, length=0)
|
||
ax.set_xlabel("x in layout units", color=MUTED)
|
||
_waveguide(ax, result, color=ROUTE)
|
||
for label, port in (("Start (50, 100)", net.start), ("Target (250, 100)", net.target)):
|
||
_heading(ax, port, 15)
|
||
ax.text(port.x, 119, label, color=INK, va="center", ha="center", fontsize=10)
|
||
_save(fig, directory, "first-route.png")
|
||
|
||
|
||
def _placed_crossing(directory: Path) -> None:
|
||
# Match the placed devices and port access in docs/user/route-a-layout.md.
|
||
a = box(30, 50, 80, 100)
|
||
b = box(260, 90, 310, 140)
|
||
a_keepout = a.difference(box(74, 69, 82, 81))
|
||
b_keepout = b.difference(box(258, 109, 266, 121))
|
||
link = NetSpec("A_east_to_B_west", Port(80, 75, 0), Port(260, 115, 0), width=2)
|
||
problem = RoutingProblem((0, 0, 340, 180), (link,), (a_keepout, b_keepout), clearance=4)
|
||
options = RoutingOptions(search=SearchOptions(bend_radii=(25,), sbend_radii=(25,)))
|
||
result = route(problem, options=options).results_by_net[link.net_id]
|
||
assert result.is_valid
|
||
assert all(shape.intersection(cell).area == 0 for shape in result.locked_geometry for cell in (a, b))
|
||
|
||
fig, ax = plt.subplots(figsize=(7.1, 3.4), layout="constrained")
|
||
_board(ax, problem)
|
||
ax.set(xlim=(14, 326), ylim=(27, 159))
|
||
for name, cell in (("A", a), ("B", b)):
|
||
_polygon(ax, cell, fill="none", edge=INK, linestyle="--", linewidth=1.2, zorder=3)
|
||
ax.text(cell.centroid.x, cell.centroid.y + 12, f"Crossing {name}", color=INK, fontsize=10, ha="center", va="center")
|
||
|
||
_waveguide(ax, result, color=ROUTE)
|
||
for label, port, dx, dy in (("A east port", link.start, 14, -13), ("B west port", link.target, -14, 13)):
|
||
_heading(ax, port, 10)
|
||
ax.text(port.x + dx, port.y + dy, label, color=INK, fontsize=10, ha="left" if dx > 0 else "right")
|
||
|
||
for label, opening, label_position in (
|
||
("A port opening", (76, 79), (94, 117)),
|
||
("B port opening", (263, 111), (219, 77)),
|
||
):
|
||
ax.annotate(
|
||
label, xy=opening, xytext=label_position, color=INK, fontsize=10,
|
||
arrowprops={"arrowstyle": "->", "color": MUTED}, zorder=8,
|
||
)
|
||
ax.annotate(
|
||
"External waveguide", xy=(154, 75), xytext=(168, 47), color=ROUTE, fontsize=10,
|
||
arrowprops={"arrowstyle": "->", "color": ROUTE},
|
||
)
|
||
_save(fig, directory, "placed-crossing.png")
|
||
|
||
|
||
def _search_limits(directory: Path) -> None:
|
||
# Match examples/09_unroutable_best_effort.py apart from the second run's budget.
|
||
net = NetSpec("budget_limited_net", Port(10, 50, 0), Port(85, 60, 180), width=2)
|
||
problem = RoutingProblem((0, 0, 100, 100), (net,), (box(35, 35, 45, 65), box(55, 35, 65, 65)))
|
||
options = RoutingOptions(
|
||
search=SearchOptions(node_limit=3, bend_radii=(10.0,)),
|
||
objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0),
|
||
congestion=CongestionOptions(warm_start_enabled=False, max_iterations=1),
|
||
)
|
||
fig, panels = plt.subplots(1, 2, figsize=(6.5, 3.5), layout="constrained")
|
||
for ax, limit, outcome, color in zip(panels, (3, 500), ("partial", "completed"), (PARTIAL, ROUTE), strict=True):
|
||
configured = replace(options, search=replace(options.search, node_limit=limit))
|
||
result = route(problem, options=configured).results_by_net[net.net_id]
|
||
assert result.outcome == outcome
|
||
_board(ax, problem)
|
||
ax.set_title(f"{limit} nodes · {outcome}", loc="left", color=INK, fontsize=12)
|
||
_waveguide(ax, result, color=color, linestyle="--" if outcome == "partial" else "-")
|
||
for port in (net.start, net.target):
|
||
_heading(ax, port, 7)
|
||
ax.text(10, 42, "Start", color=INK, fontsize=10, ha="left")
|
||
ax.text(85, 69, "Target", color=INK, fontsize=10, ha="center")
|
||
if outcome == "partial":
|
||
end = result.path[-1].end_port
|
||
ax.annotate(
|
||
"Path stops here", xy=(end.x, end.y), xytext=(11, 83), fontsize=10, color=PARTIAL,
|
||
arrowprops={"arrowstyle": "->", "color": PARTIAL},
|
||
)
|
||
_save(fig, directory, "partial-and-complete.png")
|
||
|
||
|
||
def _corridor(directory: Path) -> None:
|
||
(case,) = CASE_GROUPS["offset-gates"]
|
||
problem = case.problem
|
||
(net,) = problem.nets
|
||
options = profile_options(case, "matched-budget")
|
||
options = replace(options, search=replace(options.search, node_limit=100), topology=replace(options.topology, mode="guide"))
|
||
radius = min(options.search.bend_radii)
|
||
mesh = _Mesh(box(*problem.bounds), problem.static_obstacles, net.width / 2, problem.clearance)
|
||
endpoints, leads = _endpoint_access(mesh, problem.nets, radius)
|
||
selected = _plan_lane_assignments(
|
||
mesh, problem.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors,
|
||
)[net.net_id][0]
|
||
result = route(problem, options=options).results_by_net[net.net_id]
|
||
assert result.is_valid
|
||
|
||
fig, (free, lane, physical) = plt.subplots(3, 1, figsize=(7.1, 6.3), layout="constrained")
|
||
titles = ("1 Mesh and crossed portals", "2 Selected portal lanes", "3 Verified physical path")
|
||
for ax, title in zip((free, lane, physical), titles, strict=True):
|
||
_board(ax, problem)
|
||
ax.set_title(title, loc="left", color=INK, fontsize=11)
|
||
for port in (net.start, net.target):
|
||
_heading(ax, port, 17)
|
||
for cell in mesh.cells:
|
||
_polygon(free, cell, fill="#edf4f7", edge="#a3b7c4", linewidth=0.7, zorder=1)
|
||
for a, b in pairwise(selected.cells):
|
||
portal = mesh.cells[a].intersection(mesh.cells[b])
|
||
free.plot(*portal.xy, color=PORTAL, linewidth=1.8, zorder=3)
|
||
lane.plot(*portal.xy, color="#a3b7c4", linewidth=0.8, zorder=1)
|
||
|
||
x, y = zip(*selected.points, strict=True)
|
||
lane.plot(x, y, linestyle="--", color=ROUTE, marker="o", markersize=3, linewidth=1.6, zorder=4)
|
||
physical.plot(x, y, linestyle="--", color=EDGE, linewidth=1, zorder=3)
|
||
_waveguide(physical, result, color=ROUTE)
|
||
_save(fig, directory, "corridor-realization.png")
|
||
|
||
|
||
def _automatic_stages(directory: Path) -> None:
|
||
fig, ax = plt.subplots(figsize=(7.2, 4.2))
|
||
ax.set(xlim=(0, 1), ylim=(0.12, 1))
|
||
ax.axis("off")
|
||
|
||
def stage(x: float, y: float, label: str, *, fill: str = "#edf4f7") -> None:
|
||
ax.add_patch(FancyBboxPatch(
|
||
(x - 0.167, y - 0.042), 0.334, 0.084, boxstyle="round,pad=0.015",
|
||
facecolor=fill, edgecolor=INK, linewidth=0.9, zorder=2,
|
||
))
|
||
ax.text(x, y, label, color=INK, fontsize=11, weight="bold", ha="center", va="center", zorder=3)
|
||
|
||
def arrow(start: tuple[float, float], end: tuple[float, float]) -> None:
|
||
ax.annotate("", xy=end, xytext=start, arrowprops={"arrowstyle": "-|>", "color": MUTED, "lw": 1.2}, zorder=4)
|
||
|
||
ax.text(0.21, 0.98, "Set the routing bound", color=INK, ha="center", va="top", fontsize=11, weight="bold")
|
||
arrow((0.21, 0.91), (0.21, 0.86))
|
||
rows = (0.80, 0.61, 0.42, 0.23)
|
||
for y, label in zip(rows, ("Construct layout", "Probe near ports", "Widen search", "Recover or fall back"), strict=True):
|
||
stage(0.21, y, label)
|
||
ax.plot([0.392, 0.49], [y, y], color=MUTED, linewidth=1.2)
|
||
for previous, next_y in pairwise(rows):
|
||
arrow((0.21, previous - 0.058), (0.21, next_y + 0.058))
|
||
ax.text(0.004, 0.50, "Below target", color=MUTED, rotation=90, fontsize=10, ha="center", va="center")
|
||
ax.plot([0.49, 0.49], [rows[-1], rows[0]], color=MUTED, linewidth=1.2)
|
||
ax.text(0.49, 0.88, "Verify candidates", color=INK, fontsize=11, weight="bold", ha="center")
|
||
ax.text(0.80, 0.79, "Target reached or\nattempts exhausted", color=MUTED, fontsize=10, ha="center", va="center")
|
||
stage(0.79, 0.61, "Select best layout", fill="#dcefe9")
|
||
arrow((0.49, 0.61), (0.606, 0.61))
|
||
stage(0.79, 0.42, "Refine if enabled", fill="#dcefe9")
|
||
arrow((0.79, 0.55), (0.79, 0.48))
|
||
arrow((0.79, 0.36), (0.79, 0.28))
|
||
ax.text(0.79, 0.23, "Return per-net results", color=INK, ha="center", va="center", fontsize=11, weight="bold")
|
||
_save(fig, directory, "automatic-stages.png")
|
||
|
||
|
||
def _seed_paths(problem: RoutingProblem, search: SearchOptions) -> PathMap:
|
||
paths = {}
|
||
for net in problem.nets:
|
||
path = materialize_path_seed(
|
||
problem.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance,
|
||
)
|
||
assert path
|
||
paths[net.net_id] = path
|
||
return paths
|
||
|
||
|
||
def _result_paths(run: RoutingRunResult) -> PathMap:
|
||
return {net_id: result.path for net_id, result in run.results_by_net.items()}
|
||
|
||
|
||
def _footprint(ax: Axes, path: Sequence[ComponentResult], color: str, *, dashed: bool = False) -> None:
|
||
for shape in get_parts(union_all([polygon for move in path for polygon in move.physical_geometry])):
|
||
_polygon(ax, shape, fill="none" if dashed else color, edge=color, linewidth=0.9, linestyle="--" if dashed else "-", zorder=4)
|
||
|
||
|
||
def _waypoints(ax: Axes, path: Sequence[ComponentResult], color: str, *, marker: str | None = None) -> None:
|
||
x, y = zip(*export_waypoints(path), strict=True)
|
||
ax.plot(x, y, color=color, marker=marker, markersize=2.6, linewidth=1.35, zorder=4)
|
||
|
||
|
||
def _input_figure(directory: Path, problem: RoutingProblem) -> None:
|
||
first, last = sorted({x for shape in problem.static_obstacles for x in (shape.bounds[0], shape.bounds[2])})[:2]
|
||
cut = (first + last) / 2
|
||
_, bottom, _, top = problem.bounds
|
||
solid = [(y0, y1) for x0, y0, x1, y1 in (shape.bounds for shape in problem.static_obstacles) if x0 < cut < x1]
|
||
openings = open_intervals(solid, bottom, top)
|
||
width = min(net.width for net in problem.nets)
|
||
pitch = width + problem.clearance - TOLERANCE_LINEAR
|
||
|
||
fig, (board, section) = plt.subplots(1, 2, figsize=(10, 3.6), width_ratios=(4.5, 1), layout="constrained")
|
||
_board(board, problem, grid=True)
|
||
board.set_title("Input ports, headings, and keepouts", loc="left", color=INK)
|
||
board.set_xlabel("x in layout units", color=MUTED)
|
||
for net in problem.nets:
|
||
_draw_ports(board, net.start, net.target, RETURN if net.net_id == "net_08" else INK, arrow_length=55)
|
||
board.axvline(cut, color=SHORT, linestyle="--", linewidth=1.4, zorder=3)
|
||
board.text(cut + 33, 260, f"Cut at x = {cut:g}", rotation=90, color=SHORT, fontsize=9)
|
||
section.set(title="Openings on the cut", xlim=(0, 1), ylim=(bottom, top), xticks=[])
|
||
section.tick_params(axis="y", labelsize=8, colors=MUTED)
|
||
for low, high in solid:
|
||
section.axhspan(low, high, color="#d9e1e4")
|
||
track_count = 0
|
||
for low, high in openings:
|
||
first_track = low + width / 2 + (problem.clearance if low != bottom else 0)
|
||
last_track = high - width / 2 - (problem.clearance if high != top else 0)
|
||
count = max(0, 1 + floor((last_track - first_track + 2 * TOLERANCE_LINEAR) / pitch))
|
||
track_count += count
|
||
section.plot([0.15, 0.15], [low, high], color=SHORT, linewidth=2)
|
||
section.scatter([0.27] * count, [first_track + i * pitch for i in range(count)], s=4, color=SHORT)
|
||
section.text(0.40, (low + high) / 2, f"{low:g}–{high:g}", va="center", color=INK, fontsize=9)
|
||
section.set_xlabel(f"{track_count} available tracks", color=MUTED, fontsize=9)
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-input.png")
|
||
|
||
|
||
def _lane_figure(directory: Path, problem: RoutingProblem, paths: PathMap, colors: Mapping[str, str]) -> None:
|
||
fig, (board, detail) = plt.subplots(2, 1, figsize=(9.5, 5.4), height_ratios=(3, 1), layout="constrained")
|
||
fig.suptitle("Ordered bundle waypoints", x=0.01, ha="left", color=INK, fontsize=13)
|
||
_board(board, problem)
|
||
for net_id, path in paths.items():
|
||
_waypoints(board, path, colors[net_id], marker="o")
|
||
groups = (("Lower group", LOWER), ("Upper group", UPPER), ("Short connection", SHORT), ("Outer return", RETURN))
|
||
handles = [Line2D([], [], color=color, label=label) for label, color in groups]
|
||
board.legend(handles=handles, loc="lower center", bbox_to_anchor=(0.5, 1), ncols=4, frameon=False, fontsize=9)
|
||
|
||
_board(detail, problem, grid=True)
|
||
detail.set(xlim=(1270, 1615), ylim=(-5, 64), yticks=(1, 10, 18, 45), xticks=(1350, 1450, 1537))
|
||
detail.set_title("Two continuous lanes below the tower", loc="left", color=INK, fontsize=10)
|
||
detail.tick_params(labelsize=8, colors=MUTED)
|
||
for net_id in ("net_00", "net_08"):
|
||
_waypoints(detail, paths[net_id], colors[net_id])
|
||
detail.text(1450, 33, "Tower", color=MUTED, fontsize=9, ha="center")
|
||
detail.text(1292, 10, "net_00", color=LOWER, fontsize=8, va="bottom")
|
||
detail.text(1550, 1, "net_08", color=RETURN, fontsize=8, va="bottom")
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-lanes.png")
|
||
|
||
|
||
def _turnaround_figure(directory: Path, problem: RoutingProblem, proposal: PathMap, verified: PathMap) -> None:
|
||
fig, panels = plt.subplots(2, 1, figsize=(9.5, 4.0), layout="constrained")
|
||
for ax, paths, title in zip(panels, (proposal, verified), ("Inferred westbound arrival", "Candidate with eastbound arrival"), strict=True):
|
||
_board(ax, problem, grid=True)
|
||
ax.set(xlim=(995, 2500), ylim=(785, 1028), xticks=(1112, 1500, 2000, 2412), yticks=(850, 991))
|
||
ax.tick_params(labelsize=8, colors=MUTED)
|
||
ax.set_title(title, loc="left", color=INK, fontsize=11)
|
||
for net_id, color in (("net_07", UPPER), ("net_08", RETURN)):
|
||
_footprint(ax, paths[net_id], color)
|
||
port = paths["net_08"][-1].end_port
|
||
dx = 25 if port.r == 0 else -25
|
||
ax.annotate(
|
||
"", xy=(port.x + dx, port.y + 21), xytext=(port.x - dx, port.y + 21),
|
||
arrowprops={"arrowstyle": "-|>", "color": RETURN, "lw": 1.5}, zorder=6,
|
||
)
|
||
ax.scatter(port.x, port.y, marker="s", s=22, facecolor="white", edgecolor=RETURN, zorder=7)
|
||
ax.text(1950, 902, "net_07 · shelf", color=UPPER, fontsize=9)
|
||
ax.text(1250, 1004 if paths is proposal else 844, "net_08 · return", color=RETURN, fontsize=9)
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-turnaround.png")
|
||
|
||
|
||
def _verify_figure(directory: Path, problem: RoutingProblem, paths: PathMap, colors: Mapping[str, str]) -> None:
|
||
fig, panels = plt.subplots(2, 1, figsize=(8.5, 6.4), layout="constrained")
|
||
prefix = tuple(net.net_id for net in problem.nets[:4])
|
||
for ax, ids, title in zip(
|
||
panels, (prefix, paths), ("First four seeds in install order", "Installed layout after verification · 9/9"), strict=True,
|
||
):
|
||
_board(ax, problem)
|
||
ax.set_title(title, loc="left", color=INK, fontsize=11)
|
||
for net in problem.nets:
|
||
_draw_ports(ax, net.start, net.target, colors[net.net_id] if net.net_id in ids else EDGE, arrow_length=0)
|
||
for net_id in ids:
|
||
_footprint(ax, paths[net_id], colors[net_id])
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-verification.png")
|
||
|
||
|
||
def _refine_figure(directory: Path, problem: RoutingProblem, before: PathMap, after: PathMap) -> None:
|
||
fig, ax = plt.subplots(figsize=(9.5, 2.5), layout="constrained")
|
||
_board(ax, problem, grid=True)
|
||
ax.set(xlim=(990, 2500), ylim=(793, 1022), xticks=(1100, 1500, 2000, 2412), yticks=(850, 890, 999))
|
||
ax.tick_params(labelsize=8, colors=MUTED)
|
||
ax.set_title("Selected refinement of the shelf route · net_07", loc="left", color=INK, fontsize=11)
|
||
_footprint(ax, before["net_07"], SHORT, dashed=True)
|
||
_footprint(ax, after["net_07"], UPPER)
|
||
_footprint(ax, after["net_08"], RETURN)
|
||
ax.text(1520, 1005, "Selected shelf", color=UPPER, fontsize=9)
|
||
ax.text(1510, 895, "Previous shelf (dashed)", color=SHORT, fontsize=9)
|
||
ax.text(1460, 845, "Outer return", color=RETURN, fontsize=9)
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-refinement.png")
|
||
|
||
|
||
def _guide_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None:
|
||
net = next(net for net in problem.nets if net.net_id == "net_08")
|
||
single = replace(problem, nets=(net,))
|
||
radius = min(options.search.bend_radii)
|
||
board = box(*single.bounds)
|
||
mesh = _Mesh(board, single.static_obstacles, net.width / 2, single.clearance)
|
||
endpoints, leads = _endpoint_access(mesh, single.nets, radius)
|
||
assignments = _plan_lane_assignments(
|
||
mesh, single.nets, endpoints, leads, bend_radius=radius, limit=options.topology.max_corridors,
|
||
)
|
||
corridors = _build_corridors(mesh, board, single.nets, assignments, radius)
|
||
config = replace(
|
||
options,
|
||
search=replace(options.search, node_limit=12),
|
||
topology=replace(options.topology, mode="guide"),
|
||
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
|
||
diagnostics=DiagnosticsOptions(capture_expanded=True),
|
||
)
|
||
run = route_once(single, options=config, corridors=corridors)
|
||
result = run.results_by_net[net.net_id]
|
||
assert result.outcome == "partial"
|
||
assert run.metrics.nodes_expanded == config.search.node_limit
|
||
|
||
assignment = assignments[net.net_id][0]
|
||
guide = corridors[net.net_id][0]
|
||
fig, (overview, search) = plt.subplots(1, 2, figsize=(10, 4.3), width_ratios=(2, 1), layout="constrained")
|
||
for ax in (overview, search):
|
||
_board(ax, single, grid=True)
|
||
ax.tick_params(labelsize=8, colors=MUTED)
|
||
for i, cell in enumerate(mesh.cells):
|
||
_polygon(ax, cell, fill="#dfeee7" if i in assignment.cells else "#f2f6f9", edge="#a4b5bd", linewidth=0.7, zorder=1)
|
||
ax.plot(*guide.centerline.xy, color=UPPER, linewidth=1.4, linestyle="--", zorder=3)
|
||
_draw_ports(ax, net.start, net.target, INK, arrow_length=0)
|
||
overview.set_title(f"Guide mesh · {len(mesh.cells)} triangles", loc="left", color=INK, fontsize=11)
|
||
search.set_title("Partial path after 12 expansions", loc="left", color=INK, fontsize=11)
|
||
search.set(xlim=(0, 410), ylim=(395, 945), xticks=(0, 100, 200, 300, 400))
|
||
x, y, _ = zip(*run.expanded_nodes, strict=True)
|
||
search.scatter(x, y, color=SHORT, s=12, alpha=0.8, zorder=3, label="Expanded position")
|
||
_footprint(search, result.path, RETURN)
|
||
port = result.path[-1].end_port
|
||
search.annotate(
|
||
"Partial end port", xy=(port.x, port.y), xytext=(90, 905), color=RETURN, fontsize=8,
|
||
arrowprops={"arrowstyle": "->", "color": RETURN}, zorder=5,
|
||
)
|
||
search.legend(loc="lower right", fontsize=8)
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-guide.png")
|
||
|
||
|
||
def _modes_figure(directory: Path, problem: RoutingProblem, options: RoutingOptions) -> None:
|
||
config = replace(
|
||
options,
|
||
search=replace(options.search, node_limit=100),
|
||
congestion=replace(options.congestion, max_iterations=1, warm_start_enabled=False),
|
||
refinement=replace(options.refinement, enabled=False),
|
||
)
|
||
modes = ("automatic", "off", "guide", "seed", "bundle")
|
||
fig, panels = plt.subplots(3, 2, figsize=(10, 7), layout="constrained")
|
||
fig.suptitle("One congestion iteration · 100 nodes per search", color=INK, fontsize=13)
|
||
for ax, mode in zip(panels.ravel()[:-1], modes, strict=True):
|
||
settings = replace(config, topology=replace(config.topology, mode=mode, infer_terminal_headings=mode == "bundle"))
|
||
run = route(problem, options=settings)
|
||
verified = sum(result.is_valid for result in run.results_by_net.values())
|
||
label = "bundle with heading inference" if mode == "bundle" else mode
|
||
_board(ax, problem)
|
||
ax.set_title(f"{label} · {verified}/{len(problem.nets)} verified", loc="left", color=INK, fontsize=11)
|
||
for net in problem.nets:
|
||
_draw_ports(ax, net.start, net.target, EDGE, arrow_length=0)
|
||
result = run.results_by_net[net.net_id]
|
||
if result.path:
|
||
_footprint(ax, result.path, UPPER if result.is_valid else RETURN, dashed=not result.is_valid)
|
||
|
||
legend = panels.flat[-1]
|
||
legend.set_axis_off()
|
||
handles = [
|
||
Line2D([], [], color=UPPER, label="Verified path"),
|
||
Line2D([], [], color=RETURN, linestyle="--", label="Unverified or partial path"),
|
||
]
|
||
legend.legend(handles=handles, loc="center left", frameon=False, fontsize=10)
|
||
_save(fig, directory, f"{COMPLEX_EXAMPLE}-modes.png")
|
||
|
||
|
||
def _render_walkthrough(directory: Path, layout: dict) -> None:
|
||
problem, options = build_problem(layout)
|
||
proposal = plan_ordered_bundle(problem, options.search, infer_terminal_headings=True)
|
||
verified = route(problem, options=replace(options, refinement=replace(options.refinement, enabled=False)))
|
||
refined = route(problem, options=options)
|
||
assert verified.automatic is not None
|
||
assert refined.automatic is not None
|
||
assert [stage.planner for stage in verified.automatic.stages] == ["bundle-turnaround"]
|
||
assert [stage.operation for stage in refined.automatic.stages] == ["verify", "refine"]
|
||
assert refined.automatic.selected_stage == 1
|
||
assert len(refined.automatic.verified_net_ids) == len(verified.automatic.verified_net_ids) == len(problem.nets)
|
||
assert refined.metrics.nodes_expanded == 0
|
||
|
||
layout = _identify_layout(problem, problem.nets[0].width / 2 + problem.clearance)
|
||
colors = {net.net_id: color for group, color in ((layout.lower, LOWER), (layout.upper, UPPER)) for net in group}
|
||
colors.update({layout.short.net_id: SHORT, layout.outer_return.net_id: RETURN})
|
||
proposed_paths = _seed_paths(proposal, options.search)
|
||
paths = _result_paths(verified)
|
||
_input_figure(directory, problem)
|
||
_lane_figure(directory, problem, proposed_paths, colors)
|
||
_turnaround_figure(directory, problem, proposed_paths, paths)
|
||
_verify_figure(directory, problem, paths, colors)
|
||
_refine_figure(directory, problem, paths, _result_paths(refined))
|
||
_guide_figure(directory, problem, options)
|
||
_modes_figure(directory, problem, options)
|
||
print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions")
|
||
|
||
|
||
def main() -> int:
|
||
parser = ArgumentParser(description=__doc__)
|
||
parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "docs" / "figures")
|
||
directory = parser.parse_args().output_dir
|
||
directory.mkdir(parents=True, exist_ok=True)
|
||
|
||
for render in (_first_route, _placed_crossing, _search_limits, _automatic_stages, _corridor):
|
||
render(directory)
|
||
layouts = loads(INPUTS.read_text(encoding="utf-8"))
|
||
_render_walkthrough(directory, layouts[COMPLEX_EXAMPLE])
|
||
return render_layouts(layouts, directory)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|