Repair exact visibility and hole rendering and streamline search state

This commit is contained in:
Jan Petykiewicz 2026-11-28 20:13:00 -08:00
commit 9ee786d138
10 changed files with 148 additions and 86 deletions

View file

@ -150,6 +150,15 @@ class RoutingWorld:
def _ensure_static_tree(self) -> None:
self._static_obstacles.ensure_tree()
def corner_segment_visible(self, start: tuple[float, float], end: tuple[float, float]) -> bool:
"""Allow endpoint contact while testing the open segment against keepouts."""
self._ensure_static_tree()
tree = self._static_obstacles.tree
if tree is None:
return True
segment = LineString((start, end))
return all(segment.relate_pattern(tree.geometries[index], "FF*******") for index in tree.query(segment))
def _ensure_static_raw_tree(self) -> None:
self._static_obstacles.ensure_raw_tree()

View file

@ -155,14 +155,10 @@ class AStarNode:
__slots__ = (
"port",
"g_cost",
"h_cost",
"fh_cost",
"parent",
"component_result",
"base_move_cost",
"cache_key",
"seed_index",
"congestion_resolved",
)
def __init__(
@ -173,21 +169,14 @@ class AStarNode:
parent: AStarNode | None = None,
component_result: ComponentResult | None = None,
*,
base_move_cost: float = 0.0,
cache_key: tuple | None = None,
seed_index: int | None = None,
congestion_resolved: bool = True,
) -> None:
self.port = port
self.g_cost = g_cost
self.h_cost = h_cost
self.fh_cost = (g_cost + h_cost, h_cost)
self.parent = parent
self.component_result = component_result
self.base_move_cost = base_move_cost
self.cache_key = cache_key
self.seed_index = seed_index
self.congestion_resolved = congestion_resolved
def __lt__(self, other: AStarNode) -> bool:
return self.fh_cost < other.fh_cost

View file

