initial pass on examples

This commit is contained in:
Jan Petykiewicz 2026-03-08 14:40:36 -07:00
commit 82aaf066e2
2 changed files with 600 additions and 238 deletions

View file

@ -40,16 +40,9 @@ class CollisionEngine:
self.obstacle_geometries[obj_id] = polygon
self.prepared_obstacles[obj_id] = prep(polygon)
# Index the bounding box of the polygon (dilated for broad prune)
# Spec: "All user-provided obstacles are pre-dilated by (W_max + C)/2"
dilation = (self.max_net_width + self.clearance) / 2.0
dilated_bounds = (
polygon.bounds[0] - dilation,
polygon.bounds[1] - dilation,
polygon.bounds[2] + dilation,
polygon.bounds[3] + dilation,
)
self.static_obstacles.insert(obj_id, dilated_bounds)
# Index the bounding box of the original polygon
# We query with dilated moves, so original bounds are enough
self.static_obstacles.insert(obj_id, polygon.bounds)
def add_path(self, net_id: str, geometry: list[Polygon]) -> None:
"""Add a net's routed path to the dynamic R-Tree."""
@ -119,13 +112,13 @@ class CollisionEngine:
end_port: Port | None = None,
) -> bool:
"""Check if a pre-dilated geometry collides with static obstacles."""
# Broad prune with R-Tree
# Query R-Tree using the bounds of the dilated move
candidates = self.static_obstacles.intersection(dilated_geometry.bounds)
for obj_id in candidates:
# Use prepared geometry for fast intersection
if self.prepared_obstacles[obj_id].intersects(dilated_geometry):
# Check safety zone (2nm = 0.002 um)
# Check safety zone (2nm radius)
if start_port or end_port:
obstacle = self.obstacle_geometries[obj_id]
intersection = dilated_geometry.intersection(obstacle)
@ -133,20 +126,23 @@ class CollisionEngine:
if intersection.is_empty:
continue
# Create safety zone polygons
safety_zones = []
# Precise check: is every point in the intersection close to either port?
ix_minx, ix_miny, ix_maxx, ix_maxy = intersection.bounds
is_near_start = False
if start_port:
safety_zones.append(Point(start_port.x, start_port.y).buffer(0.002))
if (abs(ix_minx - start_port.x) < 0.0021 and abs(ix_maxx - start_port.x) < 0.0021 and
abs(ix_miny - start_port.y) < 0.0021 and abs(ix_maxy - start_port.y) < 0.0021):
is_near_start = True
is_near_end = False
if end_port:
safety_zones.append(Point(end_port.x, end_port.y).buffer(0.002))
if safety_zones:
safe_poly = unary_union(safety_zones)
# Remove safe zones from intersection
remaining_collision = intersection.difference(safe_poly)
if remaining_collision.is_empty or remaining_collision.area < 1e-9:
continue
if (abs(ix_minx - end_port.x) < 0.0021 and abs(ix_maxx - end_port.x) < 0.0021 and
abs(ix_miny - end_port.y) < 0.0021 and abs(ix_maxy - end_port.y) < 0.0021):
is_near_end = True
if is_near_start or is_near_end:
continue
return True
return False

View file

