4.2.3. pde.grids.base module

Bases classes

exception DimensionError[source]

Bases: ValueError

exception indicating that dimensions were inconsistent

exception DomainError[source]

Bases: ValueError

exception indicating that point lies outside domain

class GridBase[source]

Bases: object

Base class for all grids defining common methods and interfaces

initialize the grid

assert_grid_compatible(other: GridBase) None[source]

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

axes: List[str]

Names of all axes that are described by the grid

Type

list

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

lower and upper bounds of each axis

Type

tuple

property axes_coords: Tuple[ndarray, ...]

coordinates of the cells for each axis

Type

tuple

axes_symmetric: List[str] = []

The names of the additional axes that the fields do not depend on, e.g. along which they are constant.

Type

list

boundary_names: Dict[str, Tuple[int, bool]] = {}

Names of boundaries to select them conveniently

Type

dict

cell_coords

coordinate values for all axes of each cell

Type

ndarray

cell_to_point(cells: ndarray, cartesian: bool = True) ndarray[source]

convert cell coordinates to real coordinates

Parameters
  • cells (ndarray) – Indices of the cells whose center coordinates are requested. This can be float values to indicate positions relative to the cell center.

  • cartesian (bool) – Determines whether the point is returned in Cartesian coordinates or grid coordinates.

Returns

The center points of the respective cells

Return type

ndarray

Warning

This method is deprecated since 2022-03-14 and will be removed soon.

cell_volume_data: Sequence[Union[float, ndarray]]

Information about the size of discretization cells

Type

list

cell_volumes

volume of each cell

Type

ndarray

compatible_with(other: GridBase) bool[source]

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: ndarray, *, coords: str = 'cartesian', wrap: bool = True) ndarray[source]

check whether the point is contained in the grid

Parameters
  • point (ndarray) – Coordinates of the point

  • 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

coordinate_arrays

for each axes: coordinate values for all cells

Type

tuple

coordinate_constraints: List[int] = []

axes that not described explicitly

Type

list

copy() GridBase[source]

return a copy of the grid

difference_vector_real(p1: ndarray, p2: ndarray) ndarray[source]

return the vector pointing from p1 to p2

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

Parameters
Returns

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

Return type

ndarray

dim: int

The spatial dimension in which the grid is embedded

Type

int

property discretization: ndarray

the linear size of a cell along each axis

Type

numpy.array

distance_real(p1: ndarray, p2: ndarray) float[source]

Calculate the distance between two points given in real coordinates

This takes periodic boundary conditions into account if necessary.

Parameters
Returns

Distance between the two positions

Return type

float

classmethod from_state(state: Union[str, Dict[str, Any]]) GridBase[source]

create a field from a stored state.

Parameters

state (str or dict) – The state from which the grid is reconstructed. If state is a string, it is decoded as JSON, which should yield a dict.

get_axis_index(key: Union[int, str], allow_symmetric: bool = True) int[source]

return the index belonging to an axis

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

  • allow_symmetric (bool) – Whether axes with assumed symmetry are included

Returns

The index of the axis

Return type

int

abstract get_boundary_conditions(bc: BoundariesData = 'auto_periodic_neumann', rank: int = 0, normal: bool = False) Boundaries[source]
abstract get_image_data(data: ndarray) Dict[str, Any][source]
abstract get_line_data(data: ndarray, extract: str = 'auto') Dict[str, Any][source]
abstract get_random_point(*, boundary_distance: float = 0, coords: str = 'cartesian') ndarray[source]
get_subgrid(indices: Sequence[int]) GridBase[source]

return a subgrid of only the specified axes

integrate(data: Union[int, float, complex, ndarray], axes: Optional[Union[int, Sequence[int]]] = None) ndarray[source]

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, 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

abstract iter_mirror_points(point: ndarray, with_self: bool = False, only_periodic: bool = True) Generator[source]
make_cell_volume_compiled(flat_index: bool = False) Callable[[...], float][source]

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(*, full_data: bool = False) Callable[[ndarray, ndarray, Union[int, float, complex, ndarray]], None][source]

return a compiled function to insert values at interpolated positions

Parameters

full_data (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.

make_integrator() Callable[[ndarray], ndarray][source]

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

Note that currently only scalar fields are supported.

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[[ndarray], None][source]

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: Union[str, OperatorInfo], bc: BoundariesData, *, normal_bcs: bool = None, **kwargs) Callable[..., np.ndarray][source]

