rework structure of everything

This commit is contained in:
Jan Petykiewicz 2026-03-30 15:32:29 -07:00
commit 941d3e01df
64 changed files with 3819 additions and 3559 deletions

210
DOCS.md
View file

@ -1,107 +1,159 @@
# Inire Configuration & API Documentation # Inire Configuration & API Documentation
This document describes the user-tunable parameters for the `inire` auto-router. This document describes the current public API for `inire`.
## 1. AStarContext Parameters ## 1. Primary API
The `AStarContext` stores the configuration and persistent state for the A* search. It is initialized once and passed to `route_astar` or the `PathFinder`. ### `RoutingProblem`
| Parameter | Type | Default | Description | `RoutingProblem` describes the physical routing problem:
| :-------------------- | :------------ | :----------------- | :------------------------------------------------------------------------------------ |
| `node_limit` | `int` | 1,000,000 | Maximum number of states to explore per net. Increase for very complex paths. |
| `max_straight_length` | `float` | 2000.0 | Maximum length (µm) of a single straight segment. |
| `min_straight_length` | `float` | 5.0 | Minimum length (µm) of a single straight segment. |
| `bend_radii` | `list[float]` | `[50.0, 100.0]` | Available radii for 90-degree turns (µm). |
| `sbend_radii` | `list[float]` | `[5.0, 10.0, 50.0, 100.0]` | Available radii for S-bends (µm). |
| `sbend_offsets` | `list[float] \| None` | `None` (Auto) | Lateral offsets for parametric S-bends. |
| `bend_penalty` | `float` | 250.0 | Flat cost added for every 90-degree bend. |
| `sbend_penalty` | `float` | 500.0 | Flat cost added for every S-bend. |
| `bend_collision_type` | `str` | `"arc"` | Collision model for bends: `"arc"`, `"bbox"`, or `"clipped_bbox"` (an 8-point conservative arc proxy). |
| `bend_clip_margin` | `float` | 10.0 | Extra space (µm) around the waveguide for clipped models. |
| `visibility_guidance` | `str` | `"tangent_corner"` | Visibility-driven straight candidate mode: `"off"`, `"exact_corner"`, or `"tangent_corner"`. |
## 2. AStarMetrics - `bounds`
- `nets`
- `static_obstacles`
- `locked_routes`
- `clearance`
- `max_net_width`
- `safety_zone_radius`
The `AStarMetrics` object collects performance data during the search. ### `RoutingOptions`
| Property | Type | Description | `RoutingOptions` groups all expert controls for the routing engine:
| :--------------------- | :---- | :---------------------------------------------------- |
| `nodes_expanded` | `int` | Number of nodes expanded in the last `route_astar` call. |
| `total_nodes_expanded` | `int` | Cumulative nodes expanded across all calls. |
| `max_depth_reached` | `int` | Deepest point in the search tree reached. |
--- - `search`
- `objective`
- `congestion`
- `refinement`
- `diagnostics`
## 3. CostEvaluator Parameters Route a problem with:
The `CostEvaluator` defines the "goodness" of a path. ```python
run = route(problem, options=options)
```
| Parameter | Type | Default | Description | If you omit `options`, `route(problem)` uses `RoutingOptions()` defaults.
| :------------------- | :------ | :--------- | :--------------------------------------------------------------------------------------- |
| `unit_length_cost` | `float` | 1.0 | Cost per µm of wire length. |
| `greedy_h_weight` | `float` | 1.1 | Heuristic weight. `1.0` is optimal; higher values (e.g. `1.5`) speed up search. |
| `congestion_penalty` | `float` | 10,000.0 | Multiplier for overlaps in the multi-net Negotiated Congestion loop. |
--- ### Incremental routing with `LockedRoute`
## 3. PathFinder Parameters For incremental workflows, route one problem, convert a result into a `LockedRoute`, and feed it into the next problem:
The `PathFinder` orchestrates multi-net routing using the Negotiated Congestion algorithm. ```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()},
)
run_b = route(problem_b)
```
| Parameter | Type | Default | Description | `LockedRoute` stores canonical physical geometry only. The next run applies its own clearance rules when treating it as a static obstacle.
| :------------------------ | :------ | :------ | :-------------------------------------------------------------------------------------- |
| `max_iterations` | `int` | 10 | Maximum number of rip-up and reroute iterations to resolve congestion. |
| `base_congestion_penalty` | `float` | 100.0 | Starting penalty for overlaps. Multiplied by `1.5` each iteration if congestion remains.|
| `refine_paths` | `bool` | `True` | Run the post-route path simplifier that removes unnecessary bend ladders when it finds a valid lower-cost replacement. |
--- ## 2. Search Options
## 4. CollisionEngine Parameters `RoutingOptions.search` is a `SearchOptions` object.
| Parameter | Type | Default | Description | | Field | Default | Description |
| :------------------- | :------ | :--------- | :------------------------------------------------------------------------------------ | | :-- | :-- | :-- |
| `clearance` | `float` | (Required) | Minimum required distance between any two waveguides or obstacles (µm). | | `node_limit` | `1_000_000` | Maximum number of states to explore per net. |
| `safety_zone_radius` | `float` | 0.0021 | Radius (µm) around ports where collisions are ignored for PDK boundary incidence. | | `max_straight_length` | `2000.0` | Maximum length of a single straight segment. |
| `min_straight_length` | `5.0` | Minimum length of a single straight segment. |
| `greedy_h_weight` | `1.5` | Heuristic weight. `1.0` is optimal but slower. |
| `bend_radii` | `(50.0, 100.0)` | Available radii for 90-degree bends. |
| `sbend_radii` | `(10.0,)` | Available radii for S-bends. |
| `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
## 4. Physical Units & Precision `RoutingOptions.objective` and `RoutingOptions.refinement.objective` use `ObjectiveWeights`.
- **Coordinates**: Micrometers (µm).
- **Grid Snapping**: The router internally operates on a **1nm** grid for final ports and a **1µm** lattice for expansion moves.
- **Search Space**: Assumptions are optimized for design areas up to **20mm x 20mm**.
- **Design Bounds**: The boundary limits defined in `DangerMap` strictly constrain the **physical edges** (dilated geometry) of the waveguide. Any move that would cause the waveguide or its required clearance to extend beyond these bounds is rejected with an infinite cost.
--- | Field | Default | Description |
| :-- | :-- | :-- |
| `unit_length_cost` | `1.0` | Cost per unit length. |
| `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. |
## 5. Best Practices & Tuning Advice ## 4. Congestion Options
### Speed vs. Optimality `RoutingOptions.congestion` is a `CongestionOptions` object.
The `greedy_h_weight` is your primary lever for search performance.
- **`1.0`**: Dijkstra-like behavior. Guarantees the shortest path but is very slow.
- **`1.1` to `1.2`**: Recommended range. Balances wire length with fast convergence.
- **`> 1.5`**: Extremely fast "greedy" search. May produce zig-zags or suboptimal detours.
### Avoiding "Zig-Zags" | Field | Default | Description |
If the router produces many small bends instead of a long straight line: | :-- | :-- | :-- |
1. Increase `bend_penalty` (e.g., set to `100.0` or higher). | `max_iterations` | `10` | Maximum rip-up and reroute iterations. |
2. Increase available `bend_radii` if larger turns are physically acceptable. | `base_penalty` | `100.0` | Starting overlap penalty for negotiated congestion. |
3. Decrease `greedy_h_weight` closer to `1.0`. | `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. |
| `shuffle_nets` | `False` | Shuffle routing order between iterations. |
| `sort_nets` | `None` | Optional deterministic routing order. |
| `seed` | `None` | RNG seed for shuffled routing order. |
### Visibility Guidance ## 5. Refinement Options
The router can bias straight stop points using static obstacle corners.
- **`"tangent_corner"`**: Default. Proposes straight lengths that set up a clean tangent bend around nearby visible corners. This helps obstacle-dense layouts more than open space.
- **`"exact_corner"`**: Only uses precomputed corner-to-corner visibility when the current search state already lands on an obstacle corner.
- **`"off"`**: Disables visibility-derived straight candidates entirely.
The arbitrary-point visibility scan remains available for diagnostics, but the router hot path intentionally uses the exact-corner / tangent-corner forms only.
### Handling Congestion `RoutingOptions.refinement` is a `RefinementOptions` object.
In multi-net designs, if nets are overlapping:
1. Increase `congestion_penalty` in `CostEvaluator`.
2. Increase `max_iterations` in `PathFinder`.
3. If a solution is still not found, check if the `clearance` is physically possible given the design's narrowest bottlenecks.
### S-Bend Usage | Field | Default | Description |
Parametric S-bends bridge lateral gaps without changing the waveguide's orientation. | :-- | :-- | :-- |
- **Automatic Selection**: If `sbend_offsets` is set to `None` (the default), the router automatically chooses from a set of "natural" offsets (Fibonacci-aligned grid steps) and the offset needed to hit the target. | `enabled` | `True` | Enable post-route refinement. |
- **Specific Offsets**: To use specific offsets (e.g., 5.86µm for a 45° switchover), provide them in the `sbend_offsets` list. The router will prioritize these but will still try to align with the target if possible. | `objective` | `None` | Optional override objective for refinement. `None` reuses the search objective. |
- **Constraints**: S-bends are only used for offsets $O < 2R$. For larger shifts, the router naturally combines two 90° bends and a straight segment.
## 6. Diagnostics Options
`RoutingOptions.diagnostics` is a `DiagnosticsOptions` object.
| Field | Default | Description |
| :-- | :-- | :-- |
| `capture_expanded` | `False` | Record expanded nodes for diagnostics and visualization. |
## 7. RouteMetrics
`RoutingRunResult.metrics` is an immutable per-run snapshot.
| Field | Type | Description |
| :-- | :-- | :-- |
| `nodes_expanded` | `int` | Total nodes expanded during the run. |
| `moves_generated` | `int` | Total candidate moves generated during the run. |
| `moves_added` | `int` | Total candidate moves admitted to the open set during the run. |
| `pruned_closed_set` | `int` | Total moves pruned because the state was already closed at lower cost. |
| `pruned_hard_collision` | `int` | Total moves pruned by hard collision checks. |
| `pruned_cost` | `int` | Total moves pruned by cost ceilings or invalid costs. |
## 8. Internal Modules
Lower-level search and collision modules are internal implementation details. The supported entrypoint is `route(problem, options=...)`.
## 9. Tuning Notes
### Speed vs. optimality
- Lower `search.greedy_h_weight` toward `1.0` for better optimality.
- Raise `search.greedy_h_weight` for faster, greedier routing.
### Congestion handling
- Increase `congestion.base_penalty` to separate nets more aggressively in the first iteration.
- Increase `congestion.max_iterations` if congestion needs more reroute passes.
- Increase `congestion.multiplier` if later iterations need to escalate more quickly.
### Bend-heavy routes
- Increase `objective.bend_penalty` to discourage ladders of small bends.
- Increase available `search.bend_radii` when larger turns are physically acceptable.
### Visibility guidance
- `"tangent_corner"` is the default and best general-purpose setting in obstacle-dense layouts.
- `"exact_corner"` is more conservative.
- `"off"` disables visibility-derived straight candidates.
### S-bends
- Leave `search.sbend_offsets=None` to let the router derive natural offsets automatically.
- Provide explicit `search.sbend_offsets` for known process-preferred offsets.
- S-bends are only used for offsets smaller than `2R`.

View file

@ -1,6 +1,6 @@
# inire: Auto-Routing for Photonic and RF Integrated Circuits # inire: Auto-Routing for Photonic and RF Integrated Circuits
`inire` is a high-performance auto-router designed specifically for the physical constraints of photonic and RF integrated circuits. It utilizes a Hybrid State-Lattice A* search combined with "Negotiated Congestion" (PathFinder) to route multiple nets while maintaining strict geometric fidelity and clearance. `inire` is a high-performance auto-router designed specifically for the physical constraints of photonic and RF integrated circuits. It uses a Hybrid State-Lattice A* search combined with negotiated congestion to route multiple nets while maintaining strict geometric fidelity and clearance.
## Key Features ## Key Features
@ -9,7 +9,7 @@
* **Analytic Correctness**: Every move is verified against an R-Tree spatial index of obstacles and other paths. * **Analytic Correctness**: Every move is verified against an R-Tree spatial index of obstacles and other paths.
* **1nm Precision**: All coordinates and ports are snapped to a 1nm manufacturing grid. * **1nm Precision**: All coordinates and ports are snapped to a 1nm manufacturing grid.
* **Safety & Proximity**: Incorporates a "Danger Map" (pre-computed distance transform) to maintain optimal spacing and reduce crosstalk. * **Safety & Proximity**: Incorporates a "Danger Map" (pre-computed distance transform) to maintain optimal spacing and reduce crosstalk.
* **Locked Paths**: Supports treating existing geometries as fixed obstacles for incremental routing sessions. * **Locked Routes**: Supports treating prior routed nets as fixed obstacles in later runs.
## Installation ## Installation
@ -26,42 +26,32 @@ pip install numpy scipy shapely rtree matplotlib
## Quick Start ## Quick Start
```python ```python
from inire.geometry.primitives import Port from inire import NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.geometry.collision import CollisionEngine
from inire.router.danger_map import DangerMap
from inire.router.cost import CostEvaluator
from inire.router.astar import AStarContext
from inire.router.pathfinder import PathFinder
# 1. Setup Environment problem = RoutingProblem(
engine = CollisionEngine(clearance=2.0) bounds=(0, 0, 1000, 1000),
danger_map = DangerMap(bounds=(0, 0, 1000, 1000)) nets=(
danger_map.precompute([]) # Add polygons here for obstacles NetSpec("net1", Port(0, 0, 0), Port(100, 50, 0), width=2.0),
),
# 2. Configure Router
evaluator = CostEvaluator(
collision_engine=engine,
danger_map=danger_map,
greedy_h_weight=1.2
) )
context = AStarContext( options = RoutingOptions(
cost_evaluator=evaluator, search=SearchOptions(
bend_penalty=10.0 bend_radii=(50.0, 100.0),
greedy_h_weight=1.2,
),
objective=ObjectiveWeights(
bend_penalty=10.0,
),
) )
pf = PathFinder(context)
# 3. Define Netlist run = route(problem, options=options)
netlist = {
"net1": (Port(0, 0, 0), Port(100, 50, 0)),
}
# 4. Route if run.results_by_net["net1"].is_valid:
results = pf.route_all(netlist, {"net1": 2.0})
if results["net1"].is_valid:
print("Successfully routed net1!") print("Successfully routed net1!")
``` ```
For incremental workflows, feed prior routed results back into a new `RoutingProblem` via `locked_routes` using `RoutingResult.as_locked_route()`.
## Usage Examples ## Usage Examples
For detailed visual demonstrations and architectural deep-dives, see the **[Examples README](examples/README.md)**. For detailed visual demonstrations and architectural deep-dives, see the **[Examples README](examples/README.md)**.
@ -82,11 +72,11 @@ Full documentation for all user-tunable parameters, cost functions, and collisio
2. **90° Bends**: Fixed-radius PDK cells. 2. **90° Bends**: Fixed-radius PDK cells.
3. **Parametric S-Bends**: Procedural arcs for bridging small lateral offsets ($O < 2R$). 3. **Parametric S-Bends**: Procedural arcs for bridging small lateral offsets ($O < 2R$).
For multi-net problems, the **PathFinder** loop handles rip-up and reroute logic, ensuring that paths find the globally optimal configuration without crossings. For multi-net problems, the negotiated-congestion loop handles rip-up and reroute logic, ensuring that paths find the globally optimal configuration without crossings.
## Configuration ## Configuration
`inire` is highly tunable. Every major component (Router, CostEvaluator, PathFinder) accepts explicit named arguments in its constructor to control expansion rules, cost weights, and convergence limits. See `DOCS.md` for a full parameter reference. `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.
## License ## License

