performance improvements

This commit is contained in:
Jan Petykiewicz 2026-03-09 12:23:17 -07:00
commit 8424171946

View file

@ -1,14 +1,12 @@
from __future__ import annotations
from typing import Literal, cast, TYPE_CHECKING, Union, Any
from typing import Literal, cast
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)
@ -32,11 +30,14 @@ class ComponentResult:
"""
The result of a component generation: geometry, final port, and physical length.
"""
__slots__ = ('geometry', 'end_port', 'length')
__slots__ = ('geometry', 'dilated_geometry', 'end_port', 'length')
geometry: list[Polygon]
""" List of polygons representing the component geometry """
dilated_geometry: list[Polygon] | None
""" Optional list of pre-dilated polygons for collision optimization """
end_port: Port
""" The final port after the component """
@ -48,8 +49,10 @@ class ComponentResult:
geometry: list[Polygon],
end_port: Port,
length: float,
dilated_geometry: list[Polygon] | None = None,
) -> None:
self.geometry = geometry
self.dilated_geometry = dilated_geometry
self.end_port = end_port
self.length = length
@ -64,6 +67,7 @@ class Straight:
length: float,
width: float,
snap_to_grid: bool = True,
dilation: float = 0.0,
) -> ComponentResult:
"""
Generate a straight waveguide segment.
@ -73,16 +77,17 @@ class Straight:
length: Requested length.
width: Waveguide width.
snap_to_grid: Whether to snap the end port to the search grid.
dilation: Optional dilation distance for pre-calculating collision geometry.
Returns:
A ComponentResult containing the straight segment.
"""
rad = numpy.radians(start_port.orientation)
dx = length * numpy.cos(rad)
dy = length * numpy.sin(rad)
cos_val = numpy.cos(rad)
sin_val = numpy.sin(rad)
ex = start_port.x + dx
ey = start_port.y + dy
ex = start_port.x + length * cos_val
ey = start_port.y + length * sin_val
if snap_to_grid:
ex = snap_search_grid(ex)
@ -91,21 +96,36 @@ class Straight:
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 polygon
# Create polygons using vectorized points
half_w = width / 2.0
# Points relative to start port (0,0)
points = [(0, half_w), (actual_length, half_w), (actual_length, -half_w), (0, -half_w)]
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)]
# Transform points
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
ty = start_port.y + px * sin_val + py * cos_val
poly_points.append((tx, ty))
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)]
return ComponentResult(geometry=[Polygon(poly_points)], end_port=end_port, length=actual_length)
return ComponentResult(geometry=geom, end_port=end_port, length=actual_length, dilated_geometry=dilated_geom)
def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int:
@ -140,7 +160,7 @@ def _get_arc_polygons(
sagitta: float = 0.01,
) -> list[Polygon]:
"""
Helper to generate arc-shaped polygons.
Helper to generate arc-shaped polygons using vectorized NumPy operations.
Args:
cx, cy: Center coordinates.
@ -154,11 +174,20 @@ def _get_arc_polygons(
"""
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)
cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles)
inner_radius = radius - width / 2.0
outer_radius = radius + width / 2.0
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)]
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)]
def _clip_bbox(
@ -291,6 +320,7 @@ class Bend90:
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0,
dilation: float = 0.0,
) -> ComponentResult:
"""
Generate a 90-degree bend.
@ -303,6 +333,7 @@ class Bend90:
sagitta: Geometric fidelity.
collision_type: Collision model.
clip_margin: Margin for clipped_bbox.
dilation: Optional dilation distance for pre-calculating collision geometry.
Returns:
A ComponentResult containing the bend.
@ -323,8 +354,15 @@ class Bend90:
collision_polys = _apply_collision_model(
arc_polys[0], collision_type, radius, width, cx, cy, clip_margin
)
dilated_geom = [p.buffer(dilation) for p in collision_polys] if dilation > 0 else None
return ComponentResult(geometry=collision_polys, end_port=end_port, length=radius * numpy.pi / 2.0)
return ComponentResult(
geometry=collision_polys,
end_port=end_port,
length=radius * numpy.pi / 2.0,
dilated_geometry=dilated_geom
)
class SBend:
@ -340,6 +378,7 @@ class SBend:
sagitta: float = 0.01,
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
clip_margin: float = 10.0,
dilation: float = 0.0,
) -> ComponentResult:
"""
Generate a parametric S-bend (two tangent arcs).
@ -352,6 +391,7 @@ class SBend:
sagitta: Geometric fidelity.
collision_type: Collision model.
clip_margin: Margin for clipped_bbox.
dilation: Optional dilation distance for pre-calculating collision geometry.
Returns:
A ComponentResult containing the S-bend.
@ -385,13 +425,22 @@ class SBend:
arc2 = _get_arc_polygons(cx2, cy2, radius, width, ts2, te2, sagitta)[0]
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 = [cast('Polygon', unary_union(col1 + col2))]
col1 = _apply_collision_model(arc1, collision_type, radius, width, cx1, cy1, clip_margin)[0]
col2 = _apply_collision_model(arc2, collision_type, radius, width, cx2, cy2, clip_margin)[0]
# Optimization: keep as list instead of unary_union for search efficiency
collision_polys = [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
)
# For other models, we can either combine or keep separate.
# Keeping separate is generally better for CollisionEngine.
col1 = _apply_collision_model(arc1, collision_type, radius, width, cx1, cy1, clip_margin)[0]
col2 = _apply_collision_model(arc2, collision_type, radius, width, cx2, cy2, clip_margin)[0]
collision_polys = [col1, col2]
return ComponentResult(geometry=collision_polys, end_port=end_port, length=2 * radius * theta)
dilated_geom = [p.buffer(dilation) for p in collision_polys] if dilation > 0 else None
return ComponentResult(
geometry=collision_polys,
end_port=end_port,
length=2 * radius * theta,
dilated_geometry=dilated_geom
)