@ -12,32 +12,40 @@ SEARCH_GRID_SNAP_UM = 1.0
def snap_search_grid(value: float) -> float:
"""Snap a coordinate to the nearest 1µm."""
"""Snap a coordinate to the nearest search grid unit."""
return round(value / SEARCH_GRID_SNAP_UM) * SEARCH_GRID_SNAP_UM
class ComponentResult(NamedTuple):
"""The result of a component generation: geometry and the final port."""
"""The result of a component generation: geometry, final port, and physical length."""
geometry: list[Polygon]
end_port: Port
length: float
class Straight:
@staticmethod
def generate(start_port: Port, length: float, width: float) -> ComponentResult:
def generate(start_port: Port, length: float, width: float, snap_to_grid: bool = True) -> ComponentResult:
"""Generate a straight waveguide segment."""
# Calculate end port position
rad = np.radians(start_port.orientation)
dx = length * np.cos(rad)
dy = length * np.sin(rad)
end_port = Port(start_port.x + dx, start_port.y + dy, start_port.orientation)
ex = start_port.x + dx
ey = start_port.y + dy
if snap_to_grid:
ex = snap_search_grid(ex)
ey = snap_search_grid(ey)
# Create polygon (centered on port)
end_port = Port(ex, ey, start_port.orientation)
actual_length = np.sqrt((end_port.x - start_port.x)**2 + (end_port.y - start_port.y)**2)
# Create polygon
half_w = width / 2.0
# Points relative to start port (0,0)
points = [(0, half_w), (length, half_w), (length, -half_w), (0, -half_w)]
points = [(0, half_w), (actual_length, half_w), (actual_length, -half_w), (0, -half_w)]
# Transform points
cos_val = np.cos(rad)
@ -48,56 +56,48 @@ class Straight:
ty = start_port.y + px * sin_val + py * cos_val
poly_points.append((tx, ty))
return ComponentResult(geometry=[Polygon(poly_points)], end_port=end_port)
return ComponentResult(geometry=[Polygon(poly_points)], end_port=end_port, length=actual_length)
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
# angle_deg is absolute angle turned
# s = R(1 - cos(theta/2)) => cos(theta/2) = 1 - s/R
# theta = 2 * acos(1 - s/R)
# n = total_angle / theta
ratio = max(0.0, min(1.0, 1.0 - sagitta / radius))
theta_max = 2.0 * np.arccos(ratio)
if theta_max == 0:
if theta_max < 1e-9:
return 16
num = int(np.ceil(np.radians(abs(angle_deg)) / theta_max))
return max(4, num)
return max(8, num)
class Bend90:
@staticmethod
def generate(start_port: Port, radius: float, width: float, direction: str = "CW", sagitta: float = 0.01) -> ComponentResult:
"""Generate a 90-degree bend."""
# direction: 'CW' (-90) or 'CCW' (+90)
turn_angle = -90 if direction == "CW" else 90
# Calculate center of the arc
# Calculate center
rad_start = np.radians(start_port.orientation)
center_angle = rad_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
cx = start_port.x + radius * np.cos(center_angle)
cy = start_port.y + radius * np.sin(center_angle)
c_angle = rad_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
cx = start_port.x + radius * np.cos(c_angle)
cy = start_port.y + radius * np.sin(c_angle)
# Center to start is radius at center_angle + pi
theta_start = center_angle + np.pi
theta_end = theta_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
t_start = c_angle + np.pi
t_end = t_start + (np.pi / 2 if direction == "CCW" else -np.pi / 2)
ex = cx + radius * np.cos(theta_end)
ey = cy + radius * np.sin(theta_end)
# End port orientation
# End port (snapped to lattice)
ex = snap_search_grid(cx + radius * np.cos(t_end))
ey = snap_search_grid(cy + radius * np.sin(t_end))
end_orientation = (start_port.orientation + turn_angle) % 360
snapped_ex = snap_search_grid(ex)
snapped_ey = snap_search_grid(ey)
end_port = Port(snapped_ex, snapped_ey, float(end_orientation))
end_port = Port(ex, ey, float(end_orientation))
actual_length = radius * np.pi / 2.0
# Generate arc geometry
num_segments = _get_num_segments(radius, 90, sagitta)
angles = np.linspace(theta_start, theta_end, num_segments + 1)
angles = np.linspace(t_start, t_end, num_segments + 1)
inner_radius = radius - width / 2.0
outer_radius = radius + width / 2.0
@ -105,66 +105,55 @@ class Bend90:
inner_points = [(cx + inner_radius * np.cos(a), cy + inner_radius * np.sin(a)) for a in angles]
outer_points = [(cx + outer_radius * np.cos(a), cy + outer_radius * np.sin(a)) for a in reversed(angles)]
return ComponentResult(geometry=[Polygon(inner_points + outer_points)], end_port=end_port)
return ComponentResult(geometry=[Polygon(inner_points + outer_points)], end_port=end_port, length=actual_length)
class SBend:
@staticmethod
def generate(start_port: Port, offset: float, radius: float, width: float, sagitta: float = 0.01) -> ComponentResult:
"""Generate a parametric S-bend (two tangent arcs). Only for offset < 2*radius."""
"""Generate a parametric S-bend (two tangent arcs)."""
if abs(offset) >= 2 * radius:
raise ValueError(f"SBend offset {offset} must be less than 2*radius {2 * radius}")
# Analytical length: L = 2 * sqrt(O * (2*R - O/4)) is for a specific S-bend type.
# Standard S-bend with two equal arcs:
# Offset O = 2 * R * (1 - cos(theta))
# theta = acos(1 - O / (2*R))
theta = np.arccos(1 - abs(offset) / (2 * radius))
# Length of one arc = R * theta
# Total length of S-bend = 2 * R * theta (arc length)
# Horizontal distance dx = 2 * R * sin(theta)
dx = 2 * radius * np.sin(theta)
dy = offset
# End port
# End port (snapped to lattice)
rad_start = np.radians(start_port.orientation)
ex = start_port.x + dx * np.cos(rad_start) - dy * np.sin(rad_start)
ey = start_port.y + dx * np.sin(rad_start) + dy * np.cos(rad_start)
ex = snap_search_grid(start_port.x + dx * np.cos(rad_start) - dy * np.sin(rad_start))
ey = snap_search_grid(start_port.y + dx * np.sin(rad_start) + dy * np.cos(rad_start))
end_port = Port(ex, ey, start_port.orientation)
actual_length = 2 * radius * theta
# Geometry: two arcs
# First arc center
# Arc centers and angles (Relative to start orientation)
direction = 1 if offset > 0 else -1
center_angle1 = rad_start + direction * np.pi / 2
cx1 = start_port.x + radius * np.cos(center_angle1)
cy1 = start_port.y + radius * np.sin(center_angle1)
# Arc 1
c1_angle = rad_start + direction * np.pi / 2
cx1 = start_port.x + radius * np.cos(c1_angle)
cy1 = start_port.y + radius * np.sin(c1_angle)
t_start1 = c1_angle + np.pi
t_end1 = t_start1 + direction * theta
# Second arc center
center_angle2 = rad_start - direction * np.pi / 2
cx2 = ex + radius * np.cos(center_angle2)
cy2 = ey + radius * np.sin(center_angle2)
# Arc 2 (Calculated relative to un-snapped end to ensure perfect tangency)
ex_raw = start_port.x + dx * np.cos(rad_start) - dy * np.sin(rad_start)
ey_raw = start_port.y + dx * np.sin(rad_start) + dy * np.cos(rad_start)
c2_angle = rad_start - direction * np.pi / 2
cx2 = ex_raw + radius * np.cos(c2_angle)
cy2 = ey_raw + radius * np.sin(c2_angle)
t_end2 = c2_angle + np.pi
t_start2 = t_end2 + direction * theta
# Generate points for both arcs
num_segments = _get_num_segments(radius, float(np.degrees(theta)), sagitta)
# Arc 1: theta_start1 to theta_end1
theta_start1 = center_angle1 + np.pi
theta_end1 = theta_start1 - direction * theta
# Arc 2: theta_start2 to theta_end2
theta_start2 = center_angle2
theta_end2 = theta_start2 + direction * theta
def get_arc_points(cx: float, cy: float, r_inner: float, r_outer: float, t_start: float, t_end: float) -> list[tuple[float, float]]:
angles = np.linspace(t_start, t_end, num_segments + 1)
def get_arc_points(cx: float, cy: float, r_inner: float, r_outer: float, ts: float, te: float) -> list[tuple[float, float]]:
num_segments = _get_num_segments(radius, float(np.degrees(theta)), sagitta)
angles = np.linspace(ts, te, num_segments + 1)
inner = [(cx + r_inner * np.cos(a), cy + r_inner * np.sin(a)) for a in angles]
outer = [(cx + r_outer * np.cos(a), cy + r_outer * np.sin(a)) for a in reversed(angles)]
return inner + outer
poly1 = Polygon(get_arc_points(cx1, cy1, radius - width / 2, radius + width / 2, theta_start1, theta_end1))
poly2 = Polygon(get_arc_points(cx2, cy2, radius - width / 2, radius + width / 2, theta_end2, theta_start2))
return ComponentResult(geometry=[poly1, poly2], end_port=end_port)
poly1 = Polygon(get_arc_points(cx1, cy1, radius - width / 2, radius + width / 2, t_start1, t_end1))
poly2 = Polygon(get_arc_points(cx2, cy2, radius - width / 2, radius + width / 2, t_start2, t_end2))
return ComponentResult(geometry=[poly1, poly2], end_port=end_port, length=actual_length)