View file

@ -1,54 +1,29 @@
from inire.geometry.collision import CollisionEngine from inire import NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 01: Simple Route...") print("Running Example 01: Simple Route...")
# 1. Setup Environment
# We define a 100um x 100um routing area
bounds = (0, 0, 100, 100) bounds = (0, 0, 100, 100)
# Clearance of 2.0um between waveguides
engine = CollisionEngine(clearance=2.0)
# Precompute DangerMap for heuristic speedup
danger_map = DangerMap(bounds=bounds)
danger_map.precompute([]) # No obstacles yet
# 2. Configure Router
evaluator = CostEvaluator(engine, danger_map)
context = AStarContext(evaluator, bend_radii=[10.0])
metrics = AStarMetrics()
pf = PathFinder(context, metrics)
# 3. Define Netlist
# Start at (10, 50) pointing East (0 deg)
# Target at (90, 50) pointing East (0 deg)
netlist = { netlist = {
"net1": (Port(10, 50, 0), Port(90, 50, 0)), "net1": (Port(10, 50, 0), Port(90, 50, 0)),
} }
net_widths = {"net1": 2.0} problem = RoutingProblem(
bounds=bounds,
nets=(NetSpec("net1", *netlist["net1"], width=2.0),),
)
options = RoutingOptions(search=SearchOptions(bend_radii=(10.0,)))
# 4. Route run = route(problem, options=options)
results = pf.route_all(netlist, net_widths) result = run.results_by_net["net1"]
if result.is_valid:
# 5. Check Results
res = results["net1"]
if res.is_valid:
print("Success! Route found.") print("Success! Route found.")
print(f"Path collisions: {res.collisions}") print(f"Path collisions: {result.collisions}")
else: else:
print("Failed to find route.") print("Failed to find route.")
# 6. Visualize fig, _ax = plot_routing_results(run.results_by_net, [], bounds, netlist=netlist)
# plot_routing_results takes a dict of RoutingResult objects
fig, ax = plot_routing_results(results, [], bounds)
fig.savefig("examples/01_simple_route.png") fig.savefig("examples/01_simple_route.png")
print("Saved plot to examples/01_simple_route.png") print("Saved plot to examples/01_simple_route.png")

View file

@ -1,49 +1,41 @@
from inire.geometry.collision import CollisionEngine from inire import CongestionOptions, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 02: Congestion Resolution (Triple Crossing)...") print("Running Example 02: Congestion Resolution (Triple Crossing)...")
# 1. Setup Environment
bounds = (0, 0, 100, 100) bounds = (0, 0, 100, 100)
engine = CollisionEngine(clearance=2.0)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute([])
# Configure a router with high congestion penalties
evaluator = CostEvaluator(engine, danger_map, greedy_h_weight=1.5, bend_penalty=250.0, sbend_penalty=500.0)
context = AStarContext(evaluator, bend_radii=[10.0], sbend_radii=[10.0])
metrics = AStarMetrics()
pf = PathFinder(context, metrics, base_congestion_penalty=1000.0)
# 2. Define Netlist
# Three nets that must cross each other in a small area
netlist = { netlist = {
"horizontal": (Port(10, 50, 0), Port(90, 50, 0)), "horizontal": (Port(10, 50, 0), Port(90, 50, 0)),
"vertical_up": (Port(45, 10, 90), Port(45, 90, 90)), "vertical_up": (Port(45, 10, 90), Port(45, 90, 90)),
"vertical_down": (Port(55, 90, 270), Port(55, 10, 270)), "vertical_down": (Port(55, 90, 270), Port(55, 10, 270)),
} }
net_widths = {nid: 2.0 for nid in netlist} problem = RoutingProblem(
bounds=bounds,
nets=tuple(NetSpec(net_id, start, target, width=2.0) for net_id, (start, target) in netlist.items()),
)
options = RoutingOptions(
search=SearchOptions(
bend_radii=(10.0,),
sbend_radii=(10.0,),
greedy_h_weight=1.5,
),
objective=ObjectiveWeights(
bend_penalty=250.0,
sbend_penalty=500.0,
),
congestion=CongestionOptions(base_penalty=1000.0),
)
# 3. Route run = route(problem, options=options)
# PathFinder uses Negotiated Congestion to resolve overlaps iteratively all_valid = all(result.is_valid for result in run.results_by_net.values())
results = pf.route_all(netlist, net_widths)
# 4. Check Results
all_valid = all(res.is_valid for res in results.values())
if all_valid: if all_valid:
print("Success! Congestion resolved for all nets.") print("Success! Congestion resolved for all nets.")
else: else:
print("Failed to resolve congestion for some nets.") print("Failed to resolve congestion for some nets.")
# 5. Visualize fig, _ax = plot_routing_results(run.results_by_net, [], bounds, netlist=netlist)
fig, ax = plot_routing_results(results, [], bounds, netlist=netlist)
fig.savefig("examples/02_congestion_resolution.png") fig.savefig("examples/02_congestion_resolution.png")
print("Saved plot to examples/02_congestion_resolution.png") print("Saved plot to examples/02_congestion_resolution.png")

View file

@ -1,42 +1,37 @@
from inire.geometry.collision import CollisionEngine from inire import NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 03: Locked Paths...") print("Running Example 03: Locked Routes...")
# 1. Setup Environment
bounds = (0, -50, 100, 50) bounds = (0, -50, 100, 50)
engine = CollisionEngine(clearance=2.0) options = RoutingOptions(
danger_map = DangerMap(bounds=bounds) search=SearchOptions(bend_radii=(10.0,)),
danger_map.precompute([]) objective=ObjectiveWeights(
bend_penalty=250.0,
evaluator = CostEvaluator(engine, danger_map, bend_penalty=250.0, sbend_penalty=500.0) sbend_penalty=500.0,
context = AStarContext(evaluator, bend_radii=[10.0]) ),
metrics = AStarMetrics() )
pf = PathFinder(context, metrics)
# 2. Route Net A and 'Lock' it
# Net A is a straight path blocking the direct route for Net B
print("Routing initial net...") print("Routing initial net...")
netlist_a = {"netA": (Port(10, 0, 0), Port(90, 0, 0))} results_a = route(
results_a = pf.route_all(netlist_a, {"netA": 2.0}) RoutingProblem(
bounds=bounds,
# Locking prevents Net A from being removed or rerouted during NC iterations nets=(NetSpec("netA", Port(10, 0, 0), Port(90, 0, 0), width=2.0),),
engine.lock_net("netA") ),
print("Initial net locked as static obstacle.") options=options,
).results_by_net
# 3. Route Net B (forced to detour)
print("Routing detour net around locked path...") print("Routing detour net around locked path...")
netlist_b = {"netB": (Port(50, -20, 90), Port(50, 20, 90))} results_b = route(
results_b = pf.route_all(netlist_b, {"netB": 2.0}) 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()},
),
options=options,
).results_by_net
# 4. Visualize
results = {**results_a, **results_b} results = {**results_a, **results_b}
fig, ax = plot_routing_results(results, [], bounds) fig, ax = plot_routing_results(results, [], bounds)
fig.savefig("examples/03_locked_paths.png") fig.savefig("examples/03_locked_paths.png")

View file

