Illustrate the intermediate stages of complex-routing example 1
This commit is contained in:
parent
365c14c59a
commit
c3e420eadb
1 changed files with 402 additions and 86 deletions
257
scripts/render_complex_routing_example.py
Normal file
257
scripts/render_complex_routing_example.py
Normal file
|
|
@ -0,0 +1,257 @@
|
|||
"""Render intermediate router states for complex-routing example 1."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from dataclasses import replace
|
||||
from json import loads
|
||||
from math import floor
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from matplotlib.lines import Line2D
|
||||
from shapely import get_parts, union_all
|
||||
from shapely.geometry import box
|
||||
|
||||
from examples.advanced_layouts import COMPLEX_EXAMPLE, INPUTS, _draw_ports, build_problem
|
||||
from inire import DiagnosticsOptions, 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 _build_corridors, _endpoint_access, _Mesh, _plan_lane_assignments
|
||||
from inire.router._waypoints import export_waypoints
|
||||
from scripts.render_documentation_figures import EDGE, INK, MUTED, _board, _polygon, _save, plt
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
||||
from matplotlib.axes import Axes
|
||||
|
||||
from inire import RoutingOptions, RoutingProblem, RoutingRunResult, SearchOptions
|
||||
from inire.geometry.components import ComponentResult
|
||||
|
||||
PathMap = Mapping[str, Sequence[ComponentResult]]
|
||||
|
||||
|
||||
LOWER = "#326a9b"
|
||||
UPPER = "#26785e"
|
||||
SHORT = "#725197"
|
||||
RETURN = "#b34331"
|
||||
|
||||
|
||||
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, joint_net_ids=frozenset(),
|
||||
)
|
||||
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 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)
|
||||
|
||||
problem, options = build_problem(loads(INPUTS.read_text(encoding="utf-8"))[COMPLEX_EXAMPLE])
|
||||
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)
|
||||
print(f"{COMPLEX_EXAMPLE}: {len(problem.nets)}/{len(problem.nets)} verified, {refined.metrics.nodes_expanded} A* expansions")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in a new issue