diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index d182a9c..3f38a4a 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -92,7 +92,7 @@ The search objective scores path length, components, and proximity. All weights | Field | Default | Effect | | --- | --- | --- | -| `unit_length_cost` | `1.0` | Cost per unit of path length. | +| `unit_length_cost` | `1.0` | Cost per unit of path length, including estimated remaining distance in lattice and corridor search. At zero, the estimate still includes configured turning penalties. | | `bend_penalty` | `250.0` | Additional cost of a 90-degree bend. Smaller radii incur a larger surcharge when this penalty is positive. | | `sbend_penalty` | `500.0` | Additional cost of an S-bend. | | `danger_weight` | `1.0` | Weight of the obstacle proximity cost. | diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index 8487f2f..fba68ef 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -148,8 +148,10 @@ def add_node( context.metrics.total_static_safe_cache_hits += 1 else: ce = context.cost_evaluator.collision_engine + danger = context.cost_evaluator.danger_map collision_found = ( (ce.board is not None and not path_within_board((result,), ce.board)) + or (ce.board is None and danger is not None and not danger.is_within_bounds(end_p.x, end_p.y)) or ce.check_move_static(result, start_port=parent_p, end_port=end_p) ) if collision_found: @@ -212,13 +214,6 @@ def add_node( metrics.pruned_cost += 1 metrics.total_pruned_cost += 1 return - if move_cost > 1e12: - if frontier_trace is not None: - frontier_trace.record("cost", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) - metrics.pruned_cost += 1 - metrics.total_pruned_cost += 1 - return - if context.congestion_penalty >= 0 and state in closed_set and closed_set[state] <= parent.g_cost + move_cost + TOLERANCE_LINEAR: if frontier_trace is not None: frontier_trace.record("closed_set", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index ee3bed9..da12347 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -100,7 +100,8 @@ class SearchRunConfig: evaluator = context.cost_evaluator cost = evaluator.h_manhattan(current, target, min_bend_radius=context.min_bend_radius) if self.restrict_to_corridor and self.corridor is not None and current != target: - return 0.4 * cost + 0.6 * evaluator.greedy_h_weight * self.corridor.remaining(current) + distance_cost = self.corridor.remaining(current) * evaluator.default_weights.unit_length_cost + return 0.4 * cost + 0.6 * evaluator.greedy_h_weight * distance_cost return cost @classmethod diff --git a/inire/router/_search.py b/inire/router/_search.py index 0f61ab9..1e33afb 100644 --- a/inire/router/_search.py +++ b/inire/router/_search.py @@ -40,6 +40,11 @@ def _reconstruct_path(end_node: _AStarNode) -> list[ComponentResult]: return path[::-1] +def _distance_to_terminal(port: Port, target: Port) -> tuple[float, float]: + turn = (port.r - target.r) % 360 + return abs(port.x - target.x) + abs(port.y - target.y), min(turn, 360 - turn) + + def route_astar( start: Port, target: Port, @@ -69,6 +74,7 @@ def route_astar( ) heapq.heappush(open_set, start_node) best_node = start_node + best_distance = _distance_to_terminal(start, target) nodes_expanded = 0 while open_set or deferred_turns: @@ -90,13 +96,14 @@ def route_astar( metrics.total_pruned_cost += 1 continue - if current.h_cost < best_node.h_cost: - best_node = current - state = current.port.as_tuple() if state in closed_set and closed_set[state] <= current.g_cost + TOLERANCE_LINEAR: continue closed_set[state] = current.g_cost + if config.return_partial: + distance = _distance_to_terminal(current.port, target) + if distance < best_distance: + best_node, best_distance = current, distance if config.store_expanded: metrics.last_expanded_nodes.append(state) diff --git a/inire/router/cost.py b/inire/router/cost.py index 6782a0c..02bd882 100644 --- a/inire/router/cost.py +++ b/inire/router/cost.py @@ -3,10 +3,9 @@ from __future__ import annotations from time import perf_counter_ns from typing import TYPE_CHECKING -import numpy as np - from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld +from inire.geometry.primitives import rotate_cardinal from inire.model import ObjectiveWeights from inire.router.danger_map import DangerMap @@ -110,9 +109,7 @@ class CostEvaluator: self._target_x = target.x self._target_y = target.y self._target_r = int(target.r) - rad = np.radians(target.r) - self._target_cos = np.cos(rad) - self._target_sin = np.sin(rad) + self._target_cos, self._target_sin = rotate_cardinal(1.0, 0.0, int(target.r)) def h_manhattan( self, @@ -143,14 +140,7 @@ class CostEvaluator: if side_proj < 0 or (side_proj < min_bend_radius and perp_dist > 0): penalty += 2 * bp - if curr_r == 0: - c_cos, c_sin = 1.0, 0.0 - elif curr_r == 90: - c_cos, c_sin = 0.0, 1.0 - elif curr_r == 180: - c_cos, c_sin = -1.0, 0.0 - else: - c_cos, c_sin = 0.0, -1.0 + c_cos, c_sin = rotate_cardinal(1.0, 0.0, int(curr_r)) move_proj = v_dx * c_cos + v_dy * c_sin if move_proj < 0: @@ -158,7 +148,7 @@ class CostEvaluator: if diff == 0 and perp_dist > 0: penalty += 2 * bp - return self._greedy_h_weight * (dist + penalty) + return self._greedy_h_weight * (dist * self._search_weights.unit_length_cost + penalty) def score_component( self, diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 95c8da8..72ed31b 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -3,7 +3,7 @@ from dataclasses import replace import pytest import shapely -from shapely.affinity import translate +from shapely.affinity import rotate, translate from shapely.geometry import Polygon, box import inire @@ -582,6 +582,62 @@ def test_active_search_can_recover_from_width_incompatible_seed() -> None: assert result.as_seed() == PathSeed((StraightSeed(50),)) +@pytest.mark.parametrize("rotation", [0, 90, 180, 270]) +def test_lattice_heading_heuristic_is_cardinally_invariant(rotation) -> None: + origin = (60, 60) + start = Port(8, 60, 0).rotated(rotation, origin) + target = Port(112, 101, 0).rotated(rotation, origin) + keepouts = tuple(rotate(polygon, rotation, origin=origin) for polygon in (box(87, 48, 99, 71), box(28, 84, 47, 107))) + problem = RoutingProblem((0, 0, 120, 120), (NetSpec("turn", start, target, 1.75),), keepouts, clearance=1.25) + options = RoutingOptions( + search=SearchOptions(node_limit=50, bend_radii=(10,), sbend_radii=()), + objective=ObjectiveWeights(danger_weight=0), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="off"), + ) + + run = route(problem, options=options) + + assert run.results_by_net["turn"].is_valid + assert run.metrics.nodes_expanded == 17 + + +@pytest.mark.parametrize("price", [0.001, 1, 1000, 1e12]) +def test_lattice_length_cost_units_preserve_search_order(price) -> None: + net = NetSpec("turn", Port(15, 40, 0), Port(165, 80, 0)) + problem = RoutingProblem((0, 0, 190, 100), (net,), (box(63, 7, 85, 55),)) + options = RoutingOptions( + search=SearchOptions(node_limit=32, min_straight_length=2, bend_radii=(10,), sbend_radii=()), + objective=ObjectiveWeights(price, 0, 0, 0), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="off"), + ) + + run = route(problem, options=options) + + assert run.results_by_net["turn"].is_valid + assert run.metrics.nodes_expanded == 12 + + +@pytest.mark.parametrize(("heuristic", "price"), [(1.5, 1), (0, 1), (1.5, 0)]) +def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic, price) -> None: + net = NetSpec("across", Port(5, 20, 0), Port(90, 20, 0)) + problem = RoutingProblem((0, 0, 100, 40), (net,), (box(45, 0, 55, 40),)) + options = RoutingOptions( + search=SearchOptions(node_limit=5, greedy_h_weight=heuristic, bend_radii=(), sbend_radii=()), + objective=ObjectiveWeights(price, 0, 0, 0), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), + refinement=RefinementOptions(enabled=False), + topology=TopologyOptions(mode="off"), + ) + + run = route(problem, options=options) + + assert run.results_by_net["across"].outcome == "partial" + + def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None: monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)) diff --git a/plans/full-project-review.md b/plans/full-project-review.md index 44ce08c..5a7296d 100644 --- a/plans/full-project-review.md +++ b/plans/full-project-review.md @@ -26,6 +26,8 @@ Implemented items 3, 6, and 21 retain constructive planning for unused custom ou Implemented items 11, 13, and 30 preserve replay diagnostics across all four modes, report the segment of a width-incompatible seed, skip proximity work in geometry-only runs, and use explicit refinement weights for automatic refinement selection. +Implemented items 25 and 36 use cardinal heading vectors and consistent length units in the lattice and corridor heuristics. Partial results track geometric progress even with zero heuristic weight, and a high legal move cost no longer acts as a collision sentinel. + | Batch | Work | Acceptance gate | | --- | --- | --- | | Physical verification | 1, 2, 17, 23, and 38 | Reject the faulty geometry and keep legal joins valid in search and seed replay. Check circular bend accuracy, folded-route spacing, and isolation between different nets. |