@ -1,60 +1,38 @@
from inire.geometry.collision import CollisionEngine from inire import NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 04: S-Bends and Multiple Radii...") print("Running Example 04: S-Bends and Multiple Radii...")
# 1. Setup Environment
bounds = (0, 0, 100, 100) bounds = (0, 0, 100, 100)
engine = CollisionEngine(clearance=2.0)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute([])
# 2. Configure Router
evaluator = CostEvaluator(
engine,
danger_map,
unit_length_cost=1.0,
bend_penalty=10.0,
sbend_penalty=20.0,
)
context = AStarContext(
evaluator,
node_limit=50000,
bend_radii=[10.0, 30.0],
sbend_offsets=[5.0], # Use a simpler offset
bend_penalty=10.0,
sbend_penalty=20.0,
)
metrics = AStarMetrics()
pf = PathFinder(context, metrics)
# 3. Define Netlist
# start (10, 50), target (60, 55) -> 5um offset
netlist = { netlist = {
"sbend_only": (Port(10, 50, 0), Port(60, 55, 0)), "sbend_only": (Port(10, 50, 0), Port(60, 55, 0)),
"multi_radii": (Port(10, 10, 0), Port(90, 90, 0)), "multi_radii": (Port(10, 10, 0), Port(90, 90, 0)),
} }
net_widths = {"sbend_only": 2.0, "multi_radii": 2.0} problem = RoutingProblem(
bounds=bounds,
nets=tuple(NetSpec(net_id, start, target, width=2.0) for net_id, (start, target) in netlist.items()),
)
options = RoutingOptions(
search=SearchOptions(
node_limit=50000,
bend_radii=(10.0, 30.0),
sbend_offsets=(5.0,),
),
objective=ObjectiveWeights(
unit_length_cost=1.0,
bend_penalty=10.0,
sbend_penalty=20.0,
),
)
# 4. Route run = route(problem, options=options)
results = pf.route_all(netlist, net_widths) for net_id, result in run.results_by_net.items():
status = "Success" if result.is_valid else "Failed"
print(f"{net_id}: {status}, collisions={result.collisions}")
# 5. Check Results fig, _ax = plot_routing_results(run.results_by_net, [], bounds, netlist=netlist)
for nid, res in results.items():
status = "Success" if res.is_valid else "Failed"
print(f"{nid}: {status}, collisions={res.collisions}")
# 6. Visualize
fig, ax = plot_routing_results(results, [], bounds, netlist=netlist)
fig.savefig("examples/04_sbends_and_radii.png") fig.savefig("examples/04_sbends_and_radii.png")
print("Saved plot to examples/04_sbends_and_radii.png") print("Saved plot to examples/04_sbends_and_radii.png")

View file

@ -1,46 +1,32 @@
from inire.geometry.collision import CollisionEngine from inire import NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 05: Orientation Stress Test...") print("Running Example 05: Orientation Stress Test...")
# 1. Setup Environment
bounds = (0, 0, 200, 200) bounds = (0, 0, 200, 200)
engine = CollisionEngine(clearance=2.0)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute([])
evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0)
context = AStarContext(evaluator, bend_radii=[20.0])
metrics = AStarMetrics()
pf = PathFinder(context, metrics)
# 2. Define Netlist
# Challenging orientation combinations
netlist = { netlist = {
"u_turn": (Port(50, 50, 0), Port(50, 70, 180)), "u_turn": (Port(50, 50, 0), Port(50, 70, 180)),
"loop": (Port(100, 100, 90), Port(100, 80, 270)), "loop": (Port(100, 100, 90), Port(100, 80, 270)),
"zig_zag": (Port(20, 150, 0), Port(180, 150, 0)), "zig_zag": (Port(20, 150, 0), Port(180, 150, 0)),
} }
net_widths = {nid: 2.0 for nid in netlist} problem = RoutingProblem(
bounds=bounds,
nets=tuple(NetSpec(net_id, start, target, width=2.0) for net_id, (start, target) in netlist.items()),
)
options = RoutingOptions(
search=SearchOptions(bend_radii=(20.0,)),
objective=ObjectiveWeights(bend_penalty=50.0),
)
# 3. Route
print("Routing complex orientation nets...") print("Routing complex orientation nets...")
results = pf.route_all(netlist, net_widths) run = route(problem, options=options)
for net_id, result in run.results_by_net.items():
status = "Success" if result.is_valid else "Failed"
print(f" {net_id}: {status}")
# 4. Check Results fig, _ax = plot_routing_results(run.results_by_net, [], bounds, netlist=netlist)
for nid, res in results.items():
status = "Success" if res.is_valid else "Failed"
print(f" {nid}: {status}")
# 5. Visualize
fig, ax = plot_routing_results(results, [], bounds, netlist=netlist)
fig.savefig("examples/05_orientation_stress.png") fig.savefig("examples/05_orientation_stress.png")
print("Saved plot to examples/05_orientation_stress.png") print("Saved plot to examples/05_orientation_stress.png")

View file

@ -1,11 +1,7 @@
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.geometry.collision import CollisionEngine from inire import CongestionOptions, NetSpec, ObjectiveWeights, RoutingOptions, RoutingProblem, RoutingResult, SearchOptions, route
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router.astar import AStarContext
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
@ -15,34 +11,30 @@ def _route_scenario(
bend_collision_type: str, bend_collision_type: str,
netlist: dict[str, tuple[Port, Port]], netlist: dict[str, tuple[Port, Port]],
widths: dict[str, float], widths: dict[str, float],
*, ) -> dict[str, RoutingResult]:
bend_clip_margin: float = 10.0, problem = RoutingProblem(
) -> dict[str, object]: bounds=bounds,
engine = CollisionEngine(clearance=2.0) nets=tuple(NetSpec(net_id, start, target, width=widths[net_id]) for net_id, (start, target) in netlist.items()),
for obstacle in obstacles: static_obstacles=tuple(obstacles),
engine.add_static_obstacle(obstacle)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute(obstacles)
evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0)
context = AStarContext(
evaluator,
bend_radii=[10.0],
bend_collision_type=bend_collision_type,
bend_clip_margin=bend_clip_margin,
) )
return PathFinder(context, use_tiered_strategy=False).route_all(netlist, widths) options = RoutingOptions(
search=SearchOptions(
bend_radii=(10.0,),
bend_collision_type=bend_collision_type,
),
objective=ObjectiveWeights(
bend_penalty=50.0,
sbend_penalty=150.0,
),
congestion=CongestionOptions(use_tiered_strategy=False),
)
return route(problem, options=options).results_by_net
def main() -> None: def main() -> None:
print("Running Example 06: Bend Collision Models...") print("Running Example 06: Bend Collision Models...")
# 1. Setup Environment
# Give room for 10um bends near the edges
bounds = (-20, -20, 170, 170) bounds = (-20, -20, 170, 170)
# Create three scenarios with identical obstacles
# We'll space them out vertically
obs_arc = Polygon([(40, 110), (60, 110), (60, 130), (40, 130)]) obs_arc = Polygon([(40, 110), (60, 110), (60, 130), (40, 130)])
obs_bbox = Polygon([(40, 60), (60, 60), (60, 80), (40, 80)]) obs_bbox = Polygon([(40, 60), (60, 60), (60, 80), (40, 80)])
obs_clipped = Polygon([(40, 10), (60, 10), (60, 30), (40, 30)]) obs_clipped = Polygon([(40, 10), (60, 10), (60, 30), (40, 30)])
@ -52,29 +44,17 @@ def main() -> None:
netlist_bbox = {"bbox_model": (Port(10, 70, 0), Port(90, 90, 90))} netlist_bbox = {"bbox_model": (Port(10, 70, 0), Port(90, 90, 90))}
netlist_clipped = {"clipped_model": (Port(10, 20, 0), Port(90, 40, 90))} netlist_clipped = {"clipped_model": (Port(10, 20, 0), Port(90, 40, 90))}
# 2. Route each scenario
print("Routing Scenario 1 (Arc)...") print("Routing Scenario 1 (Arc)...")
res_arc = _route_scenario(bounds, obstacles, "arc", netlist_arc, {"arc_model": 2.0}) res_arc = _route_scenario(bounds, obstacles, "arc", netlist_arc, {"arc_model": 2.0})
print("Routing Scenario 2 (BBox)...") print("Routing Scenario 2 (BBox)...")
res_bbox = _route_scenario(bounds, obstacles, "bbox", netlist_bbox, {"bbox_model": 2.0}) res_bbox = _route_scenario(bounds, obstacles, "bbox", netlist_bbox, {"bbox_model": 2.0})
print("Routing Scenario 3 (Clipped BBox)...") print("Routing Scenario 3 (Clipped BBox)...")
res_clipped = _route_scenario( res_clipped = _route_scenario(bounds, obstacles, "clipped_bbox", netlist_clipped, {"clipped_model": 2.0})
bounds,
obstacles,
"clipped_bbox",
netlist_clipped,
{"clipped_model": 2.0},
bend_clip_margin=1.0,
)
# 3. Combine results for visualization
all_results = {**res_arc, **res_bbox, **res_clipped} all_results = {**res_arc, **res_bbox, **res_clipped}
all_netlists = {**netlist_arc, **netlist_bbox, **netlist_clipped} all_netlists = {**netlist_arc, **netlist_bbox, **netlist_clipped}
# 4. Visualize fig, _ax = plot_routing_results(all_results, obstacles, bounds, netlist=all_netlists)
fig, ax = plot_routing_results(all_results, obstacles, bounds, netlist=all_netlists)
fig.savefig("examples/06_bend_collision_models.png") fig.savefig("examples/06_bend_collision_models.png")
print("Saved plot to examples/06_bend_collision_models.png") print("Saved plot to examples/06_bend_collision_models.png")

View file