return a compiled function applying an operator with boundary conditions

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.

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 list with one condition for each axis. For periodic axis, 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 a tuple of two conditions). 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 ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • normal_bcs (bool) – Flag indicating whether the condition is only applied in the normal direction. This value normally determined automatically from the properties of the operator. Here, normal=True is assumed if the operator reduced the rank of the field, so that the output has lower rank than the input.

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

Returns

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

Return type

callable

make_operator_no_bc(operator: Union[str, OperatorInfo], **kwargs) Callable[[ndarray, ndarray], None][source]

return a compiled function applying an operator without boundary conditions

A function that takes the discretized full data as an input and an array of valid data points to which the result of applying the operator is written.

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.

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

Returns

the function that applies the operator. This function has the signature (arr: np.ndarray, out: np.ndarray), so they out array need to be supplied explicitly.

Return type

callable

normalize_point(point: ndarray, *, reflect: bool = False) ndarray[source]

normalize grid coordinates by applying periodic boundary conditions

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
  • point (ndarray) – Coordinates of a single point

  • 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

num_axes: int

Number of axes that are not assumed symmetrically

Type

int

property numba_type: str

represents type of the grid data in numba signatures

Type

str

operators: Set[str] = {}

names of all operators defined for this grid

Type

set

periodic: List[bool]

Flags that describe which axes are periodic

Type

list

plot()[source]

visualize the grid

abstract point_from_cartesian(points: ndarray) ndarray[source]
abstract point_to_cartesian(points: ndarray, *, full: bool = False) ndarray[source]
point_to_cell(points: ndarray) ndarray[source]

Determine cell(s) corresponding to given point(s)

Parameters

points (ndarray) – Real coordinates

Returns

The indices of the respective cells

Return type

ndarray

Warning

This method is deprecated since 2022-03-14 and will be removed soon.

abstract polar_coordinates_real(origin: ndarray, *, ret_angle: bool = False) Union[ndarray, Tuple[ndarray, ...]][source]
classmethod register_operator(name: str, factory_func: Optional[Callable] = None, rank_in: int = 0, rank_out: int = 0)[source]

register an operator for this grid

Example

The method can either be used directly:

GridClass.register_operator("operator", make_operator)

or as a decorator for the factory function:

@GridClass.register_operator("operator")
def make_operator(bcs: Boundaries):
    ...
Parameters
  • name (str) – The name of the operator to register

  • factory_func (callable) – A function with signature (bcs: Boundaries, **kwargs), which takes boundary conditions and optional keyword arguments and returns an implementation of the given operator. This implementation is a function that takes a ndarray of discretized values as arguments and returns the resulting discretized data in a ndarray after applying the operator.

  • rank_in (int) – The rank of the input field for the operator

  • rank_out (int) – The rank of the field that is returned by the operator

property shape: Tuple[int, ...]

the number of support points of each axis

Type

tuple of int

abstract property state: Dict[str, Any]
property state_serialized: str

JSON-serialized version of the state of this grid

Type

str

transform(coordinates: ndarray, source: str, target: str) ndarray[source]

converts coordinates from one coordinate system to another

Supported coordinate systems include

  • cartesian: Cartesian coordinates where each point carries dim values

  • cell: Grid coordinates based on indexing the discretization cells

  • grid: Grid coordinates where each point carries num_axes values

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

uniform_cell_volumes

returns True if all cell volumes are the same

Type

bool

abstract property volume: float
class OperatorInfo(factory: Callable[..., OperatorType], rank_in: int, rank_out: int, name: str = '')[source]

Bases: tuple

stores information about an operator

Create new instance of OperatorInfo(factory, rank_in, rank_out, name)

property factory

Alias for field number 0

property name

Alias for field number 3

property rank_in

Alias for field number 1

property rank_out

Alias for field number 2

exception PeriodicityError[source]

Bases: RuntimeError

exception indicating that the grid periodicity is inconsistent

discretize_interval(x_min: float, x_max: float, num: int) Tuple[ndarray, float][source]

construct a list of equidistantly placed intervals

The discretization is defined as

\[\begin{split}x_i &= x_\mathrm{min} + \left(i + \frac12\right) \Delta x \quad \text{for} \quad i = 0, \ldots, N - 1 \\ \Delta x &= \frac{x_\mathrm{max} - x_\mathrm{min}}{N}\end{split}\]

where \(N\) is the number of intervals given by num.

Parameters
  • x_min (float) – Minimal value of the axis

  • x_max (float) – Maximal value of the axis

  • num (int) – Number of intervals

Returns

(midpoints, dx): the midpoints of the intervals and the used discretization dx.

Return type

tuple

registered_operators() Dict[str, List[str]][source]

returns all operators that are currently defined

Returns

a dictionary with the names of the operators defined for each grid class

Return type

dict