diff --git a/docs/architecture.md b/docs/architecture.md index c328c93..5fb0d18 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2,6 +2,8 @@ An explicit routing mode runs one worker with that mode's settings. Automatic routing can run several workers with different obstacles, locks, or starting paths, then select a result. To see what a single worker receives and returns, start at [`route_once()`](../inire/router/_stack.py#L71). +Follow one complete run from board input through planning, verification, and plotting in the [Terminal-Bench walkthrough](terminal-bench-walkthrough.md). + ## Automatic routing ![Automatic routing sets a target for the number of verified nets and tries several ways to reach it. The router selects and optionally refines its best layout before returning a result for each net.](figures/automatic-stages.png) diff --git a/docs/terminal-bench-walkthrough.md b/docs/terminal-bench-walkthrough.md new file mode 100644 index 0000000..cc5ab7f --- /dev/null +++ b/docs/terminal-bench-walkthrough.md @@ -0,0 +1,48 @@ +# Walk through the nine-net Terminal-Bench example + +Run the fixed-heading example from the repository root. It prints `9/9 verified` and saves a setup and result figure in `/tmp/inire-terminal-bench-walkthrough/example-terminal-bench.png`. Keep that figure open while following the outer return, `net_08`. [Example figures](../examples/advanced.md#nine-net-terminal-bench-board) + +```sh +python examples/advanced_layouts.py \ + --case terminal-bench \ + --output-dir /tmp/inire-terminal-bench-walkthrough +``` + +## 1. Load the board and set the routing target + +`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) + +## 2. Assign lanes and compile path seeds + +The bundle planner groups the obstacles into two barriers with openings and three obstacles between them. It sorts the launches by height and separates the short connection `net_03`, the lower and upper groups, and the outer return `net_08`. The planner budgets 7 units from a keepout edge to a guide centerline and uses a 9-unit pitch between neighboring lanes. It reserves the bottommost lane for the return and has room for one more lane beneath the tower. [Layout recognition](../inire/router/_bundle.py#L46) · [Lane assignment](../inire/router/_bundle.py#L114) + +For `net_08`, the initial plan drops from `(12, 450)` to the bottom lane at `y = 1`, crosses east, climbs on the right, and heads west to `(1112, 991)`. The planner compiles the waypoints into straight, 90-degree bend, and S-bend seeds as appropriate. A Manhattan corner becomes a quarter turn with room for its tangencies. A diagonal step in a bundle waypoint list represents an S-bend with an exact grid span. [Bundle seed construction](../inire/router/_bundle.py#L213) · [Waypoint compiler](../inire/router/_waypoints.py#L33) + +## 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) + +## 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#L656) + +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) + +## 5. Inspect the result + +The example counts `RoutingResult.is_valid` and plots each path from its physical polygons. To see the router's decisions, run the same board with the benchmark CLI and inspect the selected stage and its zero A* node count. The JSON records both stages under `runs[0].samples[0].stages`. [Plotting code](../examples/advanced_layouts.py#L71) + +```sh +python -m scripts.compare_topological_routing \ + --case terminal-bench --profile public-defaults --mode automatic \ + --json /tmp/inire-terminal-bench-stages.json +``` + +| Stage | Planner | Operation | Verified nets | +| --- | --- | --- | --- | +| 0 | `bundle-turnaround` | Verify the compiled seeds | 9 | +| 1, selected | `bundle-turnaround` | Refine and verify the layout | 9 | + +To see how heading inference changes the route, rerun the gallery command with `--case terminal-bench-point-terminals`. Automatic accepts the westbound arrival for `net_08`, verifies the original `bundle` plan, and then refines it. Both stages again verify nine nets with zero A* expansions. The waypoint exporter is a separate entry point that runs explicit `bundle` mode with heading inference and refinement disabled. [Point-terminal figure](../examples/advanced.md#point-terminals) · [Waypoint export command](benchmark-fixtures.md#automatic-nine-net-terminal-bench-routing) diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index f63a5fd..c72f406 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -32,7 +32,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate ## Path seeds -`PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Lengths and radii must be finite and positive. Bend directions are `"CW"` and `"CCW"`. S-bend offsets must be nonzero integers with magnitude less than twice the radius. A seed is materialized from the net's current start port using its width and the run's geometry options. A radius absent from the corresponding option list raises `ValueError`. Search skips seeds with a configured bend radius below half the net width. For a workflow that starts from an existing route, see [Reuse an existing route](route-a-layout.md#reuse-an-existing-route). +`PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Lengths and radii must be finite and positive. When routing a seed, straight lengths are rounded to the nearest grid unit, with ties rounded to even and a minimum of one unit. Bend directions are `"CW"` and `"CCW"`. S-bend offsets must be nonzero integers with magnitude less than twice the radius. A seed is materialized from the net's current start port using its width and the run's geometry options. A radius absent from the corresponding option list raises `ValueError`. Search skips seeds with a configured bend radius below half the net width. For a workflow that starts from an existing route, see [Reuse an existing route](route-a-layout.md#reuse-an-existing-route). ## Results @@ -76,7 +76,7 @@ To read a route's polygons and write them to a test file, follow the [geometry e | `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"`. Custom polygons for fractional 90-degree bends are positioned relative to the arc center and must include both tangent extensions. | -| `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses the eight-point proxy. | +| `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"`. | ### ObjectiveWeights diff --git a/examples/advanced.md b/examples/advanced.md index 6f4bea3..96605cb 100644 --- a/examples/advanced.md +++ b/examples/advanced.md @@ -94,6 +94,8 @@ In `stress-crossings-shared-outside-detour`, a straight external waveguide joins Nine closely spaced source ports on the left feed routes around seven keepouts. Both examples use guides 2 units wide, a clearance of 6 units, and a radius of 50 units for bends and S-bends. For the original board data and the waypoint export command, see the [Terminal-Bench fixture guide](../docs/benchmark-fixtures.md#automatic-nine-net-terminal-bench-routing). +To follow how the router builds and checks the paths in these figures, read the [Terminal-Bench walkthrough](../docs/terminal-bench-walkthrough.md). + ### Fixed eastbound headings In `terminal-bench`, all routes must leave and arrive heading east. Follow `net_08` from the bottommost source around the board. Near the top edge, it turns back to approach its target from the west. diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index 7ff1bbe..a5dc88c 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -6,7 +6,8 @@ from typing import TYPE_CHECKING import numpy from shapely.geometry import LineString, box -from inire.geometry.component_overlap import components_overlap +from inire.constants import TOLERANCE_LINEAR +from inire.geometry.component_overlap import count_path_self_collisions from inire.geometry.components import check_path_geometry, path_within_board from inire.geometry.dynamic_path_index import DynamicPathIndex from inire.geometry.index_helpers import grid_cell_span @@ -49,6 +50,13 @@ def _has_non_touching_overlap(left: BaseGeometry, right: BaseGeometry) -> bool: return left.intersects(right) and not left.touches(right) +def _violates_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool: + if clearance <= 0: + return _has_non_touching_overlap(left, right) + tolerance = TOLERANCE_LINEAR * min(1.0, clearance) + return left.distance(right) < clearance - tolerance + + def _span_to_bounds( gx_min: int, gy_min: int, @@ -656,7 +664,6 @@ class RoutingWorld: self.metrics.total_verify_path_report_calls += 1 static_collision_count = 0 dynamic_collision_count = 0 - self_collision_count = 0 total_length = sum(component.length for component in components) valid_geometry, continuous = check_path_geometry(components) if not valid_geometry: @@ -678,16 +685,10 @@ class RoutingWorld: hits = static_obstacles.raw_tree.query(buffered, predicate="intersects") for hit_idx in hits: obstacle = raw_geometries[hit_idx] - if buffered.touches(obstacle): - continue # A mitre may extend past the physical clearance # radius at a component corner. Check the distance # before counting an overlap with that broad phase. - if self.clearance > 0 and polygon.distance(obstacle) >= self.clearance: - continue - - obj_id = static_obstacles.raw_obj_ids[hit_idx] - if not self._is_in_safety_zone(polygon, obj_id, None, None): + if _violates_clearance(polygon, obstacle, self.clearance): static_collision_count += 1 if dynamic_paths.has_physical_paths(): @@ -702,12 +703,11 @@ class RoutingWorld: self.metrics.total_verify_dynamic_candidate_nets += len({candidate[0] for candidate in candidates}) polygon_hits: set[str] = set() for hit_net_id, hit_component_index, other in candidates: - if hit_net_id in polygon_hits: + if hit_net_id in polygon_hits and not capture_component_conflicts: continue if self.metrics is not None: self.metrics.total_verify_dynamic_exact_pair_checks += 1 - overlaps = polygon.distance(other) < clearance if clearance > 0 else _has_non_touching_overlap(polygon, other) - if overlaps: + if _violates_clearance(polygon, other, clearance): polygon_hits.add(hit_net_id) if capture_component_conflicts: component_conflicts.add((component_index, hit_net_id, hit_component_index)) @@ -715,16 +715,11 @@ class RoutingWorld: dynamic_collision_count += len(component_hits) conflicting_net_ids.update(component_hits) - for index, component in enumerate(components): - for other_index in range(index + 1, len(components)): - if components_overlap(component, components[other_index], prefer_actual=True, at_join=other_index == index + 1): - self_collision_count += 1 - return PathVerificationDetail( report=RoutingReport( static_collision_count=static_collision_count, dynamic_collision_count=dynamic_collision_count, - self_collision_count=self_collision_count, + self_collision_count=count_path_self_collisions(components), total_length=total_length, out_of_bounds=self.board is not None and not path_within_board(components, self.board), discontinuous=not continuous, diff --git a/inire/geometry/component_overlap.py b/inire/geometry/component_overlap.py index 5c6f650..ae6ef5c 100644 --- a/inire/geometry/component_overlap.py +++ b/inire/geometry/component_overlap.py @@ -2,6 +2,9 @@ from __future__ import annotations from typing import TYPE_CHECKING +from shapely.geometry import box +from shapely.strtree import STRtree + from inire.constants import TOLERANCE_LINEAR if TYPE_CHECKING: @@ -23,10 +26,8 @@ def components_overlap( if prefer_actual: polygons_a = component_a.physical_geometry polygons_b = component_b.physical_geometry - extents_a = tuple(polygon.bounds for polygon in polygons_a) - extents_b = tuple(polygon.bounds for polygon in polygons_b) - bounds_a = (min(b[0] for b in extents_a), min(b[1] for b in extents_a), max(b[2] for b in extents_a), max(b[3] for b in extents_a)) - bounds_b = (min(b[0] for b in extents_b), min(b[1] for b in extents_b), max(b[2] for b in extents_b), max(b[3] for b in extents_b)) + bounds_a = component_a.total_physical_bounds + bounds_b = component_b.total_physical_bounds else: polygons_a = component_a.collision_geometry polygons_b = component_b.collision_geometry @@ -55,3 +56,19 @@ def components_overlap( elif polygon_a.intersects(polygon_b) and not polygon_a.touches(polygon_b): return True return False + + +def count_path_self_collisions(components: Sequence[ComponentResult]) -> int: + if len(components) < 2: + return 0 + envelopes = [ + component.physical_geometry[0] if len(component.physical_geometry) == 1 else box(*component.total_physical_bounds) + for component in components + ] + index = STRtree(envelopes) + return sum( + components_overlap(component, components[other], prefer_actual=True, at_join=other == i + 1) + for i, (component, envelope) in enumerate(zip(components, envelopes, strict=True)) + for other in index.query(envelope) + if other > i + ) diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 4114eff..f2df049 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -101,6 +101,7 @@ class ComponentResult: _total_bounds: tuple[float, float, float, float] = field(init=False, repr=False) _dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False) _total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False) + _total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None) _physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None) def __post_init__(self) -> None: @@ -139,6 +140,15 @@ class ComponentResult: def total_dilated_bounds(self) -> tuple[float, float, float, float]: return self._total_dilated_bounds + @property + def total_physical_bounds(self) -> tuple[float, float, float, float]: + bounds = self._total_physical_bounds + if bounds is None: + shapes = self.physical_geometry + bounds = shapes[0].bounds if len(shapes) == 1 else _combine_bounds([shape.bounds for shape in shapes]) + object.__setattr__(self, "_total_physical_bounds", bounds) + return bounds + @property def bend_radius(self) -> float | None: return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None @@ -245,22 +255,14 @@ def _get_arc_polygons( return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))] -def _clip_bbox_legacy( +def _clip_bbox_polygonal( cxy: tuple[float, float], radius: float, width: float, ts: tuple[float, float], - clip_margin: float, + tangent_extensions: tuple[float, float], ) -> Polygon: - arc_poly = _get_arc_polygons(cxy, radius, width, ts)[0] - minx, miny, maxx, maxy = arc_poly.bounds - bbox_poly = box(minx, miny, maxx, maxy) - shrink = min(clip_margin, max(radius, width)) - return bbox_poly.buffer(-shrink, join_style="mitre") if shrink > 0 else bbox_poly - - -def _clip_bbox_polygonal(cxy: tuple[float, float], radius: float, width: float, ts: tuple[float, float]) -> Polygon: - """Return a conservative 8-point polygonal proxy for the arc. + """Return a conservative polygonal proxy for the arc and its tangents. The polygon uses 4 points along the outer edge and 4 along the inner edge. The outer edge is a circumscribed polyline and the inner edge is an @@ -289,21 +291,20 @@ def _clip_bbox_polygonal(cxy: tuple[float, float], radius: float, width: float, outer_points = numpy.column_stack((cx + conservative_outer_radius * cos_a, cy + conservative_outer_radius * sin_a)) inner_points = numpy.column_stack((cx + conservative_inner_radius * cos_a[::-1], cy + conservative_inner_radius * sin_a[::-1])) + start_extension, end_extension = tangent_extensions + sweep_sign = 1 if ts[1] > ts[0] else -1 + # Keep the same conservative radial width along each attached tangent. + if start_extension > 0: + shift = numpy.array((sin_a[0], -cos_a[0])) * (sweep_sign * (start_extension + TOLERANCE_LINEAR)) + outer_points = numpy.vstack((outer_points[0] + shift, outer_points)) + inner_points = numpy.vstack((inner_points, inner_points[-1] + shift)) + if end_extension > 0: + shift = numpy.array((-sin_a[-1], cos_a[-1])) * (sweep_sign * (end_extension + TOLERANCE_LINEAR)) + outer_points = numpy.vstack((outer_points, outer_points[-1] + shift)) + inner_points = numpy.vstack((inner_points[0] + shift, inner_points)) return Polygon(numpy.concatenate((outer_points, inner_points), axis=0)) -def _clip_bbox( - cxy: tuple[float, float], - radius: float, - width: float, - ts: tuple[float, float], - clip_margin: float | None, -) -> Polygon: - if clip_margin is not None: - return _clip_bbox_legacy(cxy, radius, width, ts, clip_margin) - return _clip_bbox_polygonal(cxy, radius, width, ts) - - def _transform_custom_collision_polygon( collision_poly: Polygon, cxy: tuple[float, float], @@ -328,15 +329,24 @@ def _apply_collision_model( clip_margin: float | None = None, rotation_deg: float = 0.0, mirror_y: bool = False, + tangent_extensions: tuple[float, float] = (0.0, 0.0), ) -> list[Polygon]: if isinstance(collision_type, Polygon): return [_transform_custom_collision_polygon(collision_type, cxy, rotation_deg, mirror_y)] if collision_type == "arc": return [arc_poly] - if collision_type == "clipped_bbox": - clipped = _clip_bbox(cxy, radius, width, ts, clip_margin) - return [clipped if not clipped.is_empty else box(*arc_poly.bounds)] - return [box(*arc_poly.bounds)] + if collision_type != "clipped_bbox": + return [box(*arc_poly.bounds)] + if clip_margin is None: + return [_clip_bbox_polygonal(cxy, radius, width, ts, tangent_extensions)] + bbox = box(*arc_poly.bounds) + shrink = min(clip_margin, max(radius, width)) + clipped = bbox.buffer(-shrink, join_style="mitre") if shrink > 0 else bbox + return [clipped if not clipped.is_empty else bbox] + + +def _buffer_geometry(polygons: list[Polygon], dilation: float) -> list[Polygon]: + return [polygon.buffer(dilation) for polygon in polygons] if dilation > 0 else polygons class Straight: @@ -415,8 +425,6 @@ class Bend90: port_faces = (start_port, end_port) arc_polys = _get_arc_polygons(center, radius, width, ts, sagitta, port_faces=port_faces) - if tangent_length and collision_type == "clipped_bbox": - collision_type = "bbox" collision_polys = _apply_collision_model( arc_polys[0], collision_type, @@ -427,6 +435,7 @@ class Bend90: 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): @@ -440,15 +449,12 @@ class Bend90: rotation_deg=float(start_port.r), mirror_y=(sign < 0), ) - uses_physical_custom_geometry = True else: physical_geometry = arc_polys - uses_physical_custom_geometry = False - if dilation > 0: - if uses_physical_custom_geometry or not bend_fits_width(radius, width + 2 * dilation): - dilated_physical_geometry = [poly.buffer(dilation) for poly in physical_geometry] - else: - dilated_physical_geometry = _get_arc_polygons( + 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, @@ -457,12 +463,10 @@ class Bend90: dilation=dilation, port_faces=port_faces, ) - dilated_collision_geometry = ( - dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys] - ) - else: - dilated_physical_geometry = physical_geometry - dilated_collision_geometry = collision_polys + else: + 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) return ComponentResult( start_port=start_port, @@ -538,6 +542,7 @@ class SBend: theta = numpy.arccos(1.0 - abs(offset) / (2.0 * radius)) 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) @@ -554,7 +559,6 @@ class SBend: actual_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, sagitta) arc1, arc2 = actual_geometry - end_collision_type = "bbox" if collision_type == "clipped_bbox" and grid_span - dx > TOLERANCE_LINEAR else collision_type geometry = [ _apply_collision_model( arc1, @@ -569,7 +573,7 @@ class SBend: )[0], _apply_collision_model( arc2, - end_collision_type, + collision_type, radius, width, (float(c2_xy[0]), float(c2_xy[1])), @@ -577,6 +581,7 @@ class SBend: clip_margin=clip_margin, rotation_deg=float(start_port.r), mirror_y=(sign > 0), + tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0), )[0], ] @@ -603,29 +608,24 @@ class SBend: mirror_y=(sign > 0), )[0], ] - uses_physical_custom_geometry = True else: physical_geometry = actual_geometry - uses_physical_custom_geometry = False - if dilation > 0: - if uses_physical_custom_geometry or not bend_fits_width(radius, width + 2 * dilation): - dilated_physical_geometry = [poly.buffer(dilation) for poly in physical_geometry] - else: - dilated_physical_geometry = SBend._arcs( + 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( start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, sagitta, ) - dilated_collision_geometry = ( - dilated_physical_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in geometry] - ) - else: - dilated_physical_geometry = physical_geometry - dilated_collision_geometry = geometry + 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) return ComponentResult( start_port=start_port, collision_geometry=geometry, end_port=end_port, - length=2.0 * radius * theta + max(0.0, grid_span - dx), + length=2.0 * radius * theta + max(0.0, tail), move_type="sbend", move_spec=seed, physical_geometry=physical_geometry, diff --git a/inire/geometry/primitives.py b/inire/geometry/primitives.py index d76aa13..2f7068e 100644 --- a/inire/geometry/primitives.py +++ b/inire/geometry/primitives.py @@ -47,11 +47,9 @@ class Port: origin: tuple[int | float, int | float] = (0, 0), ) -> Self: angle_i = _normalize_angle(angle) - rot = rotation_matrix2(angle_i) - origin_xy = numpy.array((int(round(origin[0])), int(round(origin[1]))), dtype=numpy.int32) - rel = numpy.array((self.x, self.y), dtype=numpy.int32) - origin_xy - rotated = origin_xy + rot @ rel - return type(self)(int(rotated[0]), int(rotated[1]), self.r + angle_i) + ox, oy = round(origin[0]), round(origin[1]) + dx, dy = rotate_cardinal(self.x - ox, self.y - oy, angle_i) + return type(self)(ox + dx, oy + dy, self.r + angle_i) ROT2_0 = numpy.array(((1, 0), (0, 1)), dtype=numpy.int32) diff --git a/inire/geometry/static_obstacle_index.py b/inire/geometry/static_obstacle_index.py index 9582d50..2a9cea4 100644 --- a/inire/geometry/static_obstacle_index.py +++ b/inire/geometry/static_obstacle_index.py @@ -6,6 +6,7 @@ import numpy import rtree from shapely.strtree import STRtree +from inire.constants import TOLERANCE_LINEAR from inire.geometry.index_helpers import build_index_payload, is_axis_aligned_rect if TYPE_CHECKING: @@ -26,7 +27,6 @@ class StaticObstacleIndex: "bounds_array", "is_rect_array", "raw_tree", - "raw_obj_ids", "net_specific_trees", "net_specific_is_rect", "net_specific_bounds", @@ -46,7 +46,6 @@ class StaticObstacleIndex: self.bounds_array: numpy.ndarray | None = None self.is_rect_array: numpy.ndarray | None = None self.raw_tree: STRtree | None = None - self.raw_obj_ids: list[int] = [] self.net_specific_trees: dict[tuple[float, float], STRtree] = {} self.net_specific_is_rect: dict[tuple[float, float], numpy.ndarray] = {} self.net_specific_bounds: dict[tuple[float, float], numpy.ndarray] = {} @@ -87,7 +86,6 @@ class StaticObstacleIndex: self.is_rect_array = None self.obj_ids = [] self.raw_tree = None - self.raw_obj_ids = [] self.net_specific_trees.clear() self.net_specific_is_rect.clear() self.net_specific_bounds.clear() @@ -110,6 +108,8 @@ class StaticObstacleIndex: if self.engine.metrics is not None: self.engine.metrics.total_static_net_tree_rebuilds += 1 total_dilation = net_width / 2.0 + self.engine.clearance + # A ray grazing the clearance boundary can still place a legal straight. + total_dilation -= TOLERANCE_LINEAR * min(1.0, total_dilation) geometries = [] is_rect_list = [] bounds_list = [] @@ -131,5 +131,4 @@ class StaticObstacleIndex: if self.raw_tree is None and self.geometries: if self.engine.metrics is not None: self.engine.metrics.total_static_raw_tree_rebuilds += 1 - self.raw_obj_ids, geometries, _bounds_array = build_index_payload(self.geometries) - self.raw_tree = STRtree(geometries) + self.raw_tree = STRtree(list(self.geometries.values())) diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 6299e97..131f850 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -32,7 +32,7 @@ def materialize_path_seed( for segment in seed.segments: if isinstance(segment, StraightSeed): - kind, parameters = "straight", (segment.length,) + kind, parameters = "straight", (max(1, round(segment.length)),) elif isinstance(segment, Bend90Seed): kind, parameters = "bend90", (segment.radius, segment.direction) elif isinstance(segment, SBendSeed): diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 92181c8..0443013 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -276,17 +276,19 @@ def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> No assert result.report.discontinuous is wrong_side -def test_route_verification_rejects_geometry_past_its_arrival_port() -> None: - net = NetSpec("straight", Port(10, 25, 0), Port(50, 25, 0)) - seed = PathSeed((StraightSeed(40.49),)) +@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) +@pytest.mark.parametrize(("seed_length", "grid_length"), [(0.2, 1), (19.5, 20), (19.75, 20), (20.49, 20)]) +def test_fractional_straight_seed_uses_grid_length(mode, seed_length, grid_length) -> None: + net = NetSpec("straight", Port(11, 25, 0), Port(11 + grid_length, 25, 0)) + seed = PathSeed((StraightSeed(seed_length),)) problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"straight": seed}) - options = RoutingOptions(topology=TopologyOptions(mode="off"), congestion=CongestionOptions(max_iterations=1)) + options = RoutingOptions(topology=TopologyOptions(mode=mode), congestion=CongestionOptions(max_iterations=1)) result = route(problem, options=options).results_by_net["straight"] - assert result.reached_target - assert not result.is_valid - assert result.report.discontinuous + assert result.is_valid + assert result.report.total_length == grid_length + assert result.as_seed() == PathSeed((StraightSeed(grid_length),)) @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) @@ -387,6 +389,24 @@ def test_lattice_search_detours_inside_board() -> None: assert all(board.covers(polygon) for polygon in result.locked_geometry) +@pytest.mark.parametrize("y", [1, 2, 50]) +@pytest.mark.parametrize(("gap", "valid"), [(0.1, True), (0.099, False)]) +def test_lattice_straight_can_run_along_a_keepout_at_clearance(y, gap, valid) -> None: + problem = RoutingProblem( + (0, 0, 100, 100), + nets=(NetSpec("straight", Port(10, y, 0), Port(30, y, 0), width=0.9),), + static_obstacles=(box(15, y + 0.45 + gap, 25, y + 1),), + clearance=0.1, + ) + options = RoutingOptions( + search=SearchOptions(bend_radii=(), sbend_radii=(), node_limit=100), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="off"), + ) + + assert route(problem, options=options).results_by_net["straight"].is_valid is valid + + @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) def test_fractional_quarter_turn_reaches_its_terminal_face(mode) -> None: problem = RoutingProblem((0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),)) @@ -402,6 +422,26 @@ def test_fractional_quarter_turn_reaches_its_terminal_face(mode) -> None: assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) +def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_bounding_box() -> None: + problem = RoutingProblem( + (0, 0, 100, 100), + nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),), + static_obstacles=(box(20, 28, 24, 30),), + clearance=0, + ) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="off"), + ) + + result = route(problem, options=options).results_by_net["bend"] + + assert result.is_valid + assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) + + @pytest.mark.parametrize("mode", ["automatic", "off"]) @pytest.mark.parametrize("proxy", ["clipped_bbox", "custom"]) def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None: diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index a613753..cff398a 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -5,6 +5,7 @@ import pytest from shapely.geometry import Polygon, box import inire.geometry.collision as collision_module +import inire.geometry.component_overlap as overlap_module from inire.geometry.collision import RoutingWorld from inire.geometry.components import ComponentResult from inire.geometry.components import Straight @@ -252,6 +253,45 @@ def test_verify_path_report_uses_physical_distance_between_routes(clearance, val assert engine.verify_path_report("query", (query,)).is_valid +@pytest.mark.parametrize("y", [1, 2, 50]) +@pytest.mark.parametrize(("gap", "valid"), [(0.1, True), (0.099, False), (0, False)]) +def test_verify_path_clearance_threshold_survives_translation(y, gap, valid) -> None: + engine = RoutingWorld(clearance=0.1) + width = 1 - gap + tested = Straight.generate(Port(0, y, 0), 20, width) + peer = Straight.generate(Port(0, y + 1, 0), 20, width) + + engine.install_path("peer", (peer,)) + assert engine.verify_path_report("query", (tested,)).is_valid is valid + engine.remove_path("peer") + engine.add_static_obstacle(peer.physical_geometry[0]) + assert engine.verify_path_report("query", (tested,)).is_valid is valid + + +def test_verify_geometry_rejects_a_straight_past_its_arrival_port() -> None: + component = Straight.generate(Port(10, 25, 0), 40.49, 2) + report = RoutingWorld(0).verify_path_report("straight", (component,)) + assert component.end_port == Port(50, 25, 0) + assert report.discontinuous + + +def test_self_collision_check_only_visits_spatial_candidates(monkeypatch) -> None: + path = tuple(Straight.generate(Port(x, 0, 0), 5, 2) for x in range(0, 500, 5)) + original_check = overlap_module.components_overlap + checks = 0 + + def count_check(*args, **kwargs): + nonlocal checks + checks += 1 + return original_check(*args, **kwargs) + + monkeypatch.setattr(overlap_module, "components_overlap", count_check) + report = RoutingWorld(0).verify_path_report("straight", path) + + assert report.is_valid + assert checks == len(path) - 1 + + def test_verify_path_details_returns_conflicting_net_ids() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() @@ -276,20 +316,18 @@ def test_verify_path_details_reports_component_conflicts() -> None: path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] path_b = [ Straight.generate(Port(100, 0, 0), 10.0, width=2.0, dilation=1.0), - Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0), + Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0), + Straight.generate(Port(10, 0, 0), 10.0, width=2.0, dilation=1.0), ] - engine.add_path( - "netB", - [poly for component in path_b for poly in component.collision_geometry], - dilated_geometry=[poly for component in path_b for poly in component.dilated_collision_geometry], - component_indexes=[0] * len(path_b[0].collision_geometry) + [1] * len(path_b[1].collision_geometry), - ) + engine.install_path("netB", path_b) detail = engine.verify_path_details("netA", path_a, capture_component_conflicts=True) assert detail.conflicting_net_ids == ("netB",) - assert detail.component_conflicts == ((0, "netB", 1),) + assert detail.component_conflicts == ((0, "netB", 1), (0, "netB", 2)) + assert detail.report.dynamic_collision_count == 1 + assert engine.verify_path_report("netA", path_a) == detail.report def test_verify_path_details_deduplicates_component_conflicts() -> None: diff --git a/inire/tests/test_components.py b/inire/tests/test_components.py index be8f32a..4df48cd 100644 --- a/inire/tests/test_components.py +++ b/inire/tests/test_components.py @@ -209,6 +209,24 @@ def test_custom_bend_collision_polygon_can_differ_from_physical_geometry() -> No assert result.dilated_collision_geometry[0].symmetric_difference(result.dilated_physical_geometry[0]).area > 1e-6 +@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: + 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) + + assert custom.collision_geometry == default.collision_geometry + assert custom.dilated_collision_geometry == default.dilated_collision_geometry + assert custom.dilated_physical_geometry == tuple(shape.buffer(dilation) for shape in custom.physical_geometry) + assert custom.dilated_physical_geometry != custom.dilated_collision_geometry + + def test_sbend_collision_models() -> None: start = Port(0, 0, 0) offset = 5.0 diff --git a/inire/tests/test_primitives.py b/inire/tests/test_primitives.py index 15d3659..718ca18 100644 --- a/inire/tests/test_primitives.py +++ b/inire/tests/test_primitives.py @@ -32,6 +32,11 @@ def test_port_snapping() -> None: assert p.y == 1 +def test_port_rotation_preserves_coordinates_beyond_int32() -> None: + assert Port(-2**31, 20, 0).rotated(180) == Port(2**31, -20, 180) + assert Port(3_000_000_004, 25, 270).rotated(90, origin=(3_000_000_000, 20)) == Port(2_999_999_995, 24, 0) + + @given(p=port_strategy()) def test_port_transform_invariants(p: Port) -> None: # Rotating 90 degrees 4 times should return to same orientation