@ -2,11 +2,12 @@
from __future__ import annotations
from itertools import combinations, pairwise
from itertools import pairwise
from math import floor, isfinite
from typing import TYPE_CHECKING
from shapely.geometry import box
from shapely.strtree import STRtree
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.intervals import open_intervals
@ -74,12 +75,35 @@ def port_conflicts(problem: RoutingProblem, options: RoutingOptions) -> tuple[tu
# A terminal's physical cross-section is fixed by its heading and width.
pairs = []
matched = set()
for ports in aligned.values():
for (a, y1, w1), (b, y2, w2) in combinations(ports, 2):
if a == b or a in matched or b in matched:
separation = problem.clearance - TOLERANCE_LINEAR
for bank in aligned.values():
ports = [port for port in bank if port[0] not in matched]
if len(ports) < 2:
continue
gap = abs(y1 - y2) - (w1 + w2) / 2
if gap < problem.clearance - TOLERANCE_LINEAR:
pairs.extend(_match_bank(ports, separation, matched))
return tuple(pairs)
def _match_bank(ports: list[tuple[str, float, float]], separation: float, matched: set[str]) -> list[tuple[str, str]]:
spans = [box(y - (width + separation) / 2, 0, y + (width + separation) / 2, 1) for _, y, width in ports]
index = STRtree(spans)
def conflicts(i: int, j: int) -> bool:
a, y1, w1 = ports[i]
b, y2, w2 = ports[j]
return a != b and b not in matched and abs(y1 - y2) - (w1 + w2) / 2 < separation
pairs = []
for i, (a, _, _) in enumerate(ports):
if a in matched:
continue
# Dense banks usually match consecutive terminals in input order.
j = i + 1 if i + 1 < len(ports) and conflicts(i, i + 1) else min(
(j for j in index.query(spans[i]) if j > i and conflicts(i, j)), default=None,
)
if j is None:
continue
b = ports[j][0]
pairs.append((a, b))
matched.update((a, b))
return tuple(pairs)
return pairs

View file

@ -1,6 +1,6 @@
from __future__ import annotations
import numpy
from math import hypot
from typing import TYPE_CHECKING
import rtree
@ -9,9 +9,6 @@ if TYPE_CHECKING:
from inire.geometry.collision import RoutingWorld
from inire.geometry.primitives import Port
from inire.geometry.primitives import Port
class VisibilityManager:
"""
Manages corners of static obstacles for sparse A* / Visibility Graph jumps.
@ -19,6 +16,7 @@ class VisibilityManager:
__slots__ = (
"collision_engine",
"corners",
"_exact_corners",
"corner_index",
"_corner_graph",
"_point_visibility_cache",
@ -29,6 +27,7 @@ class VisibilityManager:
def __init__(self, collision_engine: RoutingWorld) -> None:
self.collision_engine = collision_engine
self.corners: list[tuple[float, float]] = []
self._exact_corners: list[tuple[float, float]] = []
self.corner_index = rtree.index.Index()
self._corner_graph: dict[int, list[tuple[float, float, float]]] = {}
self._point_visibility_cache: dict[tuple[int, int, int], list[tuple[float, float, float]]] = {}
@ -40,6 +39,7 @@ class VisibilityManager:
Reset all static visibility data.
"""
self.corners = []
self._exact_corners = []
self.corner_index = rtree.index.Index()
self._corner_graph = {}
self._point_visibility_cache = {}
@ -60,6 +60,7 @@ class VisibilityManager:
if self.collision_engine.metrics is not None:
self.collision_engine.metrics.total_visibility_corner_index_builds += 1
self.corners = []
self._exact_corners = []
self.corner_index = rtree.index.Index()
self._corner_graph = {}
self._point_visibility_cache = {}
@ -86,6 +87,7 @@ class VisibilityManager:
if (sx, sy) not in seen:
seen.add((sx, sy))
self.corners.append((sx, sy))
self._exact_corners.append((x, y))
for i, (x, y) in enumerate(self.corners):
self.corner_index.insert(i, (x, y, x, y))
@ -111,19 +113,15 @@ class VisibilityManager:
for i in range(num_corners):
self._corner_graph[i] = []
p1 = Port(self.corners[i][0], self.corners[i][1], 0)
for j in range(num_corners):
if i == j:
continue
if self.collision_engine.metrics is not None:
self.collision_engine.metrics.total_visibility_corner_pairs_checked += 1
start, end = self._exact_corners[i], self._exact_corners[j]
if self.collision_engine.corner_segment_visible(start, end):
cx, cy = self.corners[j]
dx, dy = cx - p1.x, cy - p1.y
dist = numpy.sqrt(dx**2 + dy**2)
angle = numpy.degrees(numpy.arctan2(dy, dx))
reach = self.collision_engine.ray_cast(p1, angle, max_dist=dist + 0.05, caller="visibility_build")
if reach >= dist - 0.01:
self._corner_graph[i].append((cx, cy, dist))
self._corner_graph[i].append((cx, cy, hypot(end[0] - start[0], end[1] - start[1])))
def _corner_idx_at(self, origin: Port) -> int | None:
self.ensure_corner_index_current()
@ -181,7 +179,7 @@ class VisibilityManager:
def get_point_visibility(self, origin: Port, max_dist: float = 1000.0) -> list[tuple[float, float, float]]:
"""
Find visible corners from an arbitrary point.
This may perform direct ray-cast scans and is not intended for hot search paths.
This may test local corner segments against keepouts.
"""
if self.collision_engine.metrics is not None:
self.collision_engine.metrics.total_visibility_point_queries += 1
@ -205,39 +203,38 @@ class VisibilityManager:
self.collision_engine.metrics.total_visibility_point_cache_misses += 1
bounds = (origin.x - max_dist, origin.y - max_dist, origin.x + max_dist, origin.y + max_dist)
candidates = list(self.corner_index.intersection(bounds))
candidates = sorted(self.corner_index.intersection(bounds))
visible = []
start = (origin.x, origin.y) if corner_idx is None else self._exact_corners[corner_idx]
for i in candidates:
cx, cy = self.corners[i]
dx, dy = cx - origin.x, cy - origin.y
dist = numpy.sqrt(dx**2 + dy**2)
end = self._exact_corners[i]
dist = hypot(end[0] - start[0], end[1] - start[1])
if dist > max_dist or dist < 1e-3:
continue
angle = numpy.degrees(numpy.arctan2(dy, dx))
reach = self.collision_engine.ray_cast(origin, angle, max_dist=dist + 0.05, caller="visibility_query")
if reach >= dist - 0.01:
if self.collision_engine.corner_segment_visible(start, end):
cx, cy = self.corners[i]
visible.append((cx, cy, dist))
if len(self._point_visibility_cache) >= 4096:
self._point_visibility_cache.clear()
self._point_visibility_cache[cache_key] = visible
return visible
def get_corner_visibility(self, origin: Port, max_dist: float = 1000.0) -> list[tuple[float, float, float]]:
"""
Return precomputed visibility only when the origin is already at a known corner.
This avoids the expensive arbitrary-point visibility scan in hot search paths.
Return visible neighbors when the origin is already at a known corner.
"""
if self.collision_engine.metrics is not None:
self.collision_engine.metrics.total_visibility_corner_queries_exact += 1
self.ensure_corner_graph_current()
if max_dist < 0:
return []
corner_idx = self._corner_idx_at(origin)
if corner_idx is not None and corner_idx in self._corner_graph:
if corner_idx is None:
return []
if self.collision_engine.metrics is not None:
self.collision_engine.metrics.total_visibility_corner_hits_exact += 1
return [corner for corner in self._corner_graph[corner_idx] if corner[2] <= max_dist]
return []
return self.get_point_visibility(origin, max_dist)

View file

@ -12,6 +12,7 @@ from inire import (
)
from inire.constants import TOLERANCE_LINEAR
from inire.router._automatic import _AutomaticRun
from inire.router._capacity import port_conflicts
from inire.router._routing_policy import _disconnected_nets
from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES
from inire.tests.routing_benchmarks import (
@ -587,6 +588,17 @@ def test_port_spacing_certificate_reaches_clements_capacity() -> None:
assert len(sample.stages) == 1
def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> None:
nets = tuple(
NetSpec(name, Port(5, y, 0), Port(95, y + 40, 0), width)
for name, y, width in (("a", 15, 6), ("b", 19, 2), ("c", 11, 3), ("d", 18, 2), ("clear", 30, 2))
)
problem = RoutingProblem((0, 0, 100, 100), nets)
assert port_conflicts(problem, RoutingOptions()) == (("a", "b"),)
assert port_conflicts(replace(problem, nets=(nets[0], nets[2], nets[1], *nets[3:])), RoutingOptions()) == (("a", "c"), ("b", "d"))
def test_paired_perimeters_respect_the_supplied_detour() -> None:
case = next(case for case in FALLBACK_BENCHMARK_CASES if case.name == "fallback-seeded-detour")
options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="automatic"))

