inire/inire/geometry/primitives.py

77 lines
2.2 KiB
Python
Raw Normal View History

2026-03-07 08:26:29 -08:00
from __future__ import annotations
2026-03-09 03:19:01 -07:00
import numpy
2026-03-07 08:26:29 -08:00
# 1nm snap (0.001 µm)
GRID_SNAP_UM = 0.001
2026-03-09 03:19:01 -07:00
2026-03-07 08:26:29 -08:00
def snap_nm(value: float) -> float:
2026-03-09 03:19:01 -07:00
"""
Snap a coordinate to the nearest 1nm (0.001 um).
"""
2026-03-12 23:50:25 -07:00
return round(value * 1000) / 1000
2026-03-07 08:26:29 -08:00
from inire.constants import TOLERANCE_LINEAR
2026-03-09 03:19:01 -07:00
class Port:
"""
A port defined by (x, y, orientation) in micrometers.
"""
__slots__ = ('x', 'y', 'orientation')
def __init__(
self,
x: float,
y: float,
orientation: float,
2026-03-20 16:59:36 -07:00
snap: bool = True
2026-03-09 03:19:01 -07:00
) -> None:
2026-03-20 16:59:36 -07:00
if snap:
self.x = round(x * 1000) / 1000
self.y = round(y * 1000) / 1000
# Faster orientation normalization for common cases
if 0 <= orientation < 360:
self.orientation = float(orientation)
else:
self.orientation = float(orientation % 360)
else:
self.x = x
self.y = y
self.orientation = float(orientation)
2026-03-09 03:19:01 -07:00
def __repr__(self) -> str:
return f'Port(x={self.x}, y={self.y}, orientation={self.orientation})'
def __eq__(self, other: object) -> bool:
if not isinstance(other, Port):
return False
return (abs(self.x - other.x) < TOLERANCE_LINEAR and
abs(self.y - other.y) < TOLERANCE_LINEAR and
abs(self.orientation - other.orientation) < TOLERANCE_LINEAR)
2026-03-09 03:19:01 -07:00
def __hash__(self) -> int:
return hash((round(self.x, 6), round(self.y, 6), round(self.orientation, 6)))
2026-03-07 08:26:29 -08:00
def translate_port(port: Port, dx: float, dy: float) -> Port:
2026-03-09 03:19:01 -07:00
"""
Translate a port by (dx, dy).
"""
2026-03-07 08:26:29 -08:00
return Port(port.x + dx, port.y + dy, port.orientation)
def rotate_port(port: Port, angle: float, origin: tuple[float, float] = (0, 0)) -> Port:
2026-03-09 03:19:01 -07:00
"""
Rotate a port by a multiple of 90 degrees around an origin.
"""
2026-03-07 08:26:29 -08:00
ox, oy = origin
px, py = port.x, port.y
2026-03-09 03:19:01 -07:00
rad = numpy.radians(angle)
qx = snap_nm(ox + numpy.cos(rad) * (px - ox) - numpy.sin(rad) * (py - oy))
qy = snap_nm(oy + numpy.sin(rad) * (px - ox) + numpy.cos(rad) * (py - oy))
2026-03-07 08:26:29 -08:00
return Port(qx, qy, port.orientation + angle)