4.3.6 pde.grids.spherical module

Spherically-symmetric grids in 2 and 3 dimensions. These are grids that only discretize the radial direction, assuming symmetry with respect to all angles. This choice implies that differential operators might not be applicable to all fields. For instance, the divergence of a vector field on a spherical grid can only be represented as a scalar field on the same grid if the θ-component of the vector field vanishes.

PolarSymGrid

2-dimensional polar grid assuming angular symmetry.

SphericalSymGrid

3-dimensional spherical grid assuming spherical symmetry.

volume_from_radius

Return the volume of a sphere with a given radius.

class PolarSymGrid(radius: float | tuple[float, float], shape: int | tuple[int])[source]

Bases: SphericalSymGridBase

2-dimensional polar grid assuming angular symmetry.

The angular symmetry implies that states only depend on the radial coordinate \(r\), which is discretized uniformly as

\[r_i = R_\mathrm{inner} + \left(i + \frac12\right) \Delta r \quad \text{for} \quad i = 0, \ldots, N - 1 \quad \text{with} \quad \Delta r = \frac{R_\mathrm{outer} - R_\mathrm{inner}}{N}\]

where \(R_\mathrm{outer}\) is the outer radius of the grid and \(R_\mathrm{inner}\) corresponds to a possible inner radius, which is zero by default. The radial direction is discretized by \(N\) support points.

Parameters:
  • radius (float or tuple of floats) – Radius \(R_\mathrm{outer}\) in case a simple float is given. If a tuple is supplied it is interpreted as the inner and outer radius, \((R_\mathrm{inner}, R_\mathrm{outer})\).

  • shape (tuple or int) – The number \(N\) of support points along the radial coordinate.

assert_grid_compatible(other: GridBase) → None

Checks whether other is compatible with the current grid.

Parameters:

other (GridBase) – The grid compared to this one

Raises:

ValueError – if grids are not compatible

property axes_bounds: tuple[tuple[float, float], ...]

lower and upper bounds of each axis

Type:

tuple

property axes_coords: tuple[FloatingArray, ...]

coordinates of the cells for each axis

Type:

tuple

c = PolarCoordinates()

Coordinates of the grid.

Type:

CoordinatesBase

compatible_with(other: GridBase) → bool

Tests whether this grid is compatible with other grids.

Grids are compatible when they cover the same area with the same discretization. The difference to equality is that compatible grids do not need to have the same periodicity in their boundaries.

Parameters:

other (GridBase) – The other grid to test against

Returns:

Whether the grid is compatible

Return type:

bool

contains_point(points: FloatingArray, *, coords: Literal['cartesian', 'cell', 'grid'] = 'cartesian') → NDArray[np.bool]

Check whether the point is contained in the grid.

Parameters:
  • points (ndarray) – Coordinates of the point(s)

  • coords (str) – The coordinate system in which the points are given

Returns:

A boolean array indicating which points lie within the grid

Return type:

ndarray

copy() → GridBase

Return a copy of the grid.

difference_vector(p1: FloatingArray, p2: FloatingArray, *, coords: CoordsType = 'grid') → FloatingArray

Return Cartesian vector(s) pointing from p1 to p2.

In case of periodic boundary conditions, the shortest vector is returned.

Parameters:
  • p1 (ndarray) – First point(s)

  • p2 (ndarray) – Second point(s)

  • coords (str) – Coordinate system in which points are specified. Valid values are cartesian, cell, and grid; see transform().

Returns:

The difference vectors between the points with periodic boundary conditions applied.

Return type:

ndarray

property dim: int

The spatial dimension in which the grid is embedded

Type:

int

property discretization: FloatingArray

the linear size of a cell along each axis.

Type:

numpy.array

distance(p1: FloatingArray, p2: FloatingArray, *, coords: CoordsType = 'grid') → float

Calculate the distance between two points given in real coordinates.

This takes periodic boundary conditions into account if necessary.

Parameters:
  • p1 (ndarray) – First position

  • p2 (ndarray) – Second position

  • coords (str) – Coordinate system in which points are specified. Valid values are cartesian, cell, and grid; see transform().

Returns:

Distance between the two positions

Return type:

float

classmethod from_bounds(bounds: tuple[tuple[float, float]], shape: tuple[int], periodic: tuple[bool]) → SphericalSymGridBase
Parameters:
  • bounds (tuple) – Give the coordinate range for the radial axis.

  • shape (tuple) – The number of support points for the radial axis

  • periodic (tuple) – Flag indicating whether the grid is periodic (not used here)

Returns:

represents the region chosen by bounds

Return type:

SphericalGridBase

classmethod from_state(state: dict[str, Any]) → SphericalSymGridBase

Create a field from a stored state.

Parameters:

state (dict) – The state from which the grid is reconstructed.

get_axis_index(axis_id: int | str, *, allow_symmetric: bool = False) → int

Return the index belonging to an axis.

Parameters:
  • axis_id (int or str) – The index or name of an axis

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included. This particular affects negative axis_id

Returns:

The non-negative index of the axis.

Raises:
  • ValueError – If axis_id is a name that is not present on this grid.

  • IndexError – If axis_id is an out-of-range integer index.

get_axis_tuple(axes: int | str | Sequence[int | str], *, allow_symmetric: bool = False) → tuple[int, ...]

Convert axis indices or names to normalized axis indices.

Parameters:
  • axes – A single axis index or name, or a sequence of them.

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included. This particular affects negative axis_id

Returns:

The non-negative indices of the axes, in the order given.

Raises:
  • ValueError – If an axis name is not present on this grid.

  • IndexError – If an integer axis index is out of range.

get_boundary_conditions(bc: BoundariesData = 'auto_periodic_neumann', rank: int = 0) → BoundariesBase

Constructs boundary conditions from a flexible data format.

Parameters:
  • bc (str or list or tuple or dict) – The boundary conditions applied to the field. Boundary conditions are generally given as a dictionary with one condition for each axis side. For periodic axes, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using specific identifiers, like x- and y+). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘auto_periodic_neumann’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • rank (int) – The tensorial rank of the value associated with the boundary conditions.

Returns:

The boundary conditions for all axes.

Return type:

BoundariesBase

Raises:
  • ValueError – If the data given in bc cannot be read

  • PeriodicityError – If the boundaries are not compatible with the periodic axes of the grid.

get_cartesian_grid(mode: Literal['valid', 'inscribed', 'full', 'circumscribed'] = 'valid', num: int | None = None) → CartesianGrid

Return a Cartesian grid for this spherical one.

Parameters:
  • mode (str) – Determines how the grid is determined. Setting it to ‘valid’ (or ‘inscribed’) only returns points that are fully resolved in the spherical grid, e.g., the Cartesian grid is inscribed in the sphere. Conversely, ‘full’ (or ‘circumscribed’) returns all data, so the Cartesian grid is circumscribed.

  • num (int) – Number of support points along each axis of the returned grid.

