Initial buildout
This commit is contained in:
parent
34615f3aac
commit
f600b52f32
3 changed files with 1856 additions and 23 deletions
140
inire/geometry/collision.py
Normal file
140
inire/geometry/collision.py
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import rtree
|
||||
from shapely.geometry import Point, Polygon
|
||||
from shapely.ops import unary_union
|
||||
from shapely.prepared import prep
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from shapely.prepared import PreparedGeometry
|
||||
|
||||
from inire.geometry.primitives import Port
|
||||
|
||||
|
||||
class CollisionEngine:
|
||||
"""Manages spatial queries for collision detection."""
|
||||
|
||||
def __init__(self, clearance: float, max_net_width: float = 2.0) -> None:
|
||||
self.clearance = clearance
|
||||
self.max_net_width = max_net_width
|
||||
self.static_obstacles = rtree.index.Index()
|
||||
# To store geometries for precise checks
|
||||
self.obstacle_geometries: dict[int, Polygon] = {} # ID -> Polygon
|
||||
self.prepared_obstacles: dict[int, PreparedGeometry] = {} # ID -> PreparedGeometry
|
||||
self._id_counter = 0
|
||||
|
||||
# Dynamic paths for multi-net congestion
|
||||
self.dynamic_paths = rtree.index.Index()
|
||||
# obj_id -> (net_id, geometry)
|
||||
self.path_geometries: dict[int, tuple[str, Polygon]] = {}
|
||||
self._dynamic_id_counter = 0
|
||||
|
||||
def add_static_obstacle(self, polygon: Polygon, pre_dilate: bool = True) -> None:
|
||||
"""Add a static obstacle to the engine."""
|
||||
_ = pre_dilate # Keep for API compatibility
|
||||
obj_id = self._id_counter
|
||||
self._id_counter += 1
|
||||
|
||||
self.obstacle_geometries[obj_id] = polygon
|
||||
self.prepared_obstacles[obj_id] = prep(polygon)
|
||||
|
||||
# Index the bounding box of the polygon (dilated for broad prune)
|
||||
# Spec: "All user-provided obstacles are pre-dilated by (W_max + C)/2"
|
||||
dilation = (self.max_net_width + self.clearance) / 2.0
|
||||
dilated_bounds = (
|
||||
polygon.bounds[0] - dilation,
|
||||
polygon.bounds[1] - dilation,
|
||||
polygon.bounds[2] + dilation,
|
||||
polygon.bounds[3] + dilation,
|
||||
)
|
||||
self.static_obstacles.insert(obj_id, dilated_bounds)
|
||||
|
||||
def add_path(self, net_id: str, geometry: list[Polygon]) -> None:
|
||||
"""Add a net's routed path to the dynamic R-Tree."""
|
||||
# Dilate by clearance/2 for congestion
|
||||
dilation = self.clearance / 2.0
|
||||
for poly in geometry:
|
||||
dilated = poly.buffer(dilation)
|
||||
obj_id = self._dynamic_id_counter
|
||||
self._dynamic_id_counter += 1
|
||||
self.path_geometries[obj_id] = (net_id, dilated)
|
||||
self.dynamic_paths.insert(obj_id, dilated.bounds)
|
||||
|
||||
def remove_path(self, net_id: str) -> None:
|
||||
"""Remove a net's path from the dynamic R-Tree."""
|
||||
to_remove = [obj_id for obj_id, (nid, _) in self.path_geometries.items() if nid == net_id]
|
||||
for obj_id in to_remove:
|
||||
nid, dilated = self.path_geometries.pop(obj_id)
|
||||
self.dynamic_paths.delete(obj_id, dilated.bounds)
|
||||
|
||||
def lock_net(self, net_id: str) -> None:
|
||||
"""Move a net's dynamic path to static obstacles permanently."""
|
||||
to_move = [obj_id for obj_id, (nid, _) in self.path_geometries.items() if nid == net_id]
|
||||
for obj_id in to_move:
|
||||
nid, dilated = self.path_geometries.pop(obj_id)
|
||||
self.dynamic_paths.delete(obj_id, dilated.bounds)
|
||||
|
||||
# Add to static (already dilated for clearance)
|
||||
new_static_id = self._id_counter
|
||||
self._id_counter += 1
|
||||
self.obstacle_geometries[new_static_id] = dilated
|
||||
self.prepared_obstacles[new_static_id] = prep(dilated)
|
||||
self.static_obstacles.insert(new_static_id, dilated.bounds)
|
||||
|
||||
def count_congestion(self, geometry: Polygon, net_id: str) -> int:
|
||||
"""Count how many other nets collide with this geometry."""
|
||||
dilation = self.clearance / 2.0
|
||||
test_poly = geometry.buffer(dilation)
|
||||
candidates = self.dynamic_paths.intersection(test_poly.bounds)
|
||||
count = 0
|
||||
for obj_id in candidates:
|
||||
other_net_id, other_poly = self.path_geometries[obj_id]
|
||||
if other_net_id != net_id and test_poly.intersects(other_poly):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
def is_collision(
|
||||
self,
|
||||
geometry: Polygon,
|
||||
net_width: float,
|
||||
start_port: Port | None = None,
|
||||
end_port: Port | None = None,
|
||||
) -> bool:
|
||||
"""Check if a geometry (e.g. a Move) collides with static obstacles."""
|
||||
_ = net_width # Width is already integrated into engine dilation settings
|
||||
dilation = self.clearance / 2.0
|
||||
test_poly = geometry.buffer(dilation)
|
||||
|
||||
# Broad prune with R-Tree
|
||||
candidates = self.static_obstacles.intersection(test_poly.bounds)
|
||||
|
||||
for obj_id in candidates:
|
||||
# Use prepared geometry for fast intersection
|
||||
if self.prepared_obstacles[obj_id].intersects(test_poly):
|
||||
# Check safety zone (2nm = 0.002 um)
|
||||
if start_port or end_port:
|
||||
obstacle = self.obstacle_geometries[obj_id]
|
||||
intersection = test_poly.intersection(obstacle)
|
||||
|
||||
if intersection.is_empty:
|
||||
continue
|
||||
|
||||
# Create safety zone polygons
|
||||
safety_zones = []
|
||||
if start_port:
|
||||
safety_zones.append(Point(start_port.x, start_port.y).buffer(0.002))
|
||||
if end_port:
|
||||
safety_zones.append(Point(end_port.x, end_port.y).buffer(0.002))
|
||||
|
||||
if safety_zones:
|
||||
safe_poly = unary_union(safety_zones)
|
||||
# Remove safe zones from intersection
|
||||
remaining_collision = intersection.difference(safe_poly)
|
||||
if remaining_collision.is_empty or remaining_collision.area < 1e-9:
|
||||
continue
|
||||
|
||||
return True
|
||||
return False
|
||||
|
||||
170
inire/geometry/components.py
Normal file
170
inire/geometry/components.py
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import NamedTuple
|
||||
|
||||
import numpy as np
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
from .primitives import Port
|
||||
|
||||
# Search Grid Snap (1.0 µm)
|
||||
SEARCH_GRID_SNAP_UM = 1.0
|
||||
|
||||
|
||||
def snap_search_grid(value: float) -> float:
|
||||
"""Snap a coordinate to the nearest 1µm."""
|
||||
return round(value / SEARCH_GRID_SNAP_UM) * SEARCH_GRID_SNAP_UM
|
||||
|
||||
|
||||
class ComponentResult(NamedTuple):
|
||||
"""The result of a component generation: geometry and the final port."""
|
||||
|
||||
geometry: list[Polygon]
|
||||
end_port: Port
|
||||
|
||||
|
||||
class Straight:
|
||||
@staticmethod
|
||||
def generate(start_port: Port, length: float, width: float) -> ComponentResult:
|
||||
"""Generate a straight waveguide segment."""
|
||||
# Calculate end port position
|
||||
rad = np.radians(start_port.orientation)
|
||||
dx = length * np.cos(rad)
|
||||
dy = length * np.sin(rad)
|
||||
|
||||
end_port = Port(start_port.x + dx, start_port.y + dy, start_port.orientation)
|
||||
|
||||
# Create polygon (centered on port)
|
||||
half_w = width / 2.0
|
||||
# Points relative to start port (0,0)
|
||||
points = [(0, half_w), (length, half_w), (length, -half_w), (0, -half_w)]
|
||||
|
||||
# Transform points
|
||||
cos_val = np.cos(rad)
|
||||
sin_val = np.sin(rad)
|
||||
poly_points = []
|
||||
for px, py in points:
|
||||
tx = start_port.x + px * cos_val - py * sin_val
|
||||
ty = start_port.y + px * sin_val + py * cos_val
|
||||
poly_points.append((tx, ty))
|
||||
|
||||
return ComponentResult(geometry=[Polygon(poly_points)], end_port=end_port)
|
||||
|
||||
|
||||
def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int:
|
||||
"""Calculate number of segments for an arc to maintain a maximum sagitta."""
|
||||
if radius <= 0:
|
||||
return 1
|
||||
# angle_deg is absolute angle turned
|
||||
# s = R(1 - cos(theta/2)) => cos(theta/2) = 1 - s/R
|
||||
# theta = 2 * acos(1 - s/R)
|
||||
# n = total_angle / theta
|
||||
ratio = max(0.0, min(1.0, 1.0 - sagitta / radius))
|
||||
theta_max = 2.0 * np.arccos(ratio)
|
||||
if theta_max == 0:
|
||||
return 16
|
||||
num = int(np.ceil(np.radians(abs(angle_deg)) / theta_max))
|
||||
return max(4, num)
|
||||
|
||||
|
||||
class Bend90:
|
||||
@staticmethod
|
||||
def generate(start_port: Port, radius: float, width: float, direction: str = "CW", sagitta: float = 0.01) -> ComponentResult:
|
||||
"""Generate a 90-degree bend."""
|
||||
# direction: 'CW' (-90) or 'CCW' (+90)
|
||||
turn_angle = -90 if direction == "CW" else 90
|
||||
|
||||
# Calculate center of the arc
|
||||
rad_start = np.radians(start_port.orientation)
|
||||
center_angle = rad_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
|
||||
cx = start_port.x + radius * np.cos(center_angle)
|
||||
cy = start_port.y + radius * np.sin(center_angle)
|
||||
|
||||
# Center to start is radius at center_angle + pi
|
||||
theta_start = center_angle + np.pi
|
||||
theta_end = theta_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
|
||||
|
||||
ex = cx + radius * np.cos(theta_end)
|
||||
ey = cy + radius * np.sin(theta_end)
|
||||
|
||||
# End port orientation
|
||||
end_orientation = (start_port.orientation + turn_angle) % 360
|
||||
|
||||
snapped_ex = snap_search_grid(ex)
|
||||
snapped_ey = snap_search_grid(ey)
|
||||
|
||||
end_port = Port(snapped_ex, snapped_ey, float(end_orientation))
|
||||
|
||||
# Generate arc geometry
|
||||
num_segments = _get_num_segments(radius, 90, sagitta)
|
||||
angles = np.linspace(theta_start, theta_end, num_segments + 1)
|
||||
|
||||
inner_radius = radius - width / 2.0
|
||||
outer_radius = radius + width / 2.0
|
||||
|
||||
inner_points = [(cx + inner_radius * np.cos(a), cy + inner_radius * np.sin(a)) for a in angles]
|
||||
outer_points = [(cx + outer_radius * np.cos(a), cy + outer_radius * np.sin(a)) for a in reversed(angles)]
|
||||
|
||||
return ComponentResult(geometry=[Polygon(inner_points + outer_points)], end_port=end_port)
|
||||
|
||||
|
||||
class SBend:
|
||||
@staticmethod
|
||||
def generate(start_port: Port, offset: float, radius: float, width: float, sagitta: float = 0.01) -> ComponentResult:
|
||||
"""Generate a parametric S-bend (two tangent arcs). Only for offset < 2*radius."""
|
||||
if abs(offset) >= 2 * radius:
|
||||
raise ValueError(f"SBend offset {offset} must be less than 2*radius {2 * radius}")
|
||||
|
||||
# Analytical length: L = 2 * sqrt(O * (2*R - O/4)) is for a specific S-bend type.
|
||||
# Standard S-bend with two equal arcs:
|
||||
# Offset O = 2 * R * (1 - cos(theta))
|
||||
# theta = acos(1 - O / (2*R))
|
||||
theta = np.arccos(1 - abs(offset) / (2 * radius))
|
||||
|
||||
# Length of one arc = R * theta
|
||||
# Total length of S-bend = 2 * R * theta (arc length)
|
||||
# Horizontal distance dx = 2 * R * sin(theta)
|
||||
|
||||
dx = 2 * radius * np.sin(theta)
|
||||
dy = offset
|
||||
|
||||
# End port
|
||||
rad_start = np.radians(start_port.orientation)
|
||||
ex = start_port.x + dx * np.cos(rad_start) - dy * np.sin(rad_start)
|
||||
ey = start_port.y + dx * np.sin(rad_start) + dy * np.cos(rad_start)
|
||||
|
||||
end_port = Port(ex, ey, start_port.orientation)
|
||||
|
||||
# Geometry: two arcs
|
||||
# First arc center
|
||||
direction = 1 if offset > 0 else -1
|
||||
center_angle1 = rad_start + direction * np.pi / 2
|
||||
cx1 = start_port.x + radius * np.cos(center_angle1)
|
||||
cy1 = start_port.y + radius * np.sin(center_angle1)
|
||||
|
||||
# Second arc center
|
||||
center_angle2 = rad_start - direction * np.pi / 2
|
||||
cx2 = ex + radius * np.cos(center_angle2)
|
||||
cy2 = ey + radius * np.sin(center_angle2)
|
||||
|
||||
# Generate points for both arcs
|
||||
num_segments = _get_num_segments(radius, float(np.degrees(theta)), sagitta)
|
||||
# Arc 1: theta_start1 to theta_end1
|
||||
theta_start1 = center_angle1 + np.pi
|
||||
theta_end1 = theta_start1 - direction * theta
|
||||
|
||||
# Arc 2: theta_start2 to theta_end2
|
||||
theta_start2 = center_angle2
|
||||
theta_end2 = theta_start2 + direction * theta
|
||||
|
||||
def get_arc_points(cx: float, cy: float, r_inner: float, r_outer: float, t_start: float, t_end: float) -> list[tuple[float, float]]:
|
||||
angles = np.linspace(t_start, t_end, num_segments + 1)
|
||||
inner = [(cx + r_inner * np.cos(a), cy + r_inner * np.sin(a)) for a in angles]
|
||||
outer = [(cx + r_outer * np.cos(a), cy + r_outer * np.sin(a)) for a in reversed(angles)]
|
||||
return inner + outer
|
||||
|
||||
poly1 = Polygon(get_arc_points(cx1, cy1, radius - width / 2, radius + width / 2, theta_start1, theta_end1))
|
||||
poly2 = Polygon(get_arc_points(cx2, cy2, radius - width / 2, radius + width / 2, theta_end2, theta_start2))
|
||||
|
||||
return ComponentResult(geometry=[poly1, poly2], end_port=end_port)
|
||||
|
||||
50
inire/geometry/primitives.py
Normal file
50
inire/geometry/primitives.py
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
import numpy as np
|
||||
|
||||
# 1nm snap (0.001 µm)
|
||||
GRID_SNAP_UM = 0.001
|
||||
|
||||
def snap_nm(value: float) -> float:
|
||||
"""Snap a coordinate to the nearest 1nm (0.001 um)."""
|
||||
return round(value / GRID_SNAP_UM) * GRID_SNAP_UM
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Port:
|
||||
"""A port defined by (x, y, orientation) in micrometers."""
|
||||
x: float
|
||||
y: float
|
||||
orientation: float # Degrees: 0, 90, 180, 270
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Snap x, y to 1nm
|
||||
# We need to use object.__setattr__ because the dataclass is frozen.
|
||||
snapped_x = snap_nm(self.x)
|
||||
snapped_y = snap_nm(self.y)
|
||||
|
||||
# Ensure orientation is one of {0, 90, 180, 270}
|
||||
norm_orientation = int(round(self.orientation)) % 360
|
||||
if norm_orientation not in {0, 90, 180, 270}:
|
||||
norm_orientation = (round(norm_orientation / 90) * 90) % 360
|
||||
|
||||
object.__setattr__(self, "x", snapped_x)
|
||||
object.__setattr__(self, "y", snapped_y)
|
||||
object.__setattr__(self, "orientation", float(norm_orientation))
|
||||
|
||||
|
||||
def translate_port(port: Port, dx: float, dy: float) -> Port:
|
||||
"""Translate a port by (dx, dy)."""
|
||||
return Port(port.x + dx, port.y + dy, port.orientation)
|
||||
|
||||
|
||||
def rotate_port(port: Port, angle: float, origin: tuple[float, float] = (0, 0)) -> Port:
|
||||
"""Rotate a port by a multiple of 90 degrees around an origin."""
|
||||
ox, oy = origin
|
||||
px, py = port.x, port.y
|
||||
|
||||
rad = np.radians(angle)
|
||||
qx = ox + np.cos(rad) * (px - ox) - np.sin(rad) * (py - oy)
|
||||
qy = oy + np.sin(rad) * (px - ox) + np.cos(rad) * (py - oy)
|
||||
|
||||
return Port(qx, qy, port.orientation + angle)
|
||||
|
||||
Loading…
Reference in a new issue