@ -1,108 +1,111 @@
import numpy as np
import time import time
from inire.geometry.collision import CollisionEngine
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results, plot_danger_map, plot_expanded_nodes, plot_expansion_density
from shapely.geometry import box from shapely.geometry import box
from inire import (
CongestionOptions,
DiagnosticsOptions,
NetSpec,
ObjectiveWeights,
Port,
RoutingOptions,
RoutingProblem,
RoutingResult,
SearchOptions,
route,
)
from inire.utils.visualization import plot_expanded_nodes, plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 07: Fan-Out (10 Nets, 50um Radius)...") print("Running Example 07: Fan-Out (10 Nets, 50um Radius)...")
# 1. Setup Environment
bounds = (0, 0, 1000, 1000) bounds = (0, 0, 1000, 1000)
engine = CollisionEngine(clearance=6.0)
# Bottleneck at x=500, 200um gap
obstacles = [ obstacles = [
box(450, 0, 550, 400), box(450, 0, 550, 400),
box(450, 600, 550, 1000), box(450, 600, 550, 1000),
] ]
for obs in obstacles:
engine.add_static_obstacle(obs)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute(obstacles)
evaluator = CostEvaluator(engine, danger_map, greedy_h_weight=1.5, unit_length_cost=0.1, bend_penalty=100.0, sbend_penalty=400.0, congestion_penalty=100.0)
context = AStarContext(evaluator, node_limit=2000000, bend_radii=[50.0], sbend_radii=[50.0])
metrics = AStarMetrics()
pf = PathFinder(context, metrics, max_iterations=15, base_congestion_penalty=100.0, congestion_multiplier=1.4)
# 2. Define Netlist
netlist = {}
num_nets = 10 num_nets = 10
start_x = 50 start_x = 50
start_y_base = 500 - (num_nets * 10.0) / 2.0 start_y_base = 500 - (num_nets * 10.0) / 2.0
end_x = 950 end_x = 950
end_y_base = 100 end_y_base = 100
end_y_pitch = 800.0 / (num_nets - 1) end_y_pitch = 800.0 / (num_nets - 1)
for i in range(num_nets): netlist: dict[str, tuple[Port, Port]] = {}
sy = int(round(start_y_base + i * 10.0)) for index in range(num_nets):
ey = int(round(end_y_base + i * end_y_pitch)) start_y = int(round(start_y_base + index * 10.0))
netlist[f"net_{i:02d}"] = (Port(start_x, sy, 0), Port(end_x, ey, 0)) end_y = int(round(end_y_base + index * end_y_pitch))
netlist[f"net_{index:02d}"] = (Port(start_x, start_y, 0), Port(end_x, end_y, 0))
net_widths = {nid: 2.0 for nid in netlist} problem = RoutingProblem(
bounds=bounds,
nets=tuple(NetSpec(net_id, start, target, width=2.0) for net_id, (start, target) in netlist.items()),
static_obstacles=tuple(obstacles),
clearance=6.0,
)
options = RoutingOptions(
search=SearchOptions(
node_limit=2_000_000,
bend_radii=(50.0,),
sbend_radii=(50.0,),
greedy_h_weight=1.5,
),
objective=ObjectiveWeights(
unit_length_cost=0.1,
bend_penalty=100.0,
sbend_penalty=400.0,
),
congestion=CongestionOptions(
max_iterations=15,
base_penalty=100.0,
multiplier=1.4,
shuffle_nets=True,
seed=42,
),
diagnostics=DiagnosticsOptions(capture_expanded=True),
)
iteration_stats: list[dict[str, int]] = []
def iteration_callback(iteration: int, current_results: dict[str, RoutingResult]) -> None:
successes = sum(1 for result in current_results.values() if result.is_valid)
total_collisions = sum(result.collisions for result in current_results.values())
print(f" Iteration {iteration} finished. Successes: {successes}/{len(netlist)}, Collisions: {total_collisions}")
iteration_stats.append(
{
"Iteration": iteration,
"Success": successes,
"Congestion": total_collisions,
}
)
# 3. Route
print(f"Routing {len(netlist)} nets through 200um bottleneck...") print(f"Routing {len(netlist)} nets through 200um bottleneck...")
start_time = time.perf_counter()
run = route(problem, options=options, iteration_callback=iteration_callback)
end_time = time.perf_counter()
iteration_stats = [] print(f"Routing took {end_time - start_time:.4f}s")
def iteration_callback(idx, current_results):
successes = sum(1 for r in current_results.values() if r.is_valid)
total_collisions = sum(r.collisions for r in current_results.values())
total_nodes = metrics.nodes_expanded
print(f" Iteration {idx} finished. Successes: {successes}/{len(netlist)}, Collisions: {total_collisions}")
# Adaptive Greediness: Decay from 1.5 to 1.1 over 10 iterations
new_greedy = max(1.1, 1.5 - ((idx + 1) / 10.0) * 0.4)
evaluator.greedy_h_weight = new_greedy
print(f" Adaptive Greedy Weight for Next Iteration: {new_greedy:.3f}")
iteration_stats.append({
'Iteration': idx,
'Success': successes,
'Congestion': total_collisions,
'Nodes': total_nodes
})
metrics.reset_per_route()
t0 = time.perf_counter()
results = pf.route_all(netlist, net_widths, store_expanded=True, iteration_callback=iteration_callback, shuffle_nets=True, seed=42)
t1 = time.perf_counter()
print(f"Routing took {t1-t0:.4f}s")
# 4. Check Results
print("\n--- Iteration Summary ---") print("\n--- Iteration Summary ---")
print(f"{'Iter':<5} | {'Success':<8} | {'Congest':<8} | {'Nodes':<10}") print(f"{'Iter':<5} | {'Success':<8} | {'Congest':<8}")
print("-" * 40) print("-" * 30)
for s in iteration_stats: for stats in iteration_stats:
print(f"{s['Iteration']:<5} | {s['Success']:<8} | {s['Congestion']:<8} | {s['Nodes']:<10}") print(f"{stats['Iteration']:<5} | {stats['Success']:<8} | {stats['Congestion']:<8}")
success_count = sum(1 for res in results.values() if res.is_valid) success_count = sum(1 for result in run.results_by_net.values() if result.is_valid)
print(f"\nFinal: Routed {success_count}/{len(netlist)} nets successfully.") print(f"\nFinal: Routed {success_count}/{len(netlist)} nets successfully.")
for net_id, result in run.results_by_net.items():
for nid, res in results.items(): if not result.is_valid:
if not res.is_valid: print(f" FAILED: {net_id}, collisions={result.collisions}")
print(f" FAILED: {nid}, collisions={res.collisions}")
else: else:
print(f" {nid}: SUCCESS") print(f" {net_id}: SUCCESS")
# 5. Visualize
fig, ax = plot_routing_results(results, obstacles, bounds, netlist=netlist)
plot_danger_map(danger_map, ax=ax)
fig, ax = plot_routing_results(run.results_by_net, list(obstacles), bounds, netlist=netlist)
plot_expanded_nodes(list(run.expanded_nodes), ax=ax)
fig.savefig("examples/07_large_scale_routing.png") fig.savefig("examples/07_large_scale_routing.png")
print("Saved plot to examples/07_large_scale_routing.png") print("Saved plot to examples/07_large_scale_routing.png")
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -1,59 +1,61 @@
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.geometry.collision import CollisionEngine from inire import CongestionOptions, NetSpec, ObjectiveWeights, RoutingOptions, RoutingProblem, RoutingResult, SearchOptions, route
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results from inire.utils.visualization import plot_routing_results
def _route_with_context( def _run_request(
context: AStarContext, bounds: tuple[float, float, float, float],
metrics: AStarMetrics, bend_collision_type: object,
netlist: dict[str, tuple[Port, Port]], net_id: str,
net_widths: dict[str, float], start: Port,
) -> dict[str, object]: target: Port,
return PathFinder(context, metrics, use_tiered_strategy=False).route_all(netlist, net_widths) ) -> dict[str, RoutingResult]:
problem = RoutingProblem(
bounds=bounds,
nets=(NetSpec(net_id, start, target, width=2.0),),
)
options = RoutingOptions(
search=SearchOptions(
bend_radii=(10.0,),
bend_collision_type=bend_collision_type,
sbend_radii=(),
),
objective=ObjectiveWeights(
bend_penalty=50.0,
sbend_penalty=150.0,
),
congestion=CongestionOptions(use_tiered_strategy=False),
)
return route(problem, options=options).results_by_net
def main() -> None: def main() -> None:
print("Running Example 08: Custom Bend Geometry...") print("Running Example 08: Custom Bend Geometry...")
# 1. Setup Environment
bounds = (0, 0, 150, 150) bounds = (0, 0, 150, 150)
start = Port(20, 20, 0)
target = Port(100, 100, 90)
# 2. Define Netlist
netlist = {
"custom_bend": (Port(20, 20, 0), Port(100, 100, 90)),
}
net_widths = {"custom_bend": 2.0}
def build_context(bend_collision_type: object = "arc") -> tuple[AStarContext, AStarMetrics]:
engine = CollisionEngine(clearance=2.0)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute([])
evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0)
return AStarContext(evaluator, bend_radii=[10.0], bend_collision_type=bend_collision_type, sbend_radii=[]), AStarMetrics()
# 3. Route with standard arc first
print("Routing with standard arc...") print("Routing with standard arc...")
context_std, metrics_std = build_context() results_std = _run_request(bounds, "arc", "custom_bend", start, target)
results_std = _route_with_context(context_std, metrics_std, netlist, net_widths)
# 4. Define a custom Manhattan 90-degree bend proxy in bend-local coordinates.
# The polygon origin is the bend center. It is mirrored for CW bends and
# rotated with the bend orientation before being translated into place.
custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) custom_poly = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)])
print("Routing with custom bend geometry...") print("Routing with custom bend geometry...")
context_custom, metrics_custom = build_context(custom_poly) results_custom = _run_request(bounds, custom_poly, "custom_model", start, target)
results_custom = _route_with_context(context_custom, metrics_custom, {"custom_model": netlist["custom_bend"]}, {"custom_model": 2.0})
# 5. Visualize
all_results = {**results_std, **results_custom} all_results = {**results_std, **results_custom}
fig, ax = plot_routing_results(all_results, [], bounds, netlist=netlist) fig, _ax = plot_routing_results(
all_results,
[],
bounds,
netlist={
"custom_bend": (start, target),
"custom_model": (start, target),
},
)
fig.savefig("examples/08_custom_bend_geometry.png") fig.savefig("examples/08_custom_bend_geometry.png")
print("Saved plot to examples/08_custom_bend_geometry.png") print("Saved plot to examples/08_custom_bend_geometry.png")

View file

@ -1,58 +1,46 @@
from inire.geometry.collision import CollisionEngine
from inire.geometry.primitives import Port
from inire.router.astar import AStarContext, AStarMetrics
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
from inire.router.pathfinder import PathFinder
from inire.utils.visualization import plot_routing_results
from shapely.geometry import box from shapely.geometry import box
from inire import CongestionOptions, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, route
from inire.utils.visualization import plot_routing_results
def main() -> None: def main() -> None:
print("Running Example 09: Best-Effort Under Tight Search Budget...") print("Running Example 09: Best-Effort Under Tight Search Budget...")
# 1. Setup Environment
bounds = (0, 0, 100, 100) bounds = (0, 0, 100, 100)
engine = CollisionEngine(clearance=2.0)
# A small obstacle cluster keeps the partial route visually interesting.
obstacles = [ obstacles = [
box(35, 35, 45, 65), box(35, 35, 45, 65),
box(55, 35, 65, 65), box(55, 35, 65, 65),
] ]
for obs in obstacles: problem = RoutingProblem(
engine.add_static_obstacle(obs) bounds=bounds,
nets=(NetSpec("budget_limited_net", Port(10, 50, 0), Port(85, 60, 180), width=2.0),),
static_obstacles=tuple(obstacles),
)
options = RoutingOptions(
search=SearchOptions(
node_limit=3,
bend_radii=(10.0,),
),
objective=ObjectiveWeights(
bend_penalty=50.0,
sbend_penalty=150.0,
),
congestion=CongestionOptions(warm_start=None),
)
danger_map = DangerMap(bounds=bounds)
danger_map.precompute(obstacles)
evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0)
# Keep the search budget intentionally tiny so the router returns a partial path.
context = AStarContext(evaluator, node_limit=3, bend_radii=[10.0])
metrics = AStarMetrics()
pf = PathFinder(context, metrics, warm_start=None)
# 2. Define Netlist: reaching the target requires additional turns the search budget cannot afford.
netlist = {
"budget_limited_net": (Port(10, 50, 0), Port(85, 60, 180)),
}
net_widths = {"budget_limited_net": 2.0}
# 3. Route
print("Routing with a deliberately tiny node budget (should return a partial path)...") print("Routing with a deliberately tiny node budget (should return a partial path)...")
results = pf.route_all(netlist, net_widths) run = route(problem, options=options)
result = run.results_by_net["budget_limited_net"]
# 4. Check Results if not result.reached_target:
res = results["budget_limited_net"] print(f"Target not reached as expected. Partial path length: {len(result.path)} segments.")
if not res.reached_target:
print(f"Target not reached as expected. Partial path length: {len(res.path)} segments.")
else: else:
print("The route unexpectedly reached the target. Increase difficulty or reduce the node budget further.") print("The route unexpectedly reached the target. Increase difficulty or reduce the node budget further.")
# 5. Visualize fig, _ax = plot_routing_results(run.results_by_net, list(obstacles), bounds, netlist={"budget_limited_net": (Port(10, 50, 0), Port(85, 60, 180))})
fig, ax = plot_routing_results(results, obstacles, bounds, netlist=netlist)
fig.savefig("examples/09_unroutable_best_effort.png") fig.savefig("examples/09_unroutable_best_effort.png")
print("Saved plot to examples/09_unroutable_best_effort.png") print("Saved plot to examples/09_unroutable_best_effort.png")
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View file

