Skip to content

Commit

Permalink
Added pyupgrade to format code (#54)
Browse files Browse the repository at this point in the history
* Added pyupgrade to format code
  • Loading branch information
david-zwicker authored Jan 3, 2024
1 parent 78ab086 commit 9758bab
Show file tree
Hide file tree
Showing 13 changed files with 117 additions and 125 deletions.
2 changes: 1 addition & 1 deletion docs/source/run_autodoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def replace_in_file(infile, replacements, outfile=None):
if outfile is None:
outfile = infile

with open(infile, "r") as fp:
with open(infile) as fp:
content = fp.read()

for key, value in replacements.items():
Expand Down
2 changes: 1 addition & 1 deletion docs/source/sphinx_simplify_typehints.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
# replacement rules based on regular expressions
REPLACEMENTS_REGEX = {
# remove full package path and only leave the module/class identifier
"pde\.(\w+\.)*": "",
r"pde\.(\w+\.)*": "",
}


Expand Down
28 changes: 14 additions & 14 deletions droplets/droplet_tracks.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import json
import logging
from typing import Callable, List, Literal, Optional
from typing import Callable, Literal

import numpy as np
from numpy.lib import recfunctions as rfn
Expand Down Expand Up @@ -159,15 +159,15 @@ def last(self) -> SphericalDroplet:
return self.droplets[-1] # type: ignore

@property
def dim(self) -> Optional[int]:
def dim(self) -> int | None:
"""return the space dimension of the droplets"""
try:
return self.last.dim
except IndexError:
return None

@property
def data(self) -> Optional[np.ndarray]:
def data(self) -> np.ndarray | None:
""":class:`~numpy.ndarray`: an array containing the data of the full track"""
if len(self) == 0:
return None
Expand All @@ -187,7 +187,7 @@ def items(self):
"""iterate over all times and droplets, returning them in pairs"""
return zip(self.times, self.droplets)

def append(self, droplet: SphericalDroplet, time: Optional[float] = None) -> None:
def append(self, droplet: SphericalDroplet, time: float | None = None) -> None:
"""append a new droplet with a time code
Args:
Expand Down Expand Up @@ -260,7 +260,7 @@ def get_volumes(self, smoothing: float = 0) -> np.ndarray:
"""
return self.get_trajectory(smoothing, attribute="volume")

def time_overlaps(self, other: "DropletTrack") -> bool:
def time_overlaps(self, other: DropletTrack) -> bool:
"""determine whether two DropletTrack instances overlaps in time
Args:
Expand Down Expand Up @@ -334,7 +334,7 @@ def _write_hdf_dataset(self, hdf_path, key: str = "droplet_track"):

return dataset

def to_file(self, path: str, info: Optional[InfoDict] = None) -> None:
def to_file(self, path: str, info: InfoDict | None = None) -> None:
"""store data in hdf5 file
The data can be read using the classmethod :meth:`DropletTrack.from_file`.
Expand All @@ -360,7 +360,7 @@ def plot(
self,
attribute: str = "radius",
smoothing: float = 0,
t_max: Optional[float] = None,
t_max: float | None = None,
ax=None,
**kwargs,
) -> PlotReference:
Expand Down Expand Up @@ -409,7 +409,7 @@ def plot(

@plot_on_axes()
def plot_positions(
self, grid: Optional[GridBase] = None, arrow: bool = True, ax=None, **kwargs
self, grid: GridBase | None = None, arrow: bool = True, ax=None, **kwargs
) -> PlotReference:
"""plot the droplet track
Expand Down Expand Up @@ -495,7 +495,7 @@ def from_emulsion_time_course(
time_course: EmulsionTimeCourse,
*,
method: Literal["distance", "overlap"] = "overlap",
grid: Optional[GridBase] = None,
grid: GridBase | None = None,
progress: bool = False,
**kwargs,
) -> DropletTrackList:
Expand Down Expand Up @@ -531,13 +531,13 @@ def from_emulsion_time_course(
# track droplets by their physical overlap

def match_tracks(
emulsion: Emulsion, tracks_alive: List[DropletTrack], time: float
emulsion: Emulsion, tracks_alive: list[DropletTrack], time: float
) -> None:
"""helper function adding emulsions to the tracks"""
found_multiple_overlap = False
for droplet in emulsion:
# determine which old tracks could be extended
overlaps: List[DropletTrack] = []
overlaps: list[DropletTrack] = []
for track in tracks_alive:
if track.last.overlaps(droplet, grid=grid):
overlaps.append(track)
Expand All @@ -558,7 +558,7 @@ def match_tracks(
max_dist = kwargs.pop("max_dist", np.inf)

def match_tracks(
emulsion: Emulsion, tracks_alive: List[DropletTrack], time: float
emulsion: Emulsion, tracks_alive: list[DropletTrack], time: float
) -> None:
"""helper function adding emulsions to the tracks"""
added = set()
Expand Down Expand Up @@ -619,7 +619,7 @@ def from_storage(
method: Literal["distance", "overlap"] = "overlap",
refine: bool = False,
num_processes: int | Literal["auto"] = 1,
progress: Optional[bool] = None,
progress: bool | None = None,
) -> DropletTrackList:
r"""obtain droplet tracks from stored scalar field data
Expand Down Expand Up @@ -675,7 +675,7 @@ def from_file(cls, path: str) -> DropletTrackList:
obj.append(DropletTrack._from_hdf_dataset(dataset))
return obj

def to_file(self, path: str, info: Optional[InfoDict] = None) -> None:
def to_file(self, path: str, info: InfoDict | None = None) -> None:
"""store data in hdf5 file
The data can be read using the classmethod :meth:`DropletTrackList.from_file`.
Expand Down
52 changes: 25 additions & 27 deletions droplets/droplets.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
import warnings
from abc import ABCMeta, abstractmethod
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, TypeVar, Union
from typing import Any, Callable, List, Tuple, Type, TypeVar, Union

import numpy as np
from numba.extending import register_jitable
Expand Down Expand Up @@ -103,7 +103,7 @@ class DropletBase:
`dtype` of the array determines what information the droplet class stores.
"""

_subclasses: Dict[str, DropletBase] = {} # collect all inheriting classes
_subclasses: dict[str, DropletBase] = {} # collect all inheriting classes

__slots__ = ["data"]

Expand Down Expand Up @@ -238,7 +238,7 @@ def merge(self: TDroplet, other: TDroplet, *, inplace: bool = False) -> TDroplet
return self.__class__.from_data(result) # type: ignore

@property
def data_bounds(self) -> Tuple[np.ndarray, np.ndarray]:
def data_bounds(self) -> tuple[np.ndarray, np.ndarray]:
"""tuple: lower and upper bounds on the parameters"""
num = len(self._data_array)
return np.full(num, -np.inf), np.full(num, np.inf)
Expand Down Expand Up @@ -290,7 +290,7 @@ def dim(self) -> int:
return get_dtype_field_size(self.data.dtype, "position")

@property
def data_bounds(self) -> Tuple[np.ndarray, np.ndarray]:
def data_bounds(self) -> tuple[np.ndarray, np.ndarray]:
"""tuple: lower and upper bounds on the parameters"""
l, h = super().data_bounds
l[self.dim] = 0 # radius must be non-negative
Expand Down Expand Up @@ -356,9 +356,7 @@ def bbox(self) -> Cuboid:
self.position - self.radius, self.position + self.radius
)

def overlaps(
self, other: SphericalDroplet, grid: Optional[GridBase] = None
) -> bool:
def overlaps(self, other: SphericalDroplet, grid: GridBase | None = None) -> bool:
"""determine whether another droplet overlaps with this one
Note that this function so far only compares the distances of the droplets to
Expand Down Expand Up @@ -475,7 +473,7 @@ def get_phase_field(
*,
vmin: float = 0,
vmax: float = 1,
label: Optional[str] = None,
label: str | None = None,
) -> ScalarField:
"""Creates an image of the droplet on the `grid`
Expand All @@ -497,7 +495,7 @@ def get_phase_field(
data = vmin + (vmax - vmin) * data # scale data
return ScalarField(grid, data=data, label=label)

def get_triangulation(self, resolution: float = 1) -> Dict[str, Any]:
def get_triangulation(self, resolution: float = 1) -> dict[str, Any]:
"""obtain a triangulated shape of the droplet surface
Args:
Expand Down Expand Up @@ -567,7 +565,7 @@ def _get_mpl_patch(self, dim=None, **kwargs):
return mpl.patches.Circle(position, self.radius, **kwargs)

@plot_on_axes()
def plot(self, ax, value: Optional[Callable] = None, **kwargs) -> PlotReference:
def plot(self, ax, value: Callable | None = None, **kwargs) -> PlotReference:
"""Plot the droplet
Args:
Expand Down Expand Up @@ -601,7 +599,7 @@ def __init__(
self,
position: np.ndarray,
radius: float,
interface_width: Optional[float] = None,
interface_width: float | None = None,
):
"""
Args:
Expand All @@ -617,7 +615,7 @@ def __init__(
self.interface_width = interface_width

@property
def data_bounds(self) -> Tuple[np.ndarray, np.ndarray]:
def data_bounds(self) -> tuple[np.ndarray, np.ndarray]:
"""tuple: lower and upper bounds on the parameters"""
l, h = super().data_bounds
l[self.dim + 1] = 0 # interface width must be non-negative
Expand Down Expand Up @@ -651,15 +649,15 @@ def merge_data(drop1: np.ndarray, drop2: np.ndarray, out: np.ndarray) -> None:
return merge_data # type: ignore

@property
def interface_width(self) -> Optional[float]:
def interface_width(self) -> float | None:
"""float: the width of the interface of this droplet"""
if np.isnan(self.data["interface_width"]):
return None
else:
return float(self.data["interface_width"])

@interface_width.setter
def interface_width(self, value: Optional[float]) -> None:
def interface_width(self, value: float | None) -> None:
if value is None:
self.data["interface_width"] = math.nan
elif value < 0:
Expand Down Expand Up @@ -718,8 +716,8 @@ def __init__(
self,
position: np.ndarray,
radius: float,
interface_width: Optional[float] = None,
amplitudes: Optional[np.ndarray] = None,
interface_width: float | None = None,
amplitudes: np.ndarray | None = None,
):
"""
Args:
Expand Down Expand Up @@ -768,7 +766,7 @@ def get_dtype(cls, **kwargs) -> DTypeList:
return dtype + [("amplitudes", float, (modes,))]

@property
def data_bounds(self) -> Tuple[np.ndarray, np.ndarray]:
def data_bounds(self) -> tuple[np.ndarray, np.ndarray]:
"""tuple: lower and upper bounds on the parameters"""
l, h = super().data_bounds
n = self.dim + 2
Expand All @@ -789,7 +787,7 @@ def amplitudes(self) -> np.ndarray:
return np.atleast_1d(self.data["amplitudes"]) # type: ignore

@amplitudes.setter
def amplitudes(self, value: Optional[np.ndarray] = None) -> None:
def amplitudes(self, value: np.ndarray | None = None) -> None:
if value is None:
assert self.modes == 0
self.data["amplitudes"] = np.broadcast_to(0.0, (0,))
Expand Down Expand Up @@ -888,8 +886,8 @@ def __init__(
self,
position: np.ndarray,
radius: float,
interface_width: Optional[float] = None,
amplitudes: Optional[np.ndarray] = None,
interface_width: float | None = None,
amplitudes: np.ndarray | None = None,
):
r"""
Args:
Expand Down Expand Up @@ -1066,8 +1064,8 @@ def __init__(
self,
position: np.ndarray,
radius: float,
interface_width: Optional[float] = None,
amplitudes: Optional[np.ndarray] = None,
interface_width: float | None = None,
amplitudes: np.ndarray | None = None,
):
r"""
Args:
Expand Down Expand Up @@ -1097,7 +1095,7 @@ def __init__(

@preserve_scalars
def interface_distance( # type: ignore
self, θ: np.ndarray, φ: Optional[np.ndarray] = None
self, θ: np.ndarray, φ: np.ndarray | None = None
) -> np.ndarray:
r"""calculates the distance of the droplet interface to the origin
Expand All @@ -1122,7 +1120,7 @@ def interface_distance( # type: ignore

@preserve_scalars
def interface_position(
self, θ: np.ndarray, φ: Optional[np.ndarray] = None
self, θ: np.ndarray, φ: np.ndarray | None = None
) -> np.ndarray:
r"""calculates the position of the interface of the droplet
Expand All @@ -1146,7 +1144,7 @@ def interface_position(

@preserve_scalars
def interface_curvature( # type: ignore
self, θ: np.ndarray, φ: Optional[np.ndarray] = None
self, θ: np.ndarray, φ: np.ndarray | None = None
) -> np.ndarray:
r"""calculates the mean curvature of the interface of the droplet
Expand Down Expand Up @@ -1296,7 +1294,7 @@ class _TriangulatedSpheres:
def __init__(self) -> None:
self.path = Path(__file__).resolve().parent / "resources" / "spheres_3d.hdf5"
self.num_list = np.zeros((0,))
self.data: Optional[Dict[int, Dict[str, Any]]] = None
self.data: dict[int, dict[str, Any]] | None = None

def _load(self):
"""load the stored resource"""
Expand All @@ -1316,7 +1314,7 @@ def _load(self):
}
self.data[num] = tri

def get_triangulation(self, num_est: int = 1) -> Dict[str, Any]:
def get_triangulation(self, num_est: int = 1) -> dict[str, Any]:
"""get a triangulation of a sphere
Args:
Expand Down
Loading

0 comments on commit 9758bab

Please sign in to comment.