performance bottleneck
This commit is contained in:
parent
c6116f88f3
commit
3810e64a5c
1 changed files with 298 additions and 412 deletions
|
|
@ -1,9 +1,10 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from typing import Literal, cast
|
||||
import math
|
||||
from typing import Literal, cast, Any
|
||||
import numpy
|
||||
import shapely
|
||||
from shapely.geometry import Polygon, box
|
||||
from shapely.geometry import Polygon, box, MultiPolygon
|
||||
from shapely.ops import unary_union
|
||||
|
||||
from .primitives import Port
|
||||
|
|
@ -17,54 +18,18 @@ SEARCH_GRID_SNAP_UM = 5.0
|
|||
def snap_search_grid(value: float, snap_size: float = SEARCH_GRID_SNAP_UM) -> float:
|
||||
"""
|
||||
Snap a coordinate to the nearest search grid unit.
|
||||
|
||||
Args:
|
||||
value: Value to snap.
|
||||
snap_size: The grid size to snap to.
|
||||
|
||||
Returns:
|
||||
Snapped value.
|
||||
"""
|
||||
if snap_size <= 0:
|
||||
return value
|
||||
return round(value / snap_size) * snap_size
|
||||
|
||||
|
||||
class ComponentResult:
|
||||
"""
|
||||
The result of a component generation: geometry, final port, and physical length.
|
||||
Standard container for generated move geometry and state.
|
||||
"""
|
||||
__slots__ = ('geometry', 'dilated_geometry', 'proxy_geometry', 'actual_geometry', 'end_port', 'length', 'bounds', 'dilated_bounds', 'move_type', '_t_cache')
|
||||
|
||||
geometry: list[Polygon]
|
||||
""" List of polygons representing the component geometry (could be proxy or arc) """
|
||||
|
||||
dilated_geometry: list[Polygon] | None
|
||||
""" Optional list of pre-dilated polygons for collision optimization """
|
||||
|
||||
proxy_geometry: list[Polygon] | None
|
||||
""" Simplified conservative proxy for tiered collision checks """
|
||||
|
||||
actual_geometry: list[Polygon] | None
|
||||
""" High-fidelity 'actual' geometry for visualization (always the arc) """
|
||||
|
||||
end_port: Port
|
||||
""" The final port after the component """
|
||||
|
||||
length: float
|
||||
""" Physical length of the component path """
|
||||
|
||||
bounds: numpy.ndarray
|
||||
""" Pre-calculated bounds for each polygon in geometry """
|
||||
|
||||
dilated_bounds: numpy.ndarray | None
|
||||
""" Pre-calculated bounds for each polygon in dilated_geometry """
|
||||
|
||||
move_type: str | None
|
||||
""" Identifier for the type of move (e.g. 'Straight', 'Bend90', 'SBend') """
|
||||
|
||||
_t_cache: dict[tuple[float, float], ComponentResult]
|
||||
""" Cache for translated versions of this result """
|
||||
__slots__ = (
|
||||
'geometry', 'dilated_geometry', 'proxy_geometry', 'actual_geometry',
|
||||
'end_port', 'length', 'move_type', 'bounds', 'dilated_bounds', '_t_cache'
|
||||
)
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
|
@ -75,7 +40,7 @@ class ComponentResult:
|
|||
proxy_geometry: list[Polygon] | None = None,
|
||||
actual_geometry: list[Polygon] | None = None,
|
||||
skip_bounds: bool = False,
|
||||
move_type: str | None = None,
|
||||
move_type: str = 'Unknown'
|
||||
) -> None:
|
||||
self.geometry = geometry
|
||||
self.dilated_geometry = dilated_geometry
|
||||
|
|
@ -100,7 +65,7 @@ class ComponentResult:
|
|||
if (dxr, dyr) in self._t_cache:
|
||||
return self._t_cache[(dxr, dyr)]
|
||||
|
||||
# Vectorized translation if possible, else list comp
|
||||
# Vectorized translation
|
||||
geoms = list(self.geometry)
|
||||
num_geom = len(self.geometry)
|
||||
|
||||
|
|
@ -117,13 +82,14 @@ class ComponentResult:
|
|||
geoms.extend(self.actual_geometry)
|
||||
offsets.append(len(geoms))
|
||||
|
||||
from shapely.affinity import translate
|
||||
translated = [translate(p, dx, dy) for p in geoms]
|
||||
import shapely
|
||||
coords = shapely.get_coordinates(geoms)
|
||||
translated = shapely.set_coordinates(geoms, coords + [dx, dy])
|
||||
|
||||
new_geom = translated[:offsets[0]]
|
||||
new_dil = translated[offsets[0]:offsets[1]] if self.dilated_geometry is not None else None
|
||||
new_proxy = translated[offsets[1]:offsets[2]] if self.proxy_geometry is not None else None
|
||||
new_actual = translated[offsets[2]:offsets[3]] if self.actual_geometry is not None else None
|
||||
new_geom = list(translated[:offsets[0]])
|
||||
new_dil = list(translated[offsets[0]:offsets[1]]) if self.dilated_geometry is not None else None
|
||||
new_proxy = list(translated[offsets[1]:offsets[2]]) if self.proxy_geometry is not None else None
|
||||
new_actual = list(translated[offsets[2]:offsets[3]]) if self.actual_geometry is not None else None
|
||||
|
||||
new_port = Port(self.end_port.x + dx, self.end_port.y + dy, self.end_port.orientation)
|
||||
res = ComponentResult(new_geom, new_port, self.length, new_dil, new_proxy, new_actual, skip_bounds=True, move_type=self.move_type)
|
||||
|
|
@ -156,17 +122,6 @@ class Straight:
|
|||
) -> 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.
|
||||
dilation: Optional dilation distance for pre-calculating collision geometry.
|
||||
snap_size: Grid size for snapping.
|
||||
|
||||
Returns:
|
||||
A ComponentResult containing the straight segment.
|
||||
"""
|
||||
rad = numpy.radians(start_port.orientation)
|
||||
cos_val = numpy.cos(rad)
|
||||
|
|
@ -218,14 +173,6 @@ 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.
|
||||
|
||||
Args:
|
||||
radius: Arc radius.
|
||||
angle_deg: Total angle turned.
|
||||
sagitta: Maximum allowed deviation.
|
||||
|
||||
Returns:
|
||||
Minimum number of segments needed.
|
||||
"""
|
||||
if radius <= 0:
|
||||
return 1
|
||||
|
|
@ -249,17 +196,6 @@ def _get_arc_polygons(
|
|||
) -> list[Polygon]:
|
||||
"""
|
||||
Helper to generate arc-shaped polygons using vectorized NumPy operations.
|
||||
|
||||
Args:
|
||||
cx, cy: Center coordinates.
|
||||
radius: Arc radius.
|
||||
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.
|
||||
"""
|
||||
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)
|
||||
|
|
@ -318,14 +254,12 @@ def _clip_bbox(
|
|||
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)
|
||||
angle = numpy.arctan2(dy, dx)
|
||||
|
||||
# Check if corner angle is within the arc's angular sweep
|
||||
angle_rel = (angle - ts_norm) % (2 * numpy.pi)
|
||||
is_in_sweep = angle_rel <= sweep + 1e-6
|
||||
|
||||
|
|
@ -379,48 +313,36 @@ def _apply_collision_model(
|
|||
) -> 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.
|
||||
t_start, t_end: Arc angles.
|
||||
|
||||
Returns:
|
||||
List of polygons representing the collision model.
|
||||
"""
|
||||
if isinstance(collision_type, Polygon):
|
||||
return [collision_type]
|
||||
|
||||
if collision_type == "arc":
|
||||
return [arc_poly]
|
||||
|
||||
# Get bounding box
|
||||
|
||||
# Bounding box of the high-fidelity arc
|
||||
minx, miny, maxx, maxy = arc_poly.bounds
|
||||
bbox = box(minx, miny, maxx, maxy)
|
||||
bbox_poly = box(minx, miny, maxx, maxy)
|
||||
|
||||
if collision_type == "bbox":
|
||||
return [bbox]
|
||||
|
||||
return [bbox_poly]
|
||||
|
||||
if collision_type == "clipped_bbox":
|
||||
return [_clip_bbox(bbox, cx, cy, radius, width, clip_margin, arc_poly, t_start, t_end)]
|
||||
return [_clip_bbox(bbox_poly, cx, cy, radius, width, clip_margin, arc_poly, t_start, t_end)]
|
||||
|
||||
return [arc_poly]
|
||||
|
||||
|
||||
class Bend90:
|
||||
"""
|
||||
Move generator for 90-degree bends.
|
||||
Move generator for 90-degree waveguide bends.
|
||||
"""
|
||||
@staticmethod
|
||||
def generate(
|
||||
start_port: Port,
|
||||
radius: float,
|
||||
width: float,
|
||||
direction: str = "CW",
|
||||
direction: Literal["CW", "CCW"],
|
||||
sagitta: float = 0.01,
|
||||
collision_type: Literal["arc", "bbox", "clipped_bbox"] | Polygon = "arc",
|
||||
clip_margin: float = 10.0,
|
||||
|
|
@ -430,52 +352,37 @@ class Bend90:
|
|||
"""
|
||||
Generate a 90-degree 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)
|
||||
|
||||
# Initial guess for center
|
||||
cx_init = start_port.x + radius * numpy.cos(c_angle)
|
||||
cy_init = start_port.y + radius * numpy.sin(c_angle)
|
||||
t_start_init = c_angle + numpy.pi
|
||||
t_end_init = t_start_init + (numpy.pi / 2 if direction == "CCW" else -numpy.pi / 2)
|
||||
|
||||
# Snap the target point
|
||||
ex = snap_search_grid(cx_init + radius * numpy.cos(t_end_init), snap_size)
|
||||
ey = snap_search_grid(cy_init + radius * numpy.sin(t_end_init), snap_size)
|
||||
end_port = Port(ex, ey, float((start_port.orientation + turn_angle) % 360))
|
||||
|
||||
# Adjust geometry to perfectly hit snapped port
|
||||
dx = ex - start_port.x
|
||||
dy = ey - start_port.y
|
||||
dist = numpy.sqrt(dx**2 + dy**2)
|
||||
|
||||
# New radius for the right triangle connecting start to end with 90 deg
|
||||
actual_radius = dist / numpy.sqrt(2)
|
||||
|
||||
# Vector from start to end
|
||||
mid_x, mid_y = (start_port.x + ex)/2, (start_port.y + ey)/2
|
||||
# Normal vector (orthogonal to start->end)
|
||||
# Flip direction based on CW/CCW
|
||||
dir_sign = 1 if direction == "CCW" else -1
|
||||
cx = mid_x - dir_sign * (ey - start_port.y) / 2
|
||||
cy = mid_y + dir_sign * (ex - start_port.x) / 2
|
||||
|
||||
# Update angles based on new center
|
||||
t_start = numpy.arctan2(start_port.y - cy, start_port.x - cx)
|
||||
t_end = numpy.arctan2(ey - cy, ex - cx)
|
||||
|
||||
# Maintain directionality and angular span near pi/2
|
||||
# Center of the arc
|
||||
if direction == "CCW":
|
||||
while t_end < t_start: t_end += 2 * numpy.pi
|
||||
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:
|
||||
while t_end > t_start: t_end -= 2 * numpy.pi
|
||||
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
|
||||
|
||||
# Snap the end point to the grid
|
||||
ex_raw = cx + radius * numpy.cos(t_end)
|
||||
ey_raw = cy + radius * numpy.sin(t_end)
|
||||
ex = snap_search_grid(ex_raw, snap_size)
|
||||
ey = snap_search_grid(ey_raw, snap_size)
|
||||
|
||||
# Slightly adjust radius to hit snapped point exactly
|
||||
actual_radius = numpy.sqrt((ex - cx)**2 + (ey - cy)**2)
|
||||
end_port = Port(ex, ey, new_ori)
|
||||
|
||||
arc_polys = _get_arc_polygons(cx, cy, actual_radius, width, t_start, t_end, sagitta)
|
||||
collision_polys = _apply_collision_model(
|
||||
arc_polys[0], collision_type, actual_radius, width, cx, cy, clip_margin, t_start, t_end
|
||||
)
|
||||
|
||||
|
||||
proxy_geom = None
|
||||
if collision_type == "arc":
|
||||
# Auto-generate a clipped_bbox proxy for tiered collision checks
|
||||
|
|
@ -500,8 +407,6 @@ class Bend90:
|
|||
move_type='Bend90'
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
|
||||
class SBend:
|
||||
"""
|
||||
|
|
|
|||
Loading…
Reference in a new issue