View file

@ -54,6 +54,26 @@ def test_exact_corner_visibility_builds_graph_once_per_static_version() -> None:
assert engine.metrics.total_visibility_builds == 1
def test_exact_corner_visibility_accepts_only_endpoint_contact_and_scales_to_large_boards() -> None:
engine = RoutingWorld(clearance=0.0)
engine.add_static_obstacle(box(10, 20, 20, 30))
engine.add_static_obstacle(box(-10, 10, 0, 15))
visibility = VisibilityManager(engine)
origin = Port(10, 20, 0)
local = visibility.get_corner_visibility(origin, max_dist=25)
assert (0, 15) in {(x, y) for x, y, _ in local}
assert not engine.corner_segment_visible((10, 20), (20, 30))
for index in range(49):
engine.add_static_obstacle(box(100 + 10 * index, 0, 105 + 10 * index, 5))
assert visibility.get_corner_visibility(origin, max_dist=25) == local
engine.add_static_obstacle(box(4, 16, 6, 19))
blocked = visibility.get_corner_visibility(origin, max_dist=25)
assert (0, 15) not in {(x, y) for x, y, _ in blocked}
def test_clear_cache_invalidates_without_rebuilding_and_static_change_rebuilds_lazily() -> None:
engine = RoutingWorld(clearance=0.0)
engine.metrics = AStarMetrics()

View file

@ -1,26 +1,27 @@
import matplotlib
from matplotlib import pyplot as plt
from numpy import asarray
from shapely.geometry import Polygon, box
matplotlib.use("Agg")
from inire.geometry.components import Bend90
from inire.geometry.primitives import Port
from inire import RoutingResult
from inire.utils.visualization import plot_routing_results
from scripts.render_documentation_figures import _polygon
def test_plot_routing_results_respects_show_actual() -> None:
bend = Bend90.generate(Port(0, 0, 0), 10.0, 2.0, direction="CCW", collision_type="bbox")
result = RoutingResult("net", [bend], reached_target=True)
def test_polygon_holes_remain_unfilled_in_routes_and_documentation() -> None:
keepout = Polygon(box(1, 1, 9, 9).exterior, [box(3, 3, 7, 7).exterior])
figure, route_axes = plot_routing_results({}, [keepout], (0, 0, 10, 10))
walkthrough_axes = figure.add_axes((0.6, 0.6, 0.25, 0.25))
_polygon(walkthrough_axes, keepout, fill="gray", edge="black")
walkthrough_axes.set(xlim=(0, 10), ylim=(0, 10))
route_axes.grid(False)
try:
figure.canvas.draw()
pixels = asarray(figure.canvas.buffer_rgba())
for axes in (route_axes, walkthrough_axes):
def pixel(x, y, axes=axes):
xp, yp = axes.transData.transform((x, y))
return tuple(pixels[-1 - round(yp), round(xp)])
fig_actual, ax_actual = plot_routing_results({"net": result}, [], (-5.0, -5.0, 20.0, 20.0), show_actual=True)
fig_proxy, ax_proxy = plot_routing_results({"net": result}, [], (-5.0, -5.0, 20.0, 20.0), show_actual=False)
actual_line_points = max(len(line.get_xdata()) for line in ax_actual.lines)
proxy_line_points = max(len(line.get_xdata()) for line in ax_proxy.lines)
assert actual_line_points > proxy_line_points
assert ax_actual.get_title().endswith("Actual Geometry)")
assert ax_proxy.get_title().endswith("(Proxy Geometry)")
fig_actual.clf()
fig_proxy.clf()
assert pixel(2.5, 2.5) != pixel(5, 5)
assert pixel(5, 5) == pixel(0.5, 0.5)
finally:
plt.close(figure)

