Skip to content

Commit

Permalink
Merge pull request #591 from gdsfactory/add-ruff-naming
Browse files Browse the repository at this point in the history
Add ruff Naming rule and fix most errors
  • Loading branch information
MatthewMckee4 authored Jan 30, 2025
2 parents 6168530 + 6e10f48 commit 2d6c317
Show file tree
Hide file tree
Showing 39 changed files with 501 additions and 490 deletions.
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,13 @@ target-version = "py311"

[tool.ruff.lint]
select = [
"E", # pycodestyle
"F", # pyflakes
"E", # pycodestyle
"W", # pycodestyle
"UP", # pyupgrade
"N", # pep8-naming
# "D", # pydocstyle
"I", # isort
"W", # pycodestyle
"ANN", # annotations
"RUF", # ruff
"B",
Expand Down
4 changes: 2 additions & 2 deletions src/kfactory/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ class LogLevel(str, Enum):
CRITICAL = "CRITICAL"


class CHECK_INSTANCES(str, Enum):
class CheckInstances(str, Enum):
RAISE = "error"
FLATTEN = "flatten"
VINSTANCES = "vinstances"
Expand Down Expand Up @@ -220,7 +220,7 @@ class Settings(BaseSettings):
cell_overwrite_existing: bool = False
connect_use_angle: bool = True
connect_use_mirror: bool = True
check_instances: CHECK_INSTANCES = CHECK_INSTANCES.RAISE
check_instances: CheckInstances = CheckInstances.RAISE
max_cellname_length: int = 99
debug_names: bool = False

Expand Down
6 changes: 3 additions & 3 deletions src/kfactory/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
if TYPE_CHECKING:
from cachetools import Cache

from .conf import CHECK_INSTANCES
from .conf import CheckInstances
from .kcell import TKCell
from .layout import KCLayout
from .protocols import KCellFunc
Expand All @@ -23,7 +23,7 @@ class ModuleCellKWargs(TypedDict, total=False):
set_settings: bool
set_name: bool
check_ports: bool
check_instances: CHECK_INSTANCES | None
check_instances: CheckInstances | None
snap_ports: bool
add_port_layers: bool
cache: Cache[int, Any] | dict[int, Any] | None
Expand All @@ -42,7 +42,7 @@ class KCellDecoratorKWargs(TypedDict, total=False):
set_settings: bool
set_name: bool
check_ports: bool
check_instances: CHECK_INSTANCES | None
check_instances: CheckInstances | None
snap_ports: bool
add_port_layers: bool
cache: Cache[int, Any] | dict[int, Any] | None
Expand Down
1 change: 1 addition & 0 deletions src/kfactory/enclosure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1177,6 +1177,7 @@ def __hash__(self) -> int:
return hash(tuple(self.enclosures))

@field_validator("enclosures")
@classmethod
def enclosures_must_have_main_layer(
cls, v: list[LayerEnclosure]
) -> list[LayerEnclosure]:
Expand Down
6 changes: 3 additions & 3 deletions src/kfactory/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class MergeError(ValueError):
"""Raised if two layout's have conflicting cell definitions."""


class PortWidthMismatch(ValueError):
class PortWidthMismatchError(ValueError):
"""Error thrown when two ports don't have a matching `width`."""

def __init__(
Expand Down Expand Up @@ -55,7 +55,7 @@ def __init__(
)


class PortLayerMismatch(ValueError):
class PortLayerMismatchError(ValueError):
"""Error thrown when two ports don't have a matching `layer`."""

def __init__(
Expand Down Expand Up @@ -95,7 +95,7 @@ def __init__(
)


class PortTypeMismatch(ValueError):
class PortTypeMismatchError(ValueError):
"""Error thrown when two ports don't have a matching `port_type`."""

def __init__(
Expand Down
38 changes: 17 additions & 21 deletions src/kfactory/factories/euler.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,32 +91,29 @@ def euler_bend_points(
if eth == 0:
return [kdb.DPoint(0, 0)]

# Curve min radius
R = radius

# Total displaced angle
th = eth / 2

# Total length of curve
Ltot = 4 * R * th
total_length = 4 * radius * th

# Compute curve ##
a = np.sqrt(R**2 * np.abs(th))
a = np.sqrt(radius**2 * np.abs(th))
sq2pi = np.sqrt(2 * np.pi)

# Function for computing curve coords
(fasin, facos) = fresnel(np.sqrt(2 / np.pi) * R * th / a)
(fasin, facos) = fresnel(np.sqrt(2 / np.pi) * radius * th / a)

def _xy(s: float) -> kdb.DPoint:
if th == 0:
return kdb.DPoint(0, 0)
elif s <= Ltot / 2:
elif s <= total_length / 2:
(fsin, fcos) = fresnel(s / (sq2pi * a))
X = sq2pi * a * fcos
Y = sq2pi * a * fsin
x = sq2pi * a * fcos
y = sq2pi * a * fsin
else:
(fsin, fcos) = fresnel((Ltot - s) / (sq2pi * a))
X = (
(fsin, fcos) = fresnel((total_length - s) / (sq2pi * a))
x = (
sq2pi
* a
* (
Expand All @@ -125,7 +122,7 @@ def _xy(s: float) -> kdb.DPoint:
+ np.sin(2 * th) * (fasin - fsin)
)
)
Y = (
y = (
sq2pi
* a
* (
Expand All @@ -134,13 +131,13 @@ def _xy(s: float) -> kdb.DPoint:
+ np.sin(2 * th) * (facos - fcos)
)
)
return kdb.DPoint(X, Y)
return kdb.DPoint(x, y)

# Parametric step size
step = Ltot / max(int(th * resolution), 1)
step = total_length / max(int(th * resolution), 1)

# Generate points
points = [_xy(i * step) for i in range(int(round(Ltot / step)) + 1)]
points = [_xy(i * step) for i in range(int(round(total_length / step)) + 1)]

return points

Expand All @@ -153,20 +150,19 @@ def euler_endpoint(
) -> tuple[float, float]:
"""Gives the end point of a simple Euler bend as a i3.Coord2."""
th = abs(angle_amount) * np.pi / 180 / 2
R = radius
clockwise = angle_amount < 0

(fsin, fcos) = fresnel(np.sqrt(2 * th / np.pi))

a = 2 * np.sqrt(2 * np.pi * th) * (np.cos(th) * fcos + np.sin(th) * fsin)
r = a * R
X = r * np.cos(th)
Y = r * np.sin(th)
r = a * radius
x = r * np.cos(th)
y = r * np.sin(th)

if clockwise:
Y *= -1
y *= -1

return X + start_point[0], Y + start_point[1]
return x + start_point[0], y + start_point[1]


def euler_sbend_points(
Expand Down
39 changes: 20 additions & 19 deletions src/kfactory/instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

from .conf import PROPID, config, logger
from .exceptions import (
PortLayerMismatch,
PortTypeMismatch,
PortWidthMismatch,
PortLayerMismatchError,
PortTypeMismatchError,
PortWidthMismatchError,
)
from .geometry import DBUGeometricObject, GeometricObject, UMGeometricObject
from .instance_ports import (
Expand Down Expand Up @@ -352,28 +352,29 @@ def connect(
if use_angle is None:
use_angle = config.connect_use_angle

if isinstance(other, Instance):
if isinstance(other, ProtoTInstance):
if other_port_name is None:
raise ValueError(
"portname cannot be None if an Instance Object is given. For"
"complex connections (non-90 degree and floating point ports) use"
"route_cplx instead"
)
op = Port(base=other.ports[other_port_name].base)
elif isinstance(other, ProtoPort):
op = Port(base=other.base)
op = other.ports[other_port_name].to_itype()
else:
raise ValueError("other_instance must be of type Instance or Port")
op = other.to_itype()
if isinstance(port, ProtoPort):
p = Port(base=port.base.transformed(self.dcplx_trans.inverted()))
else:
p = Port(base=self.cell.ports[port].base)
p = self.cell.ports[port].to_itype()

assert isinstance(p, Port) and isinstance(op, Port)

if p.width != op.width and not allow_width_mismatch:
raise PortWidthMismatch(self, other, p, op)
raise PortWidthMismatchError(self, other, p, op)
if p.layer != op.layer and not allow_layer_mismatch:
raise PortLayerMismatch(self.cell.kcl, self, other, p, op)
raise PortLayerMismatchError(self.cell.kcl, self, other, p, op)
if p.port_type != op.port_type and not allow_type_mismatch:
raise PortTypeMismatch(self, other, p, op)
raise PortTypeMismatchError(self, other, p, op)
if p.base.dcplx_trans or op.base.dcplx_trans:
dconn_trans = kdb.DCplxTrans.M90 if mirror else kdb.DCplxTrans.R180
match (use_mirror, use_angle):
Expand Down Expand Up @@ -896,22 +897,22 @@ def connect(
"complex connections (non-90 degree and floating point ports) use"
"route_cplx instead"
)
op = Port(base=other.ports[other_port_name].base)
op = other.ports[other_port_name].to_itype()
else:
op = Port(base=other.base)
op = other.to_itype()
if isinstance(port, ProtoPort):
p = Port(base=port.copy(self.trans.inverted()).base)
p = port.copy(self.trans.inverted()).to_itype()
else:
p = Port(base=self.cell.ports[port].base)
p = self.cell.ports[port].to_itype()

assert isinstance(p, Port) and isinstance(op, Port)

if p.width != op.width and not allow_width_mismatch:
raise PortWidthMismatch(self, other, p, op)
raise PortWidthMismatchError(self, other, p, op)
if p.layer != op.layer and not allow_layer_mismatch:
raise PortLayerMismatch(self.cell.kcl, self, other, p, op)
raise PortLayerMismatchError(self.cell.kcl, self, other, p, op)
if p.port_type != op.port_type and not allow_type_mismatch:
raise PortTypeMismatch(self, other, p, op)
raise PortTypeMismatchError(self, other, p, op)
dconn_trans = kdb.DCplxTrans.M90 if mirror else kdb.DCplxTrans.R180
match (use_mirror, use_angle):
case True, True:
Expand Down
4 changes: 2 additions & 2 deletions src/kfactory/kcell.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@
from ruamel.yaml.representer import BaseRepresenter, MappingNode

from . import kdb, rdb
from .conf import CHECK_INSTANCES, DEFAULT_TRANS, ShowFunction, config, logger
from .conf import DEFAULT_TRANS, CheckInstances, ShowFunction, config, logger
from .cross_section import SymmetricalCrossSection
from .exceptions import LockedError, MergeError
from .geometry import DBUGeometricObject, GeometricObject, UMGeometricObject
Expand Down Expand Up @@ -95,8 +95,8 @@
from .layout import KCLayout

__all__ = [
"CHECK_INSTANCES",
"BaseKCell",
"CheckInstances",
"DKCell",
"KCell",
]
Expand Down
17 changes: 9 additions & 8 deletions src/kfactory/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
)

from . import __version__
from .conf import CHECK_INSTANCES, config, logger
from .conf import CheckInstances, config, logger
from .cross_section import (
CrossSectionModel,
CrossSectionSpec,
Expand Down Expand Up @@ -279,6 +279,7 @@ def __init__(
kcls[self.name] = self

@model_validator(mode="before")
@classmethod
def _validate_layers(cls, data: dict[str, Any]) -> dict[str, Any]:
data["layers"] = layerenum_from_dict(
layers=data["infos"], layout=data["library"].layout()
Expand Down Expand Up @@ -487,7 +488,7 @@ def cell(
set_settings: bool = ...,
set_name: bool = ...,
check_ports: bool = ...,
check_instances: CHECK_INSTANCES | None = ...,
check_instances: CheckInstances | None = ...,
snap_ports: bool = ...,
add_port_layers: bool = ...,
cache: Cache[int, Any] | dict[int, Any] | None = ...,
Expand All @@ -512,7 +513,7 @@ def cell(
set_settings: bool = ...,
set_name: bool = ...,
check_ports: bool = ...,
check_instances: CHECK_INSTANCES | None = ...,
check_instances: CheckInstances | None = ...,
snap_ports: bool = ...,
add_port_layers: bool = ...,
cache: Cache[int, Any] | dict[int, Any] | None = ...,
Expand All @@ -538,7 +539,7 @@ def cell( # type: ignore[misc]
set_settings: bool = True,
set_name: bool = True,
check_ports: bool = True,
check_instances: CHECK_INSTANCES | None = None,
check_instances: CheckInstances | None = None,
snap_ports: bool = True,
add_port_layers: bool = True,
cache: Cache[int, Any] | dict[int, Any] | None = None,
Expand Down Expand Up @@ -760,7 +761,7 @@ def wrapped_cell(
"`check_ports=False` to the @cell decorator"
)
match check_instances:
case CHECK_INSTANCES.RAISE:
case CheckInstances.RAISE:
if any(inst.is_complex() for inst in cell.each_inst()):
raise ValueError(
"Most foundries will not allow off-grid "
Expand All @@ -773,10 +774,10 @@ def wrapped_cell(
if inst.is_complex()
)
)
case CHECK_INSTANCES.FLATTEN:
case CheckInstances.FLATTEN:
if any(inst.is_complex() for inst in cell.each_inst()):
cell.flatten()
case CHECK_INSTANCES.VINSTANCES:
case CheckInstances.VINSTANCES:
if any(inst.is_complex() for inst in cell.each_inst()):
complex_insts = [
inst
Expand All @@ -789,7 +790,7 @@ def wrapped_cell(
)
vinst.trans = inst.dcplx_trans
inst.delete()
case CHECK_INSTANCES.IGNORE:
case CheckInstances.IGNORE:
pass
cell.insert_vinsts(recursive=False)
if snap_ports:
Expand Down
6 changes: 1 addition & 5 deletions src/kfactory/port.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,11 +626,7 @@ def __init__(
) -> None: ...

@overload
def __init__(
self,
*,
base: BasePort,
) -> None: ...
def __init__(self, *, base: BasePort) -> None: ...

def __init__(
self,
Expand Down
2 changes: 1 addition & 1 deletion src/kfactory/routing/electrical.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def route_elec(
c_.shapes(layer).insert(path.polygon())


def route_L(
def route_L( # noqa: N802
c: KCell,
input_ports: Sequence[Port],
output_orientation: int = 1,
Expand Down
Loading

0 comments on commit 2d6c317

Please sign in to comment.