Returns:

The requested grid

Return type:

pde.grids.cartesian.CartesianGrid

get_image_data(data: ndarray[Any, dtype[number]], *, performance_goal: Literal['speed', 'quality'] = 'speed', fill_value: float = 0, masked: bool = True) → dict[str, Any]

Return a 2d-image of the data.

Parameters:
  • data (ndarray) – The values at the grid points

  • performance_goal (str) – Determines the method chosen for interpolation. Possible options are speed and quality.

  • fill_value (float) – The value assigned to invalid positions (those inside the hole or outside the region).

  • masked (bool) – Whether a numpy.ma.MaskedArray is returned for the data instead of the normal ndarray.

Returns:

dict: A dictionary with information about the image, which is convenient for plotting.

get_line_data(data: ndarray[Any, dtype[number]], extract: str = 'auto') → dict[str, Any]

Return a line cut along the radial axis.

Parameters:
  • data (ndarray) – The values at the grid points

  • extract (str) – Determines which cut is done through the grid. This parameter is mainly supplied for a consistent interface and has no effect for polar grids.

Returns:

A dictionary with information about the line cut, which is convenient for plotting.

get_random_point(*, boundary_distance: float = 0, avoid_center: bool = False, coords: Literal['cartesian', 'grid', 'cell'] = 'cartesian', rng: Generator | None = None) → ndarray[Any, dtype[floating]]

Return a random point within the grid.

Note that these points will be uniformly distributed in the volume, implying they are not uniformly distributed on the radial axis.

Parameters:
  • boundary_distance (float) – The minimal distance this point needs to have from all boundaries.

  • avoid_center (bool) – Determines whether the boundary distance should also be kept from the center, i.e., whether points close to the center are returned.

  • coords (str) – Determines the coordinate system in which the point is specified. Valid values are cartesian, cell, and grid; see transform().

  • rng (Generator) – Random number generator (default: default_rng())

Returns:

The coordinates of the point

Return type:

ndarray

get_vector_data(data: NumericArray, **kwargs) → dict[str, Any]

Return data to visualize vector field.

Parameters:
Returns:

A dictionary with information about the data convenient for plotting.

Return type:

dict

property has_hole: bool

Returns whether the inner radius is larger than zero.

integrate(data: NumberOrArray, axes: int | str | Sequence[int | str] | None = None) → NumberOrArray

Integrates the discretized data over the grid.

Parameters:
  • data (ndarray) – The values at the support points of the grid that need to be integrated.

  • axes (list of int or str, optional) – The axes along which the integral is performed. If omitted, all axes are integrated over.

Returns:

The values integrated over the entire grid

Return type:

ndarray

iter_mirror_points(point: FloatingArray, with_self: bool = False, only_periodic: bool = True) → Iterator[FloatingArray]

Generates all mirror points corresponding to point

Parameters:
  • point (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

make_cell_volume_compiled(flat_index: bool = False) → CellVolume

Return a compiled function returning the volume of a grid cell.

Parameters:

flat_index (bool) – When True, cell_volumes are indexed by a single integer into the flattened array.

Returns:

returning the volume of the chosen cell

Return type:

function

make_inserter_compiled(*, with_ghost_cells: bool = False) → Callable[[NumericArray, FloatingArray, NumberOrArray], None]

Return a compiled function to insert values at interpolated positions.

Parameters:

with_ghost_cells (bool) – Flag indicating that the interpolator should work on the full data array that includes values for the grid points. If this is the case, the boundaries are not checked and the coordinates are used as is.

Returns:

A function with signature (data, position, amount), where data is the numpy array containing the field data, position is denotes the position in grid coordinates, and amount is the that is to be added to the field.

Return type:

callable

make_integrator(backend: str | pde.backends.base.BackendBase = 'numpy') → Callable[[NumericArray], NumberOrArray]

Return function that can be used to integrates discretized data over the grid.

If this function is used in a multiprocessing run (using MPI), the integrals are performed on all subgrids and then accumulated. Each process then receives the same value representing the global integral.

Parameters:

backend (str) – The backend to use for making the operator

Returns:

A function that takes a numpy array and returns the integral with the correct weights given by the cell volumes.

Return type:

callable

make_normalize_point_compiled(reflect: bool = True) → Callable[[FloatingArray], None]

Return a compiled function that normalizes a point.

Here, the point is assumed to be specified by the physical values along the non-symmetric axes of the grid. Normalizing points is useful to make sure they lie within the domain of the grid. This function respects periodic boundary conditions and can also reflect points off the boundary.

Parameters:

reflect (bool) – Flag determining whether coordinates along non-periodic axes are reflected to lie in the valid range. If False, such coordinates are left unchanged and only periodic boundary conditions are enforced.

Returns:

A function that takes a ndarray as an argument, which describes the coordinates of the points. This array is modified in-place!

Return type:

callable

make_operator(operator: str | OperatorInfo, bc: BoundariesData, *, backend: str | pde.backends.base.BackendBase[TNativeArray] = 'default', dtype: DTypeLike | None = None, **kwargs) → OperatorType

Return a compiled function applying an operator with boundary conditions.

Parameters:
  • operator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the operators attribute.

  • bc (str or list or tuple or dict) – The boundary conditions applied to the field. Boundary conditions are generally given as a dictionary with one condition for each axis side. For periodic axes, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using specific identifiers, like x- and y+). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘auto_periodic_neumann’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • backend (str) – The backend to use for making the operator

  • dtype (numpy dtype) – The data type of the field.

  • **kwargs – Specifies extra arguments influencing how the operator is created.

The returned function takes the discretized data on the grid as an input and returns the data to which the operator operator has been applied. The function only takes the valid grid points and allocates memory for the ghost points internally to apply the boundary conditions specified as bc. Note that the function supports an optional argument out, which if given should provide space for the valid output array without the ghost cells. The result of the operator is then written into this output array.

The function also accepts an optional parameter args, which is forwarded to set_ghost_cells. This allows setting boundary conditions based on external parameters, like time. Note that the numba backend requires a special calling convention to make it compatible with Numba. The following example shows how to pass the current time t:

from pde.backends.numba.utils import numba_dict

operator = grid.make_operator(
    "laplace", bc={"value_expression": "t"}, backend="numba"
)
operator(field.data, args=numba_dict(t=t))
Returns:

the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).

Return type:

callable

make_operator_no_bc(operator: str | OperatorInfo, *, backend: str | pde.backends.base.BackendBase = 'default', dtype: DTypeLike | None = None, **kwargs) → OperatorType

