This commit is contained in:
Jan Petykiewicz 2026-03-09 20:37:03 -07:00
commit 8bf0ff279f

View file

@ -30,7 +30,7 @@ class ComponentResult:
"""
The result of a component generation: geometry, final port, and physical length.
"""
__slots__ = ('geometry', 'dilated_geometry', 'end_port', 'length')
__slots__ = ('geometry', 'dilated_geometry', 'end_port', 'length', 'bounds', 'dilated_bounds')
geometry: list[Polygon]
""" List of polygons representing the component geometry """
@ -44,6 +44,12 @@ class ComponentResult:
length: float
""" Physical length of the component path """
bounds: list[tuple[float, float, float, float]]
""" Pre-calculated bounds for each polygon in geometry """
dilated_bounds: list[tuple[float, float, float, float]] | None
""" Pre-calculated bounds for each polygon in dilated_geometry """
def __init__(
self,
geometry: list[Polygon],
@ -55,6 +61,22 @@ class ComponentResult:
self.dilated_geometry = dilated_geometry
self.end_port = end_port
self.length = length
self.bounds = [p.bounds for p in geometry]
self.dilated_bounds = [p.bounds for p in dilated_geometry] if dilated_geometry else None
def translate(self, dx: float, dy: float) -> ComponentResult:
"""
Create a new ComponentResult translated by (dx, dy).
"""
from shapely.affinity import translate
new_geom = [translate(p, dx, dy) for p in self.geometry]
new_dil = [translate(p, dx, dy) for p in self.dilated_geometry] if self.dilated_geometry else None
new_port = Port(self.end_port.x + dx, self.end_port.y + dy, self.end_port.orientation)
return ComponentResult(new_geom, new_port, self.length, new_dil)
class Straight:
@ -158,6 +180,7 @@ def _get_arc_polygons(
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.
@ -168,6 +191,7 @@ def _get_arc_polygons(
width: Waveguide width.
t_start, t_end: Start and end angles (radians).
sagitta: Geometric fidelity.
dilation: Optional dilation to apply directly to the arc.
Returns:
List containing the arc polygon.
@ -178,8 +202,8 @@ def _get_arc_polygons(
cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles)
inner_radius = radius - width / 2.0
outer_radius = radius + width / 2.0
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)
@ -200,21 +224,9 @@ def _clip_bbox(
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.
Clips corners of a bounding box for better collision modeling using direct vertex manipulation.
"""
res_poly = bbox
# Determine quadrant signs from arc centroid relative to center
# Determination of which corners to clip
ac = arc_poly.centroid
qsx = 1.0 if ac.x >= cx else -1.0
qsy = 1.0 if ac.y >= cy else -1.0
@ -223,46 +235,54 @@ def _clip_bbox(
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
# Initial vertices: [minx,miny], [maxx,miny], [maxx,maxy], [minx,maxy]
verts = [
numpy.array([minx, miny]),
numpy.array([maxx, miny]),
numpy.array([maxx, maxy]),
numpy.array([minx, maxy])
]
new_verts = []
for p in verts:
dx, dy = p[0] - cx, p[1] - 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
d_line = -1.0
if dist > r_out_cut:
d_line = r_out_cut * numpy.sqrt(2)
elif r_in_cut > 0 and dist < r_in_cut:
d_line = r_in_cut
if d_line > 0:
# This corner needs clipping. Replace one vertex with two at intersection of line and edges.
# Line: sx*(x-cx) + sy*(y-cy) = d_line
# Edge x=px: y = cy + (d_line - sx*(px-cx))/sy
# Edge y=py: x = cx + (d_line - sy*(py-cy))/sx
try:
p_edge_x = numpy.array([p[0], cy + (d_line - sx * (p[0] - cx)) / sy])
p_edge_y = numpy.array([cx + (d_line - sy * (p[1] - cy)) / sx, p[1]])
# Order matters for polygon winding.
# If we are at [minx, miny] and moving CCW towards [maxx, miny]:
# If we clip this corner, we should add p_edge_y then p_edge_x (or vice versa depending on orientation)
# For simplicity, we can just add both and let Polygon sort it out if it's convex,
# but better to be precise.
# Since we know the bounding box orientation, we can determine order.
# BUT: Difference was safer. Let's try a simpler approach:
# Just collect all possible vertices and use convex_hull if it's guaranteed convex.
# A clipped bbox is always convex.
new_verts.append(p_edge_x)
new_verts.append(p_edge_y)
except ZeroDivisionError:
new_verts.append(p)
else:
new_verts.append(p)
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
return Polygon(new_verts).convex_hull
def _apply_collision_model(
@ -355,7 +375,13 @@ class Bend90:
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
dilated_geom = None
if dilation > 0:
if collision_type == "arc":
dilated_geom = _get_arc_polygons(cx, cy, radius, width, t_start, t_end, sagitta, dilation=dilation)
else:
# For bbox or clipped_bbox, buffer the model itself (which is simpler than buffering the high-fidelity arc)
dilated_geom = [p.buffer(dilation) for p in collision_polys]
return ComponentResult(
geometry=collision_polys,
@ -436,7 +462,14 @@ class SBend:
col2 = _apply_collision_model(arc2, collision_type, radius, width, cx2, cy2, clip_margin)[0]
collision_polys = [col1, col2]
dilated_geom = [p.buffer(dilation) for p in collision_polys] if dilation > 0 else None
dilated_geom = None
if dilation > 0:
if collision_type == "arc":
d1 = _get_arc_polygons(cx1, cy1, radius, width, ts1, te1, sagitta, dilation=dilation)[0]
d2 = _get_arc_polygons(cx2, cy2, radius, width, ts2, te2, sagitta, dilation=dilation)[0]
dilated_geom = [d1, d2]
else:
dilated_geom = [p.buffer(dilation) for p in collision_polys]
return ComponentResult(
geometry=collision_polys,