Skip to content

Commit

Permalink
chore(ruff): #94 enable all one-letter rules (#95)
Browse files Browse the repository at this point in the history
* chore(pre-commit): #94 new ruff and more rules

* chore(ruff): #94 fixes
  • Loading branch information
cmp0xff authored Sep 9, 2024
1 parent 094c367 commit e97350c
Show file tree
Hide file tree
Showing 15 changed files with 94 additions and 64 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ repos:
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.6.3
rev: v0.6.4
hooks:
# Run the linter.
- id: ruff
Expand Down
8 changes: 4 additions & 4 deletions docs/tutorials/brownian_motion.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@
px.scatter(df_2d, x="x_0", y="x_1", color="t")
.update_traces(
mode="lines+markers",
marker=dict(
size=2.5,
),
line=dict(width=1),
marker={
"size": 2.5,
},
line={"width": 1},
)
.update_yaxes(
scaleanchor="x",
Expand Down
29 changes: 22 additions & 7 deletions docs/tutorials/complex_harmonic_oscillator.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,48 +31,63 @@

# %%
t = np.linspace(0, 3, 257)
system_specs = dict(omega=2 * math.pi)
system_specs = {"omega": 2 * math.pi}

# %% [markdown]
# ## Positive-frequency, circular-polarised mode
# Also known as the left-rotating mode.

# %%
csho = ComplexSimpleHarmonicOscillator(system_specs, initial_condition=dict(x0=(1, 0)))
csho = ComplexSimpleHarmonicOscillator(system_specs, initial_condition={"x0": (1, 0)})

df = csho(t)

arr_z = df["z"].to_numpy(copy=False)

px.line_3d(x=arr_z.real, y=arr_z.imag, z=t, labels=dict(x="real", y="imag", z="time"))
px.line_3d(
x=arr_z.real,
y=arr_z.imag,
z=t,
labels={"x": "real", "y": "imag", "z": "time"},
)

# %% [markdown]
# ## Negative-frequency, circular-polarised mode
# Also known as the right-rotating mode.

# %%
csho = ComplexSimpleHarmonicOscillator(system_specs, initial_condition=dict(x0=(0, 1)))
csho = ComplexSimpleHarmonicOscillator(system_specs, initial_condition={"x0": (0, 1)})

df = csho(t)

arr_z = df["z"].to_numpy(copy=False)

px.line_3d(x=arr_z.real, y=arr_z.imag, z=t, labels=dict(x="real", y="imag", z="time"))
px.line_3d(
x=arr_z.real,
y=arr_z.imag,
z=t,
labels={"x": "real", "y": "imag", "z": "time"},
)

# %% [markdown]
# ## Positive-frequency, elliptic-polarised mode

# %%
csho = ComplexSimpleHarmonicOscillator(
system_specs,
initial_condition=dict(x0=(math.cos(math.pi / 12), math.sin(math.pi / 12))),
initial_condition={"x0": (math.cos(math.pi / 12), math.sin(math.pi / 12))},
)

df = csho(t)

arr_z = df["z"].to_numpy(copy=False)

px.line_3d(x=arr_z.real, y=arr_z.imag, z=t, labels=dict(x="real", y="imag", z="time"))
px.line_3d(
x=arr_z.real,
y=arr_z.imag,
z=t,
labels={"x": "real", "y": "imag", "z": "time"},
)

# %% [markdown]
# # End of Notebook
12 changes: 6 additions & 6 deletions docs/tutorials/harmonic_oscillator_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
# ## Fundamental right-moving wave

# %%
ics = [dict(x0=0, v0=0), dict(amp=(1, 0))] + [dict(amp=(0, 0))] * 5
ics = [{"x0": 0, "v0": 0}, {"amp": (1, 0)}] + [{"amp": (0, 0)}] * 5
hoc = HarmonicOscillatorsChain(omega, ics, True)

df_res = hoc(t)
Expand All @@ -50,7 +50,7 @@
# ## Fundamental left-moving wave

# %%
ics = [dict(x0=0, v0=0), dict(amp=(0, 1))] + [dict(amp=(0, 0))] * 5
ics = [{"x0": 0, "v0": 0}, {"amp": (0, 1)}] + [{"amp": (0, 0)}] * 5
hoc = HarmonicOscillatorsChain(2 * math.pi, ics, True)

df_res = hoc(t)
Expand All @@ -62,7 +62,7 @@
# Also known as the first harmonic.

# %%
ics = [dict(x0=0, v0=0), dict(amp=(0, 0)), dict(amp=(1, 0))] + [dict(amp=(0, 0))] * 4
ics = [{"x0": 0, "v0": 0}, {"amp": (0, 0)}, {"amp": (1, 0)}] + [{"amp": (0, 0)}] * 4
hoc = HarmonicOscillatorsChain(omega, ics, True)

df_res = hoc(t)
Expand All @@ -73,7 +73,7 @@
# ## Fundamental stationary wave, odd dof

# %%
ics = [dict(x0=0, v0=0), dict(amp=(1, 1))] + [dict(amp=(0, 0))] * 5
ics = [{"x0": 0, "v0": 0}, {"amp": (1, 1)}] + [{"amp": (0, 0)}] * 5
hoc = HarmonicOscillatorsChain(omega, ics, True)

df_res = hoc(t)
Expand All @@ -86,7 +86,7 @@
# There are stationary nodes at $i = 3, 9$.

# %%
ics = [dict(x0=0, v0=0), dict(amp=(1, 1))] + [dict(amp=(0, 0))] * 5
ics = [{"x0": 0, "v0": 0}, {"amp": (1, 1)}] + [{"amp": (0, 0)}] * 5
hoc = HarmonicOscillatorsChain(omega, ics, False)

df_res = hoc(t)
Expand All @@ -98,7 +98,7 @@
# ## Linearly moving chain and fundamental right-moving wave

# %%
ics = [dict(x0=0, v0=2), dict(amp=(1, 0))] + [dict(amp=(0, 0))] * 5
ics = [{"x0": 0, "v0": 2}, {"amp": (1, 0)}] + [{"amp": (0, 0)}] * 5
hoc = HarmonicOscillatorsChain(omega, ics, False)

df_res = hoc(t)
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorials/pendulum.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
x="t",
y="x",
title=rf"Simple Harmonic Oscillator ($\omega_0 = {omega0:.4f})$",
labels=dict(x=r"Angle $\theta(t)$", t=r"Time $t$"),
labels={"x": r"Angle $\theta(t)$", "t": r"Time $t$"},
)