Return a compiled function applying an operator without boundary conditions.

The returned function takes the discretized full data as an input and returns an array of valid data points.

Note

The resulting function does not check whether the ghost cells of the input array have been supplied with sensible values. It is the responsibility of the user to set the values of the ghost cells beforehand. Use this function only if you absolutely know what you’re doing. In all other cases, make_operator() is probably the better choice.

Parameters:
  • operator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the operators attribute.

  • backend (str) – The backend to use for making the operator

  • dtype (numpy dtype) – The data type of the field.

  • **kwargs – Specifies extra arguments influencing how the operator is created.

Returns:

the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).

Return type:

callable

normalize_point(point: FloatingArray, *, reflect: bool = False) → FloatingArray

Normalize grid coordinates by applying periodic boundary conditions.

Here, points are assumed to be specified by the physical values along the non-symmetric axes of the grid, e.g., by grid coordinates. Normalizing points is useful to make sure they lie within the domain of the grid. This function respects periodic boundary conditions and can also reflect points off the boundary if reflect = True.

Parameters:
  • point (ndarray) – Coordinates of a single point or an array of points, where the last axis denotes the point coordinates (e.g., a list of points).

  • reflect (bool) – Flag determining whether coordinates along non-periodic axes are reflected to lie in the valid range. If False, such coordinates are left unchanged and only periodic boundary conditions are enforced.

Returns:

The respective coordinates with periodic boundary conditions applied.

Return type:

ndarray

property num_cells: int

the number of cells in this grid

Type:

int

property numba_type: str

represents type of the grid data in numba signatures

Type:

str

property periodic: list[bool]

Flags that describe which axes are periodic

Type:

list

plot(*args, title: str | None = None, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', ax_style: dict[str, Any] | None = None, fig_style: dict[str, Any] | None = None, ax=None, **kwargs)

Visualize the spherically symmetric grid in two dimensions.

Parameters:
  • title (str) – Title of the plot. If omitted, the title might be chosen automatically.

  • filename (str, optional) – If given, the plot is written to the specified file.

  • action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is auto or none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given.

  • ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item i this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

  • fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

  • ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

  • **kwargs – Extra arguments are passed on the to the matplotlib plotting routines, e.g., to set the color of the lines

point_from_cartesian(points: FloatingArray) → FloatingArray

Convert points given in Cartesian coordinates to grid coordinates.

Parameters:

points (ndarray) – Points given in Cartesian coordinates.

Returns:

Points given in the coordinates of the grid

Return type:

ndarray

point_to_cartesian(points: FloatingArray) → FloatingArray

Convert coordinates of a point in grid coordinates to Cartesian coordinates.

Parameters:

points (ndarray) – The grid coordinates of the points

Returns:

The Cartesian coordinates of the point

Return type:

ndarray

property radius: float | tuple[float, float]

radius of the sphere

Type:

float

property shape: tuple[int, ...]

the number of support points of each axis

Type:

tuple of int

slice(indices: Sequence[int]) → GridBase

Return a subgrid of only the specified axes.

Parameters:

indices (list) – Indices indicating the axes that are retained in the subgrid

Returns:

The subgrid

Return type:

GridBase

property state: dict[str, Any]

the state of the grid

Type:

state

property state_serialized: str

JSON-serialized version of the state of this grid

Type:

str

transform(coordinates: FloatingArray, source: CoordsType, target: CoordsType) → FloatingArray

Converts coordinates from one coordinate system to another.

Supported coordinate systems include the following:

  • cartesian:

    Cartesian coordinates where each point carries dim values. These are the true physical coordinates in space.

  • grid:

    Coordinates values in the coordinate system defined by the grid. A point is thus characterized by grid.num_axes values.

  • cell:

    Normalized grid coordinates based on indexing the discretization cells. A point is characterized by grid.num_axes values and the range of values for a given axis is between 0 and N, where N is the number of grid points. Consequently, the integral part of the cell coordinate denotes the cell, while the fractional part denotes the relative position within the cell. In particular, the cell center is located at i + 0.5 with i = 0, …, N-1.

Note

Some conversion might involve projections if the coordinate system imposes symmetries. For instance, converting 3d Cartesian coordinates to grid coordinates in a spherically symmetric grid will only return the radius from the origin. Conversely, converting these grid coordinates back to 3d Cartesian coordinates will only return coordinates along a particular ray originating at the origin.

Parameters:
  • coordinates (ndarray) – The coordinates to convert

  • source (str) – The source coordinate system

  • target (str) – The target coordinate system

Returns:

The transformed coordinates

Return type:

ndarray

property typical_discretization: float

the average side length of the cells

Type:

float

property volume: float

total volume of the grid

Type:

float

class SphericalSymGrid(radius: float | tuple[float, float], shape: int | tuple[int])[source]

Bases: SphericalSymGridBase

3-dimensional spherical grid assuming spherical symmetry.

The symmetry implies that states only depend on the radial coordinate \(r\), which is discretized as follows:

\[r_i = R_\mathrm{inner} + \left(i + \frac12\right) \Delta r \quad \text{for} \quad i = 0, \ldots, N - 1 \quad \text{with} \quad \Delta r = \frac{R_\mathrm{outer} - R_\mathrm{inner}}{N}\]

where \(R_\mathrm{outer}\) is the outer radius of the grid and \(R_\mathrm{inner}\) corresponds to a possible inner radius, which is zero by default. The radial direction is discretized by \(N\) support points.

Warning

Not all results of differential operators on vectorial and tensorial fields can be expressed in terms of fields that only depend on the radial coordinate \(r\). In particular, the gradient of a vector field can only be calculated if the azimuthal component of the vector field vanishes. Similarly, the divergence of a tensor field can only be taken in special situations.

Parameters:
  • radius (float or tuple of floats) – Radius \(R_\mathrm{outer}\) in case a simple float is given. If a tuple is supplied it is interpreted as the inner and outer radius, \((R_\mathrm{inner}, R_\mathrm{outer})\).

  • shape (tuple or int) – The number \(N\) of support points along the radial coordinate.

assert_grid_compatible(other: GridBase) → None

Checks whether other is compatible with the current grid.

Parameters:

other (GridBase) – The grid compared to this one

Raises:

ValueError – if grids are not compatible

property axes_bounds: tuple[tuple[float, float], ...]

lower and upper bounds of each axis

Type:

tuple

property axes_coords: tuple[FloatingArray, ...]

coordinates of the cells for each axis

Type:

tuple

c = SphericalCoordinates()

Coordinates of the grid.

Type:

CoordinatesBase

compatible_with(other: GridBase) → bool

Tests whether this grid is compatible with other grids.

Grids are compatible when they cover the same area with the same discretization. The difference to equality is that compatible grids do not need to have the same periodicity in their boundaries.

Parameters:

other (GridBase) – The other grid to test against

Returns:

Whether the grid is compatible

Return type:

bool

contains_point(points: FloatingArray, *, coords: Literal['cartesian', 'cell', 'grid'] = 'cartesian') → NDArray[np.bool]

Check whether the point is contained in the grid.

Parameters:
  • points (ndarray) – Coordinates of the point(s)

  • coords (str) – The coordinate system in which the points are given

Returns:

A boolean array indicating which points lie within the grid

Return type:

ndarray

copy() → GridBase

Return a copy of the grid.

difference_vector(p1: FloatingArray, p2: FloatingArray, *, coords: CoordsType = 'grid') → FloatingArray

Return Cartesian vector(s) pointing from p1 to p2.

In case of periodic boundary conditions, the shortest vector is returned.

Parameters:
  • p1 (ndarray) – First point(s)

  • p2 (ndarray) – Second point(s)

  • coords (str) – Coordinate system in which points are specified. Valid values are cartesian, cell, and grid; see transform().

Returns:

The difference vectors between the points with periodic boundary conditions applied.

Return type:

ndarray

property dim: int

The spatial dimension in which the grid is embedded

Type:

int

property discretization: FloatingArray

the linear size of a cell along each axis.

Type:

numpy.array

distance(p1: FloatingArray, p2: FloatingArray, *, coords: CoordsType = 'grid') → float

Calculate the distance between two points given in real coordinates.

This takes periodic boundary conditions into account if necessary.

Parameters:
  • p1 (ndarray) – First position

  • p2 (ndarray) – Second position

  • coords (str) – Coordinate system in which points are specified. Valid values are cartesian, cell, and grid; see transform().

Returns:

Distance between the two positions

Return type:

float

classmethod from_bounds(bounds: tuple[tuple[float, float]], shape: tuple[int], periodic: tuple[bool]) → SphericalSymGridBase
Parameters:
  • bounds (tuple) – Give the coordinate range for the radial axis.

  • shape (tuple) – The number of support points for the radial axis

  • periodic (tuple) – Flag indicating whether the grid is periodic (not used here)

Returns:

represents the region chosen by bounds

Return type:

SphericalGridBase

classmethod from_state(state: dict[str, Any]) → SphericalSymGridBase

Create a field from a stored state.

Parameters:

state (dict) – The state from which the grid is reconstructed.

get_axis_index(axis_id: int | str, *, allow_symmetric: bool = False) → int

Return the index belonging to an axis.

Parameters:
  • axis_id (int or str) – The index or name of an axis

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included. This particular affects negative axis_id

Returns:

The non-negative index of the axis.

Raises:
  • ValueError – If axis_id is a name that is not present on this grid.

  • IndexError – If axis_id is an out-of-range integer index.

get_axis_tuple(axes: int | str | Sequence[int | str], *, allow_symmetric: bool = False) → tuple[int, ...]

Convert axis indices or names to normalized axis indices.

Parameters:
  • axes – A single axis index or name, or a sequence of them.

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included. This particular affects negative axis_id

Returns:

The non-negative indices of the axes, in the order given.

Raises:
  • ValueError – If an axis name is not present on this grid.

  • IndexError – If an integer axis index is out of range.

get_boundary_conditions(bc: BoundariesData = 'auto_periodic_neumann', rank: int = 0) → BoundariesBase

Constructs boundary conditions from a flexible data format.

Parameters:
  • bc (str or list or tuple or dict) – The boundary conditions applied to the field. Boundary conditions are generally given as a dictionary with one condition for each axis side. For periodic axes, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using specific identifiers, like x- and y+). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘auto_periodic_neumann’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • rank (int) – The tensorial rank of the value associated with the boundary conditions.