@ -1,8 +1,43 @@
""" """
inire Wave-router inire Wave-router
""" """
from .api 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.primitives import Port as Port # noqa: PLC0414
from .geometry.components import Straight as Straight, Bend90 as Bend90, SBend as SBend # 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
__author__ = 'Jan Petykiewicz' __author__ = 'Jan Petykiewicz'
__version__ = '0.1' __version__ = '0.1'
__all__ = [
"Bend90",
"CongestionOptions",
"DiagnosticsOptions",
"LockedRoute",
"NetSpec",
"ObjectiveWeights",
"Port",
"RefinementOptions",
"RoutingOptions",
"RoutingProblem",
"RoutingReport",
"RoutingResult",
"RoutingRunResult",
"RouteMetrics",
"SBend",
"SearchOptions",
"Straight",
"route",
]

97
inire/api.py Normal file
View file

@ -0,0 +1,97 @@
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

@ -3,7 +3,7 @@ Centralized constants for the inire routing engine.
""" """
# Search Grid Snap (5.0 µm default) # Search Grid Snap (5.0 µm default)
# TODO: Make this configurable in RouterConfig and define tolerances relative to the grid. # TODO: Make this configurable in SearchOptions and define tolerances relative to the grid.
DEFAULT_SEARCH_GRID_SNAP_UM = 5.0 DEFAULT_SEARCH_GRID_SNAP_UM = 5.0
# Tolerances # Tolerances

View file

@ -3,67 +3,69 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
import numpy import numpy
from shapely.geometry import LineString, box
from inire.geometry.collision_query_checker import CollisionQueryChecker from inire.geometry.component_overlap import components_overlap
from inire.geometry.dynamic_congestion_checker import DynamicCongestionChecker
from inire.geometry.dynamic_path_index import DynamicPathIndex from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.path_verifier import PathVerificationReport, PathVerifier from inire.geometry.index_helpers import grid_cell_span
from inire.geometry.ray_caster import RayCaster
from inire.geometry.static_obstacle_index import StaticObstacleIndex from inire.geometry.static_obstacle_index import StaticObstacleIndex
from inire.geometry.static_move_checker import StaticMoveChecker from inire.router.results import RoutingReport
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable from collections.abc import Iterable, Sequence
from shapely.geometry import Polygon from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
from shapely.strtree import STRtree from shapely.strtree import STRtree
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
class CollisionEngine: def _intersection_distance(origin: Port, geometry: BaseGeometry) -> float:
if hasattr(geometry, "geoms"):
return min(_intersection_distance(origin, sub_geometry) for sub_geometry in geometry.geoms)
return float(numpy.sqrt((geometry.coords[0][0] - origin.x) ** 2 + (geometry.coords[0][1] - origin.y) ** 2))
class RoutingWorld:
""" """
Manages spatial queries for collision detection with unified dilation logic. Internal spatial state for collision detection, congestion, and verification.
""" """
__slots__ = ( __slots__ = (
'clearance', 'max_net_width', 'safety_zone_radius', "clearance",
'metrics', 'grid_cell_size', '_inv_grid_cell_size', '_dynamic_bounds_array', "max_net_width",
'_path_verifier', '_dynamic_paths', '_static_obstacles', '_ray_caster', '_static_move_checker', "safety_zone_radius",
'_dynamic_congestion_checker', '_collision_query_checker', "metrics",
"grid_cell_size",
"_dynamic_paths",
"_static_obstacles",
) )
def __init__( def __init__(
self, self,
clearance: float, clearance: float,
max_net_width: float = 2.0, max_net_width: float = 2.0,
safety_zone_radius: float = 0.0021, safety_zone_radius: float = 0.0021,
) -> None: ) -> None:
self.clearance = clearance self.clearance = clearance
self.max_net_width = max_net_width self.max_net_width = max_net_width
self.safety_zone_radius = safety_zone_radius self.safety_zone_radius = safety_zone_radius
self.grid_cell_size = 50.0 self.grid_cell_size = 50.0
self._inv_grid_cell_size = 1.0 / self.grid_cell_size
self._static_obstacles = StaticObstacleIndex(self) self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_bounds_array = numpy.array([], dtype=numpy.float64).reshape(0, 4)
self._dynamic_paths = DynamicPathIndex(self) self._dynamic_paths = DynamicPathIndex(self)
self.metrics = { self.metrics = {
'static_cache_hits': 0, "static_cache_hits": 0,
'static_grid_skips': 0, "static_grid_skips": 0,
'static_tree_queries': 0, "static_tree_queries": 0,
'static_straight_fast': 0, "static_straight_fast": 0,
'congestion_grid_skips': 0, "congestion_grid_skips": 0,
'congestion_tree_queries': 0, "congestion_tree_queries": 0,
'safety_zone_checks': 0 "safety_zone_checks": 0,
} }
self._path_verifier = PathVerifier(self)
self._ray_caster = RayCaster(self)
self._static_move_checker = StaticMoveChecker(self)
self._dynamic_congestion_checker = DynamicCongestionChecker(self)
self._collision_query_checker = CollisionQueryChecker(self)
def get_static_version(self) -> int: def get_static_version(self) -> int:
return self._static_obstacles.version return self._static_obstacles.version
@ -89,23 +91,22 @@ class CollisionEngine:
return self._dynamic_paths.geometries.values() return self._dynamic_paths.geometries.values()
def reset_metrics(self) -> None: def reset_metrics(self) -> None:
for k in self.metrics: for key in self.metrics:
self.metrics[k] = 0 self.metrics[key] = 0
def get_metrics_summary(self) -> str: def get_metrics_summary(self) -> str:
m = self.metrics metrics = self.metrics
return (f"Collision Performance: \n" return (
f" Static: {m['static_tree_queries']} checks\n" "Collision Performance: \n"
f" Congestion: {m['congestion_tree_queries']} checks\n" f" Static: {metrics['static_tree_queries']} checks\n"
f" Safety Zone: {m['safety_zone_checks']} full intersections performed") 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: def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry) return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
def remove_static_obstacle(self, obj_id: int) -> None: def remove_static_obstacle(self, obj_id: int) -> None:
"""
Remove a static obstacle by ID.
"""
self._static_obstacles.remove_obstacle(obj_id) self._static_obstacles.remove_obstacle(obj_id)
def _invalidate_static_caches(self) -> None: def _invalidate_static_caches(self) -> None:
@ -115,9 +116,6 @@ class CollisionEngine:
self._static_obstacles.ensure_tree() self._static_obstacles.ensure_tree()
def _ensure_net_static_tree(self, net_width: float) -> STRtree: def _ensure_net_static_tree(self, net_width: float) -> STRtree:
"""
Lazily generate a tree where obstacles are dilated by (net_width/2 + clearance).
"""
return self._static_obstacles.ensure_net_tree(net_width) return self._static_obstacles.ensure_net_tree(net_width)
def _ensure_static_raw_tree(self) -> None: def _ensure_static_raw_tree(self) -> None:
@ -125,7 +123,6 @@ class CollisionEngine:
def _ensure_dynamic_tree(self) -> None: def _ensure_dynamic_tree(self) -> None:
self._dynamic_paths.ensure_tree() self._dynamic_paths.ensure_tree()
self._dynamic_bounds_array = self._dynamic_paths.bounds_array
def _ensure_dynamic_grid(self) -> None: def _ensure_dynamic_grid(self) -> None:
self._dynamic_paths.ensure_grid() self._dynamic_paths.ensure_grid()
@ -134,45 +131,28 @@ class CollisionEngine:
self._dynamic_paths.tree = None self._dynamic_paths.tree = None
self._ensure_dynamic_tree() self._ensure_dynamic_tree()
def add_path(self, net_id: str, geometry: list[Polygon], dilated_geometry: list[Polygon] | None = None) -> None: 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) self._dynamic_paths.add_path(net_id, geometry, dilated_geometry=dilated_geometry)
def remove_path(self, net_id: str) -> None: def remove_path(self, net_id: str) -> None:
self._dynamic_paths.remove_path(net_id) self._dynamic_paths.remove_path(net_id)
def lock_net(self, net_id: str) -> None:
""" Convert a routed net into static obstacles. """
self._dynamic_paths.lock_net(net_id)
def unlock_net(self, net_id: str) -> None:
self._dynamic_paths.unlock_net(net_id)
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool: def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
return self._static_move_checker.check_move_straight_static(start_port, length, net_width) 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
def _is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool: def _is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool:
return self._static_move_checker.is_in_safety_zone_fast(idx, start_port, end_port) bounds = self._static_obstacles.bounds_array[idx]
safety_zone = self.safety_zone_radius
def check_move_static( if start_port and bounds[0] - safety_zone <= start_port.x <= bounds[2] + safety_zone and bounds[1] - safety_zone <= start_port.y <= bounds[3] + safety_zone:
self, return True
result: ComponentResult, return bool(
start_port: Port | None = None, end_port
end_port: Port | None = None, and bounds[0] - safety_zone <= end_port.x <= bounds[2] + safety_zone
net_width: float | None = None, and bounds[1] - safety_zone <= end_port.y <= bounds[3] + safety_zone
) -> bool:
return self._static_move_checker.check_move_static(
result,
start_port=start_port,
end_port=end_port,
net_width=net_width,
) )
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
return self._dynamic_congestion_checker.check_move_congestion(result, net_id)
def _check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
return self._dynamic_congestion_checker.check_real_congestion(result, net_id)
def _is_in_safety_zone( def _is_in_safety_zone(
self, self,
geometry: Polygon, geometry: Polygon,
@ -180,7 +160,247 @@ class CollisionEngine:
start_port: Port | None, start_port: Port | None,
end_port: Port | None, end_port: Port | None,
) -> bool: ) -> bool:
return self._static_move_checker.is_in_safety_zone(geometry, obj_id, start_port, end_port) raw_obstacle = self._static_obstacles.geometries[obj_id]
safety_zone = self.safety_zone_radius
obstacle_bounds = raw_obstacle.bounds
near_start = start_port and (
obstacle_bounds[0] - safety_zone <= start_port.x <= obstacle_bounds[2] + safety_zone
and obstacle_bounds[1] - safety_zone <= start_port.y <= obstacle_bounds[3] + safety_zone
)
near_end = end_port and (
obstacle_bounds[0] - safety_zone <= end_port.x <= obstacle_bounds[2] + safety_zone
and obstacle_bounds[1] - safety_zone <= end_port.y <= obstacle_bounds[3] + safety_zone
)
if not near_start and not near_end:
return False
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
ix_bounds = intersection.bounds
if (
start_port
and near_start
and abs(ix_bounds[0] - start_port.x) < safety_zone
and abs(ix_bounds[1] - start_port.y) < safety_zone
and abs(ix_bounds[2] - start_port.x) < safety_zone
and abs(ix_bounds[3] - start_port.y) < safety_zone
):
return True
return bool(
end_port
and near_end
and abs(ix_bounds[0] - end_port.x) < safety_zone
and abs(ix_bounds[1] - end_port.y) < safety_zone
and abs(ix_bounds[2] - end_port.x) < safety_zone
and abs(ix_bounds[3] - end_port.y) < safety_zone
)
def check_move_static(
self,
result: ComponentResult,
start_port: Port | None = None,
end_port: Port | None = None,
net_width: float | None = None,
) -> bool:
del net_width
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))
if hits.size == 0:
return False
static_bounds = static_obstacles.bounds_array
move_poly_bounds = result.dilated_bounds
for hit_idx in hits:
obstacle_bounds = static_bounds[hit_idx]
poly_hits_obstacle_aabb = False
for poly_bounds in move_poly_bounds:
if (
poly_bounds[0] < obstacle_bounds[2]
and poly_bounds[2] > obstacle_bounds[0]
and poly_bounds[1] < obstacle_bounds[3]
and poly_bounds[3] > obstacle_bounds[1]
):
poly_hits_obstacle_aabb = True
break
if not poly_hits_obstacle_aabb:
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self._is_in_safety_zone_fast(hit_idx, start_port, end_port):
collision_found = False
for polygon in result.collision_geometry:
if not self._is_in_safety_zone(polygon, obj_id, start_port, end_port):
collision_found = True
break
if collision_found:
return True
continue
static_obstacle = static_obstacles.dilated[obj_id]
for polygon in result.dilated_collision_geometry:
if polygon.intersects(static_obstacle) and not polygon.touches(static_obstacle):
return True
return False
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
total_bounds = result.total_dilated_bounds
dynamic_bounds = dynamic_paths.bounds_array
possible_total = (
(total_bounds[0] < dynamic_bounds[:, 2])
& (total_bounds[2] > dynamic_bounds[:, 0])
& (total_bounds[1] < dynamic_bounds[:, 3])
& (total_bounds[3] > dynamic_bounds[:, 1])
)
valid_hits_mask = dynamic_paths.net_ids_array != net_id
if not numpy.any(possible_total & valid_hits_mask):
return 0
geometries_to_test = result.dilated_collision_geometry
res_indices, tree_indices = dynamic_paths.tree.query(geometries_to_test, predicate="intersects")
if tree_indices.size == 0:
return 0
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
unique_other_nets = numpy.unique(hit_net_ids[hit_net_ids != net_id])
if unique_other_nets.size == 0:
return 0
tree_geometries = dynamic_paths.tree.geometries
real_hits_count = 0
for other_net_id in unique_other_nets:
other_mask = hit_net_ids == other_net_id
sub_tree_indices = tree_indices[other_mask]
sub_res_indices = res_indices[other_mask]
found_real = False
for index in range(len(sub_tree_indices)):
test_geometry = geometries_to_test[sub_res_indices[index]]
tree_geometry = tree_geometries[sub_tree_indices[index]]
if not test_geometry.touches(tree_geometry) and test_geometry.intersection(tree_geometry).area > 1e-7:
found_real = True
break
if found_real:
real_hits_count += 1
return real_hits_count
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.geometries:
return 0
total_bounds = result.total_dilated_bounds
self._ensure_dynamic_grid()
dynamic_grid = dynamic_paths.grid
if not dynamic_grid:
return 0
gx_min, gy_min, gx_max, gy_max = grid_cell_span(total_bounds, self.grid_cell_size)
if gx_min == gx_max and gy_min == gy_max:
cell = (gx_min, gy_min)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_paths.geometries[obj_id][0] != net_id:
return self._check_real_congestion(result, net_id)
return 0
any_possible = False
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
cell = (gx, gy)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_paths.geometries[obj_id][0] != net_id:
any_possible = True
break
if any_possible:
break
if any_possible:
break
if not any_possible:
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( def check_collision(
self, self,
@ -193,16 +413,16 @@ class CollisionEngine:
bounds: tuple[float, float, float, float] | None = None, bounds: tuple[float, float, float, float] | None = None,
net_width: float | None = None, net_width: float | None = None,
) -> bool | int: ) -> bool | int:
return self._collision_query_checker.check_collision( del bounds, net_width
geometry,
net_id, if buffer_mode == "static":
buffer_mode=buffer_mode, return self._check_static_collision(
start_port=start_port, geometry,
end_port=end_port, start_port=start_port,
dilated_geometry=dilated_geometry, end_port=end_port,
bounds=bounds, dilated_geometry=dilated_geometry,
net_width=net_width, )
) return self._check_dynamic_collision(geometry, net_id, dilated_geometry=dilated_geometry)
def is_collision( def is_collision(
self, self,
@ -212,7 +432,6 @@ class CollisionEngine:
start_port: Port | None = None, start_port: Port | None = None,
end_port: Port | None = None, end_port: Port | None = None,
) -> bool: ) -> bool:
""" Unified entry point for static collision checks. """
result = self.check_collision( result = self.check_collision(
geometry, geometry,
net_id, net_id,
@ -223,12 +442,157 @@ class CollisionEngine:
) )
return bool(result) return bool(result)
def verify_path_report(self, net_id: str, components: list[ComponentResult]) -> PathVerificationReport: def verify_path_report(self, net_id: str, components: Sequence[ComponentResult]) -> RoutingReport:
return self._path_verifier.verify_path_report(net_id, components) static_collision_count = 0
dynamic_collision_count = 0
self_collision_count = 0
total_length = sum(component.length for component in components)
def verify_path(self, net_id: str, components: list[ComponentResult]) -> tuple[bool, int]: static_obstacles = self._static_obstacles
dynamic_paths = self._dynamic_paths
self._ensure_static_raw_tree()
if static_obstacles.raw_tree is not None:
raw_geometries = static_obstacles.raw_tree.geometries
for component in components:
for polygon in component.physical_geometry:
buffered = polygon.buffer(self.clearance, join_style=2)
hits = static_obstacles.raw_tree.query(buffered, predicate="intersects")
for hit_idx in hits:
obstacle = raw_geometries[hit_idx]
if buffered.touches(obstacle):
continue
obj_id = static_obstacles.raw_obj_ids[hit_idx]
if not self._is_in_safety_zone(polygon, obj_id, None, None):
static_collision_count += 1
self._ensure_dynamic_tree()
if dynamic_paths.tree is not None:
tree_geometries = dynamic_paths.tree.geometries
for component in components:
test_geometries = component.dilated_physical_geometry
res_indices, tree_indices = dynamic_paths.tree.query(test_geometries, predicate="intersects")
if tree_indices.size == 0:
continue
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
component_hits = []
for index in range(len(tree_indices)):
if hit_net_ids[index] == str(net_id):
continue
new_geometry = test_geometries[res_indices[index]]
tree_geometry = tree_geometries[tree_indices[index]]
if not new_geometry.touches(tree_geometry) and new_geometry.intersection(tree_geometry).area > 1e-7:
component_hits.append(hit_net_ids[index])
if component_hits:
dynamic_collision_count += len(numpy.unique(component_hits))
for index, component in enumerate(components):
for other_index in range(index + 2, len(components)):
if components_overlap(component, components[other_index], prefer_actual=True):
self_collision_count += 1
return RoutingReport(
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=self_collision_count,
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) report = self.verify_path_report(net_id, components)
return report.is_valid, report.collision_count return report.is_valid, report.collision_count
def ray_cast(self, origin: Port, angle_deg: float, max_dist: float = 2000.0, net_width: float | None = None) -> float: def ray_cast(
return self._ray_caster.ray_cast(origin, angle_deg, max_dist=max_dist, net_width=net_width) self,
origin: Port,
angle_deg: float,
max_dist: float = 2000.0,
net_width: float | None = None,
) -> float:
static_obstacles = self._static_obstacles
radians = numpy.radians(angle_deg)
cos_v, sin_v = numpy.cos(radians), numpy.sin(radians)
dx, dy = max_dist * cos_v, max_dist * sin_v
min_x, max_x = sorted([origin.x, origin.x + dx])
min_y, max_y = sorted([origin.y, origin.y + dy])
if net_width is not None:
tree = self._ensure_net_static_tree(net_width)
key = (round(net_width, 4), round(self.clearance, 4))
is_rect_array = static_obstacles.net_specific_is_rect[key]
bounds_array = static_obstacles.net_specific_bounds[key]
else:
self._ensure_static_tree()
tree = static_obstacles.tree
is_rect_array = static_obstacles.is_rect_array
bounds_array = static_obstacles.bounds_array
if tree is None:
return max_dist
candidates = tree.query(box(min_x, min_y, max_x, max_y))
if candidates.size == 0:
return max_dist
min_dist = max_dist
inv_dx = 1.0 / dx if abs(dx) > 1e-12 else 1e30
inv_dy = 1.0 / dy if abs(dy) > 1e-12 else 1e30
tree_geometries = tree.geometries
ray_line = None
candidates_bounds = bounds_array[candidates]
dist_sq = (candidates_bounds[:, 0] - origin.x) ** 2 + (candidates_bounds[:, 1] - origin.y) ** 2
sorted_indices = numpy.argsort(dist_sq)
for idx in sorted_indices:
candidate_id = candidates[idx]
bounds = bounds_array[candidate_id]
if abs(dx) < 1e-12:
if origin.x < bounds[0] or origin.x > bounds[2]:
tx_min, tx_max = 1e30, -1e30
else:
tx_min, tx_max = -1e30, 1e30
else:
t1, t2 = (bounds[0] - origin.x) * inv_dx, (bounds[2] - origin.x) * inv_dx
tx_min, tx_max = min(t1, t2), max(t1, t2)
if abs(dy) < 1e-12:
if origin.y < bounds[1] or origin.y > bounds[3]:
ty_min, ty_max = 1e30, -1e30
else:
ty_min, ty_max = -1e30, 1e30
else:
t1, t2 = (bounds[1] - origin.y) * inv_dy, (bounds[3] - origin.y) * inv_dy
ty_min, ty_max = min(t1, t2), max(t1, t2)
t_min, t_max = max(tx_min, ty_min), min(tx_max, ty_max)
if t_max < 0 or t_min > t_max or t_min > 1.0:
continue
if t_min * max_dist >= min_dist:
continue
if is_rect_array[candidate_id]:
min_dist = max(0.0, t_min * max_dist)
continue
if ray_line is None:
ray_line = LineString([(origin.x, origin.y), (origin.x + dx, origin.y + dy)])
obstacle = tree_geometries[candidate_id]
if not obstacle.intersects(ray_line):
continue
intersection = ray_line.intersection(obstacle)
if intersection.is_empty:
continue
distance = _intersection_distance(origin, intersection)
min_dist = min(min_dist, distance)
return min_dist

