Skip to content

Commit

Permalink
Use ruff for formatting (#596)
Browse files Browse the repository at this point in the history
* Enable `ruff` as a formatter
* Moved isort formatting to ruff
* Added `ruff` as dependency
  • Loading branch information
david-zwicker authored Aug 16, 2024
1 parent e55bc14 commit 5cbd80f
Show file tree
Hide file tree
Showing 34 changed files with 101 additions and 82 deletions.
2 changes: 1 addition & 1 deletion examples/mpi_parallel_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Use multiprocessing via MPI
===========================
Use multiple cores to solve a PDE. The implementation here uses the `Message Passing
Use multiple cores to solve a PDE. The implementation here uses the `Message Passing
Interface (MPI) <https://en.wikipedia.org/wiki/Message_Passing_Interface>`_, and the
script thus needs to be run using :code:`mpiexec -n 2 python mpi_parallel_run.py`, where
`2` denotes the number of cores used. Note that macOS might require an additional hint
Expand Down
2 changes: 1 addition & 1 deletion examples/pde_custom_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
This example implements a scalar PDE using a custom class. We here consider the
`Kuramoto–Sivashinsky equation
<https://en.wikipedia.org/wiki/Kuramoto–Sivashinsky_equation>`_, which for instance
<https://en.wikipedia.org/wiki/Kuramoto–Sivashinsky_equation>`_, which for instance
describes the dynamics of flame fronts:
.. math::
Expand Down
2 changes: 1 addition & 1 deletion examples/pde_custom_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
This example implements a scalar PDE using the :class:`~pde.pdes.pde.PDE`. We here
consider the `Kuramoto–Sivashinsky equation
<https://en.wikipedia.org/wiki/Kuramoto–Sivashinsky_equation>`_, which for instance
<https://en.wikipedia.org/wiki/Kuramoto–Sivashinsky_equation>`_, which for instance
describes the dynamics of flame fronts:
.. math::
Expand Down
2 changes: 1 addition & 1 deletion examples/pde_custom_numba.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
This example implements a scalar PDE using a custom class with a numba-compiled method
for accelerated calculations. We here consider the `Kuramoto–Sivashinsky equation
<https://en.wikipedia.org/wiki/Kuramoto–Sivashinsky_equation>`_, which for instance
<https://en.wikipedia.org/wiki/Kuramoto–Sivashinsky_equation>`_, which for instance
describes the dynamics of flame fronts:
.. math::
Expand Down
2 changes: 1 addition & 1 deletion examples/pde_heterogeneous_diffusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
Note that the naive implementation,
:code:`PDE({"c": "divergence((1.01 + tanh(x)) * gradient(c))"})`, has numerical
instabilities. This is because two finite difference approximations are nested. To
arrive at a more stable numerical scheme, it is advisable to expand the divergence,
arrive at a more stable numerical scheme, it is advisable to expand the divergence,
.. math::
\partial_t c = D \nabla^2 c + \nabla D . \nabla c
Expand Down
2 changes: 1 addition & 1 deletion examples/pde_schroedinger.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
======================
This example implements a complex PDE using the :class:`~pde.pdes.pde.PDE`. We here
chose the `Schrödinger equation <https://en.wikipedia.org/wiki/Schrödinger_equation>`_
chose the `Schrödinger equation <https://en.wikipedia.org/wiki/Schrödinger_equation>`_
without a spatial potential in non-dimensional form:
.. math::
Expand Down
2 changes: 1 addition & 1 deletion examples/plot_cylindrical_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Plotting a scalar field in cylindrical coordinates
==================================================
This example shows how to initialize and visualize the scalar field
This example shows how to initialize and visualize the scalar field
:math:`u = \sqrt{z} \, \exp(-r^2)` in cylindrical coordinates.
"""

Expand Down
2 changes: 1 addition & 1 deletion examples/plot_vector_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Plotting a vector field
=======================
This example shows how to initialize and visualize the vector field
This example shows how to initialize and visualize the vector field
:math:`\boldsymbol u = \bigl(\sin(x), \cos(x)\bigr)`.
"""

Expand Down
1 change: 0 additions & 1 deletion examples/post_step_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@


class CustomPDE(PDEBase):

def make_post_step_hook(self, state):
"""Create a hook function that is called after every time step."""

Expand Down
3 changes: 2 additions & 1 deletion examples/py_modelrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
This example shows how `py-pde` can be combined with :mod:`modelrunner`. The magic first
line allows running this example as a script using :code:`./py_modelrunner.py`, which
runs the function defined below and stores all results in the file `data.hdf5`.
runs the function defined below and stores all results in the file `data.hdf5`.
The results can be read by the following code
.. code-block:: python
from modelrunner import Result
r = Result.from_file("data.hdf5")
r.result.plot() # plots the final state
r.storage["trajectory"] # allows accessing the stored trajectory
Expand Down
2 changes: 1 addition & 1 deletion examples/trajectory_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
===================================
This example illustrates how to store intermediate data to a file for later
post-processing. The storage frequency is an argument to the tracker.
post-processing. The storage frequency is an argument to the tracker.
"""

from tempfile import NamedTemporaryFile
Expand Down
1 change: 1 addition & 0 deletions examples/tutorial/Tutorial 1 - Grids and fields.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"source": [
"# import packages\n",
"import sys\n",
"\n",
"import numpy as np\n",
"\n",
"sys.path.append(\"../..\") # add the pde package to the python path\n",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"source": [
"# import packages\n",
"import sys\n",
"\n",
"import numpy as np\n",
"\n",
"sys.path.append(\"../..\") # add the pde package to the python path\n",
Expand Down
6 changes: 2 additions & 4 deletions pde/grids/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,8 @@

import numba as nb
import numpy as np
from numba.extending import is_jitted
from numba.extending import is_jitted, register_jitable
from numba.extending import overload as nb_overload
from numba.extending import register_jitable
from numpy.typing import ArrayLike

from ..tools.cache import cached_method, cached_property
Expand Down Expand Up @@ -1192,8 +1191,7 @@ def register_operator(
.. code-block:: python
@GridClass.register_operator("operator")
def make_operator(grid: GridBase):
...
def make_operator(grid: GridBase): ...
Args:
name (str):
Expand Down
3 changes: 1 addition & 2 deletions pde/grids/boundaries/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@
.. code-block:: python
bc_y = ({"type": "mixed", "value": 2, "const": 7},
{"curvature": 2})
bc_y = ({"type": "mixed", "value": 2, "const": 7}, {"curvature": 2})
which enforces the condition :math:`\partial_n c + 2 c = 7` and
:math:`\partial^2_n c = 2` onto the field :math:`c` on the lower and upper side
Expand Down
2 changes: 1 addition & 1 deletion pde/grids/boundaries/axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
This module handles the boundaries of a single axis of a grid. There are
generally only two options, depending on whether the axis of the underlying
grid is defined as periodic or not. If it is periodic, the class
grid is defined as periodic or not. If it is periodic, the class
:class:`~pde.grids.boundaries.axis.BoundaryPeriodic` should be used, while
non-periodic axes have more option, which are represented by
:class:`~pde.grids.boundaries.axis.BoundaryPair`.
Expand Down
10 changes: 5 additions & 5 deletions pde/grids/boundaries/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
Imposing the derivative of a field in the outward normal direction at the boundary
* :class:`~pde.grids.boundaries.local.MixedBC`:
Imposing the derivative of a field in the outward normal direction proportional to its
value at the boundary
value at the boundary
* :class:`~pde.grids.boundaries.local.CurvatureBC`:
Imposing the second derivative (curvature) of a field at the boundary
Expand Down Expand Up @@ -2461,8 +2461,8 @@ class MixedBC(ConstBC1stOrderBase):
.. code-block:: python
bc = {'mixed': VALUE}
bc = {'type': 'mixed', 'value': VALUE, 'const': CONST}
bc = {"mixed": VALUE}
bc = {"type": "mixed", "value": VALUE, "const": CONST}
where `VALUE` corresponds to :math:`\gamma` and `CONST` to :math:`\beta`.
"""
Expand Down Expand Up @@ -2937,8 +2937,8 @@ class NormalMixedBC(MixedBC):
.. code-block:: python
bc = {'mixed': VALUE}
bc = {'type': 'mixed', 'value': VALUE, 'const': CONST}
bc = {"mixed": VALUE}
bc = {"type": "mixed", "value": VALUE, "const": CONST}
where `VALUE` corresponds to :math:`\gamma` and `CONST` to :math:`\beta`.
"""
Expand Down
3 changes: 1 addition & 2 deletions pde/pdes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,13 @@ def make_post_step_hook(self, state: FieldBase) -> tuple[StepperHook, Any]:
.. code-block:: python
def make_post_step_hook(self, state):
def post_step_hook(state_data, t, post_step_data):
i = state_data > 1 # get violating entries
overshoot = (state_data[i] - 1).sum() # get total correction
state_data[i] = 1 # limit data entries
post_step_data += overshoot # accumulate total correction
return post_step_hook, 0. # hook function and initial value
return post_step_hook, 0.0 # hook function and initial value
Args:
state (:class:`~pde.fields.FieldBase`):
Expand Down
4 changes: 3 additions & 1 deletion pde/solvers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,9 @@ def single_step_error_estimate(

return single_step_error_estimate

def _make_adaptive_stepper(self, state: FieldBase) -> Callable[
def _make_adaptive_stepper(
self, state: FieldBase
) -> Callable[
[np.ndarray, float, float, float, OnlineStatistics | None, Any],
tuple[float, float, int],
]:
Expand Down
8 changes: 6 additions & 2 deletions pde/solvers/explicit.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ def _make_single_step_fixed_dt(
else:
raise ValueError(f"Explicit scheme `{self.scheme}` is not supported")

def _make_adaptive_euler_stepper(self, state: FieldBase) -> Callable[
def _make_adaptive_euler_stepper(
self, state: FieldBase
) -> Callable[
[np.ndarray, float, float, float, OnlineStatistics | None, Any],
tuple[float, float, int],
]:
Expand Down Expand Up @@ -371,7 +373,9 @@ def _make_single_step_error_estimate(
# optimizations; see method `_make_adaptive_euler_stepper`
raise ValueError(f"Adaptive scheme `{self.scheme}` is not supported")

def _make_adaptive_stepper(self, state: FieldBase) -> Callable[
def _make_adaptive_stepper(
self, state: FieldBase
) -> Callable[
[np.ndarray, float, float, float, OnlineStatistics | None, Any],
tuple[float, float, int],
]:
Expand Down
2 changes: 1 addition & 1 deletion pde/solvers/explicit_mpi.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ class ExplicitMPISolver(ExplicitSolver):
result = eq.solve(state, t_range=10, dt=0.1, solver="explicit_mpi")
if result is not None: # restrict the output to the main node
result.plot()
result.plot()
Saving this script as `multiprocessing.py`, a parallel simulation is started by
Expand Down
1 change: 1 addition & 0 deletions pde/storage/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,7 @@ def add_to_state(state):
transformed_field = state.smooth(1)
return field.append(transformed_field)
storage = pde.MemoryStorage()
tracker = storage.tracker(1, transformation=add_to_state)
eq.solve(..., tracker=tracker)
Expand Down
1 change: 1 addition & 0 deletions pde/storage/modelrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class ModelrunnerStorage(StorageBase):
.. code-block:: python
from modelrunner import Result
r = Result.from_file("data.hdf5")
r.result.plot() # plots the final state
r.storage["trajectory"] # allows accessing the stored trajectory
Expand Down
1 change: 1 addition & 0 deletions pde/storage/movie.py
Original file line number Diff line number Diff line change
Expand Up @@ -617,6 +617,7 @@ def add_to_state(state):
transformed_field = state.smooth(1)
return field.append(transformed_field)
storage = pde.MemoryStorage()
tracker = storage.tracker(1, transformation=add_to_state)
eq.solve(..., tracker=tracker)
Expand Down
12 changes: 4 additions & 8 deletions pde/tools/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,7 @@ def __init__(
Example:
An example for using the class is::
class Foo():
class Foo:
@cached_property()
def property(self):
return "Cached property"
Expand Down Expand Up @@ -438,13 +437,12 @@ def method(self):
Example:
An advanced example is::
class Foo():
class Foo:
def get_cache(self, name):
# `name` is the name of the method to cache
return DictFiniteCapacity()
@cached_method(factory='get_cache')
@cached_method(factory="get_cache")
def foo(self):
return "Cached"
Expand Down Expand Up @@ -592,8 +590,7 @@ class cached_property(_class_cache):
Example:
Here is an example for how to use the decorator::
class Foo():
class Foo:
@cached_property
def bar(self):
return "Cached"
Expand Down Expand Up @@ -638,7 +635,6 @@ class cached_method(_class_cache):
The decorator can be used like so::
class Foo:
@cached_method
def bar(self):
return "Cached"
Expand Down
8 changes: 4 additions & 4 deletions pde/tools/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,13 @@ class classproperty(property):
Example:
The decorator can be used much like the `property` decorator::
class Test():
item: str = 'World'
class Test:
item: str = "World"
@classproperty
def message(cls):
return 'Hello ' + cls.item
return "Hello " + cls.item
print(Test.message)
"""
Expand Down
13 changes: 6 additions & 7 deletions pde/tools/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,9 @@ def __init__(self) -> None:
def _update_plot(self, reference):
reference.element.set_ydata(self.data)
@plot_on_axes(update_method='_update_plot')
@plot_on_axes(update_method="_update_plot")
def plot(self, ax):
line, = ax.plot(np.arange(8), self.data)
(line,) = ax.plot(np.arange(8), self.data)
return PlotReference(ax, line)
Expand Down Expand Up @@ -414,17 +414,16 @@ def _update_plot(self, reference):
ref1.element.set_ydata(self.data[0])
ref2.element.set_ydata(self.data[1])
@plot_on_figure(update_method='_update_plot')
@plot_on_figure(update_method="_update_plot")
def plot(self, fig):
ax1, ax2 = fig.subplots(1, 2)
l1, = ax1.plot(np.arange(8), self.data[0])
l2, = ax2.plot(np.arange(8), self.data[1])
(l1,) = ax1.plot(np.arange(8), self.data[0])
(l2,) = ax2.plot(np.arange(8), self.data[1])
return [PlotReference(ax1, l1), PlotReference(ax2, l2)]
@plot_on_figure
def make_plot(fig):
...
def make_plot(fig): ...
When `update_method` is not supplied, the method can still be used for
Expand Down
2 changes: 2 additions & 0 deletions pde/trackers/trackers.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ def check_simulation(state, time):
if state.integral < 0:
raise StopIteration
tracker = CallbackTracker(check_simulation, interval="0:10")
Adding :code:`tracker` to the simulation will perform a check every 10 real time
Expand Down Expand Up @@ -600,6 +601,7 @@ class DataTracker(CallbackTracker):
def get_statistics(state, time):
return {"mean": state.data.mean(), "variance": state.data.var()}
data_tracker = DataTracker(get_statistics, interval=10)
Adding :code:`data_tracker` to the simulation will gather the statistics every
Expand Down
Loading

0 comments on commit 5cbd80f

Please sign in to comment.