Skip to content

Commit

Permalink
chore(ruff): #80 apply preliminary rules (#86)
Browse files Browse the repository at this point in the history
* chore(ruff): #80 add to pre-commit

* chore(ruff): #80 automatic fixes

* chore(typo): #80

* chore(pre-commit): #80 add to pyproject.toml

* chore(ruff): #80 comment by @emptymalei #86 (comment)
  • Loading branch information
cmp0xff authored Aug 24, 2024
1 parent 3d4f6f3 commit 03abcd1
Show file tree
Hide file tree
Showing 24 changed files with 259 additions and 82 deletions.
17 changes: 11 additions & 6 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,22 @@ repos:
- id: end-of-file-fixer
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.6.1
hooks:
# Run the linter.
- id: ruff
args:
- --fix
- --exit-non-zero-on-fix
# Run the formatter.
- id: ruff-format
- repo: https://github.com/ambv/black
rev: 24.4.2
hooks:
- id: black
language: python
- repo: https://github.com/pycqa/isort
rev: 5.13.2
hooks:
- id: isort
name: isort (python)
args: ["--multi-line", "3", "--profile", "black", "--treat-comment-as-code", "# %%", "--float-to-top"]
- repo: local
# We do not use pre-commit/mirrors-mypy,
# as it comes with opinionated defaults
Expand Down
10 changes: 6 additions & 4 deletions docs/tutorials/harmonic_oscillator.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,19 +91,21 @@
dfs_dho = []

for s_name, s in dho_systems.items():

dfs_dho.append(
DampedHarmonicOscillator(system=s)(
n_periods=n_periods, n_samples_per_period=n_samples_per_period
).assign(system=rf"{s_name} (omega = {s.get('omega')}, zeta = {s.get('zeta')})")
n_periods=n_periods,
n_samples_per_period=n_samples_per_period,
).assign(
system=rf"{s_name} (omega = {s.get('omega')}, zeta = {s.get('zeta')})",
),
)

fig = px.line(
pd.concat(dfs_dho),
x="t",
y="x",
color="system",
title=rf"Damped Harmonic Oscillator",
title=r"Damped Harmonic Oscillator",
labels={
"x": r"Displacement $x(t)$",
"t": r"$t$",
Expand Down
4 changes: 0 additions & 4 deletions docs/tutorials/kepler_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@
# ## Usage

# %%
import numpy as np
import pandas as pd
import plotly.express as px

from hamilflow.models.kepler_problem.model import Kepler2D

# %%
# system = {"alpha": 1.0, "mass": 1.0}
Expand Down
5 changes: 3 additions & 2 deletions docs/tutorials/pendulum.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@

# %%
df_pen = pen.generate_from(
n_periods=n_periods, n_samples_per_period=n_samples_per_period
n_periods=n_periods,
n_samples_per_period=n_samples_per_period,
)
df_pen.head()

Expand All @@ -62,7 +63,7 @@
df_pen,
x="t",
y="x",
title=r"Simple Harmonic Oscillator ($\omega_0 = {:.4f})$".format(omega0),
title=rf"Simple Harmonic Oscillator ($\omega_0 = {omega0:.4f})$",
labels=dict(x=r"Angle $\theta(t)$", t=r"Time $t$"),
)

Expand Down
1 change: 0 additions & 1 deletion hamilflow/maths/trigonometrics.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from functools import partial
from typing import TYPE_CHECKING

import numpy as np
Expand Down
2 changes: 1 addition & 1 deletion hamilflow/models/brownian_motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def _trajectory(self, n_new_steps: int, seed: int) -> "npt.NDArray[np.float64]":
)

step_history = np.concatenate(
(np.expand_dims(self.initial_condition.x0, axis=0), step_history)
(np.expand_dims(self.initial_condition.x0, axis=0), step_history),
)

trajectory = np.cumsum(step_history, axis=0)
Expand Down
3 changes: 2 additions & 1 deletion hamilflow/models/free_particle.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ class FreeParticle:
"""

def __init__(
self, initial_condition: Mapping[str, float | Sequence[float]]
self,
initial_condition: Mapping[str, float | Sequence[float]],
) -> None:
self.initial_condition = FreeParticleIC.model_validate(initial_condition)

Expand Down
14 changes: 7 additions & 7 deletions hamilflow/models/harmonic_oscillator.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def __init__(
super().__init__(system, initial_condition)
if self.system.type != "simple":
raise ValueError(
f"System is not a Simple Harmonic Oscillator: {self.system}"
f"System is not a Simple Harmonic Oscillator: {self.system}",
)

def _x(self, t: "Sequence[float] | npt.ArrayLike") -> np.ndarray:
Expand All @@ -170,7 +170,7 @@ def _x(self, t: "Sequence[float] | npt.ArrayLike") -> np.ndarray:
$$
"""
return self.initial_condition.x0 * np.cos(
self.system.omega * np.array(t, copy=False) + self.initial_condition.phi
self.system.omega * np.array(t, copy=False) + self.initial_condition.phi,
)


