inire/inire/utils/visualization.py

244 lines
8.1 KiB
Python
Raw Normal View History

2026-03-07 08:26:29 -08:00
from __future__ import annotations
2026-11-25 17:29:35 -08:00
import os
2026-03-30 23:54:30 -07:00
from typing import TYPE_CHECKING, cast
2026-11-25 17:29:35 -08:00
import matplotlib
# The example/diagnostic plotting helpers save figures to disk and do not need
# an interactive GUI backend. Default to Agg unless the caller explicitly chose
# a backend, so examples run reliably in headless or partially configured
# environments.
if "MPLBACKEND" not in os.environ:
matplotlib.use("Agg")
2026-03-07 08:26:29 -08:00
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path
2026-03-09 03:19:01 -07:00
import numpy
from shapely.geometry import MultiPolygon, Polygon
from shapely.geometry.polygon import orient
2026-03-07 08:26:29 -08:00
if TYPE_CHECKING:
from matplotlib.axes import Axes
from matplotlib.figure import Figure
2026-03-08 22:13:10 -07:00
from inire.geometry.primitives import Port
2026-03-29 20:35:58 -07:00
from inire.router.danger_map import DangerMap
2026-03-30 19:51:37 -07:00
from inire.results import RoutingResult
2026-03-07 08:26:29 -08:00
def draw_polygon(ax: Axes, polygon: Polygon, **style: object) -> None:
if not polygon.interiors:
ax.fill(*polygon.exterior.xy, **style)
return
polygon = orient(polygon)
paths = [Path(list(ring.coords), closed=True) for ring in (polygon.exterior, *polygon.interiors)]
ax.add_patch(PathPatch(Path.make_compound_path(*paths), **style))
2026-03-07 08:26:29 -08:00
def plot_routing_results(
results: dict[str, RoutingResult],
static_obstacles: list[Polygon],
bounds: tuple[float, float, float, float],
2026-03-08 22:13:10 -07:00
netlist: dict[str, tuple[Port, Port]] | None = None,
2026-03-10 21:55:54 -07:00
show_actual: bool = True,
2026-03-07 08:26:29 -08:00
) -> tuple[Figure, Axes]:
2026-03-09 03:19:01 -07:00
"""
Plot obstacles and routed paths using matplotlib.
Args:
results: Dictionary of net_id to RoutingResult.
static_obstacles: List of static obstacle polygons.
bounds: Plot limits (minx, miny, maxx, maxy).
netlist: Optional original netlist for port visualization.
2026-03-10 21:55:54 -07:00
show_actual: If True, overlay high-fidelity geometry if available.
2026-03-09 03:19:01 -07:00
Returns:
The matplotlib Figure and Axes objects.
"""
2026-03-10 21:55:54 -07:00
fig, ax = plt.subplots(figsize=(12, 12))
2026-03-07 08:26:29 -08:00
# Plot static obstacles (gray)
for poly in static_obstacles:
draw_polygon(ax, poly, alpha=0.3, fc="gray", ec="black", zorder=1)
2026-03-07 08:26:29 -08:00
# Plot paths
2026-03-10 21:55:54 -07:00
colors = plt.get_cmap("tab20")
2026-03-07 08:26:29 -08:00
for i, (net_id, res) in enumerate(results.items()):
2026-03-10 21:55:54 -07:00
color: str | tuple[float, ...] = colors(i % 20)
2026-03-07 08:26:29 -08:00
if not res.is_valid:
2026-03-10 21:55:54 -07:00
color = "red"
2026-03-07 08:26:29 -08:00
2026-03-08 14:40:36 -07:00
label_added = False
2026-03-10 21:55:54 -07:00
for comp in res.path:
# 1. Plot Collision Geometry (Translucent fill)
2026-03-30 15:32:29 -07:00
for poly in comp.collision_geometry:
2026-03-09 03:19:01 -07:00
if isinstance(poly, MultiPolygon):
geoms = list(poly.geoms)
else:
geoms = [poly]
2026-03-08 22:02:07 -07:00
for g in geoms:
if isinstance(g, Polygon):
draw_polygon(ax, g, alpha=0.15, fc=color, ec=color, linestyle='--', lw=0.5, zorder=2)
2026-03-12 23:50:25 -07:00
else:
# Fallback for LineString or other geometries
x, y = g.xy
ax.plot(x, y, color=color, alpha=0.15, linestyle='--', lw=0.5, zorder=2)
2026-03-10 21:55:54 -07:00
2026-03-30 15:32:29 -07:00
actual_geoms_to_plot = comp.physical_geometry if show_actual else comp.collision_geometry
2026-03-29 01:26:22 -07:00
2026-03-10 21:55:54 -07:00
for poly in actual_geoms_to_plot:
if isinstance(poly, MultiPolygon):
geoms = list(poly.geoms)
else:
geoms = [poly]
for g in geoms:
label = net_id if not label_added else ""
if isinstance(g, Polygon):
draw_polygon(ax, g, fc="none", ec=color, lw=1.5, alpha=0.9, zorder=3, label=label)
2026-03-12 23:50:25 -07:00
else:
x, y = g.xy
ax.plot(x, y, color=color, lw=1.5, alpha=0.9, zorder=3, label=label)
2026-03-08 22:02:07 -07:00
label_added = True
2026-03-07 08:26:29 -08:00
2026-03-10 21:55:54 -07:00
# 3. Plot subtle port orientation arrow
2026-03-08 22:13:10 -07:00
p = comp.end_port
2026-03-30 15:32:29 -07:00
rad = numpy.radians(p.r)
2026-03-29 01:26:22 -07:00
ax.quiver(p.x, p.y, numpy.cos(rad), numpy.sin(rad), color="black",
2026-03-10 21:55:54 -07:00
scale=40, width=0.002, alpha=0.2, pivot="tail", zorder=4)
2026-03-08 22:13:10 -07:00
2026-03-10 21:55:54 -07:00
# 4. Plot main arrows for netlist ports
if netlist:
2026-03-29 20:35:58 -07:00
for _net_id, (start_p, target_p) in netlist.items():
2026-03-08 22:13:10 -07:00
for p in [start_p, target_p]:
2026-03-30 15:32:29 -07:00
rad = numpy.radians(p.r)
ax.quiver(p.x, p.y, numpy.cos(rad), numpy.sin(rad), color="black",
2026-03-10 21:55:54 -07:00
scale=25, width=0.004, pivot="tail", zorder=6)
2026-03-08 22:13:10 -07:00
2026-03-07 08:26:29 -08:00
ax.set_xlim(bounds[0], bounds[2])
ax.set_ylim(bounds[1], bounds[3])
ax.set_aspect("equal")
2026-03-29 20:35:58 -07:00
if show_actual:
ax.set_title("Inire Routing Results (Dashed: Collision Proxy, Solid: Actual Geometry)")
else:
ax.set_title("Inire Routing Results (Proxy Geometry)")
2026-03-29 01:26:22 -07:00
2026-03-10 21:55:54 -07:00
# Legend handling for many nets
if len(results) < 25:
handles, labels = ax.get_legend_handles_labels()
if labels:
ax.legend(loc='upper left', bbox_to_anchor=(1, 1), fontsize='small', ncol=2)
fig.tight_layout()
2026-03-11 23:40:09 -07:00
2026-03-10 21:55:54 -07:00
plt.grid(True, which='both', linestyle=':', alpha=0.5)
2026-03-07 08:26:29 -08:00
return fig, ax
2026-03-29 01:26:22 -07:00
2026-03-11 23:40:09 -07:00
def plot_danger_map(
danger_map: DangerMap,
ax: Axes | None = None,
2026-03-29 01:26:22 -07:00
resolution: float | None = None
2026-03-11 23:40:09 -07:00
) -> tuple[Figure, Axes]:
"""
Plot the pre-computed danger map as a heatmap.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 10))
else:
2026-03-30 23:54:30 -07:00
fig = cast("Figure", ax.get_figure())
2026-03-11 23:40:09 -07:00
2026-03-29 01:26:22 -07:00
# Generate a temporary grid for visualization
res = resolution if resolution is not None else max(1.0, (danger_map.maxx - danger_map.minx) / 200.0)
x_coords = numpy.arange(danger_map.minx + res/2, danger_map.maxx, res)
y_coords = numpy.arange(danger_map.miny + res/2, danger_map.maxy, res)
xv, yv = numpy.meshgrid(x_coords, y_coords, indexing='ij')
points = numpy.column_stack((xv.ravel(), yv.ravel()))
grid = danger_map.costs_at_points(points).reshape(xv.shape)
2026-03-29 01:26:22 -07:00
2026-03-11 23:40:09 -07:00
# Need to transpose because grid is [x, y] and imshow expects [row, col] (y, x)
im = ax.imshow(
2026-03-29 01:26:22 -07:00
grid.T,
2026-03-30 23:54:30 -07:00
origin="lower",
extent=(danger_map.minx, danger_map.maxx, danger_map.miny, danger_map.maxy),
cmap="YlOrRd",
alpha=0.6,
2026-03-11 23:40:09 -07:00
)
2026-03-30 23:54:30 -07:00
plt.colorbar(im, ax=ax, label="Danger Cost")
2026-03-11 23:40:09 -07:00
ax.set_title("Danger Map (Proximity Costs)")
return fig, ax
2026-03-16 17:05:16 -07:00
2026-03-11 23:40:09 -07:00
def plot_expanded_nodes(
nodes: list[tuple[float, float, float]],
ax: Axes | None = None,
color: str = 'gray',
alpha: float = 0.3,
) -> tuple[Figure, Axes]:
"""
Plot A* expanded nodes for debugging.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(10, 10))
else:
2026-03-30 23:54:30 -07:00
fig = cast("Figure", ax.get_figure())
2026-03-11 23:40:09 -07:00
if not nodes:
return fig, ax
2026-03-29 20:35:58 -07:00
x, y, _ = zip(*nodes, strict=False)
2026-03-11 23:40:09 -07:00
ax.scatter(x, y, s=1, c=color, alpha=alpha, zorder=0)
return fig, ax
2026-03-16 17:05:16 -07:00
def plot_expansion_density(
nodes: list[tuple[float, float, float]],
bounds: tuple[float, float, float, float],
ax: Axes | None = None,
bins: int | tuple[int, int] = 50,
) -> tuple[Figure, Axes]:
"""
Plot a density heatmap (2D histogram) of expanded nodes.
Args:
nodes: List of (x, y, orientation) tuples.
bounds: (minx, miny, maxx, maxy) for the plot range.
ax: Optional existing axes to plot on.
bins: Number of bins for the histogram (int or (nx, ny)).
Returns:
Figure and Axes objects.
"""
if ax is None:
fig, ax = plt.subplots(figsize=(12, 12))
else:
2026-03-30 23:54:30 -07:00
fig = cast("Figure", ax.get_figure())
2026-03-16 17:05:16 -07:00
if not nodes:
ax.text(0.5, 0.5, "No Expansion Data", ha='center', va='center', transform=ax.transAxes)
return fig, ax
2026-03-29 20:35:58 -07:00
x, y, _ = zip(*nodes, strict=False)
2026-03-29 01:26:22 -07:00
2026-03-16 17:05:16 -07:00
# Create 2D histogram
h, xedges, yedges = numpy.histogram2d(
2026-03-29 01:26:22 -07:00
x, y,
bins=bins,
2026-03-16 17:05:16 -07:00
range=[[bounds[0], bounds[2]], [bounds[1], bounds[3]]]
)
2026-03-29 01:26:22 -07:00
2026-03-16 17:05:16 -07:00
# Plot as image
im = ax.imshow(
2026-03-29 01:26:22 -07:00
h.T,
2026-03-30 23:54:30 -07:00
origin="lower",
extent=(bounds[0], bounds[2], bounds[1], bounds[3]),
cmap="plasma",
interpolation="nearest",
alpha=0.7,
2026-03-16 17:05:16 -07:00
)
2026-03-29 01:26:22 -07:00
2026-03-30 23:54:30 -07:00
plt.colorbar(im, ax=ax, label="Expansion Count")
2026-03-16 17:05:16 -07:00
ax.set_title("Search Expansion Density")
ax.set_xlim(bounds[0], bounds[2])
ax.set_ylim(bounds[1], bounds[3])
2026-03-29 01:26:22 -07:00
2026-03-16 17:05:16 -07:00
return fig, ax