Returns:

The boundary conditions for all axes.

Return type:

BoundariesBase

Raises:
  • ValueError – If the data given in bc cannot be read

  • PeriodicityError – If the boundaries are not compatible with the periodic axes of the grid.

get_cartesian_grid(mode: Literal['valid', 'inscribed', 'full', 'circumscribed'] = 'valid', num: int | None = None) → CartesianGrid

Return a Cartesian grid for this spherical one.

Parameters:
  • mode (str) – Determines how the grid is determined. Setting it to ‘valid’ (or ‘inscribed’) only returns points that are fully resolved in the spherical grid, e.g., the Cartesian grid is inscribed in the sphere. Conversely, ‘full’ (or ‘circumscribed’) returns all data, so the Cartesian grid is circumscribed.

  • num (int) – Number of support points along each axis of the returned grid.

Returns:

The requested grid

Return type:

pde.grids.cartesian.CartesianGrid

get_image_data(data: ndarray[Any, dtype[number]], *, performance_goal: Literal['speed', 'quality'] = 'speed', fill_value: float = 0, masked: bool = True) → dict[str, Any]

Return a 2d-image of the data.

Parameters:
  • data (ndarray) – The values at the grid points

  • performance_goal (str) – Determines the method chosen for interpolation. Possible options are speed and quality.

  • fill_value (float) – The value assigned to invalid positions (those inside the hole or outside the region).

  • masked (bool) – Whether a numpy.ma.MaskedArray is returned for the data instead of the normal ndarray.

Returns:

dict: A dictionary with information about the image, which is convenient for plotting.

get_line_data(data: ndarray[Any, dtype[number]], extract: str = 'auto') → dict[str, Any]

Return a line cut along the radial axis.

Parameters:
  • data (ndarray) – The values at the grid points

  • extract (str) – Determines which cut is done through the grid. This parameter is mainly supplied for a consistent interface and has no effect for polar grids.

Returns:

A dictionary with information about the line cut, which is convenient for plotting.

get_random_point(*, boundary_distance: float = 0, avoid_center: bool = False, coords: Literal['cartesian', 'grid', 'cell'] = 'cartesian', rng: Generator | None = None) → ndarray[Any, dtype[floating]]

Return a random point within the grid.

Note that these points will be uniformly distributed in the volume, implying they are not uniformly distributed on the radial axis.

Parameters:
  • boundary_distance (float) – The minimal distance this point needs to have from all boundaries.

  • avoid_center (bool) – Determines whether the boundary distance should also be kept from the center, i.e., whether points close to the center are returned.

  • coords (str) – Determines the coordinate system in which the point is specified. Valid values are cartesian, cell, and grid; see transform().

  • rng (Generator) – Random number generator (default: default_rng())

Returns:

The coordinates of the point

Return type:

ndarray

get_vector_data(data: NumericArray, **kwargs) → dict[str, Any]

Return data to visualize vector field.

Parameters:
Returns:

A dictionary with information about the data convenient for plotting.

Return type:

dict

property has_hole: bool

Returns whether the inner radius is larger than zero.

integrate(data: NumberOrArray, axes: int | str | Sequence[int | str] | None = None) → NumberOrArray

Integrates the discretized data over the grid.

Parameters:
  • data (ndarray) – The values at the support points of the grid that need to be integrated.

  • axes (list of int or str, optional) – The axes along which the integral is performed. If omitted, all axes are integrated over.

Returns:

The values integrated over the entire grid

Return type:

ndarray

iter_mirror_points(point: FloatingArray, with_self: bool = False, only_periodic: bool = True) → Iterator[FloatingArray]

Generates all mirror points corresponding to point

Parameters:
  • point (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

make_cell_volume_compiled(flat_index: bool = False) → CellVolume

Return a compiled function returning the volume of a grid cell.

Parameters:

flat_index (bool) – When True, cell_volumes are indexed by a single integer into the flattened array.

Returns:

returning the volume of the chosen cell

Return type:

function

make_inserter_compiled(*, with_ghost_cells: bool = False) → Callable[[NumericArray, FloatingArray, NumberOrArray], None]

Return a compiled function to insert values at interpolated positions.

Parameters:

with_ghost_cells (bool) – Flag indicating that the interpolator should work on the full data array that includes values for the grid points. If this is the case, the boundaries are not checked and the coordinates are used as is.

Returns:

A function with signature (data, position, amount), where data is the numpy array containing the field data, position is denotes the position in grid coordinates, and amount is the that is to be added to the field.

Return type:

callable

make_integrator(backend: str | pde.backends.base.BackendBase = 'numpy') → Callable[[NumericArray], NumberOrArray]

Return function that can be used to integrates discretized data over the grid.

If this function is used in a multiprocessing run (using MPI), the integrals are performed on all subgrids and then accumulated. Each process then receives the same value representing the global integral.

Parameters:

backend (str) – The backend to use for making the operator

Returns:

A function that takes a numpy array and returns the integral with the correct weights given by the cell volumes.

Return type:

callable

make_normalize_point_compiled(reflect: bool = True) → Callable[[FloatingArray], None]

Return a compiled function that normalizes a point.

Here, the point is assumed to be specified by the physical values along the non-symmetric axes of the grid. Normalizing points is useful to make sure they lie within the domain of the grid. This function respects periodic boundary conditions and can also reflect points off the boundary.

Parameters:

reflect (bool) – Flag determining whether coordinates along non-periodic axes are reflected to lie in the valid range. If False, such coordinates are left unchanged and only periodic boundary conditions are enforced.

Returns:

A function that takes a ndarray as an argument, which describes the coordinates of the points. This array is modified in-place!

Return type:

callable

make_operator(operator: str | OperatorInfo, bc: BoundariesData, *, backend: str | pde.backends.base.BackendBase[TNativeArray] = 'default', dtype: DTypeLike | None = None, **kwargs) → OperatorType

Return a compiled function applying an operator with boundary conditions.

Parameters:
  • operator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the operators attribute.

  • bc (str or list or tuple or dict) – The boundary conditions applied to the field. Boundary conditions are generally given as a dictionary with one condition for each axis side. For periodic axes, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using specific identifiers, like x- and y+). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘auto_periodic_neumann’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • backend (str) – The backend to use for making the operator

  • dtype (numpy dtype) – The data type of the field.

  • **kwargs – Specifies extra arguments influencing how the operator is created.

The returned function takes the discretized data on the grid as an input and returns the data to which the operator operator has been applied. The function only takes the valid grid points and allocates memory for the ghost points internally to apply the boundary conditions specified as bc. Note that the function supports an optional argument out, which if given should provide space for the valid output array without the ghost cells. The result of the operator is then written into this output array.

The function also accepts an optional parameter args, which is forwarded to set_ghost_cells. This allows setting boundary conditions based on external parameters, like time. Note that the numba backend requires a special calling convention to make it compatible with Numba. The following example shows how to pass the current time t:

from pde.backends.numba.utils import numba_dict

operator = grid.make_operator(
    "laplace", bc={"value_expression": "t"}, backend="numba"
)
operator(field.data, args=numba_dict(t=t))
Returns:

the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).

Return type:

callable

make_operator_no_bc(operator: str | OperatorInfo, *, backend: str | pde.backends.base.BackendBase = 'default', dtype: DTypeLike | None = None, **kwargs) → OperatorType

Return a compiled function applying an operator without boundary conditions.

The returned function takes the discretized full data as an input and returns an array of valid data points.

Note

The resulting function does not check whether the ghost cells of the input array have been supplied with sensible values. It is the responsibility of the user to set the values of the ghost cells beforehand. Use this function only if you absolutely know what you’re doing. In all other cases, make_operator() is probably the better choice.

Parameters:
  • operator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the operators attribute.

  • backend (str) – The backend to use for making the operator

  • dtype (numpy dtype) – The data type of the field.

  • **kwargs – Specifies extra arguments influencing how the operator is created.

Returns:

the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).

Return type:

callable

normalize_point(point: FloatingArray, *, reflect: bool = False) → FloatingArray

Normalize grid coordinates by applying periodic boundary conditions.

Here, points are assumed to be specified by the physical values along the non-symmetric axes of the grid, e.g., by grid coordinates. Normalizing points is useful to make sure they lie within the domain of the grid. This function respects periodic boundary conditions and can also reflect points off the boundary if reflect = True.

Parameters:
  • point (ndarray) – Coordinates of a single point or an array of points, where the last axis denotes the point coordinates (e.g., a list of points).

  • reflect (bool) – Flag determining whether coordinates along non-periodic axes are reflected to lie in the valid range. If False, such coordinates are left unchanged and only periodic boundary conditions are enforced.

Returns:

The respective coordinates with periodic boundary conditions applied.

Return type:

ndarray

property num_cells: int

the number of cells in this grid

Type:

int

property numba_type: str

represents type of the grid data in numba signatures

Type:

str

property periodic: list[bool]

Flags that describe which axes are periodic

Type:

list

plot(*args, title: str | None = None, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', ax_style: dict[str, Any] | None = None, fig_style: dict[str, Any] | None = None, ax=None, **kwargs)

Visualize the spherically symmetric grid in two dimensions.

Parameters:
  • title (str) – Title of the plot. If omitted, the title might be chosen automatically.

  • filename (str, optional) – If given, the plot is written to the specified file.

  • action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is auto or none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given.

  • ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item i this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

  • fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

  • ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

  • **kwargs – Extra arguments are passed on the to the matplotlib plotting routines, e.g., to set the color of the lines

point_from_cartesian(points: FloatingArray) → FloatingArray

Convert points given in Cartesian coordinates to grid coordinates.

Parameters:

points (ndarray) – Points given in Cartesian coordinates.

Returns:

Points given in the coordinates of the grid

Return type:

ndarray

point_to_cartesian(points: FloatingArray) → FloatingArray

Convert coordinates of a point in grid coordinates to Cartesian coordinates.

Parameters:

points (ndarray) – The grid coordinates of the points

Returns:

The Cartesian coordinates of the point

Return type:

ndarray

property radius: float | tuple[float, float]

radius of the sphere

Type:

float

property shape: tuple[int, ...]

the number of support points of each axis

Type:

tuple of int

slice(indices: Sequence[int]) → GridBase

Return a subgrid of only the specified axes.

Parameters:

indices (list) – Indices indicating the axes that are retained in the subgrid

Returns:

The subgrid

Return type:

GridBase

property state: dict[str, Any]

the state of the grid

Type:

state

property state_serialized: str

JSON-serialized version of the state of this grid

Type:

str

transform(coordinates: FloatingArray, source: CoordsType, target: CoordsType) → FloatingArray

Converts coordinates from one coordinate system to another.

Supported coordinate systems include the following:

  • cartesian:

    Cartesian coordinates where each point carries dim values. These are the true physical coordinates in space.

  • grid:

    Coordinates values in the coordinate system defined by the grid. A point is thus characterized by grid.num_axes values.

  • cell:

    Normalized grid coordinates based on indexing the discretization cells. A point is characterized by grid.num_axes values and the range of values for a given axis is between 0 and N, where N is the number of grid points. Consequently, the integral part of the cell coordinate denotes the cell, while the fractional part denotes the relative position within the cell. In particular, the cell center is located at i + 0.5 with i = 0, …, N-1.

Note

Some conversion might involve projections if the coordinate system imposes symmetries. For instance, converting 3d Cartesian coordinates to grid coordinates in a spherically symmetric grid will only return the radius from the origin. Conversely, converting these grid coordinates back to 3d Cartesian coordinates will only return coordinates along a particular ray originating at the origin.

Parameters:
  • coordinates (ndarray) – The coordinates to convert

  • source (str) – The source coordinate system

  • target (str) – The target coordinate system

Returns:

The transformed coordinates

Return type:

ndarray

property typical_discretization: float

the average side length of the cells

Type:

float

property volume: float

total volume of the grid

Type:

float

class SphericalSymGridBase(radius: float | tuple[float, float], shape: int | tuple[int])[source]

Bases: GridBase

Base class for d-dimensional spherical grids with angular symmetry.

The angular symmetry implies that states only depend on the radial coordinate \(r\), which is discretized uniformly as

\[r_i = R_\mathrm{inner} + \left(i + \frac12\right) \Delta r \quad \text{for} \quad i = 0, \ldots, N - 1 \quad \text{with} \quad \Delta r = \frac{R_\mathrm{outer} - R_\mathrm{inner}}{N}\]

where \(R_\mathrm{outer}\) is the outer radius of the grid and \(R_\mathrm{inner}\) corresponds to a possible inner radius, which is zero by default. The radial direction is discretized by \(N\) support points.

Parameters:
  • radius (float or tuple of floats) – Radius \(R_\mathrm{outer}\) in case a simple float is given. If a tuple is supplied it is interpreted as the inner and outer radius, \((R_\mathrm{inner}, R_\mathrm{outer})\).

  • shape (tuple or int) – The number \(N\) of support points along the radial coordinate.

assert_grid_compatible(other: GridBase) → None

Checks whether other is compatible with the current grid.

Parameters:

other (GridBase) – The grid compared to this one

Raises:

ValueError – if grids are not compatible

property axes_bounds: tuple[tuple[float, float], ...]

lower and upper bounds of each axis

Type:

tuple

property axes_coords: tuple[FloatingArray, ...]

coordinates of the cells for each axis

Type:

tuple

cell_volume_data

Information about the size of discretization cells

Type:

list

compatible_with(other: GridBase) → bool

Tests whether this grid is compatible with other grids.

Grids are compatible when they cover the same area with the same discretization. The difference to equality is that compatible grids do not need to have the same periodicity in their boundaries.

Parameters:

other (GridBase) – The other grid to test against

Returns:

Whether the grid is compatible

Return type:

bool

contains_point(points: FloatingArray, *, coords: Literal['cartesian', 'cell', 'grid'] = 'cartesian') → NDArray[np.bool]

Check whether the point is contained in the grid.

Parameters:
  • points (ndarray) – Coordinates of the point(s)

  • coords (str) – The coordinate system in which the points are given

Returns:

A boolean array indicating which points lie within the grid

Return type:

ndarray

copy() → GridBase

Return a copy of the grid.

difference_vector(p1: FloatingArray, p2: FloatingArray, *, coords: CoordsType = 'grid') → FloatingArray

Return Cartesian vector(s) pointing from p1 to p2.

In case of periodic boundary conditions, the shortest vector is returned.

Parameters:
  • p1 (ndarray) – First point(s)

  • p2 (ndarray) – Second point(s)

  • coords (str) – Coordinate system in which points are specified. Valid values are cartesian, cell, and grid; see transform().

Returns:

The difference vectors between the points with periodic boundary conditions applied.

Return type:

ndarray

property dim: int

The spatial dimension in which the grid is embedded

Type:

int

property discretization: FloatingArray

the linear size of a cell along each axis.

Type:

numpy.array

distance(p1: FloatingArray, p2: FloatingArray, *, coords: CoordsType = 'grid') → float

Calculate the distance between two points given in real coordinates.

This takes periodic boundary conditions into account if necessary.

Parameters:
  • p1 (ndarray) – First position

  • p2 (ndarray) – Second position

  • coords (str) – Coordinate system in which points are specified. Valid values are cartesian, cell, and grid; see transform().

Returns:

Distance between the two positions

Return type:

float

classmethod from_bounds(bounds: tuple[tuple[float, float]], shape: tuple[int], periodic: tuple[bool]) → SphericalSymGridBase[source]
Parameters:
  • bounds (tuple) – Give the coordinate range for the radial axis.

  • shape (tuple) – The number of support points for the radial axis

  • periodic (tuple) – Flag indicating whether the grid is periodic (not used here)

Returns:

represents the region chosen by bounds

Return type:

SphericalGridBase

classmethod from_state(state: dict[str, Any]) → SphericalSymGridBase[source]

Create a field from a stored state.

Parameters:

state (dict) – The state from which the grid is reconstructed.

get_axis_index(axis_id: int | str, *, allow_symmetric: bool = False) → int

Return the index belonging to an axis.

Parameters:
  • axis_id (int or str) – The index or name of an axis

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included. This particular affects negative axis_id

Returns:

The non-negative index of the axis.

Raises:
  • ValueError – If axis_id is a name that is not present on this grid.

  • IndexError – If axis_id is an out-of-range integer index.

get_axis_tuple(axes: int | str | Sequence[int | str], *, allow_symmetric: bool = False) → tuple[int, ...]

Convert axis indices or names to normalized axis indices.

Parameters:
  • axes – A single axis index or name, or a sequence of them.

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included. This particular affects negative axis_id

Returns:

The non-negative indices of the axes, in the order given.

Raises:
  • ValueError – If an axis name is not present on this grid.

  • IndexError – If an integer axis index is out of range.

get_boundary_conditions(bc: BoundariesData = 'auto_periodic_neumann', rank: int = 0) → BoundariesBase

Constructs boundary conditions from a flexible data format.

Parameters:
  • bc (str or list or tuple or dict) – The boundary conditions applied to the field. Boundary conditions are generally given as a dictionary with one condition for each axis side. For periodic axes, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using specific identifiers, like x- and y+). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘auto_periodic_neumann’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • rank (int) – The tensorial rank of the value associated with the boundary conditions.

Returns:

The boundary conditions for all axes.

Return type:

BoundariesBase

Raises:
  • ValueError – If the data given in bc cannot be read

  • PeriodicityError – If the boundaries are not compatible with the periodic axes of the grid.

get_cartesian_grid(mode: Literal['valid', 'inscribed', 'full', 'circumscribed'] = 'valid', num: int | None = None) → CartesianGrid[source]

Return a Cartesian grid for this spherical one.

Parameters:
  • mode (str) – Determines how the grid is determined. Setting it to ‘valid’ (or ‘inscribed’) only returns points that are fully resolved in the spherical grid, e.g., the Cartesian grid is inscribed in the sphere. Conversely, ‘full’ (or ‘circumscribed’) returns all data, so the Cartesian grid is circumscribed.

  • num (int) – Number of support points along each axis of the returned grid.

Returns:

The requested grid

Return type:

pde.grids.cartesian.CartesianGrid

get_image_data(data: ndarray[Any, dtype[number]], *, performance_goal: Literal['speed', 'quality'] = 'speed', fill_value: float = 0, masked: bool = True) → dict[str, Any][source]

Return a 2d-image of the data.

Parameters:
  • data (ndarray) – The values at the grid points

  • performance_goal (str) – Determines the method chosen for interpolation. Possible options are speed and quality.

  • fill_value (float) – The value assigned to invalid positions (those inside the hole or outside the region).

  • masked (bool) – Whether a numpy.ma.MaskedArray is returned for the data instead of the normal ndarray.

Returns:

dict: A dictionary with information about the image, which is convenient for plotting.

get_line_data(data: ndarray[Any, dtype[number]], extract: str = 'auto') → dict[str, Any][source]

Return a line cut along the radial axis.

Parameters:
  • data (ndarray) – The values at the grid points

  • extract (str) – Determines which cut is done through the grid. This parameter is mainly supplied for a consistent interface and has no effect for polar grids.

Returns:

A dictionary with information about the line cut, which is convenient for plotting.

get_random_point(*, boundary_distance: float = 0, avoid_center: bool = False, coords: Literal['cartesian', 'grid', 'cell'] = 'cartesian', rng: Generator | None = None) → ndarray[Any, dtype[floating]][source]

Return a random point within the grid.

Note that these points will be uniformly distributed in the volume, implying they are not uniformly distributed on the radial axis.

Parameters:
  • boundary_distance (float) – The minimal distance this point needs to have from all boundaries.

  • avoid_center (bool) – Determines whether the boundary distance should also be kept from the center, i.e., whether points close to the center are returned.

  • coords (str) – Determines the coordinate system in which the point is specified. Valid values are cartesian, cell, and grid; see transform().

  • rng (Generator) – Random number generator (default: default_rng())

Returns:

The coordinates of the point

Return type:

ndarray

get_vector_data(data: NumericArray, **kwargs) → dict[str, Any]

Return data to visualize vector field.

Parameters:
Returns:

A dictionary with information about the data convenient for plotting.

Return type:

dict

property has_hole: bool

Returns whether the inner radius is larger than zero.

integrate(data: NumberOrArray, axes: int | str | Sequence[int | str] | None = None) → NumberOrArray

Integrates the discretized data over the grid.

Parameters:
  • data (ndarray) – The values at the support points of the grid that need to be integrated.

  • axes (list of int or str, optional) – The axes along which the integral is performed. If omitted, all axes are integrated over.

Returns:

The values integrated over the entire grid

Return type:

ndarray

iter_mirror_points(point: FloatingArray, with_self: bool = False, only_periodic: bool = True) → Iterator[FloatingArray]

Generates all mirror points corresponding to point

Parameters:
  • point (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

make_cell_volume_compiled(flat_index: bool = False) → CellVolume

Return a compiled function returning the volume of a grid cell.

Parameters:

flat_index (bool) – When True, cell_volumes are indexed by a single integer into the flattened array.

Returns:

returning the volume of the chosen cell

Return type:

function

make_inserter_compiled(*, with_ghost_cells: bool = False) → Callable[[NumericArray, FloatingArray, NumberOrArray], None]

Return a compiled function to insert values at interpolated positions.

Parameters:

with_ghost_cells (bool) – Flag indicating that the interpolator should work on the full data array that includes values for the grid points. If this is the case, the boundaries are not checked and the coordinates are used as is.

Returns:

A function with signature (data, position, amount), where data is the numpy array containing the field data, position is denotes the position in grid coordinates, and amount is the that is to be added to the field.

Return type:

callable

make_integrator(backend: str | pde.backends.base.BackendBase = 'numpy') → Callable[[NumericArray], NumberOrArray]

Return function that can be used to integrates discretized data over the grid.

If this function is used in a multiprocessing run (using MPI), the integrals are performed on all subgrids and then accumulated. Each process then receives the same value representing the global integral.

Parameters:

backend (str) – The backend to use for making the operator

Returns:

A function that takes a numpy array and returns the integral with the correct weights given by the cell volumes.

Return type:

callable

make_normalize_point_compiled(reflect: bool = True) → Callable[[FloatingArray], None]

Return a compiled function that normalizes a point.

Here, the point is assumed to be specified by the physical values along the non-symmetric axes of the grid. Normalizing points is useful to make sure they lie within the domain of the grid. This function respects periodic boundary conditions and can also reflect points off the boundary.

Parameters:

reflect (bool) – Flag determining whether coordinates along non-periodic axes are reflected to lie in the valid range. If False, such coordinates are left unchanged and only periodic boundary conditions are enforced.

Returns:

A function that takes a ndarray as an argument, which describes the coordinates of the points. This array is modified in-place!

Return type:

callable

make_operator(operator: str | OperatorInfo, bc: BoundariesData, *, backend: str | pde.backends.base.BackendBase[TNativeArray] = 'default', dtype: DTypeLike | None = None, **kwargs) → OperatorType

Return a compiled function applying an operator with boundary conditions.

Parameters:
  • operator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the operators attribute.

  • bc (str or list or tuple or dict) – The boundary conditions applied to the field. Boundary conditions are generally given as a dictionary with one condition for each axis side. For periodic axes, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using specific identifiers, like x- and y+). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘auto_periodic_neumann’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • backend (str) – The backend to use for making the operator

  • dtype (numpy dtype) – The data type of the field.

  • **kwargs – Specifies extra arguments influencing how the operator is created.