View file

@ -12,8 +12,11 @@ if "MPLBACKEND" not in os.environ:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
from matplotlib.path import Path
import numpy
from shapely.geometry import MultiPolygon, Polygon
from shapely.geometry.polygon import orient
if TYPE_CHECKING:
from matplotlib.axes import Axes
@ -24,6 +27,16 @@ if TYPE_CHECKING:
from inire.results import RoutingResult
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))
def plot_routing_results(
results: dict[str, RoutingResult],
static_obstacles: list[Polygon],
@ -48,8 +61,7 @@ def plot_routing_results(
# Plot static obstacles (gray)
for poly in static_obstacles:
x, y = poly.exterior.xy
ax.fill(x, y, alpha=0.3, fc="gray", ec="black", zorder=1)
draw_polygon(ax, poly, alpha=0.3, fc="gray", ec="black", zorder=1)
# Plot paths
colors = plt.get_cmap("tab20")
@ -68,9 +80,8 @@ def plot_routing_results(
geoms = [poly]
for g in geoms:
if hasattr(g, "exterior"):
x, y = g.exterior.xy
ax.fill(x, y, alpha=0.15, fc=color, ec=color, linestyle='--', lw=0.5, zorder=2)
if isinstance(g, Polygon):
draw_polygon(ax, g, alpha=0.15, fc=color, ec=color, linestyle='--', lw=0.5, zorder=2)
else:
# Fallback for LineString or other geometries
x, y = g.xy
@ -84,12 +95,12 @@ def plot_routing_results(
else:
geoms = [poly]
for g in geoms:
if hasattr(g, "exterior"):
x, y = g.exterior.xy
ax.plot(x, y, color=color, lw=1.5, alpha=0.9, zorder=3, label=net_id if not label_added else "")
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)
else:
x, y = g.xy
ax.plot(x, y, color=color, lw=1.5, alpha=0.9, zorder=3, label=net_id if not label_added else "")
ax.plot(x, y, color=color, lw=1.5, alpha=0.9, zorder=3, label=label)
label_added = True
# 3. Plot subtle port orientation arrow
@ -98,10 +109,6 @@ def plot_routing_results(
ax.quiver(p.x, p.y, numpy.cos(rad), numpy.sin(rad), color="black",
scale=40, width=0.002, alpha=0.2, pivot="tail", zorder=4)
if not res.path and not res.is_valid:
# Empty failed paths are typically unroutable.
pass
# 4. Plot main arrows for netlist ports
if netlist:
for _net_id, (start_p, target_p) in netlist.items():

View file

@ -28,6 +28,8 @@ Implemented items 11, 13, and 30 preserve replay diagnostics across all four mod
Implemented items 25 and 36 use cardinal heading vectors and consistent length units in the lattice and corridor heuristics. Partial results track geometric progress even with zero heuristic weight, and a high legal move cost no longer acts as a collision sentinel.
Implemented items 7, 8, 9, and 10 cover endpoint-aware corner visibility with a local fallback, hole-aware plots, indexed terminal-bank checks, and removal of unused private A* node fields. The seven complex-routing walkthrough figures still render byte for byte. The 4,000-net capacity probe took about 0.11 s for a clear bank and 0.04 s for a densely overlapping bank.
| Batch | Work | Acceptance gate |
| --- | --- | --- |
| Physical verification | 1, 2, 17, 23, and 38 | Reject the faulty geometry and keep legal joins valid in search and seed replay. Check circular bend accuracy, folded-route spacing, and isolation between different nets. |

View file

@ -19,6 +19,7 @@ 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
@ -43,7 +44,7 @@ def _save(fig: Figure, directory: Path, name: str) -> None:
def _polygon(ax: Axes, polygon: Polygon, *, fill: str, edge: str, **kwargs: object) -> None:
ax.fill(*polygon.exterior.xy, facecolor=fill, edgecolor=edge, **kwargs)
draw_polygon(ax, polygon, facecolor=fill, edgecolor=edge, **kwargs)
def _waveguide(ax: Axes, result: RoutingResult, *, color: str, linestyle: str = "-") -> None: