From c480871f072b22fe34ea16042964f6ddbcf145fb Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 00:16:13 -0800 Subject: [PATCH] Preflight component geometry before tessellation --- docs/user/api-reference.md | 4 +- inire/geometry/components.py | 163 +++++++++++++++++--------- inire/geometry/sbend.py | 7 +- inire/router/_astar_admission.py | 24 +--- inire/router/_astar_moves.py | 5 +- inire/router/_automatic.py | 22 +++- inire/router/_compact.py | 2 +- inire/router/_perimeter.py | 3 +- inire/router/_router.py | 21 ++-- inire/router/_routing_policy.py | 4 +- inire/router/_seed_materialization.py | 63 +++++++--- inire/router/refiner.py | 22 ++-- inire/tests/test_api.py | 25 ++++ 13 files changed, 252 insertions(+), 113 deletions(-) diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index c3db4fa..fa2b42b 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -45,7 +45,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate | `RoutingResult.requested_net` and `effective_net` | The net as supplied and the net used by the worker, including resolved headings. | | `RoutingResult.path` | Ordered path components from the source to the last reached state. An unroutable result has an empty path. | | `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. | -| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. `seed_error` identifies a supplied bend that cannot carry the net's width. `terminal_error` identifies an inaccessible start or target face. | +| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. `seed_error` identifies a supplied bend that cannot carry the net's width or cannot be safely materialized. `terminal_error` identifies an inaccessible start or target face. | | `RoutingResult.locked_geometry` and `as_seed()` | Physical polygons and the sequence of moves, respectively. Check validity before exporting polygons or [reserving a completed net](route-a-layout.md#reuse-an-existing-route). | | `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. | | `RoutingRunResult.topology` and `metrics` | Corridor counts and seed work when reported by the selected worker, plus work counters across the run. | @@ -90,7 +90,7 @@ A custom S-bend outline uses local coordinates. Its input face is centered at `( When migrating a half-arc template, supply the complete outline through `sbend_outlines` and keep `bend_physical_geometry` for custom 90-degree bends. Both terminal faces of each custom polygon must be centered on their ports and match the routed width. A custom 90-degree template is shared across nets, so it can only be used by nets whose width matches its faces. Replay an `SBendSeed` with the same outlines and bend settings to recover its physical geometry. -Circular bends approximate the outer edge within a sagitta of 0.01 layout units. The router also sizes the subdivision for the outer edge of a clearance-expanded circular proxy. +Circular bends approximate the outer edge within a sagitta of 0.01 layout units. The router also sizes the subdivision for the outer edge of a clearance-expanded circular proxy. A generated circular arc that needs more than 250,000 subdivisions is rejected before sampling. Use coarser layout units if the required radii exceed this limit. ### ObjectiveWeights diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 37a7747..d8e5c45 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -2,7 +2,7 @@ from __future__ import annotations from dataclasses import dataclass, field, replace from itertools import pairwise -from math import asin, ceil, pi, radians, sqrt +from math import asin, ceil, isfinite, pi, radians, sqrt from typing import TYPE_CHECKING, Literal import numpy @@ -15,7 +15,7 @@ from shapely.geometry import Polygon, box from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR from inire.geometry.sbend import sbend_grid_span, sbend_span from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed -from .primitives import Port, rotation_matrix2 +from .primitives import Port, rotate_cardinal, rotation_matrix2 if TYPE_CHECKING: from collections.abc import Iterable, Sequence @@ -122,9 +122,37 @@ def _normalize_length(value: float) -> float: return float(value) -def _advance_port(start: Port, rotation: NDArray[numpy.int32], forward: float, lateral: float = 0.0, turn: int = 0) -> Port: - dx, dy = rotation @ numpy.array((forward, lateral)) - return Port(start.x + dx, start.y + dy, start.r + turn) +class ComponentPreparationError(ValueError): + """A move cannot safely be materialized.""" + + +def component_endpoint(start: Port, kind: MoveKind, parameters: tuple) -> Port: + if kind == "straight": + forward, lateral, turn = _normalize_length(parameters[0]), 0, 0 + elif kind == "bend90": + radius, direction = parameters + sign = 1 if direction == "CCW" else -1 + forward = bend90_grid_span(radius) + lateral, turn = sign * forward, sign * 90 + else: + lateral, radius = parameters + try: + forward = sbend_grid_span(lateral, radius) + except (ValueError, OverflowError) as exc: + raise ComponentPreparationError("has an unrepresentable S-bend span") from exc + turn = 0 + dx, dy = rotate_cardinal(forward, lateral, int(start.r)) + return start.translate(dx, dy, turn) + + +def check_component_endpoint( + start: Port, kind: MoveKind, parameters: tuple, bounds: tuple[float, float, float, float], +) -> None: + end = component_endpoint(start, kind, parameters) + xmin, ymin, xmax, ymax = bounds + tol = TOLERANCE_LINEAR + if not (xmin - tol <= end.x <= xmax + tol and ymin - tol <= end.y <= ymax + tol): + raise ComponentPreparationError("has an endpoint outside the routing board") def _bend90_length(radius: float) -> float: @@ -291,12 +319,49 @@ def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tup def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int: + if not isfinite(radius) or not isfinite(angle_deg): + raise ComponentPreparationError("has an unrepresentable circular arc") if radius <= 0: return 1 if not numpy.isfinite(sagitta) or sagitta <= 0: raise ValueError("Arc sagitta must be finite and positive") theta_max = 4 * asin(min(1.0, sqrt(sagitta) / sqrt(radius) / sqrt(2.0))) - return max(8, ceil(radians(abs(angle_deg)) / theta_max)) + subdivisions = radians(abs(angle_deg)) / theta_max + if subdivisions > 250_000: + raise ComponentPreparationError("exceeds 250,000 subdivisions for one circular arc") + return max(8, ceil(subdivisions)) + + +def _arc_samples( + radius: float, width: float, angle: float, sagitta: float, dilation: float, *, sample_dilation: bool, +) -> tuple[int, int | None]: + physical = _get_num_segments(radius + width / 2, angle, sagitta) + dilated = None + if sample_dilation and dilation > 0 and bend_fits_width(radius, width + 2 * dilation): + dilated = _get_num_segments(radius + (width + 2 * dilation) / 2, angle, sagitta) + return physical, dilated + + +def _sbend_angle(offset: float, radius: float) -> float: + return 2 * asin(sqrt(abs(offset) / radius) / 2) + + +def prepare_component_sampling( + kind: MoveKind, parameters: tuple, width: float, *, + collision_type: BendCollisionModel, physical_geometry_type: BendPhysicalGeometry, + dilation: float, sbend_outline: Polygon | None = None, sagitta: float = 0.01, +) -> tuple[int, int | None]: + if kind == "bend90": + radius = parameters[0] + custom_physical = isinstance(physical_geometry_type, Polygon) + if custom_physical and isinstance(collision_type, Polygon): + return 0, None + return _arc_samples(radius, width, 90, sagitta, dilation, sample_dilation=not custom_physical or collision_type == "arc") + if kind == "sbend" and sbend_outline is None: + offset, radius = parameters + angle = float(numpy.degrees(_sbend_angle(offset, radius))) + return _arc_samples(radius, width, angle, sagitta, dilation, sample_dilation=True) + return 0, None def _get_arc_polygons( @@ -304,7 +369,7 @@ def _get_arc_polygons( radius: float, width: float, ts: tuple[float, float], - sagitta: float = 0.01, + num_segments: int, dilation: float = 0.0, *, port_faces: tuple[Port, Port] | None = None, @@ -313,7 +378,6 @@ def _get_arc_polygons( cx, cy = cxy inner_radius = radius - width / 2.0 - dilation outer_radius = radius + width / 2.0 + dilation - num_segments = _get_num_segments(outer_radius, abs(ts[1] - ts[0]), sagitta) angles = numpy.linspace(t_start, t_end, num_segments + 1) cos_a = numpy.cos(angles) @@ -440,7 +504,7 @@ class Straight: ) -> ComponentResult: rot2 = rotation_matrix2(start_port.r) length_f = _normalize_length(length) - end_port = _advance_port(start_port, rot2, length_f) + end_port = component_endpoint(start_port, "straight", (length_f,)) half_w = width / 2.0 pts = numpy.array(((0.0, half_w), (length_f, half_w), (length_f, -half_w), (0.0, -half_w))) @@ -500,54 +564,40 @@ class Bend90: center_local = numpy.array((tangent_length, sign * radius)) center_xy = (rot2 @ center_local) + numpy.array((start_port.x, start_port.y)) center = (float(center_xy[0]), float(center_xy[1])) - end_port = _advance_port(start_port, rot2, grid_span, sign * grid_span, sign * 90) + end_port = component_endpoint(start_port, "bend90", (radius, direction)) start_theta = start_port.r - sign * 90 end_theta = start_port.r ts = (float(start_theta), float(end_theta)) port_faces = (start_port, end_port) - arc_polys = _get_arc_polygons(center, radius, width, ts, sagitta, port_faces=port_faces) - collision_polys = _apply_collision_model( - arc_polys[0], - collision_type, - radius, - width, - center, - ts, - clip_margin=clip_margin, - rotation_deg=float(start_port.r), - mirror_y=(sign < 0), - tangent_extensions=(tangent_length, tangent_length), + custom_physical = isinstance(physical_geometry_type, Polygon) + segments, dilated_segments = prepare_component_sampling( + "bend90", (radius, direction), width, collision_type=collision_type, + physical_geometry_type=physical_geometry_type, dilation=dilation, sagitta=sagitta, ) + arc_polys = [] + if segments: + arc_polys = _get_arc_polygons(center, radius, width, ts, segments, port_faces=port_faces) + if isinstance(collision_type, Polygon): + collision_polys = [_transform_custom_collision_polygon(collision_type, center, float(start_port.r), mirror_y=(sign < 0))] + else: + collision_polys = _apply_collision_model( + arc_polys[0], collision_type, radius, width, center, ts, clip_margin=clip_margin, + rotation_deg=float(start_port.r), mirror_y=(sign < 0), tangent_extensions=(tangent_length, tangent_length), + ) if isinstance(physical_geometry_type, Polygon): - physical_geometry = _apply_collision_model( - arc_polys[0], - physical_geometry_type, - radius, - width, - center, - ts, - rotation_deg=float(start_port.r), - mirror_y=(sign < 0), - ) + physical_geometry = [_transform_custom_collision_polygon( + physical_geometry_type, center, float(start_port.r), mirror_y=(sign < 0), + )] else: physical_geometry = arc_polys dilated_arcs = arc_polys - if dilation > 0 and (physical_geometry is arc_polys or collision_type == "arc"): - if bend_fits_width(radius, width + 2 * dilation): - dilated_arcs = _get_arc_polygons( - center, - radius, - width, - ts, - sagitta, - dilation=dilation, - port_faces=port_faces, - ) - else: - dilated_arcs = _buffer_geometry(arc_polys, dilation) + if dilated_segments is not None: + dilated_arcs = _get_arc_polygons(center, radius, width, ts, dilated_segments, dilation=dilation, port_faces=port_faces) + elif dilation > 0 and (not custom_physical or collision_type == "arc"): + dilated_arcs = _buffer_geometry(arc_polys, dilation) dilated_physical_geometry = dilated_arcs if physical_geometry is arc_polys else _buffer_geometry(physical_geometry, dilation) dilated_collision_geometry = dilated_arcs if collision_type == "arc" else _buffer_geometry(collision_polys, dilation) @@ -577,12 +627,12 @@ class SBend: span: float, grid_span: int, width: float, - sagitta: float, + num_segments: int, ) -> list[Polygon]: # Reflect the first arc about the midpoint and reverse it to get the # second arc. Reuse the midpoint and its normal for both polygons. sign = 1 if offset > 0 else -1 - angles = numpy.linspace(0, theta, _get_num_segments(radius + width / 2, float(numpy.degrees(theta)), sagitta) + 1) + angles = numpy.linspace(0, theta, num_segments + 1) sin, cos = numpy.sin(angles), numpy.cos(angles) first = numpy.column_stack((radius * sin, sign * radius * (1 - cos))) first[-1] = (span / 2, offset / 2) @@ -624,22 +674,27 @@ class SBend: raise ValueError("Bend radius must be at least half the net width") sign = 1 if offset >= 0 else -1 - theta = 2 * asin(sqrt(abs(offset) / radius) / 2) + theta = _sbend_angle(offset, radius) + end_port = component_endpoint(start_port, "sbend", (offset, radius)) dx = sbend_span(offset, radius) grid_span = sbend_grid_span(offset, radius) tail = grid_span - dx rot2 = rotation_matrix2(start_port.r) - end_port = _advance_port(start_port, rot2, grid_span, offset) if outline is not None: physical = _transform_custom_collision_polygon(outline, (start_port.x, start_port.y), start_port.r, mirror_y=False) physical_geometry = geometry = [physical] dilated_physical_geometry = dilated_collision_geometry = _buffer_geometry(physical_geometry, dilation) else: - physical_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta) - if dilation > 0 and bend_fits_width(radius, width + 2 * dilation): + theta_deg = float(numpy.degrees(theta)) + segments, dilated_segments = prepare_component_sampling( + "sbend", (offset, radius), width, collision_type=collision_type, + physical_geometry_type="arc", dilation=dilation, sagitta=sagitta, + ) + physical_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, segments) + if dilated_segments is not None: dilated_physical_geometry = SBend._arcs( - start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, sagitta, + start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, dilated_segments, ) else: dilated_physical_geometry = _buffer_geometry(physical_geometry, dilation) @@ -648,7 +703,6 @@ class SBend: else: if not isinstance(collision_type, str): raise TypeError("Custom S-bend geometry requires a complete outline") - theta_deg = float(numpy.degrees(theta)) origin = numpy.array((start_port.x, start_port.y)) center1 = rot2 @ numpy.array((0.0, sign * radius)) + origin center2 = rot2 @ numpy.array((dx, offset - sign * radius)) + origin @@ -694,7 +748,10 @@ def build_component( dilation: float, sbend_outline: Polygon | None = None, physical_length: float | None = None, + bounds: tuple[float, float, float, float] | None = None, ) -> ComponentResult: + if bounds is not None: + check_component_endpoint(start, kind, parameters, bounds) if kind == "straight": return Straight.generate(start, parameters[0], width, dilation=dilation) if kind == "bend90": diff --git a/inire/geometry/sbend.py b/inire/geometry/sbend.py index 11448e3..fa61f48 100644 --- a/inire/geometry/sbend.py +++ b/inire/geometry/sbend.py @@ -1,13 +1,16 @@ """S-bend dimensions on the routing grid.""" -from math import ceil, isqrt, sqrt +from math import ceil, isfinite, isqrt, sqrt from inire.constants import TOLERANCE_LINEAR def sbend_span(offset: float, radius: float) -> float: offset = abs(offset) - return sqrt(offset * (4 * radius - offset)) + squared = offset * (4 * radius - offset) + if isfinite(squared): + return sqrt(squared) + return sqrt(offset) * sqrt(radius) * sqrt(4 - offset / radius) def sbend_grid_span(offset: float, radius: float) -> int: diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index 748edb5..757c461 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -7,9 +7,8 @@ from shapely.geometry import Polygon from inire.constants import TOLERANCE_LINEAR from inire.geometry.component_overlap import invalid_component_join -from inire.geometry.components import bend90_grid_span, build_component, path_within_board -from inire.geometry.primitives import Port, rotate_cardinal -from inire.geometry.sbend import sbend_grid_span +from inire.geometry.components import build_component, check_component_endpoint, path_within_board +from inire.geometry.primitives import Port from inire.router.refiner import component_hits_ancestor_chain from ._astar_types import AStarContext, AStarMetrics, AStarNode, SearchRunConfig @@ -19,21 +18,6 @@ if TYPE_CHECKING: from ._astar_types import CongestionCaches -def _bend_endpoint_outside_board(start: Port, kind: MoveKind, params: tuple, board: Polygon) -> bool: - if kind == "bend90": - radius, direction = params - forward = bend90_grid_span(radius) - lateral = forward if direction == "CCW" else -forward - else: - lateral, radius = params - forward = sbend_grid_span(lateral, radius) - dx, dy = rotate_cardinal(forward, lateral, int(start.r)) - x, y = start.x + dx, start.y + dy - xmin, ymin, xmax, ymax = board.bounds - tol = TOLERANCE_LINEAR - return not (xmin - tol <= x <= xmax + tol and ymin - tol <= y <= ymax + tol) - - def process_move( parent: AStarNode, target: Port, @@ -92,8 +76,8 @@ def process_move( try: board = context.cost_evaluator.collision_engine.board # The terminal center must fit before we allocate a tessellated outline. - if board is not None and move_class != "straight" and _bend_endpoint_outside_board(cp, move_class, params, board): - return + if board is not None and move_class != "straight": + check_component_endpoint(cp, move_class, params, board.bounds) res_rel = build_component( base_port, net_width, diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index 6f7baf1..a0654bd 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -46,7 +46,10 @@ def _sbend_forward_span(offset: float, radius: float) -> float | None: abs_offset = abs(offset) if abs_offset <= TOLERANCE_LINEAR or radius <= 0 or abs_offset >= 2.0 * radius: return None - return sbend_grid_span(offset, radius) + try: + return sbend_grid_span(offset, radius) + except OverflowError: + return None def _visible_straight_candidates( diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 3440106..33c4055 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -39,7 +39,7 @@ from inire.router._routing_policy import ( _route_residual, _trial, ) -from inire.router._seed_materialization import materialize_path_seed +from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error from inire.router._stack import route_once from inire.router._topology import constrained_triangulation_available, plan_corridors from inire.router.cost import build_native_cost_evaluator, weighted_path_length @@ -312,7 +312,9 @@ class _AutomaticRun: def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]: choices = [] for seed in seeds: - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance) + path = materialize_path_seed( + seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance, bounds=problem.bounds, + ) if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: continue footprint = shapely.union_all([shape for component in path for shape in component.physical_geometry]) @@ -694,7 +696,21 @@ class _AutomaticRun: timings=tuple(self.timings), duration_s=perf_counter() - started, ) - return replace(complete_final_conflict_trace(best.run), metrics=metrics, automatic=report) + results = best.run.results_by_net + if options.congestion.max_iterations and self.raw_problem.initial_paths: + results = dict(results) + for net in self.raw_problem.nets: + seed = self.raw_problem.initial_paths.get(net.net_id) + result = results[net.net_id] + if seed is None or result.report.seed_error is not None: + continue + error = seed_preparation_error( + seed, start=net.start, net_width=net.width, search=options.search, clearance=self.raw_problem.clearance, + ) + if error: + report_with_error = replace(result.report, seed_error=f"Initial path for {net.net_id!r} {error}") + results[net.net_id] = replace(result, report=report_with_error) + return replace(complete_final_conflict_trace(replace(best.run, results_by_net=results)), metrics=metrics, automatic=report) def route_automatic( diff --git a/inire/router/_compact.py b/inire/router/_compact.py index 6b369a4..8a76794 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -140,7 +140,7 @@ def _verified_candidates( seeds: Iterable[PathSeed], ) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]: for seed in seeds: - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance) + path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=board.bounds) if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: continue footprint = union_all([polygon for component in path for polygon in component.physical_geometry]) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 0c364ed..2306a34 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -126,7 +126,8 @@ def bundle_turnaround_candidates( def points_for(net: NetSpec) -> tuple[XY, ...]: path = materialize_path_seed( - proposal.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance + proposal.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance, + bounds=problem.bounds, ) return tuple((round(x), round(y)) for x, y in export_waypoints(path or ())) diff --git a/inire/router/_router.py b/inire/router/_router.py index 7c2faa3..3e64bb7 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -37,7 +37,7 @@ from inire.router._congestion_policy import ( from inire.router._pair_local import search_pair_candidate from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace from inire.router._search import incumbent_guidance, path_guidance, route_astar -from inire.router._seed_materialization import materialize_path_seed, seed_width_error +from inire.router._seed_materialization import materialize_path_seed, SeedMaterializationError, seed_width_error from inire.router.refiner import PathRefiner if TYPE_CHECKING: @@ -380,13 +380,18 @@ class PathFinder: if error is not None: raise ValueError(f"Initial path for {net_id!r} {error}") net = state.net_specs[net_id] - path = materialize_path_seed( - seed, - start=net.start, - net_width=net.width, - search=search, - clearance=self.context.cost_evaluator.collision_engine.clearance, - ) + try: + path = materialize_path_seed( + seed, + start=net.start, + net_width=net.width, + search=search, + diagnostic=True, + clearance=self.context.cost_evaluator.collision_engine.clearance, + ) + except SeedMaterializationError as exc: + state.seed_errors[net_id] = f"Initial path for {net_id!r} {exc}" + continue if path is None: state.seed_errors[net_id] = f"Initial path for {net_id!r} {seed_width_error(seed, net.width)}" elif path: diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index dd7bc78..2d47f9c 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -92,7 +92,9 @@ def _direct_paths( seed = problem.initial_paths.get(net.net_id) if seed is None or options.search.seed_geometry_error(seed): continue - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance) + path = materialize_path_seed( + seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance, bounds=problem.bounds, + ) if path and path[-1].end_port == net.target: report = world.verify_path_report(net.net_id, path) if report.is_valid: diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 018b3d5..39afcb6 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -2,7 +2,9 @@ from __future__ import annotations from typing import TYPE_CHECKING -from inire.geometry.components import bend_fits_width, build_component +from inire.geometry.components import ( + ComponentPreparationError, bend_fits_width, build_component, component_endpoint, prepare_component_sampling, +) from inire.model import resolve_bend_geometry from inire.seeds import Bend90Seed, SBendSeed, StraightSeed @@ -30,6 +32,26 @@ def seed_width_error(seed: PathSeed, net_width: float) -> str | None: return None +def seed_preparation_error(seed: PathSeed, *, start: Port, net_width: float, search: SearchOptions, clearance: float) -> str | None: + proxy, physical = resolve_bend_geometry(search) + for index, segment in enumerate(seed.segments, start=1): + kind, parameters = seed_move(segment) + template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None + try: + start = component_endpoint(start, kind, parameters) + prepare_component_sampling( + kind, parameters, net_width, collision_type=proxy, physical_geometry_type=physical, + dilation=clearance / 2, sbend_outline=template.polygon if template is not None else None, + ) + except (ComponentPreparationError, OverflowError) as exc: + return f"segment {index} ({type(segment).__name__}) {exc}" + return None + + +class SeedMaterializationError(ValueError): + """A supplied seed cannot be materialized.""" + + def materialize_path_seed( seed: PathSeed, *, @@ -37,31 +59,44 @@ def materialize_path_seed( net_width: float, search: SearchOptions, clearance: float, + bounds: tuple[float, float, float, float] | None = None, + diagnostic: bool = False, ) -> tuple[ComponentResult, ...] | None: if seed_width_error(seed, net_width) is not None: return None + if diagnostic: + error = seed_preparation_error(seed, start=start, net_width=net_width, search=search, clearance=clearance) + if error is not None: + raise SeedMaterializationError(error) + path: list[ComponentResult] = [] current = start dilation = clearance / 2.0 bend_collision_type, bend_physical_geometry = resolve_bend_geometry(search) bend_clip_margin = search.bend_clip_margin - for segment in seed.segments: + for index, segment in enumerate(seed.segments, start=1): kind, parameters = seed_move(segment) template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None - component = build_component( - current, - net_width, - kind, - parameters, - collision_type=bend_collision_type, - physical_geometry_type=bend_physical_geometry, - clip_margin=bend_clip_margin, - dilation=dilation, - sbend_outline=template.polygon if template is not None else None, - physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None), - ) + try: + component = build_component( + current, + net_width, + kind, + parameters, + collision_type=bend_collision_type, + physical_geometry_type=bend_physical_geometry, + clip_margin=bend_clip_margin, + dilation=dilation, + sbend_outline=template.polygon if template is not None else None, + bounds=None if diagnostic else bounds, + physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None), + ) + except (ComponentPreparationError, OverflowError) as exc: + if diagnostic: + raise SeedMaterializationError(f"segment {index} ({type(segment).__name__}) {exc}") from exc + return None path.append(component) current = component.end_port return tuple(path) diff --git a/inire/router/refiner.py b/inire/router/refiner.py index 66ab7b3..e3ff6dc 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -9,8 +9,10 @@ from typing import TYPE_CHECKING, Any from inire.constants import TOLERANCE_LINEAR from inire.geometry.component_overlap import components_overlap, invalid_component_join -from inire.geometry.components import _advance_port, _bend90_length, bend_fits_width, bend90_grid_span, build_component -from inire.geometry.primitives import port_local_coordinates, rotation_matrix2 +from inire.geometry.components import ( + _bend90_length, bend_fits_width, bend90_grid_span, build_component, component_endpoint, ComponentPreparationError, +) +from inire.geometry.primitives import port_local_coordinates from inire.model import resolve_bend_geometry if TYPE_CHECKING: @@ -248,11 +250,12 @@ class PathRefiner: (-first_sign, second_straight), (first_sign, 0.0), ): - curr = _advance_port(curr, rotation_matrix2(curr.r), span, sign * span, sign * 90) - moves.append(_DoglegMove(curr, bend_length, "bend90", "CCW" if sign > 0 else "CW", bend_radius=radius)) + direction = "CCW" if sign > 0 else "CW" + curr = component_endpoint(curr, "bend90", (radius, direction)) + moves.append(_DoglegMove(curr, bend_length, "bend90", direction, bend_radius=radius)) if straight_len > 0.01: length = float(straight_len) - curr = _advance_port(curr, rotation_matrix2(curr.r), length) + curr = component_endpoint(curr, "straight", (length,)) moves.append(_DoglegMove(curr, length, "straight")) return moves if curr == target else None @@ -262,12 +265,14 @@ class PathRefiner: dilation = self.collision_engine.clearance / 2.0 path = [] port = start + board = self.collision_engine.board + bounds = None if board is None else board.bounds for move in moves: parameters = (move.length,) if move.direction is None else (radius, move.direction) component = build_component( port, width, move.move_type, parameters, collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation, - physical_length=search.bend_physical_length if move.move_type == "bend90" else None, + physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds, ) path.append(component) port = component.end_port @@ -363,7 +368,10 @@ class PathRefiner: moves = self._dogleg_moves(window_start, window_end, radius, side_extent) if moves is None or not self.score_path(scoring_start, [*prefix, *moves, *suffix]) + 1e-6 < best_candidate_cost: continue - replacement = self._build_dogleg(window_start, net_width, radius, moves) + try: + replacement = self._build_dogleg(window_start, net_width, radius, moves) + except (ComponentPreparationError, OverflowError): + continue self.context.metrics.total_refinement_candidates_built += 1 candidate_path = [*prefix, *replacement, *suffix] candidate_cost = self.score_path(scoring_start, candidate_path) diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 2f0118c..b70b955 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -761,6 +761,31 @@ def test_zero_clearance_search_counts_physical_congestion_work() -> None: assert run.iteration_trace[0].congestion_exact_pair_checks == run.metrics.congestion_exact_pair_checks +@pytest.mark.parametrize("mode", ["off", "automatic"]) +@pytest.mark.parametrize("node_limit", [0, 10]) +@pytest.mark.parametrize("move", [Bend90Seed(1e11, "CCW"), SBendSeed(1e11, 1e11)]) +def test_unsafe_seed_reports_segment_without_allocating_geometry(monkeypatch, mode, node_limit, move) -> None: + def unexpected_tessellation(*_args, **_kwargs): + pytest.fail("Oversized seed reached the tessellator") + + monkeypatch.setattr(components_module, "_get_arc_polygons", unexpected_tessellation) + monkeypatch.setattr(SBend, "_arcs", unexpected_tessellation) + net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) + problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((move,))}) + options = RoutingOptions( + search=SearchOptions(node_limit=node_limit, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)), + topology=TopologyOptions(mode=mode), + refinement=RefinementOptions(enabled=False), + ) + + result = route(problem, options=options).results_by_net[net.net_id] + + assert result.is_valid is bool(node_limit) + assert result.report.seed_error == ( + f"Initial path for 'track' segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc" + ) + + def test_search_rejects_out_of_board_bends_before_tessellation(monkeypatch) -> None: def unexpected_tessellation(*_args, **_kwargs): pytest.fail("Search tessellated a bend with an endpoint outside the board")