clean up magic numbers, enable arbitrary gridding, add cache invalidatino

This commit is contained in:
Jan Petykiewicz 2026-03-26 20:22:17 -07:00
commit 519dd48131

View file

@ -6,16 +6,13 @@ import numpy
import shapely
from shapely.geometry import Polygon, box, MultiPolygon
from shapely.ops import unary_union
from shapely.affinity import translate
from inire.constants import DEFAULT_SEARCH_GRID_SNAP_UM, TOLERANCE_LINEAR, TOLERANCE_ANGULAR
from .primitives import Port
# Search Grid Snap (5.0 µm default)
SEARCH_GRID_SNAP_UM = 5.0
def snap_search_grid(value: float, snap_size: float = SEARCH_GRID_SNAP_UM) -> float:
def snap_search_grid(value: float, snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM) -> float:
"""
Snap a coordinate to the nearest search grid unit.
"""
@ -31,7 +28,7 @@ class ComponentResult:
'_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', '_lazy_evaluated', 'rel_gx', 'rel_gy', 'rel_go'
'_base_result', '_offset', 'rel_gx', 'rel_gy', 'rel_go'
)
def __init__(
@ -49,8 +46,8 @@ class ComponentResult:
_offsets: list[int] | None = None,
_coords_cache: numpy.ndarray | None = None,
_base_result: ComponentResult | None = None,
_offset: numpy.ndarray | None = None,
snap_size: float = SEARCH_GRID_SNAP_UM,
_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
@ -61,7 +58,6 @@ class ComponentResult:
self._base_result = _base_result
self._offset = _offset
self._lazy_evaluated = False
self._bounds_cached = False
if rel_gx is not None:
@ -69,9 +65,10 @@ class ComponentResult:
self.rel_gy = rel_gy
self.rel_go = rel_go
elif end_port:
self.rel_gx = int(round(end_port.x / snap_size))
self.rel_gy = int(round(end_port.y / snap_size))
self.rel_go = int(round(end_port.orientation / 1.0))
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
@ -82,14 +79,10 @@ class ComponentResult:
self._proxy_geometry = None
self._actual_geometry = None
self._dilated_actual_geometry = None
# Bounds are computed on demand
self._bounds = None
self._dilated_bounds = None
self._total_bounds = None
self._total_dilated_bounds = None
# No need to copy large arrays if we reference base
else:
# Eager Mode (Base Component)
self._geometry = geometry
@ -98,38 +91,35 @@ class ComponentResult:
self._actual_geometry = actual_geometry
self._dilated_actual_geometry = dilated_actual_geometry
if _total_geom_list is not None and _offsets is not None:
self._total_geom_list = _total_geom_list
self._offsets = _offsets
self._coords_cache = _coords_cache
else:
# Flatten everything for fast vectorized translate
gl = []
if geometry: gl.extend(geometry)
o = [len(gl)]
if dilated_geometry: gl.extend(dilated_geometry)
o.append(len(gl))
if proxy_geometry: gl.extend(proxy_geometry)
o.append(len(gl))
if actual_geometry: gl.extend(actual_geometry)
o.append(len(gl))
if dilated_actual_geometry: gl.extend(dilated_actual_geometry)
self._total_geom_list = gl
self._offsets = o
self._coords_cache = shapely.get_coordinates(gl) if gl else None
# 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:
self._bounds = shapely.bounds(geometry)
self._total_bounds = numpy.array([
numpy.min(self._bounds[:, 0]), numpy.min(self._bounds[:, 1]),
numpy.max(self._bounds[:, 2]), numpy.max(self._bounds[:, 3])
])
# 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 = shapely.bounds(dilated_geometry)
self._total_dilated_bounds = numpy.array([
numpy.min(self._dilated_bounds[:, 0]), numpy.min(self._dilated_bounds[:, 1]),
numpy.max(self._dilated_bounds[:, 2]), numpy.max(self._dilated_bounds[:, 3])
])
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
@ -140,73 +130,70 @@ class ComponentResult:
self._total_dilated_bounds = None
self._bounds_cached = True
def _ensure_evaluated(self) -> None:
if self._base_result is None or self._lazy_evaluated:
def _ensure_evaluated(self, attr_name: str) -> None:
if self._base_result is None:
return
# Perform Translation
# 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.transform which is vectorized and doesn't modify in-place.
# This is MUCH faster than cloning with copy.copy and then set_coordinates.
import shapely
new_total_arr = shapely.transform(self._base_result._total_geom_list, lambda x: x + [dx, dy])
new_total = new_total_arr.tolist()
o = self._base_result._offsets
self._geometry = new_total[:o[0]]
self._dilated_geometry = new_total[o[0]:o[1]] if self._base_result._dilated_geometry is not None else None
self._proxy_geometry = new_total[o[1]:o[2]] if self._base_result._proxy_geometry is not None else None
self._actual_geometry = new_total[o[2]:o[3]] if self._base_result._actual_geometry is not None else None
self._dilated_actual_geometry = new_total[o[3]:] if self._base_result._dilated_actual_geometry is not None else None
self._lazy_evaluated = True
# 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()
self._ensure_evaluated('geometry')
return self._geometry
@property
def dilated_geometry(self) -> list[Polygon] | None:
self._ensure_evaluated()
self._ensure_evaluated('dilated_geometry')
return self._dilated_geometry
@property
def proxy_geometry(self) -> list[Polygon] | None:
self._ensure_evaluated()
self._ensure_evaluated('proxy_geometry')
return self._proxy_geometry
@property
def actual_geometry(self) -> list[Polygon] | None:
self._ensure_evaluated()
self._ensure_evaluated('actual_geometry')
return self._actual_geometry
@property
def dilated_actual_geometry(self) -> list[Polygon] | None:
self._ensure_evaluated()
self._ensure_evaluated('dilated_actual_geometry')
return self._dilated_actual_geometry
@property
def bounds(self) -> numpy.ndarray:
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) -> numpy.ndarray:
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) -> numpy.ndarray | None:
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) -> numpy.ndarray | None:
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
@ -216,36 +203,33 @@ class ComponentResult:
base = self._base_result
if base is not None:
dx, dy = self._offset
shift = numpy.array([dx, dy, dx, dy])
# Vectorized addition is faster if we avoid creating new lists/arrays in the loop
# Direct tuple creation is much faster than NumPy for single AABBs
if base._bounds is not None:
self._bounds = base._bounds + shift
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 + shift
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 = base._dilated_bounds + shift
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 + shift
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).
"""
# Optimized: no internal cache (already cached in router) and no rounding
# Also skip snapping since parent and relative move are already snapped
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 = numpy.array([current_offset[0] + dx, current_offset[1] + dy])
new_offset = (current_offset[0] + dx, current_offset[1] + dy)
else:
base = self
new_offset = numpy.array([dx, dy])
new_offset = (dx, dy)
return ComponentResult(
end_port=new_port,
@ -270,7 +254,7 @@ class Straight:
width: float,
snap_to_grid: bool = True,
dilation: float = 0.0,
snap_size: float = SEARCH_GRID_SNAP_UM,
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
) -> ComponentResult:
"""
Generate a straight waveguide segment.
@ -318,8 +302,19 @@ class Straight:
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)
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 _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int:
@ -330,7 +325,7 @@ def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) ->
return 1
ratio = max(0.0, min(1.0, 1.0 - sagitta / radius))
theta_max = 2.0 * numpy.arccos(ratio)
if theta_max < 1e-9:
if theta_max < TOLERANCE_ANGULAR:
return 16
num = int(numpy.ceil(numpy.radians(abs(angle_deg)) / theta_max))
return max(8, num)
@ -468,7 +463,7 @@ class Bend90:
clip_margin: float = 10.0,
dilation: float = 0.0,
snap_to_grid: bool = True,
snap_size: float = SEARCH_GRID_SNAP_UM,
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
) -> ComponentResult:
"""
Generate a 90-degree bend.
@ -500,9 +495,10 @@ class Bend90:
ex, ey = ex_raw, ey_raw
# Slightly adjust radius and t_end to hit snapped point exactly
actual_radius = numpy.sqrt((ex - cx)**2 + (ey - cy)**2)
dx, dy = ex - cx, ey - cy
actual_radius = numpy.sqrt(dx**2 + dy**2)
t_end_snapped = numpy.arctan2(ey - cy, ex - cx)
t_end_snapped = numpy.arctan2(dy, dx)
# Ensure directionality and approx 90 degree sweep
if direction == "CCW":
while t_end_snapped <= t_start:
@ -539,6 +535,12 @@ class Bend90:
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))
return ComponentResult(
geometry=collision_polys,
end_port=end_port,
@ -548,7 +550,8 @@ class Bend90:
actual_geometry=arc_polys,
dilated_actual_geometry=dilated_actual_geom,
move_type='Bend90',
snap_size=snap_size
snap_size=snap_size,
rel_gx=rgx, rel_gy=rgy, rel_go=rgo
)
@ -567,7 +570,7 @@ class SBend:
clip_margin: float = 10.0,
dilation: float = 0.0,
snap_to_grid: bool = True,
snap_size: float = SEARCH_GRID_SNAP_UM,
snap_size: float = DEFAULT_SEARCH_GRID_SNAP_UM,
) -> ComponentResult:
"""
Generate a parametric S-bend (two tangent arcs).
@ -598,19 +601,18 @@ class SBend:
# tan(theta / 2) = local_dy / local_dx
theta = 2 * numpy.arctan2(abs(local_dy), local_dx)
if abs(theta) < 1e-9:
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)
denom = (2 * (1 - numpy.cos(theta)))
if abs(denom) < 1e-9:
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
# (inner_radius becomes negative if actual_radius < width/2)
if actual_radius < width:
raise ValueError(f"SBend actual_radius {actual_radius:.3f} is too small (width={width})")
@ -659,6 +661,12 @@ class SBend:
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))
return ComponentResult(
geometry=collision_polys,
end_port=end_port,
@ -668,5 +676,6 @@ class SBend:
actual_geometry=arc_polys,
dilated_actual_geometry=dilated_actual_geom,
move_type='SBend',
snap_size=snap_size
snap_size=snap_size,
rel_gx=rgx, rel_gy=rgy, rel_go=rgo
)