# %% [markdown]
Expand Down
2 changes: 1 addition & 1 deletion hamilflow/models/free_particle.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def __init__(
@cached_property
def definition(self) -> dict[str, dict[str, float | list[float]]]:
"""Model params and initial conditions defined as a dictionary."""
return dict(initial_condition=self.initial_condition.model_dump())
return {"initial_condition": self.initial_condition.model_dump()}

def _x(self, t: "Sequence[float] | npt.ArrayLike") -> "npt.NDArray[np.float64]":
t = np.asarray(t)
Expand Down
8 changes: 4 additions & 4 deletions hamilflow/models/harmonic_oscillator.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,10 +360,10 @@ def definition(
self,
) -> dict[str, dict[str, float | tuple[float, float]]]:
"""Model params and initial conditions defined as a dictionary."""
return dict(
system=self.system.model_dump(),
initial_condition=self.initial_condition.model_dump(),
)
return {
"system": self.system.model_dump(),
"initial_condition": self.initial_condition.model_dump(),
}

def _z(self, t: "Sequence[float] | npt.ArrayLike") -> npt.ArrayLike:
r"""Solution to complex simple harmonic oscillators.
Expand Down
20 changes: 10 additions & 10 deletions hamilflow/models/harmonic_oscillator_chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,10 @@ def _sho_factory(
phi: tuple[float, float] | None = None,
) -> ComplexSimpleHarmonicOscillator:
return ComplexSimpleHarmonicOscillator(
dict(
omega=2 * self.omega * np.sin(np.pi * k / self.n_dof),
),
dict(x0=amp) | (dict(phi=phi) if phi else {}),
{
"omega": 2 * self.omega * np.sin(np.pi * k / self.n_dof),
},
{"x0": amp} | ({"phi": phi} if phi else {}),
)

@cached_property
Expand All @@ -83,14 +83,14 @@ def definition(
| list[dict[str, dict[str, float | tuple[float, float]]]],
]:
"""Model params and initial conditions defined as a dictionary."""
return dict(
omega=self.omega,
n_dof=self.n_dof,
free_mode=self.free_mode.definition,
independent_csho_modes=[
return {
"omega": self.omega,
"n_dof": self.n_dof,
"free_mode": self.free_mode.definition,
"independent_csho_modes": [
rwm.definition for rwm in self.independent_csho_modes
],
)
}

def _z(
self,
Expand Down
14 changes: 8 additions & 6 deletions hamilflow/models/kepler_problem/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,17 @@ def from_geometry(
"""
mass, alpha = system["mass"], system["alpha"]
positive_angular_mom = bool(geometries["positive_angular_mom"])
ecc, parameter = map(lambda k: float(geometries[k]), ["ecc", "parameter"])
ecc, parameter = (float(geometries[k]) for k in ["ecc", "parameter"])
abs_angular_mom = math.sqrt(mass * parameter * alpha)
# abs_minimal_ene = alpha / 2 / parameter: numerically unstable
abs_minimal_ene = mass * alpha**2 / 2 / abs_angular_mom**2
ene = (ecc**2 - 1) * abs_minimal_ene
iom = dict(
ene=ene,
angular_mom=abs_angular_mom if positive_angular_mom else -abs_angular_mom,
)
iom = {
"ene": ene,
"angular_mom": (
abs_angular_mom if positive_angular_mom else -abs_angular_mom
),
}
return cls(system, iom)

@staticmethod
Expand Down Expand Up @@ -252,4 +254,4 @@ def __call__(self, t: "Collection[float] | npt.ArrayLike") -> pd.DataFrame:
r = self.r_of_u(u)
phi = self.phi_of_u_tau(u, tau)

return pd.DataFrame(dict(t=t, tau=tau, u=u, r=r, phi=phi))
return pd.DataFrame({"t": t, "tau": tau, "u": u, "r": r, "phi": phi})
10 changes: 5 additions & 5 deletions hamilflow/models/pendulum.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ def __init__(
@cached_property
def definition(self) -> dict[str, dict[str, Any]]:
"""Model params and initial conditions defined as a dictionary."""
return dict(
system=self.system.model_dump(),
initial_condition=self.initial_condition.model_dump(),
)
return {
"system": self.system.model_dump(),
"initial_condition": self.initial_condition.model_dump(),
}

@property
def omega0(self) -> float:
Expand Down Expand Up @@ -159,4 +159,4 @@ def __call__(self, t: TypeTime) -> pd.DataFrame:
thetas = self.theta(t)
us = self.u(t)

return pd.DataFrame(dict(t=t, x=thetas, u=us))
return pd.DataFrame({"t": t, "x": thetas, "u": us})
8 changes: 6 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,19 @@ line-length = 88 # black default
[tool.ruff.lint]
select = ["ALL"]
ignore = [
"D107", # undocumented-public-init: we document the class instead
"FA", "PLR", "S", "PD", "SLF", "PT", "FBT", "C", "ANN", "EM", "TRY", "ARG", "FIX", "TD", "TID", "ERA", "INP", "E", "SIM", "RUF", "RET"
"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"
]


[tool.ruff.lint.per-file-ignores]
"docs/**/*.py" = [
"D100", # undocumented-public-module: we keep tutorials clean and do not include doc strings
]
"tests/**/*.py" = [
"S101", # assert: Fine in tests
]


[tool.ruff.lint.isort]
Expand Down
11 changes: 9 additions & 2 deletions tests/models/kepler_problem/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,11 @@ def geometries(
parameter: float,
) -> dict[str, bool | float]:
"""Give geometric characteristics for initialising a KeplerSystem."""
return dict(positive_angular_mom=positive_angular_mom, ecc=ecc, parameter=parameter)
return {
"positive_angular_mom": positive_angular_mom,
"ecc": ecc,
"parameter": parameter,
}


class Test2DSystem:
Expand Down Expand Up @@ -101,7 +105,10 @@ def test_minimal_ene(
kep = Kepler2D.from_geometry(system_kwargs, geometries)
assert_equal(kep.ene, Kepler2D.minimal_ene(kep.angular_mom, system_kwargs))
with pytest.raises(ValueError):
Kepler2D(system_kwargs, dict(ene=kep.ene - 1, angular_mom=kep.angular_mom))
Kepler2D(
system_kwargs,
{"ene": kep.ene - 1, "angular_mom": kep.angular_mom},
)

def test_period_from_u(
self,
Expand Down
14 changes: 8 additions & 6 deletions tests/models/test_free_particle.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ class TestFreeParticle:
@pytest.mark.parametrize(
("x0", "v0", "expected"),
[
(1, 2, dict(initial_condition=dict(x0=1, v0=2))),
((1,), (2,), dict(initial_condition=dict(x0=(1,), v0=(2,)))),
(1, 2, {"initial_condition": {"x0": 1, "v0": 2}}),
((1,), (2,), {"initial_condition": {"x0": (1,), "v0": (2,)}}),
],
)
def test_definition(
Expand All @@ -53,17 +53,19 @@ def test_definition(
expected: Mapping[str, Mapping[str, int | Sequence[int]]],
) -> None:
"""Test the definition property."""
assert FreeParticle(initial_condition=dict(x0=x0, v0=v0)).definition == expected
assert (
FreeParticle(initial_condition={"x0": x0, "v0": v0}).definition == expected
)

@pytest.mark.parametrize(
("x0", "v0", "t", "expected"),
[
(1, 2, (3,), pd.DataFrame(dict(t=[3], x1=[7]))),
(1, 2, (3,), pd.DataFrame({"t": [3], "x1": [7]})),
(
(1, 2),
(2, 3),
(3, 4),
pd.DataFrame(dict(t=(3, 4), x1=(7, 9), x2=(11, 14))),
pd.DataFrame({"t": (3, 4), "x1": (7, 9), "x2": (11, 14)}),
),
],
)
Expand All @@ -76,6 +78,6 @@ def test_call(
) -> None:
"""Test the __call__ interface."""
assert_frame_equal(
FreeParticle(initial_condition=dict(x0=x0, v0=v0))(t).astype(float),
FreeParticle(initial_condition={"x0": x0, "v0": v0})(t).astype(float),
expected.astype(float),
)
Loading

0 comments on commit e97350c

Please sign in to comment.