Expand Down Expand Up @@ -232,7 +232,7 @@ def __init__(
if self.system.type == "simple":
raise ValueError(
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`.",
)

def _x_under_damped(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayLike:
Expand Down Expand Up @@ -277,7 +277,7 @@ def _x_critical_damped(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayL
"""
t = np.array(t, copy=False)
return self.initial_condition.x0 * np.exp(
-self.system.zeta * self.system.omega * t
-self.system.zeta * self.system.omega * t,
)

def _x_over_damped(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayLike:
Expand Down Expand Up @@ -318,7 +318,7 @@ def _x(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayLike:
x = self._x_critical_damped(t)
else:
raise ValueError(
"System type is not damped harmonic oscillator: {self.system.type}"
f"System type is not damped harmonic oscillator: {self.system.type}",
)

return x
Expand Down Expand Up @@ -349,11 +349,11 @@ def __init__(
) -> None:
self.system = HarmonicOscillatorSystem.model_validate(system)
self.initial_condition = ComplexSimpleHarmonicOscillatorIC.model_validate(
initial_condition
initial_condition,
)
if self.system.type != "simple":
raise ValueError(
f"System is not a Simple Harmonic Oscillator: {self.system}"
f"System is not a Simple Harmonic Oscillator: {self.system}",
)

@cached_property
Expand Down
28 changes: 17 additions & 11 deletions hamilflow/models/harmonic_oscillator_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,31 +92,36 @@ def definition(
)

def _z(
self, t: "Sequence[float] | npt.ArrayLike"
self,
t: "Sequence[float] | npt.ArrayLike",
) -> "tuple[npt.NDArray[np.complex64], npt.NDArray[np.complex64]]":
t = np.array(t, copy=False).reshape(-1)
all_travelling_waves = [self.free_mode._x(t).reshape(1, -1)]

if self.independent_csho_modes:
independent_cshos = np.array(
[o._z(t) for o in self.independent_csho_modes], copy=False
[o._z(t) for o in self.independent_csho_modes],
copy=False,
)
all_travelling_waves.extend(
(independent_cshos, independent_cshos[::-1].conj())
if self.odd_dof
else (
independent_cshos[:-1],
independent_cshos[[-1]],
independent_cshos[-2::-1].conj(),
)
(
(independent_cshos, independent_cshos[::-1].conj())
if self.odd_dof
else (
independent_cshos[:-1],
independent_cshos[[-1]],
independent_cshos[-2::-1].conj(),
)
),
)

travelling_waves = np.concatenate(all_travelling_waves)
original_zs = ifft(travelling_waves, axis=0, norm="ortho")
return original_zs, travelling_waves

def _x(
self, t: "Sequence[float] | npt.ArrayLike"
self,
t: "Sequence[float] | npt.ArrayLike",
) -> "tuple[npt.NDArray[np.float64], npt.NDArray[np.complex64]]":
original_xs, travelling_waves = self._z(t)

Expand All @@ -133,7 +138,8 @@ def __call__(self, t: "Sequence[float] | npt.ArrayLike") -> pd.DataFrame:
original_xs, travelling_waves = self._x(t)
data = { # type: ignore [var-annotated]
f"{name}{i}": cast(
"npt.NDArray[np.float64] | npt.NDArray[np.complex64]", values
"npt.NDArray[np.float64] | npt.NDArray[np.complex64]",
values,
)
for name, xs in zip(("x", "y"), (original_xs, travelling_waves))
for i, values in enumerate(xs) # type: ignore [arg-type]
Expand Down
21 changes: 14 additions & 7 deletions hamilflow/models/kepler_problem/dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,26 @@


def _tau_of_u_exact_elliptic(
ecc: float, u: "npt.NDArray[np.float64]"
ecc: float,
u: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
cosqr, eusqrt = 1 - ecc**2, np.sqrt(ecc**2 - u**2)
trig_numer = np.pi / 2 - np.arctan((ecc**2 + u) / np.sqrt(cosqr) / eusqrt)
return -eusqrt / cosqr / (1 + u) + trig_numer / cosqr**1.5


def _tau_of_e_plus_u_elliptic(
ecc: float, u: "npt.NDArray[np.float64]"
ecc: float,
u: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
epu = np.sqrt(2 * (ecc + u) / ecc)
const = np.pi / (1 - ecc**2) ** 1.5
return const - epu / (ecc - 1) ** 2 + epu**3 * (1 - 9 * ecc) / 24 / (1 - ecc) ** 3


def _tau_of_e_minus_u_elliptic(
ecc: float, u: "npt.NDArray[np.float64]"
ecc: float,
u: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
emu = np.sqrt(2 * (ecc - u) / ecc)
return emu / (1 + ecc) ** 2 - emu**3 * (1 + 9 * ecc) / 24 / (1 + ecc) ** 3
Expand All @@ -49,7 +52,8 @@ def tau_of_u_parabolic(ecc: float, u: "npt.ArrayLike") -> "npt.NDArray[np.float6


def _tau_of_u_exact_hyperbolic(
ecc: float, u: "npt.ArrayLike"
ecc: float,
u: "npt.ArrayLike",
) -> "npt.NDArray[np.float64]":
u = np.array(u, copy=False)
cosqr, eusqrt = ecc**2 - 1, np.sqrt(ecc**2 - u**2)
Expand All @@ -58,7 +62,8 @@ def _tau_of_u_exact_hyperbolic(


def _tau_of_1_plus_u_hyperbolic(
ecc: float, u: "npt.NDArray[np.float64]"
ecc: float,
u: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
cosqr = ecc**2 - 1
up1 = ecc * (1 + u) / 2 / cosqr
Expand All @@ -68,7 +73,8 @@ def _tau_of_1_plus_u_hyperbolic(


def _tau_of_e_minus_u_hyperbolic(
ecc: float, u: "npt.NDArray[np.float64]"
ecc: float,
u: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
emu = np.sqrt(2 * (ecc - u) / ecc)
return emu / (1 + ecc) ** 2 + emu**3 * (1 + 9 * ecc) / 24 / (1 + ecc) ** 3
Expand Down Expand Up @@ -96,7 +102,8 @@ def tau_of_u_prime2(ecc: float, u: "npt.ArrayLike") -> "npt.NDArray[np.float64]"


def esolve_u_from_tau_parabolic(
ecc: float, tau: "npt.ArrayLike"
ecc: float,
tau: "npt.ArrayLike",
) -> "npt.NDArray[np.float64]":
tau = np.array(tau, copy=False)
tau_3 = 3 * tau
Expand Down
8 changes: 5 additions & 3 deletions hamilflow/models/kepler_problem/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,9 @@ def __init__(

@classmethod
def from_geometry(
cls, system: "Mapping[str, float]", geometries: "Mapping[str, bool | float]"
cls,
system: "Mapping[str, float]",
geometries: "Mapping[str, bool | float]",
) -> "Self":
mass, alpha = system["mass"], system["alpha"]
positive_angular_mom = bool(geometries["positive_angular_mom"])
Expand Down Expand Up @@ -162,14 +164,14 @@ def parameter(self) -> float:
@cached_property
def ecc(self) -> float:
return math.sqrt(
1 + 2 * self.ene * self.angular_mom**2 / self.mass / self.alpha**2
1 + 2 * self.ene * self.angular_mom**2 / self.mass / self.alpha**2,
)

@cached_property
def period_in_tau(self) -> float:
if self.ecc >= 1:
raise TypeError(
f"Only systems with 0 <= eccentricity < 1 have a period, got {self.ecc}"
f"Only systems with 0 <= eccentricity < 1 have a period, got {self.ecc}",
)
return 2 * math.pi / (1 - self.ecc**2) ** 1.5

Expand Down
10 changes: 7 additions & 3 deletions hamilflow/models/kepler_problem/numerics.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,17 @@


def _u0_elliptic(
ecc: float, tau: "npt.NDArray[np.float64]"
ecc: float,
tau: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
cosqr = 1 - ecc**2
cot = 1 / np.tan(cosqr**1.5 * tau)
return ecc * (-ecc + cosqr * cot * np.sqrt(1 + cot**2)) / (1 + cosqr * cot**2)


def _u0_hyperbolic(
ecc: float, tau: "npt.NDArray[np.float64]"
ecc: float,
tau: "npt.NDArray[np.float64]",
) -> "npt.NDArray[np.float64]":
cosqr, tau2 = ecc**2 - 1, tau**2
numer = -(cosqr**2) * tau2 + np.sqrt(ecc**2 + cosqr**3 * tau2)
Expand Down Expand Up @@ -72,7 +74,9 @@ def f(u: float, tau: float) -> np.float64:


def u_of_tau(
ecc: float, tau: "npt.ArrayLike", method: Literal["bisect", "newton"] = "bisect"
ecc: float,
tau: "npt.ArrayLike",
method: Literal["bisect", "newton"] = "bisect",
) -> "npt.NDArray[np.float64]":
tau = np.array(tau, copy=False)
if ecc == 0:
Expand Down
3 changes: 2 additions & 1 deletion hamilflow/models/pendulum.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ def period(self) -> float:
return 4 * ellipk(self._math_m) / self.omega0

def _math_u(
self, t: "Sequence[float] | npt.ArrayLike"
self,
t: "Sequence[float] | npt.ArrayLike",
) -> "npt.NDArray[np.float64]":
return self.omega0 * np.array(t, copy=False)

Expand Down
Loading

0 comments on commit 03abcd1

Please sign in to comment.