trim down
This commit is contained in:
parent
457451d3b2
commit
4c2d5051cd
1 changed files with 1789 additions and 1887 deletions
|
|
@ -1,326 +1,105 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Literal, cast, Any
|
||||
from typing import Literal
|
||||
|
||||
import numpy
|
||||
import shapely
|
||||
from shapely.geometry import Polygon, box, MultiPolygon
|
||||
from shapely.ops import unary_union
|
||||
from shapely.affinity import translate
|
||||
from shapely.affinity import translate as shapely_translate
|
||||
from shapely.geometry import Polygon, box
|
||||
|
||||
from inire.constants import DEFAULT_SEARCH_GRID_SNAP_UM, TOLERANCE_LINEAR, TOLERANCE_ANGULAR
|
||||
from .primitives import Port
|
||||
from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR
|
||||
from .primitives import Port, rotation_matrix2
|
||||
|
||||
|
||||
def snap_search_grid(value: float, snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM) -> float:
|
||||
"""
|
||||
Snap a coordinate to the nearest search grid unit.
|
||||
"""
|
||||
return round(value / snap_size) * snap_size
|
||||
def _normalize_length(value: float) -> float:
|
||||
return float(value)
|
||||
|
||||
|
||||
class ComponentResult:
|
||||
"""
|
||||
Standard container for generated move geometry and state.
|
||||
Supports Lazy Evaluation for translation to improve performance.
|
||||
"""
|
||||
__slots__ = (
|
||||
'_geometry', '_dilated_geometry', '_proxy_geometry', '_actual_geometry', '_dilated_actual_geometry',
|
||||
'end_port', 'length', 'move_type', '_bounds', '_dilated_bounds',
|
||||
'_total_bounds', '_total_dilated_bounds', '_bounds_cached', '_total_geom_list', '_offsets', '_coords_cache',
|
||||
'_base_result', '_offset', 'rel_gx', 'rel_gy', 'rel_go'
|
||||
"geometry",
|
||||
"dilated_geometry",
|
||||
"proxy_geometry",
|
||||
"actual_geometry",
|
||||
"dilated_actual_geometry",
|
||||
"end_port",
|
||||
"length",
|
||||
"move_type",
|
||||
"_bounds",
|
||||
"_total_bounds",
|
||||
"_dilated_bounds",
|
||||
"_total_dilated_bounds",
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
geometry: list[Polygon] | None = None,
|
||||
end_port: Port | None = None,
|
||||
length: float = 0.0,
|
||||
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,
|
||||
skip_bounds: bool = False,
|
||||
move_type: str = 'Unknown',
|
||||
_total_geom_list: list[Polygon] | None = None,
|
||||
_offsets: list[int] | None = None,
|
||||
_coords_cache: numpy.ndarray | None = None,
|
||||
_base_result: ComponentResult | None = None,
|
||||
_offset: tuple[float, float] | None = None,
|
||||
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
|
||||
rel_gx: int | None = None,
|
||||
rel_gy: int | None = None,
|
||||
rel_go: int | None = None
|
||||
) -> None:
|
||||
self,
|
||||
geometry: list[Polygon],
|
||||
end_port: Port,
|
||||
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.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 = length
|
||||
self.length = float(length)
|
||||
self.move_type = move_type
|
||||
|
||||
self._base_result = _base_result
|
||||
self._offset = _offset
|
||||
self._bounds_cached = False
|
||||
|
||||
if rel_gx is not None:
|
||||
self.rel_gx = rel_gx
|
||||
self.rel_gy = rel_gy
|
||||
self.rel_go = rel_go
|
||||
elif end_port:
|
||||
inv_snap = 1.0 / snap_size
|
||||
self.rel_gx = int(round(end_port.x * inv_snap))
|
||||
self.rel_gy = int(round(end_port.y * inv_snap))
|
||||
self.rel_go = int(round(end_port.orientation))
|
||||
else:
|
||||
self.rel_gx = 0; self.rel_gy = 0; self.rel_go = 0
|
||||
|
||||
if _base_result is not None:
|
||||
# Lazy Mode
|
||||
self._geometry = None
|
||||
self._dilated_geometry = None
|
||||
self._proxy_geometry = None
|
||||
self._actual_geometry = None
|
||||
self._dilated_actual_geometry = None
|
||||
self._bounds = None
|
||||
self._bounds = [poly.bounds for poly in self.geometry]
|
||||
self._total_bounds = _combine_bounds(self._bounds)
|
||||
|
||||
if self.dilated_geometry is None:
|
||||
self._dilated_bounds = None
|
||||
self._total_bounds = None
|
||||
self._total_dilated_bounds = None
|
||||
else:
|
||||
# Eager Mode (Base Component)
|
||||
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
|
||||
|
||||
# These are mostly legacy/unused but kept for slot safety
|
||||
self._total_geom_list = _total_geom_list
|
||||
self._offsets = _offsets
|
||||
self._coords_cache = _coords_cache
|
||||
|
||||
if not skip_bounds and geometry:
|
||||
# Use plain tuples for bounds to avoid NumPy overhead
|
||||
self._bounds = [p.bounds for p in geometry]
|
||||
b0 = self._bounds[0]
|
||||
minx, miny, maxx, maxy = b0
|
||||
for i in range(1, len(self._bounds)):
|
||||
b = self._bounds[i]
|
||||
if b[0] < minx: minx = b[0]
|
||||
if b[1] < miny: miny = b[1]
|
||||
if b[2] > maxx: maxx = b[2]
|
||||
if b[3] > maxy: maxy = b[3]
|
||||
self._total_bounds = (minx, miny, maxx, maxy)
|
||||
|
||||
if dilated_geometry is not None:
|
||||
self._dilated_bounds = [p.bounds for p in dilated_geometry]
|
||||
b0 = self._dilated_bounds[0]
|
||||
minx, miny, maxx, maxy = b0
|
||||
for i in range(1, len(self._dilated_bounds)):
|
||||
b = self._dilated_bounds[i]
|
||||
if b[0] < minx: minx = b[0]
|
||||
if b[1] < miny: miny = b[1]
|
||||
if b[2] > maxx: maxx = b[2]
|
||||
if b[3] > maxy: maxy = b[3]
|
||||
self._total_dilated_bounds = (minx, miny, maxx, maxy)
|
||||
else:
|
||||
self._dilated_bounds = None
|
||||
self._total_dilated_bounds = None
|
||||
else:
|
||||
self._bounds = None
|
||||
self._total_bounds = None
|
||||
self._dilated_bounds = None
|
||||
self._total_dilated_bounds = None
|
||||
self._bounds_cached = True
|
||||
|
||||
def _ensure_evaluated(self, attr_name: str) -> None:
|
||||
if self._base_result is None:
|
||||
return
|
||||
|
||||
# Check if specific attribute is already translated
|
||||
internal_name = f'_{attr_name}'
|
||||
if getattr(self, internal_name) is not None:
|
||||
return
|
||||
|
||||
# Perform Translation for the specific attribute only
|
||||
base_geoms = getattr(self._base_result, internal_name)
|
||||
if base_geoms is None:
|
||||
return
|
||||
|
||||
dx, dy = self._offset
|
||||
# Use shapely.affinity.translate (imported at top level)
|
||||
translated_geoms = [translate(p, dx, dy) for p in base_geoms]
|
||||
setattr(self, internal_name, translated_geoms)
|
||||
|
||||
@property
|
||||
def geometry(self) -> list[Polygon]:
|
||||
self._ensure_evaluated('geometry')
|
||||
return self._geometry
|
||||
|
||||
@property
|
||||
def dilated_geometry(self) -> list[Polygon] | None:
|
||||
self._ensure_evaluated('dilated_geometry')
|
||||
return self._dilated_geometry
|
||||
|
||||
@property
|
||||
def proxy_geometry(self) -> list[Polygon] | None:
|
||||
self._ensure_evaluated('proxy_geometry')
|
||||
return self._proxy_geometry
|
||||
|
||||
@property
|
||||
def actual_geometry(self) -> list[Polygon] | None:
|
||||
self._ensure_evaluated('actual_geometry')
|
||||
return self._actual_geometry
|
||||
|
||||
@property
|
||||
def dilated_actual_geometry(self) -> list[Polygon] | None:
|
||||
self._ensure_evaluated('dilated_actual_geometry')
|
||||
return self._dilated_actual_geometry
|
||||
self._dilated_bounds = [poly.bounds for poly in self.dilated_geometry]
|
||||
self._total_dilated_bounds = _combine_bounds(self._dilated_bounds)
|
||||
|
||||
@property
|
||||
def bounds(self) -> list[tuple[float, float, float, float]]:
|
||||
if not self._bounds_cached:
|
||||
self._ensure_bounds_evaluated()
|
||||
return self._bounds
|
||||
|
||||
@property
|
||||
def total_bounds(self) -> tuple[float, float, float, float]:
|
||||
if not self._bounds_cached:
|
||||
self._ensure_bounds_evaluated()
|
||||
return self._total_bounds
|
||||
|
||||
@property
|
||||
def dilated_bounds(self) -> list[tuple[float, float, float, float]] | None:
|
||||
if not self._bounds_cached:
|
||||
self._ensure_bounds_evaluated()
|
||||
return self._dilated_bounds
|
||||
|
||||
@property
|
||||
def total_dilated_bounds(self) -> tuple[float, float, float, float] | None:
|
||||
if not self._bounds_cached:
|
||||
self._ensure_bounds_evaluated()
|
||||
return self._total_dilated_bounds
|
||||
|
||||
def _ensure_bounds_evaluated(self) -> None:
|
||||
if self._bounds_cached: return
|
||||
base = self._base_result
|
||||
if base is not None:
|
||||
dx, dy = self._offset
|
||||
# Direct tuple creation is much faster than NumPy for single AABBs
|
||||
if base._bounds is not None:
|
||||
self._bounds = [(b[0]+dx, b[1]+dy, b[2]+dx, b[3]+dy) for b in base._bounds]
|
||||
if base._total_bounds is not None:
|
||||
b = base._total_bounds
|
||||
self._total_bounds = (b[0]+dx, b[1]+dy, b[2]+dx, b[3]+dy)
|
||||
if base._dilated_bounds is not None:
|
||||
self._dilated_bounds = [(b[0]+dx, b[1]+dy, b[2]+dx, b[3]+dy) for b in base._dilated_bounds]
|
||||
if base._total_dilated_bounds is not None:
|
||||
b = base._total_dilated_bounds
|
||||
self._total_dilated_bounds = (b[0]+dx, b[1]+dy, b[2]+dx, b[3]+dy)
|
||||
self._bounds_cached = True
|
||||
|
||||
def translate(self, dx: float, dy: float, rel_gx: int | None = None, rel_gy: int | None = None, rel_go: int | None = None) -> ComponentResult:
|
||||
"""
|
||||
Create a new ComponentResult translated by (dx, dy).
|
||||
"""
|
||||
new_port = Port(self.end_port.x + dx, self.end_port.y + dy, self.end_port.orientation, snap=False)
|
||||
|
||||
# LAZY TRANSLATE
|
||||
if self._base_result:
|
||||
base = self._base_result
|
||||
current_offset = self._offset
|
||||
new_offset = (current_offset[0] + dx, current_offset[1] + dy)
|
||||
else:
|
||||
base = self
|
||||
new_offset = (dx, dy)
|
||||
|
||||
def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
|
||||
return ComponentResult(
|
||||
end_port=new_port,
|
||||
geometry=[shapely_translate(poly, dx, dy) for poly in self.geometry],
|
||||
end_port=self.end_port + [dx, dy, 0],
|
||||
length=self.length,
|
||||
move_type=self.move_type,
|
||||
_base_result=base,
|
||||
_offset=new_offset,
|
||||
rel_gx=rel_gx,
|
||||
rel_gy=rel_gy,
|
||||
rel_go=rel_go
|
||||
dilated_geometry=None if self.dilated_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.dilated_geometry],
|
||||
proxy_geometry=None if self.proxy_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.proxy_geometry],
|
||||
actual_geometry=None if self.actual_geometry is None else [shapely_translate(poly, dx, dy) for poly in self.actual_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],
|
||||
)
|
||||
|
||||
|
||||
class Straight:
|
||||
"""
|
||||
Move generator for straight waveguide segments.
|
||||
"""
|
||||
@staticmethod
|
||||
def generate(
|
||||
start_port: Port,
|
||||
length: float,
|
||||
width: float,
|
||||
snap_to_grid: bool = True,
|
||||
dilation: float = 0.0,
|
||||
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
|
||||
) -> ComponentResult:
|
||||
"""
|
||||
Generate a straight waveguide segment.
|
||||
"""
|
||||
rad = numpy.radians(start_port.orientation)
|
||||
cos_val = numpy.cos(rad)
|
||||
sin_val = numpy.sin(rad)
|
||||
|
||||
ex = start_port.x + length * cos_val
|
||||
ey = start_port.y + length * sin_val
|
||||
|
||||
if snap_to_grid:
|
||||
ex = snap_search_grid(ex, snap_size)
|
||||
ey = snap_search_grid(ey, snap_size)
|
||||
|
||||
end_port = Port(ex, ey, start_port.orientation)
|
||||
actual_length = numpy.sqrt((end_port.x - start_port.x)**2 + (end_port.y - start_port.y)**2)
|
||||
|
||||
# Create polygons using vectorized points
|
||||
half_w = width / 2.0
|
||||
pts_raw = numpy.array([
|
||||
[0, half_w],
|
||||
[actual_length, half_w],
|
||||
[actual_length, -half_w],
|
||||
[0, -half_w]
|
||||
])
|
||||
|
||||
# Rotation matrix (standard 2D rotation)
|
||||
rot_matrix = numpy.array([[cos_val, -sin_val], [sin_val, cos_val]])
|
||||
|
||||
# Transform points: P' = R * P + T
|
||||
poly_points = (pts_raw @ rot_matrix.T) + [start_port.x, start_port.y]
|
||||
geom = [Polygon(poly_points)]
|
||||
|
||||
dilated_geom = None
|
||||
if dilation > 0:
|
||||
# Direct calculation of dilated rectangle instead of expensive buffer()
|
||||
half_w_dil = half_w + dilation
|
||||
pts_dil = numpy.array([
|
||||
[-dilation, half_w_dil],
|
||||
[actual_length + dilation, half_w_dil],
|
||||
[actual_length + dilation, -half_w_dil],
|
||||
[-dilation, -half_w_dil]
|
||||
])
|
||||
poly_points_dil = (pts_dil @ rot_matrix.T) + [start_port.x, start_port.y]
|
||||
dilated_geom = [Polygon(poly_points_dil)]
|
||||
|
||||
# Pre-calculate grid indices for faster ComponentResult init
|
||||
inv_snap = 1.0 / snap_size
|
||||
rgx = int(round(ex * inv_snap))
|
||||
rgy = int(round(ey * inv_snap))
|
||||
rgo = int(round(start_port.orientation))
|
||||
|
||||
# For straight segments, geom IS the actual geometry
|
||||
return ComponentResult(
|
||||
geometry=geom, end_port=end_port, length=actual_length,
|
||||
dilated_geometry=dilated_geom, actual_geometry=geom,
|
||||
dilated_actual_geometry=dilated_geom, move_type='Straight',
|
||||
snap_size=snap_size, rel_gx=rgx, rel_gy=rgy, rel_go=rgo
|
||||
)
|
||||
def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]:
|
||||
arr = numpy.asarray(bounds_list, dtype=numpy.float64)
|
||||
return (
|
||||
float(arr[:, 0].min()),
|
||||
float(arr[:, 1].min()),
|
||||
float(arr[:, 2].max()),
|
||||
float(arr[:, 3].max()),
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
ratio = max(0.0, min(1.0, 1.0 - sagitta / radius))
|
||||
|
|
@ -332,350 +111,223 @@ def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) ->
|
|||
|
||||
|
||||
def _get_arc_polygons(
|
||||
cx: float,
|
||||
cy: float,
|
||||
radius: float,
|
||||
width: float,
|
||||
t_start: float,
|
||||
t_end: float,
|
||||
sagitta: float = 0.01,
|
||||
dilation: float = 0.0,
|
||||
) -> list[Polygon]:
|
||||
"""
|
||||
Helper to generate arc-shaped polygons using vectorized NumPy operations.
|
||||
"""
|
||||
num_segments = _get_num_segments(radius, float(numpy.degrees(abs(t_end - t_start))), sagitta)
|
||||
cxy: tuple[float, float],
|
||||
radius: float,
|
||||
width: float,
|
||||
ts: tuple[float, float],
|
||||
sagitta: float = 0.01,
|
||||
dilation: float = 0.0,
|
||||
) -> list[Polygon]:
|
||||
t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1])
|
||||
num_segments = _get_num_segments(radius, abs(ts[1] - ts[0]), sagitta)
|
||||
angles = numpy.linspace(t_start, t_end, num_segments + 1)
|
||||
|
||||
cos_a = numpy.cos(angles)
|
||||
sin_a = numpy.sin(angles)
|
||||
|
||||
|
||||
cx, cy = cxy
|
||||
inner_radius = radius - width / 2.0 - dilation
|
||||
outer_radius = radius + width / 2.0 + dilation
|
||||
|
||||
inner_points = numpy.stack([cx + inner_radius * cos_a, cy + inner_radius * sin_a], axis=1)
|
||||
outer_points = numpy.stack([cx + outer_radius * cos_a[::-1], cy + outer_radius * sin_a[::-1]], axis=1)
|
||||
|
||||
# Concatenate inner and outer points to form the polygon ring
|
||||
poly_points = numpy.concatenate([inner_points, outer_points])
|
||||
|
||||
return [Polygon(poly_points)]
|
||||
|
||||
cos_a = numpy.cos(angles)
|
||||
sin_a = numpy.sin(angles)
|
||||
|
||||
inner_points = numpy.column_stack((cx + inner_radius * cos_a, cy + inner_radius * sin_a))
|
||||
outer_points = numpy.column_stack((cx + outer_radius * cos_a[::-1], cy + outer_radius * sin_a[::-1]))
|
||||
return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))]
|
||||
|
||||
|
||||
def _clip_bbox(
|
||||
cx: float,
|
||||
cy: float,
|
||||
radius: float,
|
||||
width: float,
|
||||
t_start: float,
|
||||
t_end: float,
|
||||
) -> Polygon:
|
||||
"""
|
||||
Generates a rotationally invariant bounding polygon for an arc.
|
||||
"""
|
||||
sweep = abs(t_end - t_start)
|
||||
if sweep > 2 * numpy.pi:
|
||||
sweep = sweep % (2 * numpy.pi)
|
||||
|
||||
mid_angle = (t_start + t_end) / 2.0
|
||||
# Handle wrap-around for mid_angle
|
||||
if abs(t_end - t_start) > numpy.pi:
|
||||
mid_angle += numpy.pi
|
||||
|
||||
r_out = radius + width / 2.0
|
||||
r_in = max(0.0, radius - width / 2.0)
|
||||
|
||||
half_sweep = sweep / 2.0
|
||||
|
||||
# Define vertices in local space (center at 0,0, symmetry axis along +X)
|
||||
cos_hs = numpy.cos(half_sweep)
|
||||
cos_hs2 = numpy.cos(half_sweep / 2.0)
|
||||
|
||||
# Distance to peak from center: r_out / cos(hs/2)
|
||||
peak_r = r_out / cos_hs2
|
||||
|
||||
local_verts = [
|
||||
[r_in * numpy.cos(-half_sweep), r_in * numpy.sin(-half_sweep)],
|
||||
[r_out * numpy.cos(-half_sweep), r_out * numpy.sin(-half_sweep)],
|
||||
[peak_r * numpy.cos(-half_sweep/2), peak_r * numpy.sin(-half_sweep/2)],
|
||||
[peak_r * numpy.cos(half_sweep/2), peak_r * numpy.sin(half_sweep/2)],
|
||||
[r_out * numpy.cos(half_sweep), r_out * numpy.sin(half_sweep)],
|
||||
[r_in * numpy.cos(half_sweep), r_in * numpy.sin(half_sweep)],
|
||||
[r_in, 0.0]
|
||||
]
|
||||
|
||||
# Rotate and translate to world space
|
||||
cos_m = numpy.cos(mid_angle)
|
||||
sin_m = numpy.sin(mid_angle)
|
||||
rot = numpy.array([[cos_m, -sin_m], [sin_m, cos_m]])
|
||||
|
||||
world_verts = (numpy.array(local_verts) @ rot.T) + [cx, cy]
|
||||
|
||||
return Polygon(world_verts)
|
||||
def _clip_bbox(cxy: tuple[float, float], radius: float, width: float, ts: tuple[float, float], clip_margin: float) -> Polygon:
|
||||
arc_poly = _get_arc_polygons(cxy, radius, width, ts)[0]
|
||||
minx, miny, maxx, maxy = arc_poly.bounds
|
||||
bbox_poly = box(minx, miny, maxx, maxy)
|
||||
shrink = min(clip_margin, max(radius, width))
|
||||
return bbox_poly.buffer(-shrink, join_style=2) if shrink > 0 else bbox_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,
|
||||
t_start: float | None = None,
|
||||
t_end: float | None = None,
|
||||
) -> 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,
|
||||
cxy: tuple[float, float],
|
||||
clip_margin: float,
|
||||
ts: tuple[float, float],
|
||||
) -> list[Polygon]:
|
||||
if isinstance(collision_type, Polygon):
|
||||
# Translate the custom polygon to the bend center (cx, cy)
|
||||
return [shapely.transform(collision_type, lambda x: x + [cx, cy])]
|
||||
|
||||
return [shapely_translate(collision_type, cxy[0], cxy[1])]
|
||||
if collision_type == "arc":
|
||||
return [arc_poly]
|
||||
|
||||
if collision_type == "clipped_bbox" and t_start is not None and t_end is not None:
|
||||
return [_clip_bbox(cx, cy, radius, width, t_start, t_end)]
|
||||
if collision_type == "clipped_bbox":
|
||||
clipped = _clip_bbox(cxy, radius, width, ts, clip_margin)
|
||||
return [clipped if not clipped.is_empty else box(*arc_poly.bounds)]
|
||||
return [box(*arc_poly.bounds)]
|
||||
|
||||
# Bounding box of the high-fidelity arc (fallback for bbox or missing angles)
|
||||
minx, miny, maxx, maxy = arc_poly.bounds
|
||||
bbox_poly = box(minx, miny, maxx, maxy)
|
||||
|
||||
if collision_type == "bbox":
|
||||
return [bbox_poly]
|
||||
|
||||
return [arc_poly]
|
||||
class Straight:
|
||||
@staticmethod
|
||||
def generate(
|
||||
start_port: Port,
|
||||
length: float,
|
||||
width: float,
|
||||
dilation: float = 0.0,
|
||||
) -> ComponentResult:
|
||||
rot2 = rotation_matrix2(start_port.r)
|
||||
length_f = _normalize_length(length)
|
||||
disp = rot2 @ numpy.array((length_f, 0.0))
|
||||
end_port = Port(start_port.x + disp[0], start_port.y + disp[1], start_port.r)
|
||||
|
||||
half_w = width / 2.0
|
||||
pts = numpy.array(((0.0, half_w), (length_f, half_w), (length_f, -half_w), (0.0, -half_w)))
|
||||
poly_points = (pts @ rot2.T) + numpy.array((start_port.x, start_port.y))
|
||||
geometry = [Polygon(poly_points)]
|
||||
|
||||
dilated_geometry = None
|
||||
if dilation > 0:
|
||||
half_w_d = half_w + dilation
|
||||
pts_d = numpy.array(((-dilation, half_w_d), (length_f + dilation, half_w_d), (length_f + dilation, -half_w_d), (-dilation, -half_w_d)))
|
||||
poly_points_d = (pts_d @ rot2.T) + numpy.array((start_port.x, start_port.y))
|
||||
dilated_geometry = [Polygon(poly_points_d)]
|
||||
|
||||
return ComponentResult(
|
||||
geometry=geometry,
|
||||
end_port=end_port,
|
||||
length=abs(length_f),
|
||||
move_type="Straight",
|
||||
dilated_geometry=dilated_geometry,
|
||||
actual_geometry=geometry,
|
||||
dilated_actual_geometry=dilated_geometry,
|
||||
)
|
||||
|
||||
|
||||
class Bend90:
|
||||
"""
|
||||
Move generator for 90-degree waveguide bends.
|
||||
"""
|
||||
@staticmethod
|
||||
def generate(
|
||||
start_port: Port,
|
||||
radius: float,
|
||||
width: float,
|
||||
direction: Literal["CW", "CCW"],
|
||||
sagitta: float = 0.01,
|
||||
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
|
||||
clip_margin: float = 10.0,
|
||||
dilation: float = 0.0,
|
||||
snap_to_grid: bool = True,
|
||||
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
|
||||
) -> ComponentResult:
|
||||
"""
|
||||
Generate a 90-degree bend.
|
||||
"""
|
||||
rad_start = numpy.radians(start_port.orientation)
|
||||
|
||||
# Center of the arc
|
||||
if direction == "CCW":
|
||||
cx = start_port.x + radius * numpy.cos(rad_start + numpy.pi / 2)
|
||||
cy = start_port.y + radius * numpy.sin(rad_start + numpy.pi / 2)
|
||||
t_start = rad_start - numpy.pi / 2
|
||||
t_end = t_start + numpy.pi / 2
|
||||
new_ori = (start_port.orientation + 90) % 360
|
||||
else:
|
||||
cx = start_port.x + radius * numpy.cos(rad_start - numpy.pi / 2)
|
||||
cy = start_port.y + radius * numpy.sin(rad_start - numpy.pi / 2)
|
||||
t_start = rad_start + numpy.pi / 2
|
||||
t_end = t_start - numpy.pi / 2
|
||||
new_ori = (start_port.orientation - 90) % 360
|
||||
start_port: Port,
|
||||
radius: float,
|
||||
width: float,
|
||||
direction: Literal["CW", "CCW"],
|
||||
sagitta: float = 0.01,
|
||||
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
|
||||
clip_margin: float = 10.0,
|
||||
dilation: float = 0.0,
|
||||
) -> ComponentResult:
|
||||
rot2 = rotation_matrix2(start_port.r)
|
||||
sign = 1 if direction == "CCW" else -1
|
||||
|
||||
# Snap the end point to the grid
|
||||
ex_raw = cx + radius * numpy.cos(t_end)
|
||||
ey_raw = cy + radius * numpy.sin(t_end)
|
||||
|
||||
if snap_to_grid:
|
||||
ex = snap_search_grid(ex_raw, snap_size)
|
||||
ey = snap_search_grid(ey_raw, snap_size)
|
||||
else:
|
||||
ex, ey = ex_raw, ey_raw
|
||||
|
||||
# Slightly adjust radius and t_end to hit snapped point exactly
|
||||
dx, dy = ex - cx, ey - cy
|
||||
actual_radius = numpy.sqrt(dx**2 + dy**2)
|
||||
|
||||
t_end_snapped = numpy.arctan2(dy, dx)
|
||||
# Ensure directionality and approx 90 degree sweep
|
||||
if direction == "CCW":
|
||||
while t_end_snapped <= t_start:
|
||||
t_end_snapped += 2 * numpy.pi
|
||||
while t_end_snapped > t_start + numpy.pi:
|
||||
t_end_snapped -= 2 * numpy.pi
|
||||
else:
|
||||
while t_end_snapped >= t_start:
|
||||
t_end_snapped -= 2 * numpy.pi
|
||||
while t_end_snapped < t_start - numpy.pi:
|
||||
t_end_snapped += 2 * numpy.pi
|
||||
t_end = t_end_snapped
|
||||
center_local = numpy.array((0.0, sign * radius))
|
||||
end_local = numpy.array((radius, sign * radius))
|
||||
center_xy = (rot2 @ center_local) + numpy.array((start_port.x, start_port.y))
|
||||
end_xy = (rot2 @ end_local) + numpy.array((start_port.x, start_port.y))
|
||||
end_port = Port(end_xy[0], end_xy[1], start_port.r + sign * 90)
|
||||
|
||||
end_port = Port(ex, ey, new_ori)
|
||||
start_theta = start_port.r - sign * 90
|
||||
end_theta = start_port.r
|
||||
ts = (float(start_theta), float(end_theta))
|
||||
|
||||
arc_polys = _get_arc_polygons(cx, cy, actual_radius, width, t_start, t_end, sagitta)
|
||||
arc_polys = _get_arc_polygons((float(center_xy[0]), float(center_xy[1])), radius, width, ts, sagitta)
|
||||
collision_polys = _apply_collision_model(
|
||||
arc_polys[0], collision_type, actual_radius, width, cx, cy, clip_margin, t_start, t_end
|
||||
arc_polys[0],
|
||||
collision_type,
|
||||
radius,
|
||||
width,
|
||||
(float(center_xy[0]), float(center_xy[1])),
|
||||
clip_margin,
|
||||
ts,
|
||||
)
|
||||
|
||||
proxy_geom = None
|
||||
proxy_geometry = None
|
||||
if collision_type == "arc":
|
||||
# Auto-generate a clipped_bbox proxy for tiered collision checks
|
||||
proxy_geom = _apply_collision_model(
|
||||
arc_polys[0], "clipped_bbox", actual_radius, width, cx, cy, clip_margin, t_start, t_end
|
||||
proxy_geometry = _apply_collision_model(
|
||||
arc_polys[0],
|
||||
"clipped_bbox",
|
||||
radius,
|
||||
width,
|
||||
(float(center_xy[0]), float(center_xy[1])),
|
||||
clip_margin,
|
||||
ts,
|
||||
)
|
||||
|
||||
dilated_geom = None
|
||||
dilated_actual_geom = None
|
||||
dilated_actual_geometry = None
|
||||
dilated_geometry = None
|
||||
if dilation > 0:
|
||||
dilated_actual_geom = _get_arc_polygons(cx, cy, actual_radius, width, t_start, t_end, sagitta, dilation=dilation)
|
||||
if collision_type == "arc":
|
||||
dilated_geom = dilated_actual_geom
|
||||
else:
|
||||
dilated_geom = [p.buffer(dilation) for p in collision_polys]
|
||||
|
||||
# Pre-calculate grid indices for faster ComponentResult init
|
||||
inv_snap = 1.0 / snap_size
|
||||
rgx = int(round(ex * inv_snap))
|
||||
rgy = int(round(ey * inv_snap))
|
||||
rgo = int(round(new_ori))
|
||||
dilated_actual_geometry = _get_arc_polygons((float(center_xy[0]), float(center_xy[1])), radius, width, ts, sagitta, dilation=dilation)
|
||||
dilated_geometry = dilated_actual_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in collision_polys]
|
||||
|
||||
return ComponentResult(
|
||||
geometry=collision_polys,
|
||||
end_port=end_port,
|
||||
length=actual_radius * numpy.abs(t_end - t_start),
|
||||
dilated_geometry=dilated_geom,
|
||||
proxy_geometry=proxy_geom,
|
||||
geometry=collision_polys,
|
||||
end_port=end_port,
|
||||
length=abs(radius) * numpy.pi / 2.0,
|
||||
move_type="Bend90",
|
||||
dilated_geometry=dilated_geometry,
|
||||
proxy_geometry=proxy_geometry,
|
||||
actual_geometry=arc_polys,
|
||||
dilated_actual_geometry=dilated_actual_geom,
|
||||
move_type='Bend90',
|
||||
snap_size=snap_size,
|
||||
rel_gx=rgx, rel_gy=rgy, rel_go=rgo
|
||||
dilated_actual_geometry=dilated_actual_geometry,
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
dilation: float = 0.0,
|
||||
snap_to_grid: bool = True,
|
||||
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
|
||||
) -> 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,
|
||||
dilation: float = 0.0,
|
||||
) -> ComponentResult:
|
||||
if abs(offset) >= 2 * radius:
|
||||
raise ValueError(f"SBend offset {offset} must be less than 2*radius {2 * radius}")
|
||||
|
||||
theta_init = numpy.arccos(1 - abs(offset) / (2 * radius))
|
||||
dx_init = 2 * radius * numpy.sin(theta_init)
|
||||
rad_start = numpy.radians(start_port.orientation)
|
||||
|
||||
# Target point
|
||||
ex_raw = start_port.x + dx_init * numpy.cos(rad_start) - offset * numpy.sin(rad_start)
|
||||
ey_raw = start_port.y + dx_init * numpy.sin(rad_start) + offset * numpy.cos(rad_start)
|
||||
sign = 1 if offset >= 0 else -1
|
||||
theta = numpy.arccos(1.0 - abs(offset) / (2.0 * radius))
|
||||
dx = 2.0 * radius * numpy.sin(theta)
|
||||
theta_deg = float(numpy.degrees(theta))
|
||||
|
||||
if snap_to_grid:
|
||||
ex = snap_search_grid(ex_raw, snap_size)
|
||||
ey = snap_search_grid(ey_raw, snap_size)
|
||||
else:
|
||||
ex, ey = ex_raw, ey_raw
|
||||
rot2 = rotation_matrix2(start_port.r)
|
||||
end_local = numpy.array((dx, offset))
|
||||
end_xy = (rot2 @ end_local) + numpy.array((start_port.x, start_port.y))
|
||||
end_port = Port(end_xy[0], end_xy[1], start_port.r)
|
||||
|
||||
end_port = Port(ex, ey, start_port.orientation)
|
||||
c1_local = numpy.array((0.0, sign * radius))
|
||||
c2_local = numpy.array((dx, offset - sign * radius))
|
||||
c1_xy = (rot2 @ c1_local) + numpy.array((start_port.x, start_port.y))
|
||||
c2_xy = (rot2 @ c2_local) + numpy.array((start_port.x, start_port.y))
|
||||
|
||||
# Solve for theta and radius that hit (ex, ey) exactly
|
||||
local_dx = (ex - start_port.x) * numpy.cos(rad_start) + (ey - start_port.y) * numpy.sin(rad_start)
|
||||
local_dy = -(ex - start_port.x) * numpy.sin(rad_start) + (ey - start_port.y) * numpy.cos(rad_start)
|
||||
|
||||
# tan(theta / 2) = local_dy / local_dx
|
||||
theta = 2 * numpy.arctan2(abs(local_dy), local_dx)
|
||||
|
||||
if abs(theta) < TOLERANCE_ANGULAR:
|
||||
# De-generate to straight
|
||||
actual_len = numpy.sqrt(local_dx**2 + local_dy**2)
|
||||
return Straight.generate(start_port, actual_len, width, snap_to_grid=False, dilation=dilation, snap_size=snap_size)
|
||||
ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg))
|
||||
second_base = start_port.r + (90 if sign > 0 else 270)
|
||||
ts2 = (float(second_base + sign * theta_deg), float(second_base))
|
||||
|
||||
denom = (2 * (1 - numpy.cos(theta)))
|
||||
if abs(denom) < TOLERANCE_LINEAR:
|
||||
raise ValueError("SBend calculation failed: radius denominator zero")
|
||||
|
||||
actual_radius = abs(local_dy) / denom
|
||||
|
||||
# Safety Check: Reject SBends with tiny radii that would cause self-overlap
|
||||
if actual_radius < width:
|
||||
raise ValueError(f"SBend actual_radius {actual_radius:.3f} is too small (width={width})")
|
||||
arc1 = _get_arc_polygons((float(c1_xy[0]), float(c1_xy[1])), radius, width, ts1, sagitta)[0]
|
||||
arc2 = _get_arc_polygons((float(c2_xy[0]), float(c2_xy[1])), radius, width, ts2, sagitta)[0]
|
||||
actual_geometry = [arc1, arc2]
|
||||
geometry = [
|
||||
_apply_collision_model(arc1, collision_type, radius, width, (float(c1_xy[0]), float(c1_xy[1])), clip_margin, ts1)[0],
|
||||
_apply_collision_model(arc2, collision_type, radius, width, (float(c2_xy[0]), float(c2_xy[1])), clip_margin, ts2)[0],
|
||||
]
|
||||
|
||||
# Limit radius to prevent giant arcs
|
||||
if actual_radius > 100000.0:
|
||||
actual_len = numpy.sqrt(local_dx**2 + local_dy**2)
|
||||
return Straight.generate(start_port, actual_len, width, snap_to_grid=False, dilation=dilation, snap_size=snap_size)
|
||||
|
||||
direction = 1 if local_dy > 0 else -1
|
||||
c1_angle = rad_start + direction * numpy.pi / 2
|
||||
cx1 = start_port.x + actual_radius * numpy.cos(c1_angle)
|
||||
cy1 = start_port.y + actual_radius * numpy.sin(c1_angle)
|
||||
ts1, te1 = c1_angle + numpy.pi, c1_angle + numpy.pi + direction * theta
|
||||
|
||||
c2_angle = rad_start - direction * numpy.pi / 2
|
||||
cx2 = ex + actual_radius * numpy.cos(c2_angle)
|
||||
cy2 = ey + actual_radius * numpy.sin(c2_angle)
|
||||
te2 = c2_angle + numpy.pi
|
||||
ts2 = te2 + direction * theta
|
||||
|
||||
arc1 = _get_arc_polygons(cx1, cy1, actual_radius, width, ts1, te1, sagitta)[0]
|
||||
arc2 = _get_arc_polygons(cx2, cy2, actual_radius, width, ts2, te2, sagitta)[0]
|
||||
arc_polys = [arc1, arc2]
|
||||
|
||||
# Use the provided collision model for primary geometry
|
||||
col1 = _apply_collision_model(arc1, collision_type, actual_radius, width, cx1, cy1, clip_margin, ts1, te1)[0]
|
||||
col2 = _apply_collision_model(arc2, collision_type, actual_radius, width, cx2, cy2, clip_margin, ts2, te2)[0]
|
||||
collision_polys = [col1, col2]
|
||||
|
||||
proxy_geom = None
|
||||
proxy_geometry = None
|
||||
if collision_type == "arc":
|
||||
# Auto-generate proxies
|
||||
p1 = _apply_collision_model(arc1, "clipped_bbox", actual_radius, width, cx1, cy1, clip_margin, ts1, te1)[0]
|
||||
p2 = _apply_collision_model(arc2, "clipped_bbox", actual_radius, width, cx2, cy2, clip_margin, ts2, te2)[0]
|
||||
proxy_geom = [p1, p2]
|
||||
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_geom = None
|
||||
dilated_actual_geom = None
|
||||
dilated_actual_geometry = None
|
||||
dilated_geometry = None
|
||||
if dilation > 0:
|
||||
d1 = _get_arc_polygons(cx1, cy1, actual_radius, width, ts1, te1, sagitta, dilation=dilation)[0]
|
||||
d2 = _get_arc_polygons(cx2, cy2, actual_radius, width, ts2, te2, sagitta, dilation=dilation)[0]
|
||||
dilated_actual_geom = [d1, d2]
|
||||
|
||||
if collision_type == "arc":
|
||||
dilated_geom = dilated_actual_geom
|
||||
else:
|
||||
dilated_geom = [p.buffer(dilation) for p in collision_polys]
|
||||
|
||||
# Pre-calculate grid indices for faster ComponentResult init
|
||||
inv_snap = 1.0 / snap_size
|
||||
rgx = int(round(ex * inv_snap))
|
||||
rgy = int(round(ey * inv_snap))
|
||||
rgo = int(round(start_port.orientation))
|
||||
dilated_actual_geometry = [
|
||||
_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],
|
||||
]
|
||||
dilated_geometry = dilated_actual_geometry if collision_type == "arc" else [poly.buffer(dilation) for poly in geometry]
|
||||
|
||||
return ComponentResult(
|
||||
geometry=collision_polys,
|
||||
end_port=end_port,
|
||||
length=2 * actual_radius * theta,
|
||||
dilated_geometry=dilated_geom,
|
||||
proxy_geometry=proxy_geom,
|
||||
actual_geometry=arc_polys,
|
||||
dilated_actual_geometry=dilated_actual_geom,
|
||||
move_type='SBend',
|
||||
snap_size=snap_size,
|
||||
rel_gx=rgx, rel_gy=rgy, rel_go=rgo
|
||||
geometry=geometry,
|
||||
end_port=end_port,
|
||||
length=2.0 * radius * theta,
|
||||
move_type="SBend",
|
||||
dilated_geometry=dilated_geometry,
|
||||
proxy_geometry=proxy_geometry,
|
||||
actual_geometry=actual_geometry,
|
||||
dilated_actual_geometry=dilated_actual_geometry,
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue