Skip to content

Commit

Permalink
Improved documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
david-zwicker committed Oct 5, 2023
1 parent 7a7f285 commit 8bfbd6f
Show file tree
Hide file tree
Showing 21 changed files with 266 additions and 351 deletions.
91 changes: 44 additions & 47 deletions pde/fields/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,18 @@ def _write_to_image(self, filename: str, **kwargs):
def copy(
self: TField, *, label: Optional[str] = None, dtype: Optional[DTypeLike] = None
) -> TField:
...
"""return a new field with the data (but not the grid) copied
Args:
label (str, optional):
Name of the returned field
dtype (numpy dtype):
The data type of the field. If omitted, it will be determined from
`data` automatically or the dtype of the current field is used.
Returns:
:class:`DataFieldBase`: A copy of the current field
"""

def assert_field_compatible(
self, other: FieldBase, accept_scalar: bool = False
Expand Down Expand Up @@ -694,19 +705,44 @@ def apply(
def get_line_data(
self, scalar: str = "auto", extract: str = "auto"
) -> Dict[str, Any]:
...
"""return data for a line plot of the field
Args:
scalar (str or int):
The method for extracting scalars as described in
:meth:`DataFieldBase.to_scalar`.
extract (str):
The method used for extracting the line data. See the docstring
of the grid method `get_line_data` to find supported values.
Returns:
dict: Information useful for performing a line plot of the field
"""

@abstractmethod
def get_image_data(self) -> Dict[str, Any]:
...
r"""return data for plotting an image of the field
Args:
scalar (str or int):
The method for extracting scalars as described in
:meth:`DataFieldBase.to_scalar`.
transpose (bool):
Determines whether the transpose of the data should is plotted
\**kwargs:
Additional parameters are forwarded to `grid.get_image_data`
Returns:
dict: Information useful for plotting an image of the field
"""

@abstractmethod
def plot(self, *args, **kwargs):
...
"""visualize the field"""

@abstractmethod
def _get_napari_data(self, **kwargs) -> Dict[str, Dict[str, Any]]:
...
"""returns data for plotting this field using :mod:`napari`"""

def plot_interactive(
self, viewer_args: Optional[Dict[str, Any]] = None, **kwargs
Expand Down Expand Up @@ -1164,18 +1200,6 @@ def copy(
label: Optional[str] = None,
dtype: Optional[DTypeLike] = None,
) -> TDataField:
"""return a new field with the data (but not the grid) copied
Args:
label (str, optional):
Name of the returned field
dtype (numpy dtype):
The data type of the field. If omitted, it will be determined from
`data` automatically or the dtype of the current field is used.
Returns:
:class:`DataFieldBase`: A copy of the current field
"""
if label is None:
label = self.label
if dtype is None:
Expand Down Expand Up @@ -1535,13 +1559,13 @@ def set_ghost_cells(self, bc: BoundariesData, *, args=None) -> None:
@property
@abstractmethod
def integral(self) -> NumberOrArray:
...
"""integral of the scalar field over space"""

@abstractmethod
def to_scalar(
self, scalar: str = "auto", *, label: Optional[str] = None
) -> "ScalarField":
...
"""return scalar variant of the field"""

@property
def average(self) -> NumberOrArray:
Expand Down Expand Up @@ -1902,19 +1926,6 @@ def smooth(
def get_line_data(
self, scalar: str = "auto", extract: str = "auto"
) -> Dict[str, Any]:
"""return data for a line plot of the field
Args:
scalar (str or int):
The method for extracting scalars as described in
:meth:`DataFieldBase.to_scalar`.
extract (str):
The method used for extracting the line data. See the docstring
of the grid method `get_line_data` to find supported values.
Returns:
dict: Information useful for performing a line plot of the field
"""
# turn field into scalar field
scalar_data = self.to_scalar(scalar).data

Expand All @@ -1930,20 +1941,6 @@ def get_line_data(
def get_image_data(
self, scalar: str = "auto", transpose: bool = False, **kwargs
) -> Dict[str, Any]:
r"""return data for plotting an image of the field
Args:
scalar (str or int):
The method for extracting scalars as described in
:meth:`DataFieldBase.to_scalar`.
transpose (bool):
Determines whether the transpose of the data should is plotted
\**kwargs:
Additional parameters are forwarded to `grid.get_image_data`
Returns:
dict: Information useful for plotting an image of the field
"""
# turn field into scalar field
scalar_data = self.to_scalar(scalar).data

Expand Down Expand Up @@ -2356,7 +2353,7 @@ def _get_napari_layer_data(
return result

def _get_napari_data(self, **kwargs) -> Dict[str, Dict[str, Any]]:
r"""returns data for plotting this field
r"""returns data for plotting this field using :mod:`napari`
Args:
\**kwargs: all arguments are forwarded to `_get_napari_layer_data`
Expand Down
12 changes: 6 additions & 6 deletions pde/fields/tensorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,24 +276,24 @@ def symmetrize(
def to_scalar(
self, scalar: str = "auto", *, label: Optional[str] = "scalar `{scalar}`"
) -> ScalarField:
r""" return a scalar field by applying `method`
r"""return scalar variant of the field
The invariants of the tensor field :math:`\boldsymbol{A}` are
.. math::
I_1 &= \mathrm{tr}(\boldsymbol{A}) \\
I_2 &= \frac12 \left[
(\mathrm{tr}(\boldsymbol{A})^2 -
\mathrm{tr}(\boldsymbol{A}^2)
\right] \\
I_3 &= \det(A)
where `tr` denotes the trace and `det` denotes the determinant. Note that the
three invariants can only be distinct and non-zero in three dimensions. In two
dimensional spaces, we have the identity :math:`2 I_2 = I_3` and in
one-dimensional spaces, we have :math:`I_1 = I_3` as well as
:math:`I_2 = 0`.
Args:
scalar (str):
The method to calculate the scalar. Possible choices include `norm` (the
Expand All @@ -302,7 +302,7 @@ def to_scalar(
`determinant` (or `invariant3`)
label (str, optional):
Name of the returned field
Returns:
:class:`~pde.fields.scalar.ScalarField`: the scalar field after
applying the operation
Expand Down
2 changes: 1 addition & 1 deletion pde/fields/vectorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ def to_scalar(
*,
label: Optional[str] = "scalar `{scalar}`",
) -> ScalarField:
"""return a scalar field by applying `method`
"""return scalar variant of the field
Args:
scalar (str):
Expand Down
104 changes: 88 additions & 16 deletions pde/grids/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,20 +118,14 @@ def discretize_interval(
class DomainError(ValueError):
"""exception indicating that point lies outside domain"""

pass


class DimensionError(ValueError):
"""exception indicating that dimensions were inconsistent"""

pass


class PeriodicityError(RuntimeError):
"""exception indicating that the grid periodicity is inconsistent"""

pass


class GridBase(metaclass=ABCMeta):
"""Base class for all grids defining common methods and interfaces"""
Expand Down Expand Up @@ -354,7 +348,7 @@ def set_valid(arr: np.ndarray, value: np.ndarray) -> None:
@property
@abstractmethod
def state(self) -> Dict[str, Any]:
...
"""dict: all information required for reconstructing the grid"""

@property
def state_serialized(self) -> str:
Expand Down Expand Up @@ -554,17 +548,35 @@ def _boundary_coordinates(self, axis: int, upper: bool) -> np.ndarray:
@property
@abstractmethod
def volume(self) -> float:
...
"""float: total volume of the grid"""

@abstractmethod
def point_to_cartesian(
self, points: np.ndarray, *, full: bool = False
) -> np.ndarray:
...
"""convert coordinates of a point in grid coordinates to Cartesian coordinates
Args:
points (:class:`~numpy.ndarray`):
The grid coordinates of the points
full (bool):
Flag indicating whether angular coordinates are specified
Returns:
:class:`~numpy.ndarray`: The Cartesian coordinates of the point
"""

@abstractmethod
def point_from_cartesian(self, points: np.ndarray) -> np.ndarray:
...
"""convert points given in Cartesian coordinates to grid coordinates
Args:
points (:class:`~numpy.ndarray`):
Points given in Cartesian coordinates.
Returns:
:class:`~numpy.ndarray`: Points given in the coordinates of the grid
"""

def normalize_point(
self, point: np.ndarray, *, reflect: bool = False
Expand Down Expand Up @@ -758,7 +770,16 @@ def transform(
def polar_coordinates_real(
self, origin: np.ndarray, *, ret_angle: bool = False
) -> Union[np.ndarray, Tuple[np.ndarray, ...]]:
...
"""return spherical coordinates associated with the grid
Args:
origin (:class:`~numpy.ndarray`):
Coordinates of origin at which the polar coordinate system is anchored
ret_angle (bool):
Determines whether azimuthal angles are returned alongside distances. If
`False` only the distance to the origin is returned for each support
point of the grid. If `True`, the distance and angles are returned.
"""

def contains_point(
self,
Expand All @@ -785,7 +806,19 @@ def contains_point(
def iter_mirror_points(
self, point: np.ndarray, with_self: bool = False, only_periodic: bool = True
) -> Generator:
...
"""generates all mirror points corresponding to `point`
Args:
point (:class:`~numpy.ndarray`):
The point within the grid
with_self (bool):
Whether to include the point itself
only_periodic (bool):
Whether to only mirror along periodic axes
Returns:
A generator yielding the coordinates that correspond to mirrors
"""

@fill_in_docstring
def get_boundary_conditions(
Expand Down Expand Up @@ -827,17 +860,56 @@ def get_boundary_conditions(

@abstractmethod
def get_line_data(self, data: np.ndarray, extract: str = "auto") -> Dict[str, Any]:
...
"""return a line cut through the grid
Args:
data (:class:`~numpy.ndarray`):
The values at the grid points
extract (str):
Determines which cut is done through the grid. Possible choices depend
on the actual grid.
Returns:
dict: A dictionary with information about the line cut, which is convenient
for plotting.
"""

@abstractmethod
def get_image_data(self, data: np.ndarray) -> Dict[str, Any]:
...
"""return a 2d-image of the data
Args:
data (:class:`~numpy.ndarray`):
The values at the grid points
Returns:
dict: A dictionary with information about the image, which is convenient
for plotting.
"""

@abstractmethod
def get_random_point(
self, *, boundary_distance: float = 0, coords: CoordsType = "cartesian"
self,
*,
boundary_distance: float = 0,
coords: CoordsType = "cartesian",
rng: Optional[np.random.Generator] = None,
) -> np.ndarray:
...
"""return a random point within the grid
Args:
boundary_distance (float):
The minimal distance this point needs to have from all boundaries.
coords (str):
Determines the coordinate system in which the point is specified. Valid
values are `cartesian`, `cell`, and `grid`;
see :meth:`~pde.grids.base.GridBase.transform`.
rng (:class:`~numpy.random.Generator`):
Random number generator (default: :func:`~numpy.random.default_rng()`)
Returns:
:class:`~numpy.ndarray`: The coordinates of the random point
"""

@classmethod
def register_operator(
Expand Down
Loading

0 comments on commit 8bfbd6f

Please sign in to comment.