224 lines
9.4 KiB
Python
224 lines
9.4 KiB
Python
"""Construct short links from straight sections and tangent bends."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from itertools import islice
|
|
from math import isfinite, sqrt
|
|
from typing import TYPE_CHECKING
|
|
|
|
from shapely import union_all
|
|
from shapely.geometry import box
|
|
|
|
from inire.constants import TOLERANCE_LINEAR
|
|
from inire.geometry.collision import RoutingWorld
|
|
from inire.geometry.primitives import port_local_coordinates
|
|
from inire.geometry.sbend import exact_sbend_spans
|
|
from inire.model import resolve_bend_geometry
|
|
from inire.results import RoutingResult
|
|
from inire.router._seed_materialization import materialize_path_seed
|
|
from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Iterable, Iterator
|
|
|
|
from shapely.geometry import Polygon
|
|
from shapely.geometry.base import BaseGeometry
|
|
|
|
from inire.geometry.components import ComponentResult
|
|
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
|
from inire.router._routing_policy import Scorer
|
|
from inire.seeds import PathSegmentSeed
|
|
|
|
|
|
def _path(*moves: int | PathSegmentSeed) -> PathSeed:
|
|
return PathSeed(tuple(StraightSeed(move) if isinstance(move, int) else move for move in moves if move != 0))
|
|
|
|
|
|
def _lanes(first: int, last: int) -> tuple[int, ...]:
|
|
return tuple(dict.fromkeys((*range(last, max(first - 1, last - 8), -1), *range(min(last, first + 7), first - 1, -1))))
|
|
|
|
|
|
def _shift_positions(
|
|
problem: RoutingProblem,
|
|
origin: int,
|
|
sign: int,
|
|
radius: int,
|
|
run: int,
|
|
available: int,
|
|
) -> list[int]:
|
|
positions = {i * available // 8 for i in range(9)}
|
|
for obstacle in problem.static_obstacles:
|
|
if obstacle.is_empty:
|
|
continue
|
|
low, high = sorted(sign * (y - origin) - radius for y in (obstacle.bounds[1], obstacle.bounds[3]))
|
|
positions.update((round(low - problem.clearance - run), round(high + problem.clearance), round((low + high - run) / 2)))
|
|
return sorted((y for y in positions if 0 <= y <= available), key=lambda y: (abs(2 * y - available), y))
|
|
|
|
|
|
def _candidate_jogs(
|
|
net: NetSpec,
|
|
problem: RoutingProblem,
|
|
search: SearchOptions,
|
|
radii: tuple[int, ...],
|
|
) -> Iterator[PathSeed]:
|
|
start, target = net.start, net.target
|
|
dx, dy = target.x - start.x, target.y - start.y
|
|
if dy == 0:
|
|
yield _path(dx)
|
|
return
|
|
direction = 1 if dy > 0 else -1
|
|
for radius in radii:
|
|
reach = abs(dy) - 2 * radius
|
|
if reach < 0 or dx < 2 * radius:
|
|
continue
|
|
first = Bend90Seed(radius, "CCW" if direction > 0 else "CW")
|
|
last = Bend90Seed(radius, "CW" if direction > 0 else "CCW")
|
|
turns = _lanes(start.x + radius, target.x - radius)
|
|
for x in turns:
|
|
yield _path(x - start.x - radius, first, reach, last, target.x - x - radius)
|
|
if radius not in search.sbend_radii:
|
|
continue
|
|
# Move the middle of the jog between two independently positioned
|
|
# turn lanes. The S-bend stays away from the terminal access cutouts.
|
|
for offset, span in reversed(tuple(exact_sbend_spans(radius).items())):
|
|
if span > reach:
|
|
continue
|
|
available = reach - span
|
|
for before in _shift_positions(problem, start.y, direction, radius, span, available):
|
|
for exit_x in turns:
|
|
for lateral in (offset, -offset):
|
|
lead = exit_x + lateral - start.x - radius
|
|
if lead < 0:
|
|
continue
|
|
yield _path(
|
|
lead,
|
|
first,
|
|
before,
|
|
SBendSeed(direction * lateral, radius),
|
|
available - before,
|
|
last,
|
|
target.x - exit_x - radius,
|
|
)
|
|
|
|
|
|
def _pack_routes(
|
|
candidates: dict[str, list[tuple[PathSeed, BaseGeometry]]],
|
|
clearance: float,
|
|
) -> dict[str, PathSeed] | None:
|
|
order = sorted(candidates, key=lambda net_id: len(candidates[net_id]))
|
|
chosen: dict[str, tuple[PathSeed, BaseGeometry]] = {}
|
|
remaining = 4096
|
|
choices = [iter(candidates[net_id]) for net_id in order]
|
|
index = 0
|
|
|
|
while 0 <= index < len(order):
|
|
net_id = order[index]
|
|
chosen.pop(net_id, None)
|
|
for seed, footprint in choices[index]:
|
|
if remaining <= 0:
|
|
return None
|
|
remaining -= 1
|
|
if any(footprint.distance(other) < clearance - TOLERANCE_LINEAR for _, other in chosen.values()):
|
|
continue
|
|
chosen[net_id] = (seed, footprint)
|
|
index += 1
|
|
break
|
|
else:
|
|
choices[index] = iter(candidates[net_id])
|
|
index -= 1
|
|
|
|
return {net_id: value[0] for net_id, value in chosen.items()} if index == len(order) else None
|
|
|
|
|
|
def _verified_candidates(
|
|
net: NetSpec,
|
|
world: RoutingWorld,
|
|
board: Polygon,
|
|
search: SearchOptions,
|
|
seeds: Iterable[PathSeed],
|
|
) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]:
|
|
for seed in seeds:
|
|
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance)
|
|
if path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid:
|
|
continue
|
|
footprint = union_all([polygon for component in path for polygon in component.physical_geometry])
|
|
if board.covers(footprint):
|
|
yield seed, footprint, path
|
|
|
|
|
|
def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dict[str, PathSeed] | None:
|
|
"""Verify candidates individually and find mutually clear routes for a bank."""
|
|
_, physical_geometry = resolve_bend_geometry(search)
|
|
radii = tuple(sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)}))
|
|
if problem.initial_paths or not radii or not problem.nets or physical_geometry != "arc":
|
|
return None
|
|
if any(net.start.r != 0 or net.target.r != 0 or not 0 < net.target.x - net.start.x <= 4 * radii[-1] for net in problem.nets):
|
|
return None
|
|
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius)
|
|
for obstacle in problem.static_obstacles:
|
|
world.add_static_obstacle(obstacle)
|
|
board = box(*problem.bounds)
|
|
candidates = {}
|
|
for net in problem.nets:
|
|
jogs = islice(_candidate_jogs(net, problem, search, radii), 512)
|
|
choices = [(seed, footprint) for seed, footprint, _ in islice(_verified_candidates(net, world, board, search, jogs), 20)]
|
|
if not choices:
|
|
return None
|
|
candidates[net.net_id] = choices
|
|
return _pack_routes(candidates, problem.clearance)
|
|
|
|
|
|
def _shift_seeds(forward: int, offset: int, search: SearchOptions) -> Iterator[PathSeed]:
|
|
minimum, maximum = search.min_straight_length, search.max_straight_length
|
|
if offset == 0:
|
|
if minimum <= forward <= maximum:
|
|
yield _path(forward)
|
|
return
|
|
if search.sbend_offsets is not None and offset not in {round(value) for value in search.sbend_offsets}:
|
|
return
|
|
for radius in search.sbend_radii:
|
|
if not isfinite(radius) or not 0 < abs(offset) < 2 * radius:
|
|
continue
|
|
# The physical arc must meet the snapped straight at the join.
|
|
exact = sqrt(abs(offset) * (4 * radius - abs(offset)))
|
|
if not isfinite(exact):
|
|
continue
|
|
span = round(exact)
|
|
spare = forward - span
|
|
if spare < 0 or abs(exact - span) > 1e-9:
|
|
continue
|
|
placements = {i * spare // 8 for i in range(9)}
|
|
for lead in sorted(placements, key=lambda distance: (abs(2 * distance - spare), distance)):
|
|
tail = spare - lead
|
|
if all(not length or minimum <= length <= maximum for length in (lead, tail)):
|
|
yield _path(lead, SBendSeed(offset, radius), tail)
|
|
|
|
|
|
def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: Scorer) -> dict[str, PathSeed] | None:
|
|
"""Fit exact-span links between fixed ports across both axes of a layout."""
|
|
if problem.initial_paths or len(problem.nets) < 3 or len({net.start.r % 180 for net in problem.nets}) < 2:
|
|
return None
|
|
if any(net.start.r != net.target.r for net in problem.nets):
|
|
return None
|
|
deltas = [port_local_coordinates(net.start, net.target.x, net.target.y) for net in problem.nets]
|
|
if any(forward <= 0 for forward, _ in deltas) or not any(offset for _, offset in deltas):
|
|
return None
|
|
seeds_by_net = [tuple(_shift_seeds(int(forward), int(offset), search)) for forward, offset in deltas]
|
|
if not all(seeds_by_net):
|
|
return None
|
|
|
|
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius)
|
|
for obstacle in problem.static_obstacles:
|
|
world.add_static_obstacle(obstacle)
|
|
board = box(*problem.bounds)
|
|
candidates = {}
|
|
for net, seeds in zip(problem.nets, seeds_by_net, strict=True):
|
|
ranked = [
|
|
(score(RoutingResult(net.net_id, path)), seed, footprint)
|
|
for seed, footprint, path in _verified_candidates(net, world, board, search, seeds)
|
|
]
|
|
if not ranked:
|
|
return None
|
|
ranked.sort(key=lambda choice: choice[0])
|
|
candidates[net.net_id] = [(seed, footprint) for _, seed, footprint in ranked]
|
|
return _pack_routes(candidates, problem.clearance)
|