The returned function takes the discretized data on the grid as an input and returns the data to which the operator operator has been applied. The function only takes the valid grid points and allocates memory for the ghost points internally to apply the boundary conditions specified as bc. Note that the function supports an optional argument out, which if given should provide space for the valid output array without the ghost cells. The result of the operator is then written into this output array.

The function also accepts an optional parameter args, which is forwarded to set_ghost_cells. This allows setting boundary conditions based on external parameters, like time. Note that the numba backend requires a special calling convention to make it compatible with Numba. The following example shows how to pass the current time t:

from pde.backends.numba.utils import numba_dict

operator = grid.make_operator(
    "laplace", bc={"value_expression": "t"}, backend="numba"
)
operator(field.data, args=numba_dict(t=t))
Returns:

the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).

Return type:

callable

make_operator_no_bc(operator: str | OperatorInfo, *, backend: str | pde.backends.base.BackendBase = 'default', dtype: DTypeLike | None = None, **kwargs) → OperatorType

Return a compiled function applying an operator without boundary conditions.

The returned function takes the discretized full data as an input and returns an array of valid data points.

Note

The resulting function does not check whether the ghost cells of the input array have been supplied with sensible values. It is the responsibility of the user to set the values of the ghost cells beforehand. Use this function only if you absolutely know what you’re doing. In all other cases, make_operator() is probably the better choice.

Parameters:
  • operator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the operators attribute.

  • backend (str) – The backend to use for making the operator

  • dtype (numpy dtype) – The data type of the field.

  • **kwargs – Specifies extra arguments influencing how the operator is created.

Returns:

the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).

Return type:

callable

normalize_point(point: FloatingArray, *, reflect: bool = False) → FloatingArray

Normalize grid coordinates by applying periodic boundary conditions.

Here, points are assumed to be specified by the physical values along the non-symmetric axes of the grid, e.g., by grid coordinates. Normalizing points is useful to make sure they lie within the domain of the grid. This function respects periodic boundary conditions and can also reflect points off the boundary if reflect = True.

Parameters:
  • point (ndarray) – Coordinates of a single point or an array of points, where the last axis denotes the point coordinates (e.g., a list of points).

  • reflect (bool) – Flag determining whether coordinates along non-periodic axes are reflected to lie in the valid range. If False, such coordinates are left unchanged and only periodic boundary conditions are enforced.

Returns:

The respective coordinates with periodic boundary conditions applied.

Return type:

ndarray

property num_cells: int

the number of cells in this grid

Type:

int

property numba_type: str

represents type of the grid data in numba signatures

Type:

str

property periodic: list[bool]

Flags that describe which axes are periodic

Type:

list

plot(*args, title: str | None = None, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', ax_style: dict[str, Any] | None = None, fig_style: dict[str, Any] | None = None, ax=None, **kwargs)[source]

Visualize the spherically symmetric grid in two dimensions.

Parameters:
  • title (str) – Title of the plot. If omitted, the title might be chosen automatically.

  • filename (str, optional) – If given, the plot is written to the specified file.

  • action (str) – Decides what to do with the final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is auto or none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given.

  • ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item i this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

  • fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

  • ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

  • **kwargs – Extra arguments are passed on the to the matplotlib plotting routines, e.g., to set the color of the lines

point_from_cartesian(points: FloatingArray) → FloatingArray

Convert points given in Cartesian coordinates to grid coordinates.

Parameters:

points (ndarray) – Points given in Cartesian coordinates.

Returns:

Points given in the coordinates of the grid

Return type:

ndarray

point_to_cartesian(points: FloatingArray) → FloatingArray

Convert coordinates of a point in grid coordinates to Cartesian coordinates.

Parameters:

points (ndarray) – The grid coordinates of the points

Returns:

The Cartesian coordinates of the point

Return type:

ndarray

property radius: float | tuple[float, float]

radius of the sphere

Type:

float

property shape: tuple[int, ...]

the number of support points of each axis

Type:

tuple of int

slice(indices: Sequence[int]) → GridBase

Return a subgrid of only the specified axes.

Parameters:

indices (list) – Indices indicating the axes that are retained in the subgrid

Returns:

The subgrid

Return type:

GridBase

property state: dict[str, Any]

the state of the grid

Type:

state

property state_serialized: str

JSON-serialized version of the state of this grid

Type:

str

transform(coordinates: FloatingArray, source: CoordsType, target: CoordsType) → FloatingArray

Converts coordinates from one coordinate system to another.

Supported coordinate systems include the following:

  • cartesian:

    Cartesian coordinates where each point carries dim values. These are the true physical coordinates in space.

  • grid:

    Coordinates values in the coordinate system defined by the grid. A point is thus characterized by grid.num_axes values.

  • cell:

    Normalized grid coordinates based on indexing the discretization cells. A point is characterized by grid.num_axes values and the range of values for a given axis is between 0 and N, where N is the number of grid points. Consequently, the integral part of the cell coordinate denotes the cell, while the fractional part denotes the relative position within the cell. In particular, the cell center is located at i + 0.5 with i = 0, …, N-1.

Note

Some conversion might involve projections if the coordinate system imposes symmetries. For instance, converting 3d Cartesian coordinates to grid coordinates in a spherically symmetric grid will only return the radius from the origin. Conversely, converting these grid coordinates back to 3d Cartesian coordinates will only return coordinates along a particular ray originating at the origin.

Parameters:
  • coordinates (ndarray) – The coordinates to convert

  • source (str) – The source coordinate system

  • target (str) – The target coordinate system

Returns:

The transformed coordinates

Return type:

ndarray

property typical_discretization: float

the average side length of the cells

Type:

float

property volume: float

total volume of the grid

Type:

float

volume_from_radius(radius: T, dim: int) → T[source]

Return the volume of a sphere with a given radius.

Parameters:
  • radius (float or ndarray) – Radius of the sphere

  • dim (int) – Dimension of the space

Returns:

Volume of the sphere

Return type:

float or ndarray