From 3d7fc3a705109b34091bdbf632d1773e4ebd2168 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sat, 28 Nov 2026 10:57:01 -0800 Subject: [PATCH] Support whole custom S-bend outlines and recover routing detours --- docs/architecture.md | 10 +-- docs/complex-routing-example-1.md | 8 +- docs/topological-routing.md | 4 +- docs/user/api-reference.md | 9 ++- inire/__init__.py | 2 + inire/geometry/components.py | 101 ++++++++++---------------- inire/model.py | 46 +++++++++++- inire/router/_astar_admission.py | 4 + inire/router/_astar_moves.py | 16 ++-- inire/router/_automatic.py | 18 +++-- inire/router/_bundle.py | 5 +- inire/router/_search.py | 16 +++- inire/router/_seed_materialization.py | 2 + inire/router/_topology.py | 44 +++++++++-- inire/tests/routing_corpus.py | 1 + inire/tests/test_api.py | 60 ++++++++++++--- inire/tests/test_components.py | 28 +++---- inire/tests/test_refinements.py | 35 ++++++++- inire/tests/test_topology.py | 24 ++++-- 19 files changed, 304 insertions(+), 129 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 8cc3f2b..b7d594b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -14,9 +14,9 @@ Follow the left column down while the number of verified nets is below the targe 2. **Try constructive planners.** Bundles assign ordered tracks through barriers. Column schedules place turns between openings. Compact planners fit short connections between constrained ports. Each produces seeds whose physical geometry the worker checks. 3. **Start with a small search budget.** Lock verified straight links and search for the remaining nets. A different lock order or a small unlocked probe can free room for a turn. Promising guide and column attempts can run first. 4. **Decide what to keep fixed.** If the remaining ports are connected, route around the locked geometry. If the locks disconnect them, pass the previously verified paths as seeds that can move. A joint retry can assign different lanes through a shared opening. If recovery stalls, seed and lattice attempts can search the whole layout. The final lattice retry can use the caller's full node limit. -5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L581). +5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L584). -The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L480). +The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L483). ### Example of a poor lock @@ -26,7 +26,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati ## Detailed search and congestion -- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. A long lead can use consecutive straights when a single forward scan cannot cover it. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py) +- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. A long lead can use consecutive straights when a single forward scan cannot cover it. Search can try turns away from a distant target if it exhausts its preferred moves. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py) - **Recheck the installed set.** Paths that reach their targets and pass geometry checks against themselves, the board, and keepouts participate in congestion. Partial and geometrically invalid paths remain available for diagnosis. After an iteration the driver verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. A narrowed retry includes every net that still fails verification. [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L99) @@ -34,13 +34,13 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati ## Geometry and refinement -Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within components and unintended contact between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed. +Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within components and unintended contact between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Search and seed materialization use the same custom S-bend outline when one is configured. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed. At a keepout corner, a mitred clearance buffer can reach farther than the specified clearance. Verification checks the actual distance before counting these hits as collisions. For an example with a corner close to the required clearance, see the [mitred-corner test](../inire/tests/test_collision.py#L146). Dynamic congestion queries use a grid for small spans and an R-tree for large spans. When expansion counts are similar but routing time rises, inspect ray casts for repeated visibility queries and exact pair checks for an overly broad dynamic lookup. The [metrics guide](routing-diagnostics.md#route-metrics) maps those questions to counters. -Refinement tries replacing sections of routes with at least four 90-degree bends. It indexes endpoints by heading and forward position to find eligible sections, then scores proposed detours before constructing their polygons. With a finite budget above one, it tries sections with bends at both ends first. With a budget of one or no window limit, it starts with the longest eligible section by component count. It can check just the replacement when the original route is valid against the installed geometry. Final verification checks the entire updated route. +Refinement tries replacing sections of routes with at least four 90-degree bends. It indexes endpoints by heading and forward position to find eligible sections, then scores proposed detours before constructing their polygons. With a finite budget above one, it tries sections with bends at both ends first. With a budget of one or no window limit, it starts with the longest eligible section by component count. It can check just the replacement when the original route is valid against the installed geometry. Final verification checks the entire updated route. Automatic refinement also rechecks retained partial paths against the updated layout. ## Validate a change diff --git a/docs/complex-routing-example-1.md b/docs/complex-routing-example-1.md index 5b8fdb7..d5ee224 100644 --- a/docs/complex-routing-example-1.md +++ b/docs/complex-routing-example-1.md @@ -14,7 +14,7 @@ Origin. The problem uses board 1 from Terminal-Bench pull request 345. [Pinned l `build_problem()` reads the example entry into a `RoutingProblem` and `RoutingOptions`. The board is 2,500 by 1,000 units with seven rectangular keepouts and nine nets. The guides are 2 units wide, the clearance is 6, and both kinds of bends use radius 50. The fixed-heading case starts with no seeds and requires each net to launch and arrive heading east. [Example inputs](../examples/advanced-layouts.json) · [Problem builder](../examples/advanced_layouts.py#L34) -`route()` dispatches to automatic routing. The router checks whether any aligned terminal pairs are too close and whether a vertical cut has fewer tracks than nets that need to cross it. The board passes both checks, so automatic asks the constructive planners to verify all nine nets. [Automatic entry point](../inire/router/_automatic.py#L597) · [Capacity checks](../inire/router/_capacity.py#L27) +`route()` dispatches to automatic routing. The router checks whether any aligned terminal pairs are too close and whether a vertical cut has fewer tracks than nets that need to cross it. The board passes both checks, so automatic asks the constructive planners to verify all nine nets. [Automatic entry point](../inire/router/_automatic.py#L603) · [Capacity checks](../inire/router/_capacity.py#L27) ![The nine input nets surround seven rectangular keepouts. A cut at x = 500 has openings at the bottom, center, and top of the board.](figures/complex-routing-example-1-input.png) @@ -32,7 +32,7 @@ The dots mark waypoints in the proposed seeds. The lower inset shows the two con ## 3. Fit the required eastbound arrival -Automatic routing compares the bundle's inferred headings with the input. Only `net_08` differs. Its initial bundle arrives from the east heading west. The turnaround planner adjusts the upper shelf route `net_07` and brings `net_08` back below it. Near the target, `net_08` rises west of `x = 1112` and takes a final right turn to arrive heading east. The planner recompiles the two changed seeds and submits the full set for verification. [Constructive planner dispatch](../inire/router/_automatic.py#L202) · [Turnaround candidates](../inire/router/_perimeter.py#L103) +Automatic routing compares the bundle's inferred headings with the input. Only `net_08` differs. Its initial bundle arrives from the east heading west. The turnaround planner adjusts the upper shelf route `net_07` and brings `net_08` back below it. Near the target, `net_08` rises west of `x = 1112` and takes a final right turn to arrive heading east. The planner recompiles the two changed seeds and submits the full set for verification. [Constructive planner dispatch](../inire/router/_automatic.py#L206) · [Turnaround candidates](../inire/router/_perimeter.py#L103) ![Two views show the materialized shelf and return paths. In the initial plan net_08 arrives westbound. In the turnaround candidate it passes below the shelf, rises left of the target, and arrives eastbound.](figures/complex-routing-example-1-turnaround.png) @@ -40,13 +40,13 @@ The arrow above each red target square shows the arrival heading. ## 4. Verify the seeds and refine the layout -The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one iteration with a one-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. Every net has a complete seed, so the worker records zero A* expansions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L165) · [Seed installation](../inire/router/_router.py#L819) · [Physical verification](../inire/geometry/collision.py#L592) +The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one iteration with a one-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. Every net has a complete seed, so the worker records zero A* expansions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L168) · [Seed installation](../inire/router/_router.py#L819) · [Physical verification](../inire/geometry/collision.py#L608) ![The upper panel shows the physical paths of the first four nets in installation order. The lower panel shows all nine paths after verification.](figures/complex-routing-example-1-verification.png) The upper panel reconstructs the first four installed paths from the worker's verified seeds. The lower panel shows the full set checked together. -Automatic then replays the verified seeds in a worker with refinement enabled. The refiner tries replacing sections with at least four 90-degree bends and verifies the resulting layout. In this run, refinement changes `net_05` and `net_07` and keeps all nine nets verified. The refined layout wins on the configured objective, which includes component penalties as well as length. [Refinement handoff](../inire/router/_automatic.py#L580) · [Trial comparison](../inire/router/_routing_policy.py#L44) +Automatic then replays the verified seeds in a worker with refinement enabled. The refiner tries replacing sections with at least four 90-degree bends and verifies the resulting layout. In this run, refinement changes `net_05` and `net_07` and keeps all nine nets verified. The refined layout wins on the configured objective, which includes component penalties as well as length. [Refinement handoff](../inire/router/_automatic.py#L584) · [Trial comparison](../inire/router/_routing_policy.py#L44) ![The refined net_07 stays near the top edge longer and descends close to its target. Its earlier approach is dashed, and the outer return remains visible below it.](figures/complex-routing-example-1-refinement.png) diff --git a/docs/topological-routing.md b/docs/topological-routing.md index e027d6c..ea1242a 100644 --- a/docs/topological-routing.md +++ b/docs/topological-routing.md @@ -10,13 +10,13 @@ Guide mode suggests where a path can pass through free space and lets detailed s In the offset-gates example, the two openings are at different heights. The top panel highlights the proposed sequence of triangle edges to cross. In the middle panel, the dashed line joins suggested crossing points. In the bottom panel, the solid route uses an S-bend to change height between the openings. -1. **Find connected space for centerlines.** Inset the board by half the widest guide's width and expand obstacles by that half-width plus clearance. To connect a port to the mesh, try a short straight along its departure or arrival heading, or use the port position itself. If the shared mesh finds no passage for a narrower net, retry with padding for its width. +1. **Find connected space for centerlines.** Inset the board by half the widest guide's width and expand obstacles by that half-width plus clearance. To connect a port to the mesh, try a short straight along its departure or arrival heading, or use the port position itself. A lead from a flush port can cross the inset boundary when its flat-ended footprint fits inside the board and clears the keepouts. If the shared mesh finds no passage for a narrower net, retry with padding for its width. A portal is an edge shared by adjacent free-space triangles. For an earlier representation of a route by its crossings of triangle edges, see Section III-A and Figure 1 of [Hama and Etoh's curvilinear detailed-routing paper](https://www.cecs.uci.edu/~papers/compendium94-03/papers/1998/aspdac98/pdffiles/06c_3.pdf). -2. **Choose a passage and a lane.** Rank a sequence of portals by distance and how many other nets want to use the same edges. A lane is a suggested position along an edge where a net can cross into the next triangle. Rank those positions by turn room and the lanes reserved for other nets. A joint retry can change the lane positions for several nets at the same opening. To see how the positions are scored, inspect [`assign_lanes()`](../inire/router/_topology.py#L214). +2. **Choose a passage and a lane.** Rank a sequence of portals by distance and how many other nets want to use the same edges. A lane is a suggested position along an edge where a net can cross into the next triangle. Rank those positions by turn room and the lanes reserved for other nets. A joint retry can change the lane positions for several nets at the same opening. To see how the positions are scored, inspect [`assign_lanes()`](../inire/router/_topology.py#L247). 3. **Turn the sketch into a path.** Guide mode uses the corridor to suggest moves and add a soft cost, so search can leave it to make a turn. Seed mode first searches inside a corridor and checks any seed against obstacles and earlier seeds. With alternatives, the first corridor gets at least half the per-net seed budget. Later detailed iterations can move an incumbent or use another guide. Final verification checks the installed geometry. diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index e5f84fd..4e84f68 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -74,10 +74,15 @@ To read a route's polygons and write them to a test file, follow the [geometry e | `sbend_radii` | `(10.0,)` | Finite, positive radii permitted for S-bends in search and seeds, subject to the same width requirement. An empty list disables S-bends. | | `sbend_offsets` | `None` | `None` lets the router choose signed lateral offsets. An explicit list restricts routing and seeds to those offsets after rounding to the grid. An empty list disables S-bends. | | `bend_collision_type` | `"arc"` | Search proxy, one of `"arc"`, `"bbox"`, or `"clipped_bbox"`. The legacy polygon form defines both shapes unless split geometry is supplied. | -| `bend_proxy_geometry` | `None` | Override the proxy. A custom polygon proxy by itself keeps the standard physical arc and emits a warning. | -| `bend_physical_geometry` | `None` | Override the physical geometry with `"arc"` or a polygon. A custom physical polygon also supplies the default proxy when the collision type is `"arc"`. Express a fractional 90-degree bend's polygon relative to the arc center and include both tangent extensions. For an S-bend, specify the first counterclockwise arc relative to its center. The router reflects it for negative offsets, rotates the second half, and extends its outlet face to the grid. | +| `bend_proxy_geometry` | `None` | Override the bend proxy. A polygon applies to 90-degree bends. A custom polygon proxy by itself keeps the standard physical arc and emits a warning. | +| `bend_physical_geometry` | `None` | Override 90-degree bend geometry with `"arc"` or a polygon. A custom physical polygon also supplies the default proxy when the collision type is `"arc"`. Define the polygon relative to the arc center and include both tangent extensions for a fractional radius. | | `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses an eight-point proxy for each arc and extends it along any grid tangents. | | `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. | +| `sbend_outlines` | `()` | Complete custom S-bend polygons, supplied as `SBendOutline(offset, radius, width, polygon)` entries. Each entry applies to its signed offset, radius, and net width. | + +A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and export. Supply a separate outline to customize the opposite offset. Unmatched moves use the circular S-bend, and matching moves use the same nominal length as that circular bend for scoring. Automatic mode uses lattice search when custom outlines are supplied. Bundle mode requires circular bends. + +When migrating a half-arc template, supply the complete outline through `sbend_outlines` and keep `bend_physical_geometry` for custom 90-degree bends. Replay an `SBendSeed` with the same outlines and bend settings to recover its physical geometry. ### ObjectiveWeights diff --git a/inire/__init__.py b/inire/__init__.py index 5d84ef5..e4dcaaf 100644 --- a/inire/__init__.py +++ b/inire/__init__.py @@ -12,6 +12,7 @@ from .model import ( RefinementOptions as RefinementOptions, RoutingOptions as RoutingOptions, RoutingProblem as RoutingProblem, + SBendOutline as SBendOutline, SearchOptions as SearchOptions, TopologyOptions as TopologyOptions, ) # noqa: PLC0414 @@ -81,6 +82,7 @@ __all__ = [ "RoutingRunResult", "RoutingStage", "RoutingTiming", + "SBendOutline", "SBendSeed", "SearchOptions", "StraightSeed", diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 3a48707..4879942 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -6,11 +6,11 @@ from math import ceil, pi from typing import TYPE_CHECKING, Literal import numpy -from shapely import get_parts, snap +from shapely import snap from shapely.affinity import rotate as shapely_rotate from shapely.affinity import scale as shapely_scale from shapely.affinity import translate as shapely_translate -from shapely.geometry import LineString, Polygon, box +from shapely.geometry import Polygon, box from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR from inire.geometry.sbend import sbend_grid_span, sbend_span @@ -358,21 +358,6 @@ def _buffer_geometry(polygons: list[Polygon], dilation: float) -> list[Polygon]: return [polygon.buffer(dilation) for polygon in polygons] if dilation > 0 else polygons -def _extend_custom_sbend_face(outline: Polygon, radius: float, tail: float) -> Polygon: - if tail <= TOLERANCE_LINEAR: - return outline - _, bottom, _, top = outline.bounds - # The first arc's inlet face becomes the second arc's outlet after rotation. - section = outline.intersection(LineString(((0, bottom), (0, top)))) - for face in get_parts(section): - _, low, _, high = face.bounds - if low < -radius < high: - extended = outline.union(box(-tail, low, 0, high)) - if isinstance(extended, Polygon): - return extended - return outline - - class Straight: @staticmethod def generate( @@ -552,8 +537,8 @@ class SBend: radius: float, width: float, sagitta: float = 0.01, - collision_type: BendCollisionModel = "arc", - physical_geometry_type: BendPhysicalGeometry = "arc", + collision_type: BendCollisionModelName = "arc", + outline: Polygon | None = None, clip_margin: float | None = None, dilation: float = 0.0, ) -> ComponentResult: @@ -567,54 +552,44 @@ class SBend: dx = sbend_span(offset, radius) grid_span = sbend_grid_span(offset, radius) tail = grid_span - dx - theta_deg = float(numpy.degrees(theta)) - rot2 = rotation_matrix2(start_port.r) end_port = _advance_port(start_port, rot2, grid_span, offset) - c1_local = numpy.array((0.0, sign * radius)) - c2_local = numpy.array((dx, offset - sign * radius)) - c1_xy = (rot2 @ c1_local) + numpy.array((start_port.x, start_port.y)) - c2_xy = (rot2 @ c2_local) + numpy.array((start_port.x, start_port.y)) - center1 = (float(c1_xy[0]), float(c1_xy[1])) - center2 = (float(c2_xy[0]), float(c2_xy[1])) - - ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg)) - second_base = start_port.r + (90 if sign > 0 else 270) - ts2 = (float(second_base + sign * theta_deg), float(second_base)) - - actual_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta) - arc1, arc2 = actual_geometry - - def outlines(model: BendCollisionModel) -> list[Polygon]: - if model == "arc": - return actual_geometry - if isinstance(model, Polygon): - second = _extend_custom_sbend_face(model, radius, tail) - return [ - _transform_custom_collision_polygon(model, center1, float(start_port.r), mirror_y=sign < 0), - _transform_custom_collision_polygon(second, center2, float(start_port.r + 180), mirror_y=sign < 0), - ] - return [ - _apply_collision_model(arc1, model, radius, width, center1, ts1, clip_margin=clip_margin)[0], - _apply_collision_model( - arc2, model, radius, width, center2, ts2, clip_margin=clip_margin, - tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0), - )[0], - ] - - geometry = outlines(collision_type) - physical_geometry = geometry if physical_geometry_type is collision_type else outlines(physical_geometry_type) - dilated_arcs = actual_geometry - if dilation > 0 and (physical_geometry is actual_geometry or collision_type == "arc"): - if bend_fits_width(radius, width + 2 * dilation): - dilated_arcs = SBend._arcs( + 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): + dilated_physical_geometry = SBend._arcs( start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, sagitta, ) else: - dilated_arcs = _buffer_geometry(actual_geometry, dilation) - dilated_physical_geometry = dilated_arcs if physical_geometry is actual_geometry else _buffer_geometry(physical_geometry, dilation) - dilated_collision_geometry = dilated_arcs if collision_type == "arc" else _buffer_geometry(geometry, dilation) + dilated_physical_geometry = _buffer_geometry(physical_geometry, dilation) + if collision_type == "arc": + geometry, dilated_collision_geometry = physical_geometry, dilated_physical_geometry + 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 + center1_xy = (float(center1[0]), float(center1[1])) + center2_xy = (float(center2[0]), float(center2[1])) + ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg)) + second_base = start_port.r + (90 if sign > 0 else 270) + ts2 = (float(second_base + sign * theta_deg), float(second_base)) + arc1, arc2 = physical_geometry + geometry = [ + _apply_collision_model(arc1, collision_type, radius, width, center1_xy, ts1, clip_margin=clip_margin)[0], + _apply_collision_model( + arc2, collision_type, radius, width, center2_xy, ts2, clip_margin=clip_margin, + tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0), + )[0], + ] + dilated_collision_geometry = _buffer_geometry(geometry, dilation) return ComponentResult( start_port=start_port, @@ -639,6 +614,7 @@ def build_component( physical_geometry_type: BendPhysicalGeometry, clip_margin: float | None, dilation: float, + sbend_outline: Polygon | None = None, ) -> ComponentResult: if kind == "straight": return Straight.generate(start, parameters[0], width, dilation=dilation) @@ -649,5 +625,6 @@ def build_component( ) return SBend.generate( start, parameters[0], parameters[1], width, - collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation, + collision_type="arc" if isinstance(collision_type, Polygon) else collision_type, + outline=sbend_outline, clip_margin=clip_margin, dilation=dilation, ) diff --git a/inire/model.py b/inire/model.py index 36fbd14..837e6fd 100644 --- a/inire/model.py +++ b/inire/model.py @@ -6,11 +6,14 @@ from math import isfinite from typing import TYPE_CHECKING, Literal from shapely.geometry import Polygon + +from inire.geometry.components import _has_port_face, bend_fits_width +from inire.geometry.primitives import Port +from inire.geometry.sbend import sbend_grid_span from inire.seeds import Bend90Seed, PathSeed, SBendSeed if TYPE_CHECKING: from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry - from inire.geometry.primitives import Port NetOrder = Literal["user", "shortest", "longest"] @@ -37,6 +40,28 @@ class ObjectiveWeights: danger_weight: float = 1.0 +@dataclass(frozen=True, slots=True) +class SBendOutline: + """Complete S-bend polygon in the frame of an east-facing input port at the origin.""" + + offset: float + radius: float + width: float + polygon: Polygon + + def __post_init__(self) -> None: + seed = SBendSeed(self.offset, self.radius) + if not isfinite(self.width) or self.width <= 0 or not bend_fits_width(seed.radius, self.width): + raise ValueError("S-bend outline needs a finite positive width no greater than twice its radius") + if not isinstance(self.polygon, Polygon) or self.polygon.is_empty or not self.polygon.is_valid: + raise ValueError("S-bend outline must be a valid, nonempty Polygon") + end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0) + if not _has_port_face(self.polygon, Port(0, 0, 0), arrival=False) or not _has_port_face(self.polygon, end, arrival=True): + raise ValueError(f"S-bend outline needs east-facing port faces at (0, 0) and ({end.x}, {end.y})") + object.__setattr__(self, "offset", seed.offset) + object.__setattr__(self, "radius", seed.radius) + + @dataclass(frozen=True, slots=True) class SearchOptions: node_limit: int = 1000000 @@ -51,6 +76,7 @@ class SearchOptions: bend_physical_geometry: BendPhysicalGeometry | None = None bend_clip_margin: float | None = None visibility_guidance: VisibilityGuidance = "tangent_corner" + sbend_outlines: tuple[SBendOutline, ...] = () def __post_init__(self) -> None: for field_name in ("bend_radii", "sbend_radii"): @@ -67,6 +93,18 @@ class SearchOptions: if any(not isfinite(offset) for offset in offsets): raise ValueError("S-bend offsets must be finite") object.__setattr__(self, "sbend_offsets", tuple(round(offset) for offset in offsets)) + outlines = tuple(self.sbend_outlines) + outline_keys = set() + for outline in outlines: + if not isinstance(outline, SBendOutline): + raise TypeError("sbend_outlines must contain SBendOutline entries") + if outline.radius not in self.sbend_radii or not self.allows_sbend_offset(outline.offset): + raise ValueError("S-bend outline must use a configured radius and offset") + key = outline.offset, outline.radius, outline.width + if key in outline_keys: + raise ValueError(f"Duplicate S-bend outline for offset, radius, and width {key}") + outline_keys.add(key) + object.__setattr__(self, "sbend_outlines", outlines) for geometry in (self.bend_collision_type, self.bend_proxy_geometry, self.bend_physical_geometry): if isinstance(geometry, Polygon) and (geometry.is_empty or not geometry.is_valid): raise ValueError("Custom bend geometry must be a valid, nonempty polygon") @@ -79,6 +117,12 @@ class SearchOptions: def allows_sbend_offset(self, offset: float) -> bool: return self.sbend_offsets is None or offset in self.sbend_offsets + def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None: + for outline in self.sbend_outlines: + if (outline.offset, outline.radius, outline.width) == (offset, radius, width): + return outline.polygon + return None + def seed_geometry_error(self, seed: PathSeed) -> str | None: for segment in seed.segments: if isinstance(segment, Bend90Seed) and segment.radius not in self.bend_radii: diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index 19054a6..e89ad6e 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -36,6 +36,7 @@ def process_move( coll_key = id(coll_type) if isinstance(coll_type, Polygon) else coll_type physical_type = config.bend_physical_geometry physical_key = id(physical_type) if isinstance(physical_type, Polygon) else physical_type + outline = context.options.search.sbend_outline(params[0], params[1], net_width) if move_class == "sbend" else None self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0 abs_key = ( @@ -45,6 +46,7 @@ def process_move( net_width, coll_key, physical_key, + id(outline) if outline is not None else None, self_dilation, ) if abs_key in context.move_cache_abs: @@ -61,6 +63,7 @@ def process_move( net_width, coll_key, physical_key, + id(outline) if outline is not None else None, self_dilation, ) if rel_key in context.move_cache_rel: @@ -78,6 +81,7 @@ def process_move( physical_geometry_type=physical_type, clip_margin=config.bend_clip_margin, dilation=self_dilation, + sbend_outline=outline, ) except ValueError: return diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index 0bb7c75..b95b4b5 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -12,6 +12,7 @@ from ._seed_materialization import seed_move if TYPE_CHECKING: from inire.geometry.primitives import Port + from inire.seeds import BendDirection from ._astar_types import AStarContext, AStarMetrics, AStarNode, CongestionCaches, SearchRunConfig @@ -158,6 +159,7 @@ def expand_moves( metrics: AStarMetrics, congestion: CongestionCaches, config: SearchRunConfig, + deferred_turns: list[tuple[AStarNode, float, BendDirection]], ) -> None: search_options = context.options.search scan_limit = search_options.max_straight_length @@ -297,17 +299,17 @@ def expand_moves( angle_to_target = 0.0 if dx_t != 0 or dy_t != 0: angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0) - allow_backwards = config.restrict_to_corridor or dist_sq < 150 * 150 + prefer_toward_target = not config.restrict_to_corridor and dist_sq >= 150 * 150 for radius in search_options.bend_radii: if not bend_fits_width(radius, net_width): continue for direction in ("CW", "CCW"): - if not allow_backwards: - turn = 90 if direction == "CCW" else -90 - new_ori = (cp.r + turn) % 360 - new_diff = (angle_to_target - new_ori + 180.0) % 360.0 - 180.0 - if abs(new_diff) > 135.0: + if prefer_toward_target: + heading = (cp.r + (90 if direction == "CCW" else -90)) % 360 + difference = (angle_to_target - heading + 180.0) % 360.0 - 180.0 + if abs(difference) > 135.0: + deferred_turns.append((current, radius, direction)) continue process_move( current, @@ -330,6 +332,8 @@ def expand_moves( explicit_offsets = search_options.sbend_offsets offsets = set(explicit_offsets) if explicit_offsets is not None else guide_offsets + if search_options.sbend_outlines: + offsets.update(outline.offset for outline in search_options.sbend_outlines if outline.width == net_width) if explicit_offsets is None and target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r: offsets.add(round(dy_local)) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 47f177a..3d2b1dc 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -157,8 +157,11 @@ class _AutomaticRun: with self._time("verify", planner=stage.planner, mode=stage.mode, policy=stage.policy): return _trial(run, stage, score=self._selection_cost) - def _seeded_problem(self, trial: Trial) -> RoutingProblem: - seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs} + def _seeded_problem(self, trial: Trial, *, include_unresolved: bool = False) -> RoutingProblem: + seeds = { + net_id: result.as_seed() for net_id, result in trial.run.results_by_net.items() + if result.path and (include_unresolved or net_id in trial.valid_costs) + } nets = tuple(net for net in self.problem.nets if net.net_id in seeds) return replace(self.problem, nets=nets, initial_paths=seeds) @@ -170,6 +173,7 @@ class _AutomaticRun: kind: str, policy: str | None, operation: Literal["verify", "refine"], + node_limit: int = 1, ) -> tuple[RoutingRunResult, RoutingStage]: options = self.options refinement = options.refinement @@ -177,7 +181,7 @@ class _AutomaticRun: refinement = replace(refinement, enabled=False) worker = replace( options, - search=replace(options.search, node_limit=1), + search=replace(options.search, node_limit=node_limit), topology=replace(options.topology, mode="off"), congestion=replace(options.congestion, max_iterations=1), refinement=refinement, @@ -581,14 +585,16 @@ class _AutomaticRun: best = _best_trial(trials) if not self.options.refinement.enabled or not best.valid_costs: return + has_unresolved_paths = any(result.path and not result.is_valid for result in best.run.results_by_net.values()) run, stage = self._seeded_attempt( - self._seeded_problem(best), + self._seeded_problem(best, include_unresolved=has_unresolved_paths), best.stage.planner, kind="refinement", policy=best.stage.policy, operation="refine", + node_limit=0 if has_unresolved_paths else 1, ) - # Keep reports for unresolved routes when merging the refined subset. + # Any carried-over result without a replayed seed has no path to recheck. results = {**best.run.results_by_net, **run.results_by_net} refined = self._trial(replace(run, results_by_net=results), stage) # Only a whole verified replacement of the incumbent can win. @@ -605,7 +611,7 @@ class _AutomaticRun: trials: list[Trial] = [] if not self.problem.nets or options.search.node_limit <= 0 or options.congestion.max_iterations <= 0: self._lattice_fallback(trials, options, "No automatic search requested") - elif isinstance(proxy, shapely.Polygon) or physical != "arc": + elif options.search.sbend_outlines or isinstance(proxy, shapely.Polygon) or physical != "arc": self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing") else: with self._time("plan"): diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index 5a5781b..72fb8fb 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -218,7 +218,10 @@ def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer return problem _, physical_geometry = resolve_bend_geometry(search) bend = min(search.bend_radii, default=0.0) - if not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii or physical_geometry != "arc": + if ( + not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii + or physical_geometry != "arc" or search.sbend_outlines + ): raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends") radius = int(bend) width = problem.nets[0].width diff --git a/inire/router/_search.py b/inire/router/_search.py index a26b152..0f61ab9 100644 --- a/inire/router/_search.py +++ b/inire/router/_search.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING from inire.constants import TOLERANCE_LINEAR +from ._astar_admission import process_move from ._astar_moves import expand_moves as _expand_moves from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, CongestionCaches, SearchRunConfig @@ -14,7 +15,7 @@ if TYPE_CHECKING: from inire.geometry.components import ComponentResult from inire.geometry.primitives import Port from inire.results import RoutingResult - from inire.seeds import PathSegmentSeed + from inire.seeds import BendDirection, PathSegmentSeed def incumbent_guidance( @@ -57,6 +58,7 @@ def route_astar( context.cost_evaluator.set_target(target) open_set: list[_AStarNode] = [] closed_set: dict[tuple[int, int, int], float] = {} + deferred_turns: list[tuple[_AStarNode, float, BendDirection]] = [] congestion = CongestionCaches() start_node = _AStarNode( @@ -69,9 +71,18 @@ def route_astar( best_node = start_node nodes_expanded = 0 - while open_set: + while open_set or deferred_turns: if nodes_expanded >= config.node_limit: return _reconstruct_path(best_node) if config.return_partial else None + if not open_set: + # Recover turns away from the target after exhausting the preferred frontier. + for parent, radius, direction in deferred_turns: + process_move( + parent, target, net_width, net_id, open_set, closed_set, context, metrics, congestion, config, "bend90", (radius, direction) + ) + deferred_turns.clear() + if not open_set: + break current = heapq.heappop(open_set) if config.max_cost is not None and current.fh_cost[0] > config.max_cost: @@ -108,6 +119,7 @@ def route_astar( metrics, congestion, config=config, + deferred_turns=deferred_turns, ) return _reconstruct_path(best_node) if config.return_partial else None diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 55cb6be..bfd1a26 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -42,6 +42,7 @@ def materialize_path_seed( for segment in seed.segments: kind, parameters = seed_move(segment) + outline = search.sbend_outline(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None component = build_component( current, net_width, @@ -51,6 +52,7 @@ def materialize_path_seed( physical_geometry_type=bend_physical_geometry, clip_margin=bend_clip_margin, dilation=dilation, + sbend_outline=outline, ) path.append(component) current = component.end_port diff --git a/inire/router/_topology.py b/inire/router/_topology.py index ccc0256..022019e 100644 --- a/inire/router/_topology.py +++ b/inire/router/_topology.py @@ -11,6 +11,8 @@ from typing import TYPE_CHECKING import shapely from shapely.geometry import LineString, Point, box +from inire.geometry.collision import _violates_clearance + if TYPE_CHECKING: from collections.abc import Iterable, Sequence @@ -99,8 +101,13 @@ class _Mesh: raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer") self.pitch = max(1.0, 2 * margin + clearance) - obstacles = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in obstacles]) - self.free = board.buffer(-margin).difference(obstacles) + self.board = board + self.margin = margin + self.clearance = clearance + self.keepouts = shapely.STRtree(tuple(obstacles)) + padded = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in self.keepouts.geometries]) + self.inset = board.buffer(-margin) + self.free = self.inset.difference(padded) self.boundary = self.free.boundary self.cells: tuple[Polygon, ...] = tuple(shapely.constrained_delaunay_triangles(self.free).geoms) self.index = shapely.STRtree(self.cells) @@ -132,15 +139,38 @@ class _Mesh: def endpoint(self, port: Port, direction: int, lead_length: float) -> _Endpoint | None: x, y, rotation = port.as_tuple() dx, dy = HEADINGS[rotation // 90] - for length in (lead_length, lead_length / 2, 1.0, 0.0): + point = Point(x, y) + inset_port = self.inset.covers(point) + lengths = (lead_length, lead_length / 2, 1.0, 0.0) + if not inset_port and self.board.covers(point) and not self.inset.is_empty: + axis = 0 if dx else 1 + heading_sign = direction * (dx or dy) + entry = (self.inset.bounds[axis if heading_sign > 0 else axis + 2] - (x, y)[axis]) * heading_sign + if entry > 0: + lengths = tuple(max(length, entry) for length in lengths if length > 0) + for length in lengths: lead = (x + dx * length * direction, y + dy * length * direction) - if length and not self.free.covers(LineString(((x, y), lead))): - continue cells = self.index.query(Point(lead), predicate="covered_by") - if len(cells): - return _Endpoint((x, y), lead, int(min(cells))) + if not len(cells): + continue + if length and not self._lead_is_clear(LineString(((x, y), lead)), inset_port=inset_port): + continue + return _Endpoint((x, y), lead, int(min(cells))) return None + def _lead_is_clear(self, centerline: LineString, *, inset_port: bool) -> bool: + if inset_port: + return bool(self.free.covers(centerline)) + # At the board edge, only the portion inside the inset belongs to the mesh. + # The entire straight still needs a legal flat-ended footprint. + footprint = centerline.buffer(self.margin, cap_style="flat") + if not self.board.covers(footprint) or not self.free.covers(centerline.intersection(self.inset)): + return False + left, bottom, right, top = footprint.bounds + gap = self.clearance + nearby = self.keepouts.query(box(left - gap, bottom - gap, right + gap, top + gap)) + return not any(_violates_clearance(footprint, self.keepouts.geometries[index], gap) for index in nearby) + def _crossing_cost(self, edge: Edge, demand: dict[Edge, int]) -> float: count = len(self.portals[edge].lanes) load = demand.get(edge, 0) diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index dbe8f51..d308cd9 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -71,6 +71,7 @@ def _public_defaults(case: BenchmarkCase, defaults: RoutingOptions) -> RoutingOp bend_collision_type=geometry.bend_collision_type, bend_proxy_geometry=geometry.bend_proxy_geometry, bend_physical_geometry=geometry.bend_physical_geometry, + sbend_outlines=geometry.sbend_outlines, bend_clip_margin=geometry.bend_clip_margin, min_straight_length=geometry.min_straight_length, max_straight_length=geometry.max_straight_length, diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 1eb0e6c..488d58f 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -19,6 +19,7 @@ from inire import ( RefinementOptions, RoutingOptions, RoutingProblem, + SBendOutline, SBendSeed, SearchOptions, StraightSeed, @@ -278,22 +279,48 @@ def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> No assert result.report.discontinuous is wrong_side -def test_custom_sbend_reports_overlap_inside_the_component() -> None: - arc = SBend.generate(Port(0, 0, 0), 40, 50, 2).physical_geometry[0] - outline = shapely.union_all((translate(arc, yoff=-50), box(38, -32, 43, -28))) +@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) +def test_custom_sbend_outline_is_shared_by_search_and_seed_replay(mode) -> None: + outline = Polygon([(0, -1), (20, 3), (50, 29), (80, 39), (80, 41), (50, 31), (20, 5), (0, 1)]) net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) - problem = RoutingProblem((0, 0, 160, 160), (net,), initial_paths={"shift": PathSeed((SBendSeed(40, 50),))}) + problem = RoutingProblem((0, 0, 160, 160), (net,)) options = RoutingOptions( - search=SearchOptions(bend_radii=(), sbend_radii=(50,), bend_physical_geometry=outline), + search=SearchOptions(bend_radii=(), sbend_radii=(50,), sbend_outlines=(SBendOutline(40, 50, 2, outline),)), congestion=CongestionOptions(max_iterations=1), - topology=TopologyOptions(mode="off"), + topology=TopologyOptions(mode=mode), ) result = route(problem, options=options).results_by_net["shift"] + replay = route( + replace(problem, initial_paths={"shift": result.as_seed()}), + options=replace(options, search=replace(options.search, node_limit=0)), + ).results_by_net["shift"] - assert result.outcome == "colliding" - assert result.report.self_collision_count == 1 - assert not result.report.discontinuous + assert result.is_valid + assert replay.is_valid + assert result.as_seed() == PathSeed((SBendSeed(40, 50),)) + assert len(result.locked_geometry) == 1 + assert result.locked_geometry[0].equals(translate(outline, 30, 50)) + assert result.locked_geometry == replay.locked_geometry + + +def test_sbend_outline_requires_both_port_faces() -> None: + half = SBend.generate(Port(0, 0, 0), 40, 50, 2).physical_geometry[0] + + with pytest.raises(ValueError, match="port faces"): + SBendOutline(40, 50, 2, half) + + +def test_custom_quarter_turn_outline_leaves_circular_sbends_available() -> None: + net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) + seed = PathSeed((SBendSeed(40, 50),)) + problem = RoutingProblem((0, 0, 160, 160), (net,), initial_paths={"shift": seed}) + options = RoutingOptions(search=SearchOptions(node_limit=0, sbend_radii=(50,), bend_physical_geometry=box(0, -11, 11, 0))) + + result = route(problem, options=options).results_by_net["shift"] + + assert result.is_valid + assert result.locked_geometry == SBend.generate(net.start, 40, 50, 2).physical_geometry def test_route_verification_rejects_self_contact_away_from_a_join() -> None: @@ -563,6 +590,21 @@ def test_lattice_can_chain_straights_before_a_bend_under_scan_limit() -> None: assert result.as_seed() == PathSeed((*(StraightSeed(10),) * 6, Bend90Seed(10, "CCW"))) +def test_lattice_can_turn_away_from_a_distant_target_to_leave_a_keepout() -> None: + net = NetSpec("detour", Port(300, 100, 0), Port(360, 350, 0)) + problem = RoutingProblem((0, 0, 450, 400), (net,), (box(319, 96, 390, 170),)) + options = RoutingOptions( + search=SearchOptions(node_limit=100, bend_radii=(20,), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="off"), + ) + + result = route(problem, options=options).results_by_net["detour"] + + assert result.is_valid + assert result.as_seed().segments[0] == Bend90Seed(20, "CW") + + @pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) def test_search_can_find_consecutive_sbends(mode) -> None: net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0)) diff --git a/inire/tests/test_components.py b/inire/tests/test_components.py index b6ec488..56160a2 100644 --- a/inire/tests/test_components.py +++ b/inire/tests/test_components.py @@ -9,6 +9,7 @@ from shapely.geometry import Polygon import inire.geometry.components as components_module from inire.geometry.components import Bend90, SBend, Straight from inire.geometry.primitives import Port +from inire.geometry.sbend import sbend_grid_span from inire.router.cost import CostEvaluator from inire.geometry.collision import RoutingWorld @@ -210,16 +211,11 @@ def test_custom_bend_collision_polygon_can_differ_from_physical_geometry() -> No @pytest.mark.parametrize("dilation", [1, 10]) -@pytest.mark.parametrize("kind", ["quarter_turn", "sbend"]) -def test_arc_proxy_dilation_uses_the_circular_geometry(kind, dilation) -> None: +def test_arc_proxy_dilation_uses_the_circular_geometry(dilation) -> None: outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) start = Port(20, 20, 0) - if kind == "quarter_turn": - default = Bend90.generate(start, 10, 2, "CCW", dilation=dilation) - custom = Bend90.generate(start, 10, 2, "CCW", physical_geometry_type=outline, dilation=dilation) - else: - default = SBend.generate(start, 5, 10, 2, dilation=dilation) - custom = SBend.generate(start, 5, 10, 2, physical_geometry_type=outline, dilation=dilation) + default = Bend90.generate(start, 10, 2, "CCW", dilation=dilation) + custom = Bend90.generate(start, 10, 2, "CCW", physical_geometry_type=outline, dilation=dilation) assert custom.collision_geometry == default.collision_geometry assert custom.dilated_collision_geometry == default.dilated_collision_geometry @@ -229,18 +225,22 @@ def test_arc_proxy_dilation_uses_the_circular_geometry(kind, dilation) -> None: @pytest.mark.parametrize("heading", [0, 90, 180, 270]) @pytest.mark.parametrize(("radius", "offset"), [(50, 40), (50, -40), (12.25, 11), (12.25, -11)]) -def test_custom_sbend_uses_reflected_arc_and_reaches_grid_face(heading, radius, offset) -> None: - template = SBend.generate(Port(0, 0, 0), abs(offset), radius, 2).physical_geometry[0] - outline = shapely_translate(template, 0, -radius) +def test_custom_sbend_uses_one_asymmetric_polygon_and_reaches_grid_face(heading, radius, offset) -> None: + span = sbend_grid_span(offset, radius) + profile = [(0, 0), (span // 3, offset * 0.15), (2 * span // 3, offset * 0.65), (span, offset)] + outline = Polygon([(x, y - 1) for x, y in profile] + [(x, y + 1) for x, y in reversed(profile)]) start = Port(30, 50, heading) expected = SBend.generate(start, offset, radius, 2) - result = SBend.generate(start, offset, radius, 2, collision_type=outline, physical_geometry_type=outline, dilation=1) + result = SBend.generate(start, offset, radius, 2, outline=outline, dilation=1) assert result.physical_checks == (True, True) assert result.end_port == expected.end_port assert result.collision_geometry == result.physical_geometry - for actual, arc in zip(result.physical_geometry, expected.physical_geometry, strict=True): - assert actual.symmetric_difference(arc).area < 1e-10 + placed = shapely_translate(shapely_rotate(outline, heading, origin=(0, 0)), start.x, start.y) + assert len(result.physical_geometry) == 1 + assert result.physical_geometry[0].equals(placed) + assert result.dilated_physical_geometry == result.dilated_collision_geometry + assert result.dilated_physical_geometry[0].equals(placed.buffer(1)) def test_sbend_collision_models() -> None: diff --git a/inire/tests/test_refinements.py b/inire/tests/test_refinements.py index 21dbde3..ff390b5 100644 --- a/inire/tests/test_refinements.py +++ b/inire/tests/test_refinements.py @@ -1,9 +1,10 @@ from dataclasses import replace import pytest -from shapely.geometry import Polygon +from shapely.geometry import Polygon, box from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route +from inire import DiagnosticsOptions, PathSeed, StraightSeed from inire.geometry.collision import RoutingWorld from inire.geometry.components import Bend90 from inire.geometry.primitives import Port @@ -68,6 +69,38 @@ def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None: assert paths[0].report.total_length == pytest.approx(paths[1].report.total_length) +def test_automatic_refinement_rechecks_retained_partial_paths() -> None: + base = _seeded_foldback() + blocked = NetSpec("blocked", Port(150, 120, 90), Port(150, 210, 90)) + problem = replace( + base, + nets=(*base.nets, blocked), + static_obstacles=(box(70, 180, 260, 220),), + initial_paths={**base.initial_paths, "blocked": PathSeed((StraightSeed(50),))}, + ) + options = replace( + _REFINEMENT_OPTIONS, + search=replace(_REFINEMENT_OPTIONS.search, node_limit=15), + congestion=replace(_REFINEMENT_OPTIONS.congestion, warm_start_enabled=False), + diagnostics=DiagnosticsOptions(capture_conflict_trace=True), + topology=TopologyOptions(mode="automatic"), + ) + + run = route(problem, options=options) + + assert run.automatic is not None + assert run.automatic.stages[run.automatic.selected_stage].operation == "refine" + assert run.results_by_net["foldback"].is_valid + partial = run.results_by_net["blocked"] + assert partial.outcome == "partial" + assert partial.report.dynamic_collision_count == 1 + final = run.conflict_trace[-1] + assert final.stage == "final" + traced = next(net for net in final.nets if net.net_id == "blocked") + assert traced.report == partial.report + assert traced.conflicting_net_ids == ("foldback",) + + @pytest.mark.parametrize("mode", ["automatic", "off"]) def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None: outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index cf615ac..ad74271 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -95,18 +95,28 @@ def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None: assert run.results_by_net["detour"].is_valid -def test_topological_routing_falls_back_for_ports_outside_the_inset_mesh() -> None: - problem = RoutingProblem(bounds=(0, 0, 100, 100), nets=(NetSpec("edge", Port(0, 50, 0), Port(100, 50, 0)),)) - options = RoutingOptions( - search=SearchOptions(bend_radii=(10,)), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), +def test_seed_mode_routes_a_detour_between_flush_board_ports() -> None: + problem = replace(DETOUR.problem, nets=(NetSpec("detour", Port(0, 300, 0), Port(800, 300, 0)),)) + options = replace( + DETOUR.options, + search=replace(DETOUR.options.search, node_limit=100), + congestion=replace(DETOUR.options.congestion, max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="seed"), ) run = route(problem, options=options) - assert run.results_by_net["edge"].is_valid + assert run.results_by_net["detour"].is_valid assert run.topology is not None - assert run.topology.corridor_counts == () + assert run.topology.corridor_counts == (("detour", 2),) + assert run.topology.seeded_net_ids == ("detour",) + + +def test_board_edge_lead_requires_a_clear_flat_footprint() -> None: + board = box(0, 0, 100, 100) + mesh = _Mesh(board, (box(0, 48, 1, 52),), 1, 2) + assert mesh.endpoint(Port(0, 50, 0), 1, 10) is None + assert mesh.endpoint(Port(0, 0, 0), 1, 10) is None + assert mesh.endpoint(Port(0, 60, 0), 1, 10) is not None def test_seed_mode_keeps_a_verified_route_when_another_net_is_partial() -> None: