Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(ruff): #96 enable most less-controversial rules #97

Merged
merged 18 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions hamilflow/maths/trigonometrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import numpy as np

if TYPE_CHECKING:
from typing import Collection
from collections.abc import Collection

from numpy import typing as npt

Expand All @@ -20,6 +20,6 @@ def acos_with_shift(
shift = np.asarray(shift)
period_shift = (div := np.floor(shift)) * 2 * np.pi
remainder = shift - div
value = np.where(remainder <= 0.5, value, 2 * np.pi - value)
value = np.where(remainder <= 0.5, value, 2 * np.pi - value) # noqa: PLR2004

return period_shift + value
9 changes: 5 additions & 4 deletions hamilflow/models/brownian_motion.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Main module for Brownian motion."""

from collections.abc import Mapping, Sequence
from functools import cached_property
from typing import Mapping, Sequence

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -63,9 +63,10 @@ class BrownianMotionIC(BaseModel):
@field_validator("x0")
@classmethod
def _check_x0_types(cls, v: float | Sequence[float]) -> float | Sequence[float]:
if not isinstance(v, (float, int, Sequence)):
if not isinstance(v, float | int | Sequence):
# TODO I do not think this raise can be reached
raise ValueError(f"Value of x0 should be int/float/list of int/float: {v=}")
msg = f"Value of x0 should be int/float/list of int/float: {v=}"
raise TypeError(msg)

return v

Expand Down Expand Up @@ -152,7 +153,7 @@ def __init__(
initial_condition: (
Mapping[str, "Sequence[float] | npt.ArrayLike"] | None
) = None,
):
) -> None:
initial_condition = initial_condition or {}
self.system = BrownianMotionSystem.model_validate(system)
self.initial_condition = BrownianMotionIC.model_validate(initial_condition)
Expand Down
9 changes: 6 additions & 3 deletions hamilflow/models/free_particle.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Main module for a free particle."""

from collections.abc import Mapping, Sequence
from functools import cached_property
from typing import Mapping, Sequence, cast
from typing import cast

import numpy as np
import pandas as pd
Expand All @@ -27,9 +28,11 @@ class FreeParticleIC(BaseModel):
@model_validator(mode="after")
def _check_dimensions_match(self) -> Self:
if (x0_seq := isinstance(self.x0, Sequence)) != isinstance(self.v0, Sequence):
raise TypeError("x0 and v0 need both to be scalars or Sequences")
msg = "x0 and v0 need both to be scalars or Sequences"
raise TypeError(msg)
elif x0_seq and len(cast(Sequence, self.x0)) != len(cast(Sequence, self.v0)):
raise ValueError("Sequences x0 and v0 need to have the same length")
msg = "Sequences x0 and v0 need to have the same length"
raise ValueError(msg)

return self

Expand Down
22 changes: 15 additions & 7 deletions hamilflow/models/harmonic_oscillator.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Main module for undamped and damped hamornic oscillators."""

from abc import ABC, abstractmethod
from collections.abc import Mapping, Sequence
from functools import cached_property
from typing import Literal, Mapping, Sequence
from typing import Literal

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -51,7 +52,8 @@ def type(
@classmethod
def _check_zeta_non_negative(cls, v: float) -> float:
if v < 0:
raise ValueError(f"Value of zeta should be positive: {v=}")
msg = f"Value of zeta should be positive: {v=}"
raise ValueError(msg)

return v

Expand Down Expand Up @@ -157,8 +159,9 @@ def __init__(
) -> None:
super().__init__(system, initial_condition)
if self.system.type != "simple":
msg = f"System is not a Simple Harmonic Oscillator: {self.system}"
raise ValueError(
f"System is not a Simple Harmonic Oscillator: {self.system}",
msg,
)

def _x(self, t: "Sequence[float] | npt.ArrayLike") -> np.ndarray:
Expand Down Expand Up @@ -229,9 +232,12 @@ def __init__(
) -> None:
super().__init__(system, initial_condition)
if self.system.type == "simple":
raise ValueError(
msg = (
f"System is not a Damped Harmonic Oscillator: {self.system}\n"
f"This is a simple harmonic oscillator, use `SimpleHarmonicOscillator`.",
f"This is a simple harmonic oscillator, use `SimpleHarmonicOscillator`."
)
raise ValueError(
msg,
)

def _x_under_damped(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayLike:
Expand Down Expand Up @@ -316,8 +322,9 @@ def _x(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayLike:
elif self.system.type == "critical_damped":
x = self._x_critical_damped(t)
else:
msg = f"System type is not damped harmonic oscillator: {self.system.type}"
raise ValueError(
f"System type is not damped harmonic oscillator: {self.system.type}",
msg,
)

return x
Expand Down Expand Up @@ -351,8 +358,9 @@ def __init__(
initial_condition,
)
if self.system.type != "simple":
msg = f"System is not a Simple Harmonic Oscillator: {self.system}"
raise ValueError(
f"System is not a Simple Harmonic Oscillator: {self.system}",
msg,
)

@cached_property
Expand Down
13 changes: 9 additions & 4 deletions hamilflow/models/harmonic_oscillator_chain.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Main module for a harmonic oscillator chain."""

from collections.abc import Mapping, Sequence
from functools import cached_property
from typing import Mapping, Sequence, cast
from typing import cast

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -97,11 +98,11 @@ def _z(
t: "Sequence[float] | npt.ArrayLike",
) -> "tuple[npt.NDArray[np.complex64], npt.NDArray[np.complex64]]":
t = np.asarray(t).reshape(-1)
all_travelling_waves = [self.free_mode._x(t).reshape(1, -1)]
all_travelling_waves = [self.free_mode._x(t).reshape(1, -1)] # noqa: SLF001

if self.independent_csho_modes:
independent_cshos = np.asarray(
[o._z(t) for o in self.independent_csho_modes],
[o._z(t) for o in self.independent_csho_modes], # noqa: SLF001
)
all_travelling_waves.extend(
(
Expand Down Expand Up @@ -141,7 +142,11 @@ def __call__(self, t: "Sequence[float] | npt.ArrayLike") -> pd.DataFrame:
"npt.NDArray[np.float64] | npt.NDArray[np.complex64]",
values,
)
for name, xs in zip(("x", "y"), (original_xs, travelling_waves))
for name, xs in zip(
("x", "y"),
(original_xs, travelling_waves),
strict=False,
)
for i, values in enumerate(xs) # type: ignore [arg-type]
}

Expand Down
11 changes: 7 additions & 4 deletions hamilflow/models/kepler_problem/dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import numpy as np

if TYPE_CHECKING:
from typing import Callable
from collections.abc import Callable

from numpy import typing as npt

Expand Down Expand Up @@ -81,7 +81,10 @@ def tau_of_u_elliptic(ecc: float, u: "npt.ArrayLike") -> "npt.NDArray[np.float64
)


def tau_of_u_parabolic(ecc: float, u: "npt.ArrayLike") -> "npt.NDArray[np.float64]":
def tau_of_u_parabolic(
ecc: float, # noqa: ARG001
u: "npt.ArrayLike",
) -> "npt.NDArray[np.float64]":
r"""Calculate the scaled time tau from u in the parabolic case.

For $-1 < u \le 1$,
Expand Down Expand Up @@ -194,7 +197,7 @@ def tau_of_u_prime2(ecc: float, u: "npt.ArrayLike") -> "npt.NDArray[np.float64]"


def esolve_u_from_tau_parabolic(
ecc: float,
ecc: float, # noqa: ARG001
tau: "npt.ArrayLike",
) -> "npt.NDArray[np.float64]":
r"""Calculate the convenient radial inverse u from tau in the parabolic case, using the exact solution.
Expand Down Expand Up @@ -223,7 +226,7 @@ def _approximate_at_termina(
exact: "Callable[[float, npt.NDArray[np.float64]], npt.NDArray[np.float64]]",
left: "Callable[[float, npt.NDArray[np.float64]], npt.NDArray[np.float64]]",
right: "Callable[[float, npt.NDArray[np.float64]], npt.NDArray[np.float64]]",
):
) -> "npt.NDArray[np.float64]":
u = np.asarray(u)
u_s = u.reshape(-1)
res = exact(ecc, u_s)
Expand Down
16 changes: 10 additions & 6 deletions hamilflow/models/kepler_problem/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import math
from functools import cached_property, partial
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING

import numpy as np
import pandas as pd
Expand All @@ -13,7 +13,7 @@
from .numerics import u_of_tau

if TYPE_CHECKING:
from typing import Collection, Mapping
from collections.abc import Collection, Mapping

from numpy import typing as npt
from typing_extensions import Self
Expand All @@ -29,7 +29,7 @@ class Kepler2DSystem(BaseModel):
$$

For reference, if an object is orbiting our Sun, the constant
$\alpha = G M_{\odot} ~ 1.327×10^{20} \mathrm{m}^3/\mathrm{s}^2$ in SI,
$\alpha = G M_{\odot} ~ 1.327 \times 10^{20} \mathrm{m}^3/\mathrm{s}^2$ in SI,
which is also called 1 TCB, or 1 solar mass parameter. For computational stability, we recommend using
TCB as the unit instead of the large SI values.

Expand Down Expand Up @@ -63,9 +63,10 @@ class Kepler2DFI(BaseModel):
# TODO process angular momentum = 0
@field_validator("angular_mom")
@classmethod
def _angular_mom_non_zero(cls, v: Any) -> float:
def _angular_mom_non_zero(cls, v: float) -> float:
if v == 0:
raise NotImplementedError("Only non-zero angular momenta are supported")
msg = "Only non-zero angular momenta are supported"
raise NotImplementedError(msg)
return v


Expand Down Expand Up @@ -217,8 +218,11 @@ def period_in_tau(self) -> float:
$$ T_\tau = \frac{2\pi}{(1-e^2)^\frac{3}{2}}\,. $$
"""
if self.ecc >= 1:
msg = (
f"Only systems with 0 <= eccentricity < 1 have a period, got {self.ecc}"
)
raise TypeError(
f"Only systems with 0 <= eccentricity < 1 have a period, got {self.ecc}",
msg,
emptymalei marked this conversation as resolved.
Show resolved Hide resolved
)
return 2 * math.pi / (1 - self.ecc**2) ** 1.5

Expand Down
22 changes: 16 additions & 6 deletions hamilflow/models/kepler_problem/numerics.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,15 +51,22 @@ def nsolve_u_from_tau_newton(ecc: float, tau: "npt.ArrayLike") -> OptimizeResult
tau_of_u = tau_of_u_hyperbolic
u0 = _u0_hyperbolic(ecc, tau)
else:
raise ValueError(f"Expect ecc > 0, ecc != 1, got {ecc}")
msg = f"Expect ecc > 0, ecc != 1, got {ecc}"
raise ValueError(msg)

def f(u: float, tau: "npt.NDArray[np.float64]") -> "npt.NDArray[np.float64]":
return tau_of_u(ecc, u) - tau

def fprime(u: float, tau: "npt.ArrayLike") -> "npt.NDArray[np.float64]":
def fprime(
u: float,
tau: "npt.ArrayLike", # noqa: ARG001
) -> "npt.NDArray[np.float64]":
return tau_of_u_prime(ecc, u)

def fprime2(u: float, tau: "npt.ArrayLike") -> "npt.NDArray[np.float64]":
def fprime2(
u: float,
tau: "npt.ArrayLike", # noqa: ARG001
) -> "npt.NDArray[np.float64]":
return tau_of_u_prime2(ecc, u)

return newton(f, u0, fprime, (tau,), fprime2=fprime2, full_output=True, disp=False)
Expand All @@ -78,7 +85,8 @@ def nsolve_u_from_tau_bisect(ecc: float, tau: "npt.ArrayLike") -> list[OptimizeR
elif ecc > 1:
tau_of_u = tau_of_u_hyperbolic
else:
raise ValueError(f"Expect ecc > 0, ecc != 1, got {ecc}")
msg = f"Expect ecc > 0, ecc != 1, got {ecc}"
raise ValueError(msg)

def f(u: float, tau: float) -> np.float64:
return (
Expand Down Expand Up @@ -114,6 +122,8 @@ def u_of_tau(
case "newton":
return nsolve_u_from_tau_newton(ecc, tau)[0]
case _:
raise ValueError(f"Expect 'bisect' or 'newton', got {method}")
msg = f"Expect 'bisect' or 'newton', got {method}"
raise ValueError(msg)
else:
raise ValueError(f"Expect ecc >= 0, got {ecc}")
msg = f"Expect ecc >= 0, got {ecc}"
raise ValueError(msg)
7 changes: 4 additions & 3 deletions hamilflow/models/pendulum.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
"""Main module for a pendulum."""

import math
from collections.abc import Mapping, Sequence
from functools import cached_property
from typing import Any, Mapping, Sequence
from typing import Any

import numpy as np
import pandas as pd
Expand Down Expand Up @@ -62,9 +63,9 @@ def __init__(
system: float | Mapping[str, float],
initial_condition: float | Mapping[str, float],
) -> None:
if isinstance(system, (float, int)):
if isinstance(system, float | int):
system = {"omega0": system}
if isinstance(initial_condition, (float, int)):
if isinstance(initial_condition, float | int):
initial_condition = {"theta0": initial_condition}
self.system = PendulumSystem.model_validate(system)
self.initial_condition = PendulumIC.model_validate(initial_condition)
Expand Down
3 changes: 2 additions & 1 deletion hamilflow/models/utils/typing.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Typing."""

from typing import Sequence, TypeVar
from collections.abc import Sequence
from typing import TypeVar

from numpy.typing import ArrayLike

Expand Down
12 changes: 11 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,23 +67,33 @@ formats = "ipynb,py:percent"

[tool.ruff]
line-length = 88 # black default
target-version = "py310"
# unsafe-fixes = true


[tool.ruff.lint]
select = ["ALL"]
ignore = [
"D107", # undocumented-public-init: we document the class instead
"E501", # line-too-long: we use black instead
"FA", "PLR", "PD", "SLF", "PT", "FBT", "ANN", "EM", "TRY", "ARG", "FIX", "TD", "TID", "ERA", "INP", "SIM", "RUF", "RET"
"TID252", # relative-imports
"PD901", # pandas-df-variable-name
"FBT",
"FIX",
"TD",
"RET",
]


[tool.ruff.lint.per-file-ignores]
"docs/**/*.py" = [
"D100", # undocumented-public-module: we keep tutorials clean and do not include doc strings
"ERA001", # commented-out-code: text cells
"INP001", # implicit-namespace-package: tutorials are not packages
]
"tests/**/*.py" = [
"S101", # assert: Fine in tests
"SLF001", # private-member-access: find in tests
]


Expand Down
2 changes: 1 addition & 1 deletion tests/maths/test_trigonometrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from hamilflow.maths.trigonometrics import acos_with_shift

if TYPE_CHECKING:
from typing import Collection
from collections.abc import Collection


class TestAcosWithShift:
Expand Down
Loading