lots more refactoring

This commit is contained in:
Jan Petykiewicz 2026-03-30 19:51:37 -07:00
commit bc218a416b
43 changed files with 1433 additions and 1694 deletions

37
DOCS.md
View file

@ -11,9 +11,8 @@ This document describes the current public API for `inire`.
- `bounds`
- `nets`
- `static_obstacles`
- `locked_routes`
- `initial_paths`
- `clearance`
- `max_net_width`
- `safety_zone_radius`
### `RoutingOptions`
@ -34,21 +33,39 @@ run = route(problem, options=options)
If you omit `options`, `route(problem)` uses `RoutingOptions()` defaults.
### Incremental routing with `LockedRoute`
The package root is the stable API surface. Deep imports under `inire.router.*` and `inire.geometry.*` remain accessible for advanced use, but they are unstable semi-private interfaces and may change without notice.
For incremental workflows, route one problem, convert a result into a `LockedRoute`, and feed it into the next problem:
Stable example:
```python
from inire import route, RoutingOptions, RoutingProblem
```
Unstable example:
```python
from inire.router._router import PathFinder
```
### Incremental routing with locked geometry
For incremental workflows, route one problem, reuse the result's locked geometry, and feed it into the next problem:
```python
run_a = route(problem_a)
problem_b = RoutingProblem(
bounds=problem_a.bounds,
nets=(...),
locked_routes={"netA": run_a.results_by_net["netA"].as_locked_route()},
static_obstacles=run_a.results_by_net["netA"].locked_geometry,
)
run_b = route(problem_b)
```
`LockedRoute` stores canonical physical geometry only. The next run applies its own clearance rules when treating it as a static obstacle.
`RoutingResult.locked_geometry` stores canonical physical geometry only. The next run applies its own clearance rules when treating it as a static obstacle.
### Initial paths with `PathSeed`
Use `RoutingProblem.initial_paths` to provide semantic per-net seeds. Seeds are materialized with the current width, clearance, and bend collision settings for the run, and partial seeds are retried by normal routing in later iterations.
## 2. Search Options
@ -65,7 +82,6 @@ run_b = route(problem_b)
| `sbend_offsets` | `None` | Optional explicit lateral offsets for S-bends. |
| `bend_collision_type` | `"arc"` | Bend collision model: `"arc"`, `"bbox"`, `"clipped_bbox"`, or a custom polygon. |
| `visibility_guidance` | `"tangent_corner"` | Visibility-derived straight candidate strategy. |
| `initial_paths` | `None` | Optional user-supplied initial paths for warm starts. |
## 3. Objective Weights
@ -77,7 +93,6 @@ run_b = route(problem_b)
| `bend_penalty` | `250.0` | Flat bend penalty before radius scaling. |
| `sbend_penalty` | `500.0` | Flat S-bend penalty. |
| `danger_weight` | `1.0` | Weight applied to danger-map proximity costs. |
| `congestion_penalty` | `0.0` | Congestion weight used when explicitly scoring complete paths. |
## 4. Congestion Options
@ -89,9 +104,9 @@ run_b = route(problem_b)
| `base_penalty` | `100.0` | Starting overlap penalty for negotiated congestion. |
| `multiplier` | `1.5` | Multiplier applied after an iteration still needs retries. |
| `use_tiered_strategy` | `True` | Use cheaper collision proxies in the first pass when applicable. |
| `warm_start` | `"shortest"` | Optional greedy warm-start ordering. |
| `net_order` | `"user"` | Net ordering strategy for warm-start seeding and routed iterations. |
| `warm_start_enabled` | `True` | Run the greedy warm-start seeding pass before negotiated congestion iterations. |
| `shuffle_nets` | `False` | Shuffle routing order between iterations. |
| `sort_nets` | `None` | Optional deterministic routing order. |
| `seed` | `None` | RNG seed for shuffled routing order. |
## 5. Refinement Options
@ -126,7 +141,7 @@ run_b = route(problem_b)
## 8. Internal Modules
Lower-level search and collision modules are internal implementation details. The supported entrypoint is `route(problem, options=...)`.
Lower-level search and collision modules are semi-private implementation details. They remain accessible through deep imports for advanced use, but they are unstable and may change without notice. The stable supported entrypoint is `route(problem, options=...)`.
## 9. Tuning Notes

View file