View file

@ -1,97 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal
import numpy
if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire.geometry.collision import CollisionEngine
from inire.geometry.primitives import Port
class CollisionQueryChecker:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
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 _check_static_collision(
self,
geometry: Polygon,
start_port: Port | None = None,
end_port: Port | None = None,
dilated_geometry: Polygon | None = None,
) -> bool:
engine = self.engine
static_obstacles = engine._static_obstacles
engine._ensure_static_tree()
if static_obstacles.tree is None:
return False
if dilated_geometry is not None:
test_geometry = dilated_geometry
else:
distance = engine.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 engine._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:
engine = self.engine
dynamic_paths = engine._dynamic_paths
engine._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
test_geometry = dilated_geometry if dilated_geometry else geometry.buffer(engine.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))

View file

@ -9,9 +9,9 @@ if TYPE_CHECKING:
def component_polygons(component: ComponentResult, prefer_actual: bool = False) -> list[Polygon]: def component_polygons(component: ComponentResult, prefer_actual: bool = False) -> list[Polygon]:
if prefer_actual and component.actual_geometry is not None: if prefer_actual:
return component.actual_geometry return list(component.physical_geometry)
return component.geometry return list(component.collision_geometry)
def component_bounds(component: ComponentResult, prefer_actual: bool = False) -> tuple[float, float, float, float]: def component_bounds(component: ComponentResult, prefer_actual: bool = False) -> tuple[float, float, float, float]:

View file

