This commit is contained in:
Jan Petykiewicz 2026-03-09 03:19:01 -07:00
commit 8eb0dbf64a
3 changed files with 910 additions and 391 deletions

View file

@ -1,24 +1,52 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Literal
import rtree
from shapely.geometry import Point, Polygon
from shapely.prepared import prep
if TYPE_CHECKING:
from shapely.geometry import Polygon
from shapely.prepared import PreparedGeometry
from inire.geometry.primitives import Port
class CollisionEngine:
"""Manages spatial queries for collision detection with unified dilation logic."""
"""
Manages spatial queries for collision detection with unified dilation logic.
"""
__slots__ = (
'clearance', 'max_net_width', 'safety_zone_radius',
'static_index', 'static_geometries', 'static_prepared', '_static_id_counter',
'dynamic_index', 'dynamic_geometries', '_dynamic_id_counter'
)
def __init__(self, clearance: float, max_net_width: float = 2.0, safety_zone_radius: float = 0.0021) -> None:
clearance: float
""" Minimum required distance between any two waveguides or obstacles """
max_net_width: float
""" Maximum width of any net in the session (used for pre-dilation) """
safety_zone_radius: float
""" Radius around ports where collisions are ignored """
def __init__(
self,
clearance: float,
max_net_width: float = 2.0,
safety_zone_radius: float = 0.0021,
) -> None:
"""
Initialize the Collision Engine.
Args:
clearance: Minimum required distance (um).
max_net_width: Maximum net width (um).
safety_zone_radius: Safety radius around ports (um).
"""
self.clearance = clearance
self.max_net_width = max_net_width
self.safety_zone_radius = safety_zone_radius
# Static obstacles: store raw geometries to avoid double-dilation
self.static_index = rtree.index.Index()
self.static_geometries: dict[int, Polygon] = {} # ID -> Polygon
@ -32,7 +60,12 @@ class CollisionEngine:
self._dynamic_id_counter = 0
def add_static_obstacle(self, polygon: Polygon) -> None:
"""Add a static obstacle (raw geometry) to the engine."""
"""
Add a static obstacle (raw geometry) to the engine.
Args:
polygon: Raw obstacle geometry.
"""
obj_id = self._static_id_counter
self._static_id_counter += 1
@ -41,7 +74,13 @@ class CollisionEngine:
self.static_index.insert(obj_id, polygon.bounds)
def add_path(self, net_id: str, geometry: list[Polygon]) -> None:
"""Add a net's routed path (raw geometry) to the dynamic index."""
"""
Add a net's routed path (raw geometry) to the dynamic index.
Args:
net_id: Identifier for the net.
geometry: List of raw polygons in the path.
"""
for poly in geometry:
obj_id = self._dynamic_id_counter
self._dynamic_id_counter += 1
@ -49,14 +88,24 @@ class CollisionEngine:
self.dynamic_index.insert(obj_id, poly.bounds)
def remove_path(self, net_id: str) -> None:
"""Remove a net's path from the dynamic index."""
"""
Remove a net's path from the dynamic index.
Args:
net_id: Identifier for the net to remove.
"""
to_remove = [obj_id for obj_id, (nid, _) in self.dynamic_geometries.items() if nid == net_id]
for obj_id in to_remove:
nid, poly = self.dynamic_geometries.pop(obj_id)
self.dynamic_index.delete(obj_id, poly.bounds)
def lock_net(self, net_id: str) -> None:
"""Move a net's dynamic path to static obstacles permanently."""
"""
Move a net's dynamic path to static obstacles permanently.
Args:
net_id: Identifier for the net to lock.
"""
to_move = [obj_id for obj_id, (nid, _) in self.dynamic_geometries.items() if nid == net_id]
for obj_id in to_move:
nid, poly = self.dynamic_geometries.pop(obj_id)
@ -64,59 +113,81 @@ class CollisionEngine:
self.add_static_obstacle(poly)
def is_collision(
self,
geometry: Polygon,
net_width: float = 2.0,
start_port: Port | None = None,
end_port: Port | None = None
) -> bool:
"""Alias for check_collision(buffer_mode='static') for backward compatibility."""
self,
geometry: Polygon,
net_width: float = 2.0,
start_port: Port | None = None,
end_port: Port | None = None,
) -> bool:
"""
Alias for check_collision(buffer_mode='static') for backward compatibility.
Args:
geometry: Move geometry to check.
net_width: Width of the net (unused).
start_port: Starting port for safety check.
end_port: Ending port for safety check.
Returns:
True if collision detected.
"""
_ = net_width
res = self.check_collision(geometry, "default", buffer_mode="static", start_port=start_port, end_port=end_port)
res = self.check_collision(geometry, 'default', buffer_mode='static', start_port=start_port, end_port=end_port)
return bool(res)
def count_congestion(self, geometry: Polygon, net_id: str) -> int:
"""Alias for check_collision(buffer_mode='congestion') for backward compatibility."""
res = self.check_collision(geometry, net_id, buffer_mode="congestion")
"""
Alias for check_collision(buffer_mode='congestion') for backward compatibility.
Args:
geometry: Move geometry to check.
net_id: Identifier for the net.
Returns:
Number of overlapping nets.
"""
res = self.check_collision(geometry, net_id, buffer_mode='congestion')
return int(res)
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
) -> bool | int:
self,
geometry: Polygon,
net_id: str,
buffer_mode: Literal['static', 'congestion'] = 'static',
start_port: Port | None = None,
end_port: Port | None = None,
) -> bool | int:
"""
Check for collisions using unified dilation logic.
If buffer_mode == "static":
Returns True if geometry collides with static obstacles (buffered by full clearance).
If buffer_mode == "congestion":
Returns count of other nets colliding with geometry (both buffered by clearance/2).
Args:
geometry: Raw geometry to check.
net_id: Identifier for the net.
buffer_mode: 'static' (full clearance) or 'congestion' (shared).
start_port: Optional start port for safety zone.
end_port: Optional end port for safety zone.
Returns:
Boolean if static, integer count if congestion.
"""
if buffer_mode == "static":
# Buffered move vs raw static obstacle
# Distance must be >= clearance
if buffer_mode == 'static':
test_poly = geometry.buffer(self.clearance)
candidates = self.static_index.intersection(test_poly.bounds)
for obj_id in candidates:
if self.static_prepared[obj_id].intersects(test_poly):
# Safety zone check (using exact intersection area/bounds)
if start_port or end_port:
intersection = test_poly.intersection(self.static_geometries[obj_id])
if intersection.is_empty:
continue
ix_minx, ix_miny, ix_maxx, ix_maxy = intersection.bounds
is_safe = False
for p in [start_port, end_port]:
if p and (abs(ix_minx - p.x) < self.safety_zone_radius and
if p and (abs(ix_minx - p.x) < self.safety_zone_radius and
abs(ix_maxx - p.x) < self.safety_zone_radius and
abs(ix_miny - p.y) < self.safety_zone_radius and
abs(ix_miny - p.y) < self.safety_zone_radius and
abs(ix_maxy - p.y) < self.safety_zone_radius):
is_safe = True
break
@ -125,17 +196,14 @@ class CollisionEngine:
return True
return False
else: # buffer_mode == "congestion"
# Both paths buffered by clearance/2 => Total separation = clearance
dilation = self.clearance / 2.0
test_poly = geometry.buffer(dilation)
candidates = self.dynamic_index.intersection(test_poly.bounds)
count = 0
for obj_id in candidates:
other_net_id, other_poly = self.dynamic_geometries[obj_id]
if other_net_id != net_id:
# Buffer the other path segment too
if test_poly.intersects(other_poly.buffer(dilation)):
count += 1
return count
# buffer_mode == 'congestion'
dilation = self.clearance / 2.0
test_poly = geometry.buffer(dilation)
candidates = self.dynamic_index.intersection(test_poly.bounds)
count = 0
for obj_id in candidates:
other_net_id, other_poly = self.dynamic_geometries[obj_id]
if other_net_id != net_id and test_poly.intersects(other_poly.buffer(dilation)):
count += 1
return count

View file

@ -1,37 +1,85 @@
from __future__ import annotations
from typing import NamedTuple, Literal, Any
import numpy as np
from typing import Literal, cast, TYPE_CHECKING, Union, Any
import numpy
from shapely.geometry import Polygon, box
from shapely.ops import unary_union
from .primitives import Port
if TYPE_CHECKING:
from collections.abc import Sequence
# 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 search grid unit."""
"""
Snap a coordinate to the nearest search grid unit.
Args:
value: Value to snap.
Returns:
Snapped value.
"""
return round(value / SEARCH_GRID_SNAP_UM) * SEARCH_GRID_SNAP_UM
class ComponentResult(NamedTuple):
"""The result of a component generation: geometry, final port, and physical length."""
class ComponentResult:
"""
The result of a component generation: geometry, final port, and physical length.
"""
__slots__ = ('geometry', 'end_port', 'length')
geometry: list[Polygon]
""" List of polygons representing the component geometry """
end_port: Port
""" The final port after the component """
length: float
""" Physical length of the component path """
def __init__(
self,
geometry: list[Polygon],
end_port: Port,
length: float,
) -> None:
self.geometry = geometry
self.end_port = end_port
self.length = length
class Straight:
"""
Move generator for straight waveguide segments.
"""
@staticmethod
def generate(start_port: Port, length: float, width: float, snap_to_grid: bool = True) -> ComponentResult:
"""Generate a straight waveguide segment."""
rad = np.radians(start_port.orientation)
dx = length * np.cos(rad)
dy = length * np.sin(rad)
def generate(
start_port: Port,
length: float,
width: float,
snap_to_grid: bool = True,
) -> ComponentResult:
"""
Generate a straight waveguide segment.
Args:
start_port: Port to start from.
length: Requested length.
width: Waveguide width.
snap_to_grid: Whether to snap the end port to the search grid.
Returns:
A ComponentResult containing the straight segment.
"""
rad = numpy.radians(start_port.orientation)
dx = length * numpy.cos(rad)
dy = length * numpy.sin(rad)
ex = start_port.x + dx
ey = start_port.y + dy
@ -41,7 +89,7 @@ class Straight:
ey = snap_search_grid(ey)
end_port = Port(ex, ey, start_port.orientation)
actual_length = np.sqrt((end_port.x - start_port.x)**2 + (end_port.y - start_port.y)**2)
actual_length = numpy.sqrt((end_port.x - start_port.x)**2 + (end_port.y - start_port.y)**2)
# Create polygon
half_w = width / 2.0
@ -49,8 +97,8 @@ class Straight:
points = [(0, half_w), (actual_length, half_w), (actual_length, -half_w), (0, -half_w)]
# Transform points
cos_val = np.cos(rad)
sin_val = np.sin(rad)
cos_val = numpy.cos(rad)
sin_val = numpy.sin(rad)
poly_points = []
for px, py in points:
tx = start_port.x + px * cos_val - py * sin_val
@ -61,38 +109,156 @@ class Straight:
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."""
"""
Calculate number of segments for an arc to maintain a maximum sagitta.
Args:
radius: Arc radius.
angle_deg: Total angle turned.
sagitta: Maximum allowed deviation.
Returns:
Minimum number of segments needed.
"""
if radius <= 0:
return 1
ratio = max(0.0, min(1.0, 1.0 - sagitta / radius))
theta_max = 2.0 * np.arccos(ratio)
theta_max = 2.0 * numpy.arccos(ratio)
if theta_max < 1e-9:
return 16
num = int(np.ceil(np.radians(abs(angle_deg)) / theta_max))
num = int(numpy.ceil(numpy.radians(abs(angle_deg)) / theta_max))
return max(8, num)
def _get_arc_polygons(cx: float, cy: float, radius: float, width: float, t_start: float, t_end: float, sagitta: float = 0.01) -> list[Polygon]:
"""Helper to generate arc-shaped polygons."""
num_segments = _get_num_segments(radius, float(np.degrees(abs(t_end - t_start))), sagitta)
angles = np.linspace(t_start, t_end, num_segments + 1)
def _get_arc_polygons(
cx: float,
cy: float,
radius: float,
width: float,
t_start: float,
t_end: float,
sagitta: float = 0.01,
) -> list[Polygon]:
"""
Helper to generate arc-shaped polygons.
Args:
cx, cy: Center coordinates.
radius: Arc radius.
width: Waveguide width.
t_start, t_end: Start and end angles (radians).
sagitta: Geometric fidelity.
Returns:
List containing the arc polygon.
"""
num_segments = _get_num_segments(radius, float(numpy.degrees(abs(t_end - t_start))), sagitta)
angles = numpy.linspace(t_start, t_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)]
inner_points = [(cx + inner_radius * numpy.cos(a), cy + inner_radius * numpy.sin(a)) for a in angles]
outer_points = [(cx + outer_radius * numpy.cos(a), cy + outer_radius * numpy.sin(a)) for a in reversed(angles)]
return [Polygon(inner_points + outer_points)]
def _clip_bbox(
bbox: Polygon,
cx: float,
cy: float,
radius: float,
width: float,
clip_margin: float,
arc_poly: Polygon,
) -> Polygon:
"""
Clips corners of a bounding box for better collision modeling.
Args:
bbox: Initial bounding box.
cx, cy: Arc center.
radius: Arc radius.
width: Waveguide width.
clip_margin: Minimum distance from waveguide.
arc_poly: The original arc polygon.
Returns:
The clipped polygon.
"""
res_poly = bbox
# Determine quadrant signs from arc centroid relative to center
ac = arc_poly.centroid
qsx = 1.0 if ac.x >= cx else -1.0
qsy = 1.0 if ac.y >= cy else -1.0
r_out_cut = radius + width / 2.0 + clip_margin
r_in_cut = radius - width / 2.0 - clip_margin
minx, miny, maxx, maxy = bbox.bounds
corners = [(minx, miny), (minx, maxy), (maxx, miny), (maxx, maxy)]
for px, py in corners:
dx, dy = px - cx, py - cy
dist = numpy.sqrt(dx**2 + dy**2)
# Check if corner is far enough to be clipped
if dist > r_out_cut:
# Outer corner: remove part furthest from center
# To be conservative, line is at distance r_out_cut from center.
# Equation: sx*x + sy*y = sx*cx + sy*cy + r_out_cut * sqrt(2)
d_line = r_out_cut * numpy.sqrt(2)
elif r_in_cut > 0 and dist < r_in_cut:
# Inner corner: remove part closest to center
# To be safe, line intercept must not exceed r_in_cut.
# Equation: sx*x + sy*y = sx*cx + sy*cy + r_in_cut
d_line = r_in_cut
else:
continue
# Normal vector components from center to corner
# Using rounded signs for stability
sx = 1.0 if dx > 1e-6 else (-1.0 if dx < -1e-6 else qsx)
sy = 1.0 if dy > 1e-6 else (-1.0 if dy < -1e-6 else qsy)
# val calculation based on d_line
val = sx * cx + sy * cy + d_line
try:
# Create a triangle to remove.
# Vertices: corner, intersection with x=px edge, intersection with y=py edge
p1 = (px, py)
p2 = (px, (val - sx * px) / sy)
p3 = ((val - sy * py) / sx, py)
triangle = Polygon([p1, p2, p3])
if triangle.is_valid and triangle.area > 1e-9:
res_poly = cast('Polygon', res_poly.difference(triangle))
except ZeroDivisionError:
continue
return res_poly
def _apply_collision_model(
arc_poly: Polygon,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon,
radius: float,
width: float,
cx: float = 0.0,
cy: float = 0.0,
clip_margin: float = 10.0
) -> list[Polygon]:
"""Applies the specified collision model to an arc geometry."""
arc_poly: Polygon,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon,
radius: float,
width: float,
cx: float = 0.0,
cy: float = 0.0,
clip_margin: float = 10.0,
) -> list[Polygon]:
"""
Applies the specified collision model to an arc geometry.
Args:
arc_poly: High-fidelity arc.
collision_type: Model type or custom polygon.
radius: Arc radius.
width: Waveguide width.
cx, cy: Arc center.
clip_margin: Safety margin for clipping.
Returns:
List of polygons representing the collision model.
"""
if isinstance(collision_type, Polygon):
return [collision_type]
@ -107,75 +273,50 @@ def _apply_collision_model(
return [bbox]
if collision_type == "clipped_bbox":
res_poly = bbox
# Determine quadrant signs from arc centroid relative to center
# This ensures we always cut 'into' the box correctly
ac = arc_poly.centroid
sx = 1.0 if ac.x >= cx else -1.0
sy = 1.0 if ac.y >= cy else -1.0
r_out_cut = radius + width / 2.0 + clip_margin
r_in_cut = radius - width / 2.0 - clip_margin
corners = [(minx, miny), (minx, maxy), (maxx, miny), (maxx, maxy)]
for px, py in corners:
dx, dy = px - cx, py - cy
dist = np.sqrt(dx**2 + dy**2)
if dist > r_out_cut:
# Outer corner: remove part furthest from center
# We want minimum distance to line to be r_out_cut
d_cut = r_out_cut * np.sqrt(2)
elif r_in_cut > 0 and dist < r_in_cut:
# Inner corner: remove part closest to center
# We want maximum distance to line to be r_in_cut
d_cut = r_in_cut
else:
continue
# The cut line is sx*(x-cx) + sy*(y-cy) = d_cut
# sx*x + sy*y = sx*cx + sy*cy + d_cut
val = cx * sx + cy * sy + d_cut
try:
p1 = (px, py)
p2 = (px, (val - sx * px) / sy)
p3 = ((val - sy * py) / sx, py)
triangle = Polygon([p1, p2, p3])
if triangle.is_valid and triangle.area > 1e-9:
res_poly = res_poly.difference(triangle)
except ZeroDivisionError:
continue
return [res_poly]
return [_clip_bbox(bbox, cx, cy, radius, width, clip_margin, arc_poly)]
return [arc_poly]
class Bend90:
"""
Move generator for 90-degree bends.
"""
@staticmethod
def generate(
start_port: Port,
radius: float,
width: float,
direction: str = "CW",
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0
) -> ComponentResult:
"""Generate a 90-degree bend."""
turn_angle = -90 if direction == "CW" else 90
rad_start = np.radians(start_port.orientation)
c_angle = rad_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
cx = start_port.x + radius * np.cos(c_angle)
cy = start_port.y + radius * np.sin(c_angle)
t_start = c_angle + np.pi
t_end = t_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
start_port: Port,
radius: float,
width: float,
direction: str = "CW",
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0,
) -> ComponentResult:
"""
Generate a 90-degree bend.
ex = snap_search_grid(cx + radius * np.cos(t_end))
ey = snap_search_grid(cy + radius * np.sin(t_end))
Args:
start_port: Port to start from.
radius: Bend radius.
width: Waveguide width.
direction: "CW" or "CCW".
sagitta: Geometric fidelity.
collision_type: Collision model.
clip_margin: Margin for clipped_bbox.
Returns:
A ComponentResult containing the bend.
"""
turn_angle = -90 if direction == "CW" else 90
rad_start = numpy.radians(start_port.orientation)
c_angle = rad_start + (numpy.pi / 2 if direction == "CCW" else -numpy.pi / 2)
cx = start_port.x + radius * numpy.cos(c_angle)
cy = start_port.y + radius * numpy.sin(c_angle)
t_start = c_angle + numpy.pi
t_end = t_start + (numpy.pi / 2 if direction == "CCW" else -numpy.pi / 2)
ex = snap_search_grid(cx + radius * numpy.cos(t_end))
ey = snap_search_grid(cy + radius * numpy.sin(t_end))
end_port = Port(ex, ey, float((start_port.orientation + turn_angle) % 360))
arc_polys = _get_arc_polygons(cx, cy, radius, width, t_start, t_end, sagitta)
@ -183,55 +324,72 @@ class Bend90:
arc_polys[0], collision_type, radius, width, cx, cy, clip_margin
)
return ComponentResult(geometry=collision_polys, end_port=end_port, length=radius * np.pi / 2.0)
return ComponentResult(geometry=collision_polys, end_port=end_port, length=radius * numpy.pi / 2.0)
class SBend:
"""
Move generator for parametric S-bends.
"""
@staticmethod
def generate(
start_port: Port,
offset: float,
radius: float,
width: float,
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0
) -> ComponentResult:
"""Generate a parametric S-bend (two tangent arcs)."""
start_port: Port,
offset: float,
radius: float,
width: float,
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0,
) -> ComponentResult:
"""
Generate a parametric S-bend (two tangent arcs).
Args:
start_port: Port to start from.
offset: Lateral offset.
radius: Arc radii.
width: Waveguide width.
sagitta: Geometric fidelity.
collision_type: Collision model.
clip_margin: Margin for clipped_bbox.
Returns:
A ComponentResult containing the S-bend.
"""
if abs(offset) >= 2 * radius:
raise ValueError(f"SBend offset {offset} must be less than 2*radius {2 * radius}")
theta = np.arccos(1 - abs(offset) / (2 * radius))
dx = 2 * radius * np.sin(theta)
theta = numpy.arccos(1 - abs(offset) / (2 * radius))
dx = 2 * radius * numpy.sin(theta)
dy = offset
rad_start = np.radians(start_port.orientation)
ex = snap_search_grid(start_port.x + dx * np.cos(rad_start) - dy * np.sin(rad_start))
ey = snap_search_grid(start_port.y + dx * np.sin(rad_start) + dy * np.cos(rad_start))
rad_start = numpy.radians(start_port.orientation)
ex = snap_search_grid(start_port.x + dx * numpy.cos(rad_start) - dy * numpy.sin(rad_start))
ey = snap_search_grid(start_port.y + dx * numpy.sin(rad_start) + dy * numpy.cos(rad_start))
end_port = Port(ex, ey, start_port.orientation)
direction = 1 if offset > 0 else -1
c1_angle = rad_start + direction * np.pi / 2
cx1 = start_port.x + radius * np.cos(c1_angle)
cy1 = start_port.y + radius * np.sin(c1_angle)
ts1, te1 = c1_angle + np.pi, c1_angle + np.pi + direction * theta
c1_angle = rad_start + direction * numpy.pi / 2
cx1 = start_port.x + radius * numpy.cos(c1_angle)
cy1 = start_port.y + radius * numpy.sin(c1_angle)
ts1, te1 = c1_angle + numpy.pi, c1_angle + numpy.pi + direction * theta
ex_raw = start_port.x + dx * np.cos(rad_start) - dy * np.sin(rad_start)
ey_raw = start_port.y + dx * np.sin(rad_start) + dy * np.cos(rad_start)
c2_angle = rad_start - direction * np.pi / 2
cx2 = ex_raw + radius * np.cos(c2_angle)
cy2 = ey_raw + radius * np.sin(c2_angle)
te2 = c2_angle + np.pi
ex_raw = start_port.x + dx * numpy.cos(rad_start) - dy * numpy.sin(rad_start)
ey_raw = start_port.y + dx * numpy.sin(rad_start) + dy * numpy.cos(rad_start)
c2_angle = rad_start - direction * numpy.pi / 2
cx2 = ex_raw + radius * numpy.cos(c2_angle)
cy2 = ey_raw + radius * numpy.sin(c2_angle)
te2 = c2_angle + numpy.pi
ts2 = te2 + direction * theta
arc1 = _get_arc_polygons(cx1, cy1, radius, width, ts1, te1, sagitta)[0]
arc2 = _get_arc_polygons(cx2, cy2, radius, width, ts2, te2, sagitta)[0]
combined_arc = unary_union([arc1, arc2])
if collision_type == "clipped_bbox":
col1 = _apply_collision_model(arc1, collision_type, radius, width, cx1, cy1, clip_margin)
col2 = _apply_collision_model(arc2, collision_type, radius, width, cx2, cy2, clip_margin)
collision_polys = [unary_union(col1 + col2)]
collision_polys = [cast('Polygon', unary_union(col1 + col2))]
else:
combined_arc = cast('Polygon', unary_union([arc1, arc2]))
collision_polys = _apply_collision_model(
combined_arc, collision_type, radius, width, 0, 0, clip_margin
)

View file

@ -1,50 +1,111 @@
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
import numpy
# 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)."""
"""
Snap a coordinate to the nearest 1nm (0.001 um).
Args:
value: Coordinate value to snap.
Returns:
Snapped coordinate value.
"""
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:
class Port:
"""
A port defined by (x, y, orientation) in micrometers.
"""
__slots__ = ('x', 'y', 'orientation')
x: float
""" x-coordinate in micrometers """
y: float
""" y-coordinate in micrometers """
orientation: float
""" Orientation in degrees: 0, 90, 180, 270 """
def __init__(
self,
x: float,
y: float,
orientation: float,
) -> None:
"""
Initialize and snap a Port.
Args:
x: Initial x-coordinate.
y: Initial y-coordinate.
orientation: Initial orientation in degrees.
"""
# 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)
self.x = snap_nm(x)
self.y = snap_nm(y)
# Ensure orientation is one of {0, 90, 180, 270}
norm_orientation = int(round(self.orientation)) % 360
norm_orientation = int(round(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))
self.orientation = float(norm_orientation)
def __repr__(self) -> str:
return f'Port(x={self.x}, y={self.y}, orientation={self.orientation})'
def __eq__(self, other: object) -> bool:
if not isinstance(other, Port):
return False
return (self.x == other.x and
self.y == other.y and
self.orientation == other.orientation)
def __hash__(self) -> int:
return hash((self.x, self.y, self.orientation))
def translate_port(port: Port, dx: float, dy: float) -> Port:
"""Translate a port by (dx, dy)."""
"""
Translate a port by (dx, dy).
Args:
port: Port to translate.
dx: x-offset.
dy: y-offset.
Returns:
A new translated Port.
"""
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."""
"""
Rotate a port by a multiple of 90 degrees around an origin.
Args:
port: Port to rotate.
angle: Angle to rotate by (degrees).
origin: (x, y) origin to rotate around.
Returns:
A new rotated Port.
"""
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)
rad = numpy.radians(angle)
qx = ox + numpy.cos(rad) * (px - ox) - numpy.sin(rad) * (py - oy)
qy = oy + numpy.sin(rad) * (px - ox) + numpy.cos(rad) * (py - oy)
return Port(qx, qy, port.orientation + angle)