@ -50,7 +50,7 @@ if run.results_by_net["net1"].is_valid:
print("Successfully routed net1!")
```
For incremental workflows, feed prior routed results back into a new `RoutingProblem` via `locked_routes` using `RoutingResult.as_locked_route()`.
For incremental workflows, feed prior routed results back into a new `RoutingProblem` via `static_obstacles` using `RoutingResult.locked_geometry`.
## Usage Examples
@ -65,6 +65,12 @@ python3 examples/01_simple_route.py
Full documentation for all user-tunable parameters, cost functions, and collision models can be found in **[DOCS.md](DOCS.md)**.
## API Stability
The stable API lives at the package root and is centered on `route(problem, options=...)`.
Deep-module interfaces such as `inire.router._router.PathFinder`, `inire.router._search.route_astar`, and `inire.geometry.collision.RoutingWorld` remain accessible for advanced use, but they are unstable semi-private interfaces and may change without notice.
## Architecture
`inire` operates on a **State-Lattice** defined by $(x, y, \theta)$. From any state, the router expands via three primary "Move" types:
@ -76,7 +82,7 @@ For multi-net problems, the negotiated-congestion loop handles rip-up and rerout
## Configuration
`inire` is highly tunable. The public API is `RoutingProblem` plus `RoutingOptions`, routed via `route(problem, options=...)`. Search internals remain available only for internal tests and development work; they are not a supported integration surface. See `DOCS.md` for a full parameter reference.
`inire` is highly tunable. The stable API is `RoutingProblem` plus `RoutingOptions`, routed via `route(problem, options=...)`. Deep modules remain accessible for advanced workflows, but they are unstable and may change without notice. See `DOCS.md` for a full parameter reference.
## License

View file

@ -27,7 +27,7 @@ def main() -> None:
RoutingProblem(
bounds=bounds,
nets=(NetSpec("netB", Port(50, -20, 90), Port(50, 20, 90), width=2.0),),
locked_routes={"netA": results_a["netA"].as_locked_route()},
static_obstacles=results_a["netA"].locked_geometry,
),
options=options,
).results_by_net

View file

@ -26,7 +26,7 @@ def main() -> None:
bend_penalty=50.0,
sbend_penalty=150.0,
),
congestion=CongestionOptions(warm_start=None),
congestion=CongestionOptions(warm_start_enabled=False),
)
print("Routing with a deliberately tiny node budget (should return a partial path)...")

View file

@ -1,43 +1,59 @@
"""
inire Wave-router
"""
from .api import (
from collections.abc import Callable
from .geometry.primitives import Port as Port # noqa: PLC0414
from .model import (
CongestionOptions as CongestionOptions,
DiagnosticsOptions as DiagnosticsOptions,
LockedRoute as LockedRoute,
NetSpec as NetSpec,
ObjectiveWeights as ObjectiveWeights,
RefinementOptions as RefinementOptions,
RoutingOptions as RoutingOptions,
RoutingProblem as RoutingProblem,
RoutingRunResult as RoutingRunResult,
SearchOptions as SearchOptions,
route as route,
) # noqa: PLC0414
from .geometry.primitives import Port as Port # noqa: PLC0414
from .geometry.components import Straight as Straight, Bend90 as Bend90, SBend as SBend # noqa: PLC0414
from .router.results import RouteMetrics as RouteMetrics, RoutingReport as RoutingReport, RoutingResult as RoutingResult # noqa: PLC0414
from .results import RoutingResult as RoutingResult, RoutingRunResult as RoutingRunResult # noqa: PLC0414
from .seeds import Bend90Seed as Bend90Seed, PathSeed as PathSeed, SBendSeed as SBendSeed, StraightSeed as StraightSeed # noqa: PLC0414
__author__ = 'Jan Petykiewicz'
__version__ = '0.1'
def route(
problem: RoutingProblem,
*,
options: RoutingOptions | None = None,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
from .router._stack import build_routing_stack
resolved_options = RoutingOptions() if options is None else options
stack = build_routing_stack(problem, resolved_options)
finder = stack.finder
results = finder.route_all(iteration_callback=iteration_callback)
return RoutingRunResult(
results_by_net=results,
metrics=finder.metrics.snapshot(),
expanded_nodes=tuple(finder.accumulated_expanded_nodes),
)
__all__ = [
"Bend90",
"Bend90Seed",
"CongestionOptions",
"DiagnosticsOptions",
"LockedRoute",
"NetSpec",
"ObjectiveWeights",
"PathSeed",
"Port",
"RefinementOptions",
"RoutingOptions",
"RoutingProblem",
"RoutingReport",
"RoutingResult",
"RoutingRunResult",
"RouteMetrics",
"SBend",
"SBendSeed",
"SearchOptions",
"Straight",
"StraightSeed",
"route",
]

View file

@ -1,97 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from inire.geometry.collision import RoutingWorld
from inire.model import (
CongestionOptions,
DiagnosticsOptions,
LockedRoute,
NetSpec,
ObjectiveWeights,
RefinementOptions,
RoutingOptions,
RoutingProblem,
RoutingRunResult,
SearchOptions,
)
from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.results import RouteMetrics, RoutingReport, RoutingResult
if TYPE_CHECKING:
from collections.abc import Callable, Iterable
from shapely.geometry import Polygon
__all__ = [
"CongestionOptions",
"DiagnosticsOptions",
"LockedRoute",
"NetSpec",
"ObjectiveWeights",
"RefinementOptions",
"RouteMetrics",
"RoutingOptions",
"RoutingProblem",
"RoutingReport",
"RoutingResult",
"RoutingRunResult",
"SearchOptions",
"route",
]
def _iter_locked_polygons(
locked_routes: dict[str, LockedRoute],
) -> Iterable[Polygon]:
for route in locked_routes.values():
yield from route.geometry
def _build_context(problem: RoutingProblem, options: RoutingOptions) -> AStarContext:
world = RoutingWorld(
clearance=problem.clearance,
max_net_width=problem.max_net_width,
safety_zone_radius=problem.safety_zone_radius,
)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
for polygon in _iter_locked_polygons(problem.locked_routes):
world.add_static_obstacle(polygon)
danger_obstacles = list(problem.static_obstacles)
danger_obstacles.extend(_iter_locked_polygons(problem.locked_routes))
danger_map = DangerMap(bounds=problem.bounds)
danger_map.precompute(danger_obstacles)
objective = options.objective
evaluator = CostEvaluator(
world,
danger_map,
unit_length_cost=objective.unit_length_cost,
greedy_h_weight=options.search.greedy_h_weight,
bend_penalty=objective.bend_penalty,
sbend_penalty=objective.sbend_penalty,
danger_weight=objective.danger_weight,
)
return AStarContext(evaluator, problem, options)
def route(
problem: RoutingProblem,
*,
options: RoutingOptions | None = None,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
resolved_options = RoutingOptions() if options is None else options
finder = PathFinder(_build_context(problem, resolved_options))
results = finder.route_all(iteration_callback=iteration_callback)
return RoutingRunResult(
results_by_net=results,
metrics=finder.metrics.snapshot(),
expanded_nodes=tuple(finder.accumulated_expanded_nodes),
)

View file

@ -2,11 +2,5 @@
Centralized constants for the inire routing engine.
"""
# Search Grid Snap (5.0 µm default)
# TODO: Make this configurable in SearchOptions and define tolerances relative to the grid.
DEFAULT_SEARCH_GRID_SNAP_UM = 5.0
# Tolerances
TOLERANCE_LINEAR = 1e-6
TOLERANCE_ANGULAR = 1e-3
TOLERANCE_GRID = 1e-6

View file

@ -1,6 +1,6 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal
from typing import TYPE_CHECKING
import numpy
from shapely.geometry import LineString, box
@ -8,8 +8,8 @@ from shapely.geometry import LineString, box
from inire.geometry.component_overlap import components_overlap
from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.index_helpers import grid_cell_span
from inire.results import RoutingReport
from inire.geometry.static_obstacle_index import StaticObstacleIndex
from inire.router.results import RoutingReport
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
@ -35,9 +35,7 @@ class RoutingWorld:
__slots__ = (
"clearance",
"max_net_width",
"safety_zone_radius",
"metrics",
"grid_cell_size",
"_dynamic_paths",
"_static_obstacles",
@ -46,27 +44,15 @@ class RoutingWorld:
def __init__(
self,
clearance: float,
max_net_width: float = 2.0,
safety_zone_radius: float = 0.0021,
) -> None:
self.clearance = clearance
self.max_net_width = max_net_width
self.safety_zone_radius = safety_zone_radius
self.grid_cell_size = 50.0
self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_paths = DynamicPathIndex(self)
self.metrics = {
"static_cache_hits": 0,
"static_grid_skips": 0,
"static_tree_queries": 0,
"static_straight_fast": 0,
"congestion_grid_skips": 0,
"congestion_tree_queries": 0,
"safety_zone_checks": 0,
}
def get_static_version(self) -> int:
return self._static_obstacles.version
@ -87,31 +73,12 @@ class RoutingWorld:
for obj_id in self._dynamic_paths.index.intersection(query_bounds):
yield self._dynamic_paths.geometries[obj_id][1].bounds
def iter_dynamic_paths(self) -> Iterable[tuple[str, Polygon]]:
return self._dynamic_paths.geometries.values()
def reset_metrics(self) -> None:
for key in self.metrics:
self.metrics[key] = 0
def get_metrics_summary(self) -> str:
metrics = self.metrics
return (
"Collision Performance: \n"
f" Static: {metrics['static_tree_queries']} checks\n"
f" Congestion: {metrics['congestion_tree_queries']} checks\n"
f" Safety Zone: {metrics['safety_zone_checks']} full intersections performed"
)
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
def remove_static_obstacle(self, obj_id: int) -> None:
self._static_obstacles.remove_obstacle(obj_id)
def _invalidate_static_caches(self) -> None:
self._static_obstacles.invalidate_caches()
def _ensure_static_tree(self) -> None:
self._static_obstacles.ensure_tree()
@ -127,10 +94,6 @@ class RoutingWorld:
def _ensure_dynamic_grid(self) -> None:
self._dynamic_paths.ensure_grid()
def rebuild_dynamic_tree(self) -> None:
self._dynamic_paths.tree = None
self._ensure_dynamic_tree()
def add_path(self, net_id: str, geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon]) -> None:
self._dynamic_paths.add_path(net_id, geometry, dilated_geometry=dilated_geometry)
@ -138,7 +101,6 @@ class RoutingWorld:
self._dynamic_paths.remove_path(net_id)
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
self.metrics["static_straight_fast"] += 1
reach = self.ray_cast(start_port, start_port.r, max_dist=length + 0.01, net_width=net_width)
return reach < length - 0.001
@ -178,7 +140,6 @@ class RoutingWorld:
if not geometry.intersects(raw_obstacle):
return False
self.metrics["safety_zone_checks"] += 1
intersection = geometry.intersection(raw_obstacle)
if intersection.is_empty:
return False
@ -207,15 +168,13 @@ class RoutingWorld:
result: ComponentResult,
start_port: Port | None = None,
end_port: Port | None = None,
net_width: float | None = None,
) -> bool:
del net_width
# TODO: If static buffering becomes net-width-specific, add dedicated
# width-aware geometry/index handling instead of reviving dead args here.
static_obstacles = self._static_obstacles
if not static_obstacles.dilated:
return False
self.metrics["static_tree_queries"] += 1
self._ensure_static_tree()
hits = static_obstacles.tree.query(box(*result.total_dilated_bounds))
@ -260,7 +219,6 @@ class RoutingWorld:
def _check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
dynamic_paths = self._dynamic_paths
self.metrics["congestion_tree_queries"] += 1
self._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
@ -347,101 +305,6 @@ class RoutingWorld:
return 0
return self._check_real_congestion(result, net_id)
def _check_static_collision(
self,
geometry: Polygon,
start_port: Port | None = None,
end_port: Port | None = None,
dilated_geometry: Polygon | None = None,
) -> bool:
static_obstacles = self._static_obstacles
self._ensure_static_tree()
if static_obstacles.tree is None:
return False
if dilated_geometry is not None:
test_geometry = dilated_geometry
else:
distance = self.clearance / 2.0
test_geometry = geometry.buffer(distance + 1e-7, join_style=2) if distance > 0 else geometry
hits = static_obstacles.tree.query(test_geometry, predicate="intersects")
tree_geometries = static_obstacles.tree.geometries
for hit_idx in hits:
if test_geometry.touches(tree_geometries[hit_idx]):
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self._is_in_safety_zone(geometry, obj_id, start_port, end_port):
continue
return True
return False
def _check_dynamic_collision(
self,
geometry: Polygon,
net_id: str,
dilated_geometry: Polygon | None = None,
) -> int:
dynamic_paths = self._dynamic_paths
self._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
test_geometry = dilated_geometry if dilated_geometry else geometry.buffer(self.clearance / 2.0)
hits = dynamic_paths.tree.query(test_geometry, predicate="intersects")
tree_geometries = dynamic_paths.tree.geometries
hit_net_ids: list[str] = []
for hit_idx in hits:
if test_geometry.touches(tree_geometries[hit_idx]):
continue
obj_id = dynamic_paths.obj_ids[hit_idx]
other_net_id = dynamic_paths.geometries[obj_id][0]
if other_net_id != net_id:
hit_net_ids.append(other_net_id)
if not hit_net_ids:
return 0
return len(numpy.unique(hit_net_ids))
def check_collision(
self,
geometry: Polygon,
net_id: str,
buffer_mode: Literal["static", "congestion"] = "static",
start_port: Port | None = None,
end_port: Port | None = None,
dilated_geometry: Polygon | None = None,
bounds: tuple[float, float, float, float] | None = None,
net_width: float | None = None,
) -> bool | int:
del bounds, net_width
if buffer_mode == "static":
return self._check_static_collision(
geometry,
start_port=start_port,
end_port=end_port,
dilated_geometry=dilated_geometry,
)
return self._check_dynamic_collision(geometry, net_id, dilated_geometry=dilated_geometry)
def is_collision(
self,
geometry: Polygon,
net_id: str = "default",
net_width: float | None = None,
start_port: Port | None = None,
end_port: Port | None = None,
) -> bool:
result = self.check_collision(
geometry,
net_id,
buffer_mode="static",
start_port=start_port,
end_port=end_port,
net_width=net_width,
)
return bool(result)
def verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
static_collision_count = 0
dynamic_collision_count = 0
@ -502,10 +365,6 @@ class RoutingWorld:
total_length=total_length,
)
def verify_path(self, net_id: str, components: Sequence[ComponentResult]) -> tuple[bool, int]:
report = self.verify_path_report(net_id, components)
return report.is_valid, report.collision_count
def ray_cast(
self,
origin: Port,

View file

@ -8,31 +8,34 @@ if TYPE_CHECKING:
from inire.geometry.components import ComponentResult
def component_polygons(component: ComponentResult, prefer_actual: bool = False) -> list[Polygon]:
if prefer_actual:
return list(component.physical_geometry)
return list(component.collision_geometry)
def component_bounds(component: ComponentResult, prefer_actual: bool = False) -> tuple[float, float, float, float]:
if not prefer_actual:
return component.total_bounds
polygons = component_polygons(component, prefer_actual=True)
min_x = min(polygon.bounds[0] for polygon in polygons)
min_y = min(polygon.bounds[1] for polygon in polygons)
max_x = max(polygon.bounds[2] for polygon in polygons)
max_y = max(polygon.bounds[3] for polygon in polygons)
return (min_x, min_y, max_x, max_y)
def components_overlap(
component_a: ComponentResult,
component_b: ComponentResult,
prefer_actual: bool = False,
) -> bool:
bounds_a = component_bounds(component_a, prefer_actual=prefer_actual)
bounds_b = component_bounds(component_b, prefer_actual=prefer_actual)
polygons_a: tuple[Polygon, ...]
polygons_b: tuple[Polygon, ...]
if prefer_actual:
polygons_a = component_a.physical_geometry
polygons_b = component_b.physical_geometry
bounds_a = (
min(polygon.bounds[0] for polygon in polygons_a),
min(polygon.bounds[1] for polygon in polygons_a),
max(polygon.bounds[2] for polygon in polygons_a),
max(polygon.bounds[3] for polygon in polygons_a),
)
bounds_b = (
min(polygon.bounds[0] for polygon in polygons_b),
min(polygon.bounds[1] for polygon in polygons_b),
max(polygon.bounds[2] for polygon in polygons_b),
max(polygon.bounds[3] for polygon in polygons_b),
)
else:
polygons_a = component_a.collision_geometry
polygons_b = component_b.collision_geometry
bounds_a = component_a.total_bounds
bounds_b = component_b.total_bounds
if not (
bounds_a[0] < bounds_b[2]
and bounds_a[2] > bounds_b[0]
@ -41,18 +44,8 @@ def components_overlap(
):
return False
polygons_a = component_polygons(component_a, prefer_actual=prefer_actual)
polygons_b = component_polygons(component_b, prefer_actual=prefer_actual)
for polygon_a in polygons_a:
for polygon_b in polygons_b:
if polygon_a.intersects(polygon_b) and not polygon_a.touches(polygon_b):
return True
return False
def has_self_overlap(path: list[ComponentResult], prefer_actual: bool = False) -> bool:
for i, component in enumerate(path):
for j in range(i + 2, len(path)):
if components_overlap(component, path[j], prefer_actual=prefer_actual):
return True
return False

View file

@ -10,6 +10,7 @@ from shapely.affinity import translate as shapely_translate
from shapely.geometry import Polygon, box
from inire.constants import TOLERANCE_ANGULAR
from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed
from .primitives import Port, rotation_matrix2
@ -29,6 +30,7 @@ class ComponentResult:
end_port: Port
length: float
move_type: MoveKind
move_spec: PathSegmentSeed
physical_geometry: tuple[Polygon, ...]
dilated_collision_geometry: tuple[Polygon, ...]
dilated_physical_geometry: tuple[Polygon, ...]
@ -80,6 +82,7 @@ class ComponentResult:
end_port=self.end_port.translate(dx, dy),
length=self.length,
move_type=self.move_type,
move_spec=self.move_spec,
physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.physical_geometry],
dilated_collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_collision_geometry],
dilated_physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_physical_geometry],
@ -235,6 +238,7 @@ class Straight:
end_port=end_port,
length=abs(length_f),
move_type="straight",
move_spec=StraightSeed(length=length_f),
physical_geometry=geometry,
dilated_collision_geometry=dilated_geometry,
dilated_physical_geometry=dilated_geometry,
@ -305,6 +309,7 @@ class Bend90:
end_port=end_port,
length=abs(radius) * numpy.pi / 2.0,
move_type="bend90",
move_spec=Bend90Seed(radius=radius, direction=direction),
physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry,
@ -394,6 +399,7 @@ class SBend:
end_port=end_port,
length=2.0 * radius * theta,
move_type="sbend",
move_spec=SBendSeed(offset=offset, radius=radius),
physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry,

View file

@ -87,8 +87,3 @@ class DynamicPathIndex:
self.index.delete(obj_id, self.dilated[obj_id].bounds)
del self.geometries[obj_id]
del self.dilated[obj_id]
def clear_paths(self) -> None:
if not self.geometries:
return
self.remove_obj_ids(list(self.geometries))

View file

@ -61,11 +61,3 @@ ROT2_270 = numpy.array(((0, 1), (-1, 0)), dtype=numpy.int32)
def rotation_matrix2(rotation_deg: int) -> NDArray[numpy.int32]:
quadrant = (_normalize_angle(rotation_deg) // 90) % 4
return (ROT2_0, ROT2_90, ROT2_180, ROT2_270)[quadrant]
def rotation_matrix3(rotation_deg: int) -> NDArray[numpy.int32]:
rot2 = rotation_matrix2(rotation_deg)
rot3 = numpy.zeros((3, 3), dtype=numpy.int32)
rot3[:2, :2] = rot2
rot3[2, 2] = 1
return rot3

View file

@ -1,18 +1,22 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Literal
from inire.geometry.components import BendCollisionModel
from inire.router.results import RouteMetrics, RoutingResult
from inire.seeds import PathSeed
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire.geometry.components import ComponentResult
from inire.geometry.components import BendCollisionModel
from inire.geometry.primitives import Port
NetOrder = Literal["user", "shortest", "longest"]
VisibilityGuidance = Literal["off", "exact_corner", "tangent_corner"]
@dataclass(frozen=True, slots=True)
class NetSpec:
net_id: str
@ -21,37 +25,12 @@ class NetSpec:
width: float = 2.0
@dataclass(frozen=True, slots=True)
class LockedRoute:
geometry: tuple[Polygon, ...]
def __post_init__(self) -> None:
object.__setattr__(self, "geometry", tuple(self.geometry))
@classmethod
def from_path(cls, path: tuple[ComponentResult, ...] | list[ComponentResult]) -> LockedRoute:
polygons = []
for component in path:
polygons.extend(component.physical_geometry)
return cls(geometry=tuple(polygons))
def _coerce_locked_route(route: LockedRoute | tuple | list) -> LockedRoute:
if isinstance(route, LockedRoute):
return route
route_items = tuple(route)
if route_items and hasattr(route_items[0], "physical_geometry"):
return LockedRoute.from_path(route_items) # type: ignore[arg-type]
return LockedRoute(geometry=route_items)
@dataclass(frozen=True, slots=True)
class ObjectiveWeights:
unit_length_cost: float = 1.0
bend_penalty: float = 250.0
sbend_penalty: float = 500.0
danger_weight: float = 1.0
congestion_penalty: float = 0.0
@dataclass(frozen=True, slots=True)
@ -64,23 +43,13 @@ class SearchOptions:
bend_radii: tuple[float, ...] = (50.0, 100.0)
sbend_radii: tuple[float, ...] = (10.0,)
bend_collision_type: BendCollisionModel = "arc"
visibility_guidance: str = "tangent_corner"
initial_paths: dict[str, tuple[ComponentResult, ...]] | None = None
visibility_guidance: VisibilityGuidance = "tangent_corner"
def __post_init__(self) -> None:
object.__setattr__(self, "bend_radii", tuple(self.bend_radii))
object.__setattr__(self, "sbend_radii", tuple(self.sbend_radii))
if self.sbend_offsets is not None:
object.__setattr__(self, "sbend_offsets", tuple(self.sbend_offsets))
if self.initial_paths is not None:
object.__setattr__(
self,
"initial_paths",
{
net_id: tuple(path)
for net_id, path in self.initial_paths.items()
},
)
@dataclass(frozen=True, slots=True)
@ -89,9 +58,9 @@ class CongestionOptions:
base_penalty: float = 100.0
multiplier: float = 1.5
use_tiered_strategy: bool = True
warm_start: str | None = "shortest"
net_order: NetOrder = "user"
warm_start_enabled: bool = True
shuffle_nets: bool = False
sort_nets: str | None = None
seed: int | None = None
@ -120,26 +89,18 @@ class RoutingProblem:
bounds: tuple[float, float, float, float]
nets: tuple[NetSpec, ...] = ()
static_obstacles: tuple[Polygon, ...] = ()
locked_routes: dict[str, LockedRoute] = field(default_factory=dict)
initial_paths: dict[str, PathSeed] = field(default_factory=dict)
clearance: float = 2.0
max_net_width: float = 2.0
safety_zone_radius: float = 0.0021
def __post_init__(self) -> None:
object.__setattr__(self, "nets", tuple(self.nets))
object.__setattr__(self, "static_obstacles", tuple(self.static_obstacles))
initial_paths = dict(self.initial_paths)
if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()):
raise TypeError("RoutingProblem.initial_paths values must be PathSeed instances")
object.__setattr__(
self,
"locked_routes",
{
net_id: _coerce_locked_route(route)
for net_id, route in self.locked_routes.items()
},
"initial_paths",
initial_paths,
)
@dataclass(frozen=True, slots=True)
class RoutingRunResult:
results_by_net: dict[str, RoutingResult]
metrics: RouteMetrics
expanded_nodes: tuple[tuple[int, int, int], ...] = ()

86
inire/results.py Normal file
View file

@ -0,0 +1,86 @@
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Literal
from inire.seeds import PathSeed
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire.geometry.components import ComponentResult
RoutingOutcome = Literal["completed", "colliding", "partial", "unroutable"]
@dataclass(frozen=True, slots=True)
class RoutingReport:
static_collision_count: int = 0
dynamic_collision_count: int = 0
self_collision_count: int = 0
total_length: float = 0.0
@property
def collision_count(self) -> int:
return self.static_collision_count + self.dynamic_collision_count + self.self_collision_count
@property
def is_valid(self) -> bool:
return self.collision_count == 0
@dataclass(frozen=True, slots=True)
class RouteMetrics:
nodes_expanded: int
moves_generated: int
moves_added: int
pruned_closed_set: int
pruned_hard_collision: int
pruned_cost: int
@dataclass(frozen=True, slots=True)
class RoutingResult:
net_id: str
path: tuple[ComponentResult, ...]
reached_target: bool = False
report: RoutingReport = field(default_factory=RoutingReport)
def __post_init__(self) -> None:
object.__setattr__(self, "path", tuple(self.path))
@property
def collisions(self) -> int:
return self.report.collision_count
@property
def outcome(self) -> RoutingOutcome:
if not self.path:
return "unroutable"
if not self.reached_target:
return "partial"
if self.report.collision_count > 0:
return "colliding"
return "completed"
@property
def is_valid(self) -> bool:
return self.outcome == "completed"
@property
def locked_geometry(self) -> tuple[Polygon, ...]:
polygons = []
for component in self.path:
polygons.extend(component.physical_geometry)
return tuple(polygons)
def as_seed(self) -> PathSeed:
return PathSeed(tuple(component.move_spec for component in self.path))
@dataclass(frozen=True, slots=True)
class RoutingRunResult:
results_by_net: dict[str, RoutingResult]
metrics: RouteMetrics
expanded_nodes: tuple[tuple[int, int, int], ...] = ()

View file

@ -1,16 +1,16 @@
from __future__ import annotations
import heapq
from typing import TYPE_CHECKING, Literal
from typing import TYPE_CHECKING
from shapely.geometry import Polygon
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.components import Bend90, SBend, Straight, BendCollisionModel, MoveKind
from inire.geometry.components import Bend90, SBend, Straight, MoveKind
from inire.geometry.primitives import Port
from inire.router.refiner import component_hits_ancestor_chain
from ._astar_types import AStarContext, AStarMetrics, AStarNode
from ._astar_types import AStarContext, AStarMetrics, AStarNode, SearchRunConfig
if TYPE_CHECKING:
from inire.geometry.components import ComponentResult
@ -26,15 +26,12 @@ def process_move(
context: AStarContext,
metrics: AStarMetrics,
congestion_cache: dict[tuple, int],
config: SearchRunConfig,
move_class: MoveKind,
params: tuple,
skip_congestion: bool,
bend_collision_type: BendCollisionModel,
max_cost: float | None = None,
self_collision_check: bool = False,
) -> None:
cp = parent.port
coll_type = bend_collision_type
coll_type = config.bend_collision_type
coll_key = id(coll_type) if isinstance(coll_type, Polygon) else coll_type
self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0
@ -101,12 +98,9 @@ def process_move(
context,
metrics,
congestion_cache,
config,
move_class,
abs_key,
move_radius=move_radius,
skip_congestion=skip_congestion,
max_cost=max_cost,
self_collision_check=self_collision_check,
)
@ -121,12 +115,9 @@ def add_node(
context: AStarContext,
metrics: AStarMetrics,
congestion_cache: dict[tuple, int],
config: SearchRunConfig,
move_type: MoveKind,
cache_key: tuple,
move_radius: float | None = None,
skip_congestion: bool = False,
max_cost: float | None = None,
self_collision_check: bool = False,
) -> None:
metrics.moves_generated += 1
metrics.total_moves_generated += 1
@ -151,7 +142,7 @@ def add_node(
if move_type == "straight":
collision_found = ce.check_move_straight_static(parent_p, result.length, net_width=net_width)
else:
collision_found = ce.check_move_static(result, start_port=parent_p, end_port=end_p, net_width=net_width)
collision_found = ce.check_move_static(result, start_port=parent_p, end_port=end_p)
if collision_found:
context.hard_collision_set.add(cache_key)
metrics.pruned_hard_collision += 1
@ -160,36 +151,23 @@ def add_node(
context.static_safe_cache.add(cache_key)
total_overlaps = 0
if not skip_congestion:
if not config.skip_congestion:
if cache_key in congestion_cache:
total_overlaps = congestion_cache[cache_key]
else:
total_overlaps = context.cost_evaluator.collision_engine.check_move_congestion(result, net_id)
congestion_cache[cache_key] = total_overlaps
if self_collision_check and component_hits_ancestor_chain(result, parent):
if config.self_collision_check and component_hits_ancestor_chain(result, parent):
return
penalty = context.cost_evaluator.component_penalty(
move_type,
move_radius=move_radius,
)
move_cost = context.cost_evaluator.evaluate_move(
result.collision_geometry,
result.end_port,
net_width,
net_id,
move_cost = context.cost_evaluator.score_component(
result,
start_port=parent_p,
length=result.length,
dilated_geometry=result.dilated_collision_geometry,
penalty=penalty,
skip_static=True,
skip_congestion=True,
)
move_cost += total_overlaps * context.cost_evaluator.congestion_penalty
move_cost += total_overlaps * context.congestion_penalty
if max_cost is not None and parent.g_cost + move_cost > max_cost:
if config.max_cost is not None and parent.g_cost + move_cost > config.max_cost:
metrics.pruned_cost += 1
metrics.total_pruned_cost += 1
return
@ -204,7 +182,11 @@ def add_node(
metrics.total_pruned_closed_set += 1
return
h_cost = context.cost_evaluator.h_manhattan(result.end_port, target)
h_cost = context.cost_evaluator.h_manhattan(
result.end_port,
target,
min_bend_radius=context.min_bend_radius,
)
heapq.heappush(open_set, AStarNode(result.end_port, g_cost, h_cost, parent, result))
metrics.moves_added += 1
metrics.total_moves_added += 1

View file

@ -3,11 +3,11 @@ from __future__ import annotations
import math
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.components import BendCollisionModel, MoveKind
from inire.geometry.components import MoveKind
from inire.geometry.primitives import Port
from ._astar_admission import process_move
from ._astar_types import AStarContext, AStarMetrics, AStarNode
from ._astar_types import AStarContext, AStarMetrics, AStarNode, SearchRunConfig
def _quantized_lengths(values: list[float], max_reach: float) -> list[int]:
@ -129,13 +129,9 @@ def expand_moves(
context: AStarContext,
metrics: AStarMetrics,
congestion_cache: dict[tuple, int],
bend_collision_type: BendCollisionModel | None = None,
max_cost: float | None = None,
skip_congestion: bool = False,
self_collision_check: bool = False,
config: SearchRunConfig,
) -> None:
search_options = context.options.search
effective_bend_collision_type = bend_collision_type if bend_collision_type is not None else search_options.bend_collision_type
cp = current.port
prev_move_type, prev_straight_length = _previous_move_metadata(current)
dx_t = target.x - cp.x
@ -171,12 +167,9 @@ def expand_moves(
context,
metrics,
congestion_cache,
config,
"straight",
(int(round(proj_t)),),
skip_congestion,
bend_collision_type=effective_bend_collision_type,
max_cost=max_cost,
self_collision_check=self_collision_check,
)
max_reach = context.cost_evaluator.collision_engine.ray_cast(cp, cp.r, search_options.max_straight_length, net_width=net_width)
@ -225,12 +218,9 @@ def expand_moves(
context,
metrics,
congestion_cache,
config,
"straight",
(length,),
skip_congestion,
bend_collision_type=effective_bend_collision_type,
max_cost=max_cost,
self_collision_check=self_collision_check,
)
angle_to_target = 0.0
@ -256,12 +246,9 @@ def expand_moves(
context,
metrics,
congestion_cache,
config,
"bend90",
(radius, direction),
skip_congestion,
bend_collision_type=effective_bend_collision_type,
max_cost=max_cost,
self_collision_check=self_collision_check,
)
max_sbend_r = max(search_options.sbend_radii) if search_options.sbend_radii else 0.0
@ -293,10 +280,7 @@ def expand_moves(
context,
metrics,
congestion_cache,
config,
"sbend",
(offset, radius),
skip_congestion,
bend_collision_type=effective_bend_collision_type,
max_cost=max_cost,
self_collision_check=self_collision_check,
)

View file

@ -1,16 +1,53 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from inire.geometry.components import BendCollisionModel
from inire.model import RoutingOptions, RoutingProblem
from inire.results import RouteMetrics
from inire.router.visibility import VisibilityManager
from inire.router.results import RouteMetrics
if TYPE_CHECKING:
from inire.geometry.components import ComponentResult
from inire.router.cost import CostEvaluator
@dataclass(frozen=True, slots=True)
class SearchRunConfig:
bend_collision_type: BendCollisionModel
node_limit: int
return_partial: bool = False
store_expanded: bool = False
skip_congestion: bool = False
max_cost: float | None = None
self_collision_check: bool = False
@classmethod
def from_options(
cls,
options: RoutingOptions,
*,
bend_collision_type: BendCollisionModel | None = None,
node_limit: int | None = None,
return_partial: bool = False,
store_expanded: bool = False,
skip_congestion: bool = False,
max_cost: float | None = None,
self_collision_check: bool = False,
) -> SearchRunConfig:
search = options.search
return cls(
bend_collision_type=search.bend_collision_type if bend_collision_type is None else bend_collision_type,
node_limit=search.node_limit if node_limit is None else node_limit,
return_partial=return_partial,
store_expanded=store_expanded,
skip_congestion=skip_congestion,
max_cost=max_cost,
self_collision_check=self_collision_check,
)
class AStarNode:
__slots__ = ("port", "g_cost", "h_cost", "fh_cost", "parent", "component_result")
@ -96,6 +133,8 @@ class AStarMetrics:
class AStarContext:
__slots__ = (
"cost_evaluator",
"congestion_penalty",
"min_bend_radius",
"problem",
"options",
"max_cache_size",
@ -115,10 +154,11 @@ class AStarContext:
max_cache_size: int = 1000000,
) -> None:
self.cost_evaluator = cost_evaluator
self.congestion_penalty = 0.0
self.max_cache_size = max_cache_size
self.problem = problem
self.options = options
self.cost_evaluator.set_min_bend_radius(min(self.options.search.bend_radii, default=50.0))
self.min_bend_radius = min(self.options.search.bend_radii, default=50.0)
self.visibility_manager = VisibilityManager(self.cost_evaluator.collision_engine)
self.move_cache_rel: dict[tuple, ComponentResult] = {}
self.move_cache_abs: dict[tuple, ComponentResult] = {}

View file

@ -5,19 +5,17 @@ import time
from dataclasses import dataclass
from typing import TYPE_CHECKING
from inire.model import NetSpec, RoutingOptions, RoutingProblem
from inire.router._astar_types import AStarContext, AStarMetrics
from inire.model import NetOrder, NetSpec
from inire.results import RoutingOutcome, RoutingReport, RoutingResult
from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig
from inire.router._search import route_astar
from inire.router.outcomes import RoutingOutcome, routing_outcome_needs_retry
from inire.router._seed_materialization import materialize_path_seed
from inire.router.refiner import PathRefiner
from inire.router.results import RoutingReport, RoutingResult
if TYPE_CHECKING:
from collections.abc import Callable, Sequence
from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port
from inire.router.cost import CostEvaluator
@dataclass(slots=True)
@ -31,10 +29,6 @@ class _RoutingState:
initial_paths: dict[str, tuple[ComponentResult, ...]] | None
accumulated_expanded_nodes: list[tuple[int, int, int]]
__all__ = ["PathFinder"]
class PathFinder:
__slots__ = (
"context",
@ -53,83 +47,18 @@ class PathFinder:
self.refiner = PathRefiner(self.context)
self.accumulated_expanded_nodes: list[tuple[int, int, int]] = []
@property
def problem(self) -> RoutingProblem:
return self.context.problem
@property
def options(self) -> RoutingOptions:
return self.context.options
@property
def cost_evaluator(self) -> CostEvaluator:
return self.context.cost_evaluator
def _path_cost(self, path: Sequence[ComponentResult]) -> float:
return self.refiner.path_cost(path)
def _refine_path(
self,
net_id: str,
start: Port,
target: Port,
net_width: float,
path: Sequence[ComponentResult],
) -> list[ComponentResult]:
return self.refiner.refine_path(net_id, start, target, net_width, path)
def _extract_path_geometry(self, path: Sequence[ComponentResult]) -> tuple[list, list]:
def _install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None:
all_geoms = []
all_dilated = []
for result in path:
all_geoms.extend(result.collision_geometry)
all_dilated.extend(result.dilated_collision_geometry)
return all_geoms, all_dilated
def _install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None:
all_geoms, all_dilated = self._extract_path_geometry(path)
self.cost_evaluator.collision_engine.add_path(net_id, all_geoms, dilated_geometry=all_dilated)
def _stage_path_as_static(self, path: Sequence[ComponentResult]) -> list[int]:
obj_ids: list[int] = []
for result in path:
for polygon in result.physical_geometry:
obj_ids.append(self.cost_evaluator.collision_engine.add_static_obstacle(polygon))
return obj_ids
def _remove_static_obstacles(self, obj_ids: list[int]) -> None:
for obj_id in obj_ids:
self.cost_evaluator.collision_engine.remove_static_obstacle(obj_id)
def _remove_path(self, net_id: str) -> None:
self.cost_evaluator.collision_engine.remove_path(net_id)
def _verify_path_report(self, net_id: str, path: Sequence[ComponentResult]) -> RoutingReport:
return self.cost_evaluator.collision_engine.verify_path_report(net_id, path)
def _finalize_dynamic_tree(self) -> None:
self.cost_evaluator.collision_engine.rebuild_dynamic_tree()
def _build_routing_result(
self,
*,
net_id: str,
path: Sequence[ComponentResult],
reached_target: bool | None = None,
report: RoutingReport | None = None,
) -> RoutingResult:
resolved_reached_target = bool(path) if reached_target is None else reached_target
return RoutingResult(
net_id=net_id,
path=path,
reached_target=resolved_reached_target,
report=report if report is not None else RoutingReport(),
)
self.context.cost_evaluator.collision_engine.add_path(net_id, all_geoms, dilated_geometry=all_dilated)
def _routing_order(
self,
net_specs: dict[str, NetSpec],
order: str,
order: NetOrder,
) -> list[str]:
ordered_net_ids = list(net_specs.keys())
if order == "user":
@ -144,15 +73,26 @@ class PathFinder:
def _build_greedy_warm_start_paths(
self,
net_specs: dict[str, NetSpec],
order: str,
order: NetOrder,
) -> dict[str, tuple[ComponentResult, ...]]:
greedy_paths: dict[str, tuple[ComponentResult, ...]] = {}
temp_obj_ids: list[int] = []
greedy_node_limit = min(self.options.search.node_limit, 2000)
greedy_node_limit = min(self.context.options.search.node_limit, 2000)
for net_id in self._routing_order(net_specs, order):
net = net_specs[net_id]
h_start = self.cost_evaluator.h_manhattan(net.start, net.target)
h_start = self.context.cost_evaluator.h_manhattan(
net.start,
net.target,
min_bend_radius=self.context.min_bend_radius,
)
max_cost_limit = max(h_start * 3.0, 2000.0)
run_config = SearchRunConfig.from_options(
self.context.options,
skip_congestion=True,
max_cost=max_cost_limit,
self_collision_check=True,
node_limit=greedy_node_limit,
)
path = route_astar(
net.start,
net.target,
@ -160,24 +100,24 @@ class PathFinder:
context=self.context,
metrics=self.metrics,
net_id=net_id,
skip_congestion=True,
max_cost=max_cost_limit,
self_collision_check=True,
node_limit=greedy_node_limit,
config=run_config,
)
if not path:
continue
greedy_paths[net_id] = tuple(path)
temp_obj_ids.extend(self._stage_path_as_static(path))
for result in path:
for polygon in result.physical_geometry:
temp_obj_ids.append(self.context.cost_evaluator.collision_engine.add_static_obstacle(polygon))
self.context.clear_static_caches()
self._remove_static_obstacles(temp_obj_ids)
for obj_id in temp_obj_ids:
self.context.cost_evaluator.collision_engine.remove_static_obstacle(obj_id)
return greedy_paths
def _prepare_state(self) -> _RoutingState:
problem = self.problem
congestion = self.options.congestion
initial_paths = self.options.search.initial_paths
problem = self.context.problem
congestion = self.context.options.congestion
initial_paths = self._materialize_problem_initial_paths()
net_specs = {net.net_id: net for net in problem.nets}
num_nets = len(net_specs)
state = _RoutingState(
@ -190,27 +130,45 @@ class PathFinder:
initial_paths=initial_paths,
accumulated_expanded_nodes=[],
)
if state.initial_paths is None:
warm_start_order = congestion.sort_nets if congestion.sort_nets is not None else congestion.warm_start
if warm_start_order is not None:
state.initial_paths = self._build_greedy_warm_start_paths(net_specs, warm_start_order)
self.context.clear_static_caches()
if state.initial_paths is None and congestion.warm_start_enabled:
state.initial_paths = self._build_greedy_warm_start_paths(net_specs, congestion.net_order)
self.context.clear_static_caches()
if congestion.sort_nets and congestion.sort_nets != "user":
state.ordered_net_ids = self._routing_order(net_specs, congestion.sort_nets)
if congestion.net_order != "user":
state.ordered_net_ids = self._routing_order(net_specs, congestion.net_order)
return state
def _materialize_problem_initial_paths(self) -> dict[str, tuple[ComponentResult, ...]] | None:
if not self.context.problem.initial_paths:
return None
search = self.context.options.search
net_specs = {net.net_id: net for net in self.context.problem.nets}
initial_paths: dict[str, tuple[ComponentResult, ...]] = {}
for net_id, seed in self.context.problem.initial_paths.items():
if net_id not in net_specs:
raise ValueError(f"Initial path provided for unknown net: {net_id}")
net = net_specs[net_id]
initial_paths[net_id] = materialize_path_seed(
seed,
start=net.start,
net_width=net.width,
search=search,
clearance=self.context.cost_evaluator.collision_engine.clearance,
)
return initial_paths
def _route_net_once(
self,
state: _RoutingState,
iteration: int,
net_id: str,
) -> RoutingResult:
search = self.options.search
congestion = self.options.congestion
diagnostics = self.options.diagnostics
search = self.context.options.search
congestion = self.context.options.congestion
diagnostics = self.context.options.diagnostics
net = state.net_specs[net_id]
self._remove_path(net_id)
self.context.cost_evaluator.collision_engine.remove_path(net_id)
if iteration == 0 and state.initial_paths and net_id in state.initial_paths:
path: Sequence[ComponentResult] | None = state.initial_paths[net_id]
@ -222,13 +180,8 @@ class PathFinder:
if coll_model == "arc":
coll_model = "clipped_bbox"
path = route_astar(
net.start,
net.target,
net.width,
context=self.context,
metrics=self.metrics,
net_id=net_id,
run_config = SearchRunConfig.from_options(
self.context.options,
bend_collision_type=coll_model,
return_partial=True,
store_expanded=diagnostics.capture_expanded,
@ -236,26 +189,35 @@ class PathFinder:
self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=search.node_limit,
)
path = route_astar(
net.start,
net.target,
net.width,
context=self.context,
metrics=self.metrics,
net_id=net_id,
config=run_config,
)
if diagnostics.capture_expanded and self.metrics.last_expanded_nodes:
state.accumulated_expanded_nodes.extend(self.metrics.last_expanded_nodes)
if not path:
return self._build_routing_result(net_id=net_id, path=[], reached_target=False)
return RoutingResult(net_id=net_id, path=(), reached_target=False)
reached_target = path[-1].end_port == net.target
report = None
self._install_path(net_id, path)
if reached_target:
report = self._verify_path_report(net_id, path)
report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, path)
if report.self_collision_count > 0:
state.needs_self_collision_check.add(net_id)
return self._build_routing_result(
return RoutingResult(
net_id=net_id,
path=path,
reached_target=reached_target,
report=report,
report=RoutingReport() if report is None else report,
)
def _run_iteration(
@ -265,7 +227,7 @@ class PathFinder:
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> dict[str, RoutingOutcome] | None:
outcomes: dict[str, RoutingOutcome] = {}
congestion = self.options.congestion
congestion = self.context.options.congestion
self.metrics.reset_per_route()
if congestion.shuffle_nets and (iteration > 0 or state.initial_paths is None):
@ -274,7 +236,6 @@ class PathFinder:
for net_id in state.ordered_net_ids:
if time.monotonic() - state.start_time > state.timeout_s:
self._finalize_dynamic_tree()
return None
result = self._route_net_once(state, iteration, net_id)
@ -290,30 +251,30 @@ class PathFinder:
state: _RoutingState,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> bool:
congestion = self.options.congestion
congestion = self.context.options.congestion
for iteration in range(congestion.max_iterations):
outcomes = self._run_iteration(state, iteration, iteration_callback)
if outcomes is None:
return True
if not any(routing_outcome_needs_retry(outcome) for outcome in outcomes.values()):
if not any(outcome in {"colliding", "partial", "unroutable"} for outcome in outcomes.values()):
return False
self.cost_evaluator.congestion_penalty *= congestion.multiplier
self.context.congestion_penalty *= congestion.multiplier
return False
def _refine_results(self, state: _RoutingState) -> None:
if not self.options.refinement.enabled or not state.results:
if not self.context.options.refinement.enabled or not state.results:
return
for net_id in state.ordered_net_ids:
result = state.results.get(net_id)
if not result or not result.path or routing_outcome_needs_retry(result.outcome):
if not result or not result.path or result.outcome in {"colliding", "partial", "unroutable"}:
continue
net = state.net_specs[net_id]
self._remove_path(net_id)
refined_path = self.refiner.refine_path(net_id, net.start, net.target, net.width, result.path)
self.context.cost_evaluator.collision_engine.remove_path(net_id)
refined_path = self.refiner.refine_path(net_id, net.start, net.width, result.path)
self._install_path(net_id, refined_path)
report = self._verify_path_report(net_id, refined_path)
state.results[net_id] = self._build_routing_result(
report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, refined_path)
state.results[net_id] = RoutingResult(
net_id=net_id,
path=refined_path,
reached_target=result.reached_target,
@ -322,17 +283,13 @@ class PathFinder:
def _verify_results(self, state: _RoutingState) -> dict[str, RoutingResult]:
final_results: dict[str, RoutingResult] = {}
for net in self.problem.nets:
for net in self.context.problem.nets:
result = state.results.get(net.net_id)
if not result or not result.path:
final_results[net.net_id] = self._build_routing_result(
net_id=net.net_id,
path=[],
reached_target=False,
)
final_results[net.net_id] = RoutingResult(net_id=net.net_id, path=(), reached_target=False)
continue
report = self._verify_path_report(net.net_id, result.path)
final_results[net.net_id] = self._build_routing_result(
report = self.context.cost_evaluator.collision_engine.verify_path_report(net.net_id, result.path)
final_results[net.net_id] = RoutingResult(
net_id=net.net_id,
path=result.path,
reached_target=result.reached_target,
@ -345,7 +302,7 @@ class PathFinder:
*,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> dict[str, RoutingResult]:
self.cost_evaluator.congestion_penalty = self.options.congestion.base_penalty
self.context.congestion_penalty = self.context.options.congestion.base_penalty
self.accumulated_expanded_nodes = []
self.metrics.reset_totals()
self.metrics.reset_per_route()
@ -358,5 +315,4 @@ class PathFinder:
return self._verify_results(state)
self._refine_results(state)
self._finalize_dynamic_tree()
return self._verify_results(state)

View file

@ -4,12 +4,10 @@ import heapq
from typing import TYPE_CHECKING
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.components import BendCollisionModel
from inire.geometry.primitives import Port
from ._astar_moves import expand_moves as _expand_moves
from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode
from .results import RouteMetrics
from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, SearchRunConfig
if TYPE_CHECKING:
from inire.geometry.components import ComponentResult
@ -29,21 +27,14 @@ def route_astar(
target: Port,
net_width: float,
context: AStarContext,
*,
metrics: AStarMetrics | None = None,
net_id: str = "default",
bend_collision_type: BendCollisionModel | None = None,
return_partial: bool = False,
store_expanded: bool = False,
skip_congestion: bool = False,
max_cost: float | None = None,
self_collision_check: bool = False,
node_limit: int | None = None,
config: SearchRunConfig,
) -> list[ComponentResult] | None:
if metrics is None:
metrics = AStarMetrics()
metrics.reset_per_route()
search_options = context.options.search
effective_bend_collision_type = bend_collision_type if bend_collision_type is not None else search_options.bend_collision_type
context.ensure_static_caches_current()
context.cost_evaluator.set_target(target)
@ -51,18 +42,21 @@ def route_astar(
closed_set: dict[tuple[int, int, int], float] = {}
congestion_cache: dict[tuple, int] = {}
start_node = _AStarNode(start, 0.0, context.cost_evaluator.h_manhattan(start, target))
start_node = _AStarNode(
start,
0.0,
context.cost_evaluator.h_manhattan(start, target, min_bend_radius=context.min_bend_radius),
)
heapq.heappush(open_set, start_node)
best_node = start_node
effective_node_limit = node_limit if node_limit is not None else search_options.node_limit
nodes_expanded = 0
while open_set:
if nodes_expanded >= effective_node_limit:
return _reconstruct_path(best_node) if return_partial else None
if nodes_expanded >= config.node_limit:
return _reconstruct_path(best_node) if config.return_partial else None
current = heapq.heappop(open_set)
if max_cost is not None and current.fh_cost[0] > max_cost:
if config.max_cost is not None and current.fh_cost[0] > config.max_cost:
metrics.pruned_cost += 1
metrics.total_pruned_cost += 1
continue
@ -75,7 +69,7 @@ def route_astar(
continue
closed_set[state] = current.g_cost
if store_expanded:
if config.store_expanded:
metrics.last_expanded_nodes.append(state)
nodes_expanded += 1
@ -95,18 +89,7 @@ def route_astar(
context,
metrics,
congestion_cache,
bend_collision_type=effective_bend_collision_type,
max_cost=max_cost,
skip_congestion=skip_congestion,
self_collision_check=self_collision_check,
config=config,
)
return _reconstruct_path(best_node) if return_partial else None
__all__ = [
"AStarContext",
"AStarMetrics",
"RouteMetrics",
"route_astar",
]
return _reconstruct_path(best_node) if config.return_partial else None

View file

@ -0,0 +1,53 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from inire.model import SearchOptions
from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port
def materialize_path_seed(
seed: PathSeed,
*,
start: Port,
net_width: float,
search: SearchOptions,
clearance: float,
) -> tuple[ComponentResult, ...]:
from inire.geometry.components import Bend90, SBend, Straight
path: list[ComponentResult] = []
current = start
dilation = clearance / 2.0
bend_collision_type = search.bend_collision_type
for segment in seed.segments:
if isinstance(segment, StraightSeed):
component = Straight.generate(current, segment.length, net_width, dilation=dilation)
elif isinstance(segment, Bend90Seed):
component = Bend90.generate(
current,
segment.radius,
net_width,
segment.direction,
collision_type=bend_collision_type,
dilation=dilation,
)
elif isinstance(segment, SBendSeed):
component = SBend.generate(
current,
segment.offset,
segment.radius,
net_width,
collision_type=bend_collision_type,
dilation=dilation,
)
else:
raise TypeError(f"Unsupported seed segment: {type(segment)!r}")
path.append(component)
current = component.end_port
return tuple(path)

Some files were not shown because too many files have changed in this diff Show more