50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
from dataclasses import dataclass
|
||
|
|
import numpy as np
|
||
|
|
|
||
|
|
# 1nm snap (0.001 µm)
|
||
|
|
GRID_SNAP_UM = 0.001
|
||
|
|
|
||
|
|
def snap_nm(value: float) -> float:
|
||
|
|
"""Snap a coordinate to the nearest 1nm (0.001 um)."""
|
||
|
|
return round(value / GRID_SNAP_UM) * GRID_SNAP_UM
|
||
|
|
|
||
|
|
@dataclass(frozen=True)
|
||
|
|
class Port:
|
||
|
|
"""A port defined by (x, y, orientation) in micrometers."""
|
||
|
|
x: float
|
||
|
|
y: float
|
||
|
|
orientation: float # Degrees: 0, 90, 180, 270
|
||
|
|
|
||
|
|
def __post_init__(self) -> None:
|
||
|
|
# Snap x, y to 1nm
|
||
|
|
# We need to use object.__setattr__ because the dataclass is frozen.
|
||
|
|
snapped_x = snap_nm(self.x)
|
||
|
|
snapped_y = snap_nm(self.y)
|
||
|
|
|
||
|
|
# Ensure orientation is one of {0, 90, 180, 270}
|
||
|
|
norm_orientation = int(round(self.orientation)) % 360
|
||
|
|
if norm_orientation not in {0, 90, 180, 270}:
|
||
|
|
norm_orientation = (round(norm_orientation / 90) * 90) % 360
|
||
|
|
|
||
|
|
object.__setattr__(self, "x", snapped_x)
|
||
|
|
object.__setattr__(self, "y", snapped_y)
|
||
|
|
object.__setattr__(self, "orientation", float(norm_orientation))
|
||
|
|
|
||
|
|
|
||
|
|
def translate_port(port: Port, dx: float, dy: float) -> Port:
|
||
|
|
"""Translate a port by (dx, dy)."""
|
||
|
|
return Port(port.x + dx, port.y + dy, port.orientation)
|
||
|
|
|
||
|
|
|
||
|
|
def rotate_port(port: Port, angle: float, origin: tuple[float, float] = (0, 0)) -> Port:
|
||
|
|
"""Rotate a port by a multiple of 90 degrees around an origin."""
|
||
|
|
ox, oy = origin
|
||
|
|
px, py = port.x, port.y
|
||
|
|
|
||
|
|
rad = np.radians(angle)
|
||
|
|
qx = ox + np.cos(rad) * (px - ox) - np.sin(rad) * (py - oy)
|
||
|
|
qy = oy + np.sin(rad) * (px - ox) + np.cos(rad) * (py - oy)
|
||
|
|
|
||
|
|
return Port(qx, qy, port.orientation + angle)
|
||
|
|
|