@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass, field
from typing import Literal from typing import Literal
import numpy import numpy
@ -12,61 +13,52 @@ from inire.constants import TOLERANCE_ANGULAR
from .primitives import Port, rotation_matrix2 from .primitives import Port, rotation_matrix2
MoveKind = Literal["straight", "bend90", "sbend"]
BendCollisionModelName = Literal["arc", "bbox", "clipped_bbox"]
BendCollisionModel = BendCollisionModelName | Polygon
def _normalize_length(value: float) -> float: def _normalize_length(value: float) -> float:
return float(value) return float(value)
@dataclass(frozen=True, slots=True)
class ComponentResult: class ComponentResult:
__slots__ = ( start_port: Port
"start_port", collision_geometry: tuple[Polygon, ...]
"geometry", end_port: Port
"dilated_geometry", length: float
"proxy_geometry", move_type: MoveKind
"actual_geometry", physical_geometry: tuple[Polygon, ...]
"dilated_actual_geometry", dilated_collision_geometry: tuple[Polygon, ...]
"end_port", dilated_physical_geometry: tuple[Polygon, ...]
"length", _bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
"move_type", _total_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
"_bounds", _dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
"_total_bounds", _total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
"_dilated_bounds",
"_total_dilated_bounds",
)
def __init__( def __post_init__(self) -> None:
self, collision_geometry = tuple(self.collision_geometry)
start_port: Port, physical_geometry = tuple(self.physical_geometry)
geometry: list[Polygon], dilated_collision_geometry = tuple(self.dilated_collision_geometry)
end_port: Port, dilated_physical_geometry = tuple(self.dilated_physical_geometry)
length: float,
move_type: str,
dilated_geometry: list[Polygon] | None = None,
proxy_geometry: list[Polygon] | None = None,
actual_geometry: list[Polygon] | None = None,
dilated_actual_geometry: list[Polygon] | None = None,
) -> None:
self.start_port = start_port
self.geometry = geometry
self.dilated_geometry = dilated_geometry
self.proxy_geometry = proxy_geometry
self.actual_geometry = actual_geometry
self.dilated_actual_geometry = dilated_actual_geometry
self.end_port = end_port
self.length = float(length)
self.move_type = move_type
self._bounds = [poly.bounds for poly in self.geometry] object.__setattr__(self, "collision_geometry", collision_geometry)
self._total_bounds = _combine_bounds(self._bounds) object.__setattr__(self, "physical_geometry", physical_geometry)
object.__setattr__(self, "dilated_collision_geometry", dilated_collision_geometry)
object.__setattr__(self, "dilated_physical_geometry", dilated_physical_geometry)
object.__setattr__(self, "length", float(self.length))
if self.dilated_geometry is None: bounds = tuple(poly.bounds for poly in collision_geometry)
self._dilated_bounds = None object.__setattr__(self, "_bounds", bounds)
self._total_dilated_bounds = None object.__setattr__(self, "_total_bounds", _combine_bounds(list(bounds)))
else:
self._dilated_bounds = [poly.bounds for poly in self.dilated_geometry] dilated_bounds = tuple(poly.bounds for poly in dilated_collision_geometry)
self._total_dilated_bounds = _combine_bounds(self._dilated_bounds) object.__setattr__(self, "_dilated_bounds", dilated_bounds)
object.__setattr__(self, "_total_dilated_bounds", _combine_bounds(list(dilated_bounds)))
@property @property
def bounds(self) -> list[tuple[float, float, float, float]]: def bounds(self) -> tuple[tuple[float, float, float, float], ...]:
return self._bounds return self._bounds
@property @property
@ -74,28 +66,23 @@ class ComponentResult:
return self._total_bounds return self._total_bounds
@property @property
def dilated_bounds(self) -> list[tuple[float, float, float, float]] | None: def dilated_bounds(self) -> tuple[tuple[float, float, float, float], ...]:
return self._dilated_bounds return self._dilated_bounds
@property @property
def total_dilated_bounds(self) -> tuple[float, float, float, float] | None: def total_dilated_bounds(self) -> tuple[float, float, float, float]:
return self._total_dilated_bounds return self._total_dilated_bounds
def translate(self, dx: int | float, dy: int | float) -> ComponentResult: def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
return ComponentResult( return ComponentResult(
start_port=self.start_port + [dx, dy, 0], start_port=self.start_port.translate(dx, dy),
geometry=[shapely_translate(poly, dx, dy) for poly in self.geometry], collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.collision_geometry],
end_port=self.end_port + [dx, dy, 0], end_port=self.end_port.translate(dx, dy),
length=self.length, length=self.length,
move_type=self.move_type, move_type=self.move_type,
dilated_geometry=None if self.dilated_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.dilated_geometry], physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.physical_geometry],
proxy_geometry=None if self.proxy_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.proxy_geometry], dilated_collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_collision_geometry],
actual_geometry=None if self.actual_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.actual_geometry], dilated_physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_physical_geometry],
dilated_actual_geometry=(
None
if self.dilated_actual_geometry is None
else [shapely_translate(poly, dx, dy) for poly in self.dilated_actual_geometry]
),
) )
@ -144,16 +131,13 @@ def _get_arc_polygons(
return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))] return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))]
def _clip_bbox(cxy: tuple[float, float], radius: float, width: float, ts: tuple[float, float], clip_margin: float) -> Polygon: def _clip_bbox(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 8-point polygonal proxy for the arc.
The polygon uses 4 points along the outer edge and 4 along the inner edge. 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 The outer edge is a circumscribed polyline and the inner edge is an
inscribed polyline, so the result conservatively contains the true arc. inscribed polyline, so the result conservatively contains the true arc.
`clip_margin` is kept for API compatibility but is not used by this proxy.
""" """
del clip_margin
cx, cy = cxy cx, cy = cxy
sample_count = 4 sample_count = 4
angle_span = abs(float(ts[1]) - float(ts[0])) angle_span = abs(float(ts[1]) - float(ts[0]))
@ -194,11 +178,10 @@ def _transform_custom_collision_polygon(
def _apply_collision_model( def _apply_collision_model(
arc_poly: Polygon, arc_poly: Polygon,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon, collision_type: BendCollisionModel,
radius: float, radius: float,
width: float, width: float,
cxy: tuple[float, float], cxy: tuple[float, float],
clip_margin: float,
ts: tuple[float, float], ts: tuple[float, float],
rotation_deg: float = 0.0, rotation_deg: float = 0.0,
mirror_y: bool = False, mirror_y: bool = False,
@ -208,7 +191,7 @@ def _apply_collision_model(
if collision_type == "arc": if collision_type == "arc":
return [arc_poly] return [arc_poly]
if collision_type == "clipped_bbox": if collision_type == "clipped_bbox":
clipped = _clip_bbox(cxy, radius, width, ts, clip_margin) clipped = _clip_bbox(cxy, radius, width, ts)
return [clipped if not clipped.is_empty else box(*arc_poly.bounds)] return [clipped if not clipped.is_empty else box(*arc_poly.bounds)]
return [box(*arc_poly.bounds)] return [box(*arc_poly.bounds)]
@ -231,7 +214,6 @@ class Straight:
poly_points = (pts @ rot2.T) + numpy.array((start_port.x, start_port.y)) poly_points = (pts @ rot2.T) + numpy.array((start_port.x, start_port.y))
geometry = [Polygon(poly_points)] geometry = [Polygon(poly_points)]
dilated_geometry = None
if dilation > 0: if dilation > 0:
half_w_d = half_w + dilation half_w_d = half_w + dilation
pts_d = numpy.array( pts_d = numpy.array(
@ -244,16 +226,18 @@ class Straight:
) )
poly_points_d = (pts_d @ rot2.T) + numpy.array((start_port.x, start_port.y)) poly_points_d = (pts_d @ rot2.T) + numpy.array((start_port.x, start_port.y))
dilated_geometry = [Polygon(poly_points_d)] dilated_geometry = [Polygon(poly_points_d)]
else:
dilated_geometry = geometry
return ComponentResult( return ComponentResult(
start_port=start_port, start_port=start_port,
geometry=geometry, collision_geometry=geometry,
end_port=end_port, end_port=end_port,
length=abs(length_f), length=abs(length_f),
move_type="Straight", move_type="straight",
dilated_geometry=dilated_geometry, physical_geometry=geometry,
actual_geometry=geometry, dilated_collision_geometry=dilated_geometry,
dilated_actual_geometry=dilated_geometry, dilated_physical_geometry=dilated_geometry,
) )
@ -265,8 +249,7 @@ class Bend90:
width: float, width: float,
direction: Literal["CW", "CCW"], direction: Literal["CW", "CCW"],
sagitta: float = 0.01, sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc", collision_type: BendCollisionModel = "arc",
clip_margin: float = 10.0,
dilation: float = 0.0, dilation: float = 0.0,
) -> ComponentResult: ) -> ComponentResult:
rot2 = rotation_matrix2(start_port.r) rot2 = rotation_matrix2(start_port.r)
@ -290,32 +273,18 @@ class Bend90:
radius, radius,
width, width,
(float(center_xy[0]), float(center_xy[1])), (float(center_xy[0]), float(center_xy[1])),
clip_margin,
ts, ts,
rotation_deg=float(start_port.r), rotation_deg=float(start_port.r),
mirror_y=(sign < 0), mirror_y=(sign < 0),
) )
proxy_geometry = None physical_geometry = collision_polys if uses_custom_geometry else arc_polys
if collision_type == "arc":
proxy_geometry = _apply_collision_model(
arc_polys[0],
"clipped_bbox",
radius,
width,
(float(center_xy[0]), float(center_xy[1])),
clip_margin,
ts,
)
dilated_actual_geometry = None
dilated_geometry = None
if dilation > 0: if dilation > 0:
if uses_custom_geometry: if uses_custom_geometry:
dilated_actual_geometry = [poly.buffer(dilation) for poly in collision_polys] dilated_physical_geometry = [poly.buffer(dilation) for poly in collision_polys]
dilated_geometry = dilated_actual_geometry dilated_collision_geometry = dilated_physical_geometry
else: else:
dilated_actual_geometry = _get_arc_polygons( dilated_physical_geometry = _get_arc_polygons(
(float(center_xy[0]), float(center_xy[1])), (float(center_xy[0]), float(center_xy[1])),
radius, radius,
width, width,
@ -323,18 +292,22 @@ class Bend90:
sagitta, sagitta,
dilation=dilation, dilation=dilation,
) )
dilated_geometry = dilated_actual_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys] 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
return ComponentResult( return ComponentResult(
start_port=start_port, start_port=start_port,
geometry=collision_polys, collision_geometry=collision_polys,
end_port=end_port, end_port=end_port,
length=abs(radius) * numpy.pi / 2.0, length=abs(radius) * numpy.pi / 2.0,
move_type="Bend90", move_type="bend90",
dilated_geometry=dilated_geometry, physical_geometry=physical_geometry,
proxy_geometry=proxy_geometry, dilated_collision_geometry=dilated_collision_geometry,
actual_geometry=collision_polys if uses_custom_geometry else arc_polys, dilated_physical_geometry=dilated_physical_geometry,
dilated_actual_geometry=dilated_actual_geometry,
) )
@ -346,8 +319,7 @@ class SBend:
radius: float, radius: float,
width: float, width: float,
sagitta: float = 0.01, sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc", collision_type: BendCollisionModel = "arc",
clip_margin: float = 10.0,
dilation: float = 0.0, dilation: float = 0.0,
) -> ComponentResult: ) -> ComponentResult:
if abs(offset) >= 2 * radius: if abs(offset) >= 2 * radius:
@ -383,7 +355,6 @@ class SBend:
radius, radius,
width, width,
(float(c1_xy[0]), float(c1_xy[1])), (float(c1_xy[0]), float(c1_xy[1])),
clip_margin,
ts1, ts1,
rotation_deg=float(start_port.r), rotation_deg=float(start_port.r),
mirror_y=(sign < 0), mirror_y=(sign < 0),
@ -394,41 +365,36 @@ class SBend:
radius, radius,
width, width,
(float(c2_xy[0]), float(c2_xy[1])), (float(c2_xy[0]), float(c2_xy[1])),
clip_margin,
ts2, ts2,
rotation_deg=float(start_port.r), rotation_deg=float(start_port.r),
mirror_y=(sign > 0), mirror_y=(sign > 0),
)[0], )[0],
] ]
proxy_geometry = None physical_geometry = geometry if uses_custom_geometry else actual_geometry
if collision_type == "arc":
proxy_geometry = [
_apply_collision_model(arc1, "clipped_bbox", radius, width, (float(c1_xy[0]), float(c1_xy[1])), clip_margin, ts1)[0],
_apply_collision_model(arc2, "clipped_bbox", radius, width, (float(c2_xy[0]), float(c2_xy[1])), clip_margin, ts2)[0],
]
dilated_actual_geometry = None
dilated_geometry = None
if dilation > 0: if dilation > 0:
if uses_custom_geometry: if uses_custom_geometry:
dilated_actual_geometry = [poly.buffer(dilation) for poly in geometry] dilated_physical_geometry = [poly.buffer(dilation) for poly in geometry]
dilated_geometry = dilated_actual_geometry dilated_collision_geometry = dilated_physical_geometry
else: else:
dilated_actual_geometry = [ dilated_physical_geometry = [
_get_arc_polygons((float(c1_xy[0]), float(c1_xy[1])), radius, width, ts1, sagitta, dilation=dilation)[0], _get_arc_polygons((float(c1_xy[0]), float(c1_xy[1])), radius, width, ts1, sagitta, dilation=dilation)[0],
_get_arc_polygons((float(c2_xy[0]), float(c2_xy[1])), radius, width, ts2, sagitta, dilation=dilation)[0], _get_arc_polygons((float(c2_xy[0]), float(c2_xy[1])), radius, width, ts2, sagitta, dilation=dilation)[0],
] ]
dilated_geometry = dilated_actual_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in geometry] 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
return ComponentResult( return ComponentResult(
start_port=start_port, start_port=start_port,
geometry=geometry, collision_geometry=geometry,
end_port=end_port, end_port=end_port,
length=2.0 * radius * theta, length=2.0 * radius * theta,
move_type="SBend", move_type="sbend",
dilated_geometry=dilated_geometry, physical_geometry=physical_geometry,
proxy_geometry=proxy_geometry, dilated_collision_geometry=dilated_collision_geometry,
actual_geometry=geometry if uses_custom_geometry else actual_geometry, dilated_physical_geometry=dilated_physical_geometry,
dilated_actual_geometry=dilated_actual_geometry,
) )

