inire/scripts/render_documentation_figures.py

254 lines
12 KiB
Python
Raw Normal View History

"""Render the routing figures embedded in the user and developer guides."""
from __future__ import annotations
from argparse import ArgumentParser
from dataclasses import replace
from itertools import pairwise
from pathlib import Path
from typing import TYPE_CHECKING
import matplotlib
import shapely
from shapely.geometry import box
from inire import CongestionOptions, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.router._topology import HEADINGS, _endpoint_access, _Mesh, _plan_lane_assignments
from inire.tests.routing_corpus import CASE_GROUPS, profile_options
matplotlib.use("Agg")
from matplotlib import pyplot as plt # noqa: E402
from matplotlib.patches import FancyBboxPatch # noqa: E402
from inire.utils.visualization import draw_polygon # noqa: E402
if TYPE_CHECKING:
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from shapely.geometry import Polygon
from inire import RoutingResult
INK = "#193447"
MUTED = "#4c6370"
ROUTE = "#00748b"
PARTIAL = "#a43a33"
PORTAL = "#a05221"
OBSTACLE = "#d9e1e4"
EDGE = "#738692"
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, joint_net_ids=frozenset()
)[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 main() -> None:
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)
if __name__ == "__main__":
main()