View file

@ -1,117 +0,0 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import numpy
if TYPE_CHECKING:
from inire.geometry.collision import CollisionEngine
from inire.geometry.components import ComponentResult
class DynamicCongestionChecker:
__slots__ = ("engine",)
def __init__(self, engine: CollisionEngine) -> None:
self.engine = engine
def check_move_congestion(self, result: ComponentResult, net_id: str) -> int:
engine = self.engine
dynamic_paths = engine._dynamic_paths
if not dynamic_paths.geometries:
return 0
total_bounds = result.total_dilated_bounds
if total_bounds is None:
return 0
engine._ensure_dynamic_grid()
dynamic_grid = dynamic_paths.grid
if not dynamic_grid:
return 0
cell_size_inv = engine._inv_grid_cell_size
gx_min = int(total_bounds[0] * cell_size_inv)
gy_min = int(total_bounds[1] * cell_size_inv)
gx_max = int(total_bounds[2] * cell_size_inv)
gy_max = int(total_bounds[3] * cell_size_inv)
dynamic_geometries = dynamic_paths.geometries
if gx_min == gx_max and gy_min == gy_max:
cell = (gx_min, gy_min)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_geometries[obj_id][0] != net_id:
return self.check_real_congestion(result, net_id)
return 0
any_possible = False
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
cell = (gx, gy)
if cell in dynamic_grid:
for obj_id in dynamic_grid[cell]:
if dynamic_geometries[obj_id][0] != net_id:
any_possible = True
break
if any_possible:
break
if any_possible:
break
if not any_possible:
return 0
return self.check_real_congestion(result, net_id)
def check_real_congestion(self, result: ComponentResult, net_id: str) -> int:
engine = self.engine
dynamic_paths = engine._dynamic_paths
engine.metrics["congestion_tree_queries"] += 1
engine._ensure_dynamic_tree()
if dynamic_paths.tree is None:
return 0
total_bounds = result.total_dilated_bounds
dynamic_bounds = engine._dynamic_bounds_array
possible_total = (
(total_bounds[0] < dynamic_bounds[:, 2])
& (total_bounds[2] > dynamic_bounds[:, 0])
& (total_bounds[1] < dynamic_bounds[:, 3])
& (total_bounds[3] > dynamic_bounds[:, 1])
)
valid_hits_mask = dynamic_paths.net_ids_array != net_id
if not numpy.any(possible_total & valid_hits_mask):
return 0
geoms_to_test = result.dilated_geometry if result.dilated_geometry else result.geometry
res_indices, tree_indices = dynamic_paths.tree.query(geoms_to_test, predicate="intersects")
if tree_indices.size == 0:
return 0
hit_net_ids = numpy.take(dynamic_paths.net_ids_array, tree_indices)
unique_other_nets = numpy.unique(hit_net_ids[hit_net_ids != net_id])
if unique_other_nets.size == 0:
return 0
tree_geometries = dynamic_paths.tree.geometries
real_hits_count = 0
for other_net_id in unique_other_nets:
other_mask = hit_net_ids == other_net_id
sub_tree_indices = tree_indices[other_mask]
sub_res_indices = res_indices[other_mask]
found_real = False
for index in range(len(sub_tree_indices)):
test_geometry = geoms_to_test[sub_res_indices[index]]
tree_geometry = tree_geometries[sub_tree_indices[index]]
if not test_geometry.touches(tree_geometry) and test_geometry.intersection(tree_geometry).area > 1e-7:
found_real = True
break
if found_real:
real_hits_count += 1
return real_hits_count

View file

@ -6,11 +6,14 @@ import numpy
import rtree import rtree
from shapely.strtree import STRtree from shapely.strtree import STRtree
if TYPE_CHECKING: from inire.geometry.index_helpers import build_index_payload, iter_grid_cells
from shapely.geometry import Polygon
from shapely.prepared import PreparedGeometry
from inire.geometry.collision import CollisionEngine if TYPE_CHECKING:
from collections.abc import Sequence
from shapely.geometry import Polygon
from inire.geometry.collision import RoutingWorld
class DynamicPathIndex: class DynamicPathIndex:
@ -19,47 +22,38 @@ class DynamicPathIndex:
"index", "index",
"geometries", "geometries",
"dilated", "dilated",
"prepared",
"tree", "tree",
"obj_ids", "obj_ids",
"grid", "grid",
"id_counter", "id_counter",
"tree_dirty",
"net_ids_array", "net_ids_array",
"bounds_array", "bounds_array",
"locked_nets",
) )
def __init__(self, engine: CollisionEngine) -> None: def __init__(self, engine: RoutingWorld) -> None:
self.engine = engine self.engine = engine
self.index = rtree.index.Index() self.index = rtree.index.Index()
self.geometries: dict[int, tuple[str, Polygon]] = {} self.geometries: dict[int, tuple[str, Polygon]] = {}
self.dilated: dict[int, Polygon] = {} self.dilated: dict[int, Polygon] = {}
self.prepared: dict[int, PreparedGeometry] = {}
self.tree: STRtree | None = None self.tree: STRtree | None = None
self.obj_ids: numpy.ndarray = numpy.array([], dtype=numpy.int32) self.obj_ids: numpy.ndarray = numpy.array([], dtype=numpy.int32)
self.grid: dict[tuple[int, int], list[int]] = {} self.grid: dict[tuple[int, int], list[int]] = {}
self.id_counter = 0 self.id_counter = 0
self.tree_dirty = True self.net_ids_array = numpy.array([], dtype=object)
self.net_ids_array = numpy.array([], dtype="<U32")
self.bounds_array = numpy.array([], dtype=numpy.float64).reshape(0, 4) self.bounds_array = numpy.array([], dtype=numpy.float64).reshape(0, 4)
self.locked_nets: set[str] = set()
def invalidate_queries(self) -> None: def invalidate_queries(self) -> None:
self.tree = None self.tree = None
self.grid = {} self.grid = {}
self.tree_dirty = True
def ensure_tree(self) -> None: def ensure_tree(self) -> None:
if self.tree is None and self.dilated: if self.tree is None and self.dilated:
ids = sorted(self.dilated.keys()) ids, geometries, bounds_array = build_index_payload(self.dilated)
geometries = [self.dilated[i] for i in ids]
self.tree = STRtree(geometries) self.tree = STRtree(geometries)
self.obj_ids = numpy.array(ids, dtype=numpy.int32) self.obj_ids = numpy.array(ids, dtype=numpy.int32)
self.bounds_array = numpy.array([geometry.bounds for geometry in geometries]) self.bounds_array = bounds_array
net_ids = [self.geometries[obj_id][0] for obj_id in self.obj_ids] net_ids = [self.geometries[obj_id][0] for obj_id in self.obj_ids]
self.net_ids_array = numpy.array(net_ids, dtype="<U32") self.net_ids_array = numpy.array(net_ids, dtype=object)
self.tree_dirty = False
def ensure_grid(self) -> None: def ensure_grid(self) -> None:
if self.grid or not self.dilated: if self.grid or not self.dilated:
@ -67,27 +61,20 @@ class DynamicPathIndex:
cell_size = self.engine.grid_cell_size cell_size = self.engine.grid_cell_size
for obj_id, polygon in self.dilated.items(): for obj_id, polygon in self.dilated.items():
bounds = polygon.bounds for cell in iter_grid_cells(polygon.bounds, cell_size):
for gx in range(int(bounds[0] / cell_size), int(bounds[2] / cell_size) + 1): self.grid.setdefault(cell, []).append(obj_id)
for gy in range(int(bounds[1] / cell_size), int(bounds[3] / cell_size) + 1):
cell = (gx, gy)
self.grid.setdefault(cell, []).append(obj_id)
def add_path(self, net_id: str, geometry: list[Polygon], dilated_geometry: list[Polygon] | None = None) -> None: def add_path(self, net_id: str, geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon]) -> None:
self.invalidate_queries() self.invalidate_queries()
dilation = self.engine.clearance / 2.0
for index, polygon in enumerate(geometry): for index, polygon in enumerate(geometry):
obj_id = self.id_counter obj_id = self.id_counter
self.id_counter += 1 self.id_counter += 1
dilated = dilated_geometry[index] if dilated_geometry else polygon.buffer(dilation) dilated = dilated_geometry[index]
self.geometries[obj_id] = (net_id, polygon) self.geometries[obj_id] = (net_id, polygon)
self.dilated[obj_id] = dilated self.dilated[obj_id] = dilated
self.index.insert(obj_id, dilated.bounds) self.index.insert(obj_id, dilated.bounds)
def remove_path(self, net_id: str) -> None: def remove_path(self, net_id: str) -> None:
if net_id in self.locked_nets:
return
to_remove = [obj_id for obj_id, (existing_net_id, _) in self.geometries.items() if existing_net_id == net_id] to_remove = [obj_id for obj_id, (existing_net_id, _) in self.geometries.items() if existing_net_id == net_id]
self.remove_obj_ids(to_remove) self.remove_obj_ids(to_remove)
@ -101,14 +88,7 @@ class DynamicPathIndex:
del self.geometries[obj_id] del self.geometries[obj_id]
del self.dilated[obj_id] del self.dilated[obj_id]
def lock_net(self, net_id: str) -> None: def clear_paths(self) -> None:
self.locked_nets.add(net_id) if not self.geometries:
to_move = [obj_id for obj_id, (existing_net_id, _) in self.geometries.items() if existing_net_id == net_id] return
for obj_id in to_move: self.remove_obj_ids(list(self.geometries))
polygon = self.geometries[obj_id][1]
dilated = self.dilated[obj_id]
self.engine.add_static_obstacle(polygon, dilated_geometry=dilated)
self.remove_obj_ids(to_move)
def unlock_net(self, net_id: str) -> None:
self.locked_nets.discard(net_id)

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