# 4.2.4. pde.grids.cartesian module¶

Cartesian grids of arbitrary dimension.

class CartesianGrid(bounds: , shape: Union[int, Sequence[int]], periodic: = False)[source]

d-dimensional Cartesian grid with uniform discretization for each axis

The grids can be thought of as a collection of n-dimensional boxes, called cells, of equal length in each dimension. The bounds then defined the total volume covered by these cells, while the cell coordinates give the location of the box centers. We index the boxes starting from 0 along each dimension. Consequently, the cell $$i-\frac12$$ corresponds to the left edge of the covered interval and the index $$i+\frac12$$ corresponds to the right edge, when the dimension is covered by d boxes.

In particular, the discretization along dimension $$k$$ is defined as

$\begin{split}x^{(k)}_i &= x^{(k)}_\mathrm{min} + \left(i + \frac12\right) \Delta x^{(k)} \quad \text{for} \quad i = 0, \ldots, N^{(k)} - 1 \\ \Delta x^{(k)} &= \frac{x^{(k)}_\mathrm{max} - x^{(k)}_\mathrm{min}}{N^{(k)}}\end{split}$

where $$N^{(k)}$$ is the number of cells along this dimension. Consequently, the cells have dimension $$\Delta x^{(k)}$$ and cover the interval $$[x^{(k)}_\mathrm{min}, x^{(k)}_\mathrm{max}]$$.

Parameters
• bounds (list of tuple) – Give the coordinate range for each axis. This should be a tuple of two number (lower and upper bound) for each axis. The length of bounds thus determines the grid dimension.

• shape (list) – The number of support points for each axis. The length of shape needs to match the grid dimension.

• periodic (bool or list) – Specifies which axes possess periodic boundary conditions. This is either a list of booleans defining periodicity for each individual axis or a single boolean value specifying the same periodicity for all axes.

cell_to_point(cells: numpy.ndarray, cartesian: bool = True) [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. This does not have any effect for Cartesian coordinate systems, but the argument is retained to have a unified interface for all grids.

Returns

The center points of the respective cells

Return type

ndarray

cuboid: pde.tools.cuboid.Cuboid
difference_vector_real(p1: numpy.ndarray, p2: numpy.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

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

create a field from a stored state.

Parameters

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

get_subgrid(indices: ) [source]

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

CartesianGrid

point_to_cell(points: numpy.ndarray) [source]

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

This function respects periodic boundary conditions, but it does not throw an error when coordinates lie outside the bcs (for non-periodic axes).

Parameters

points (ndarray) – Real coordinates

Returns

The indices of the respective cells

Return type

ndarray

property state: Dict[str, Any]

the state of the grid

Type

dict

property volume: float

total volume of the grid

Type

float

class CartesianGridBase(shape: , periodic: = False)[source]

Base class for UnitGrid and CartesianGrid

Parameters
• shape (list) – The number of support points for each axis. The dimension of the grid is given by len(shape).

• periodic (bool or list) – Specifies which axes possess periodic boundary conditions. This is either a list of booleans defining periodicity for each individual axis or a single boolean value specifying the same periodicity for all axes.

property cell_volume_data

size associated with each cell

contains_point(point: numpy.ndarray) [source]

check whether the point is contained in the grid

Parameters

point (ndarray) – Coordinates of the point

cuboid: pde.tools.cuboid.Cuboid
from_polar_coordinates(distance: numpy.ndarray, angle: numpy.ndarray, origin: numpy.ndarray = None) [source]

convert polar coordinates to Cartesian coordinates

This function is currently only implemented for 1d and 2d systems.

Parameters
Returns

The Cartesian coordinates corresponding to the given polar coordinates.

Return type

ndarray

get_boundary_conditions(bc: BoundariesData = 'auto_periodic_neumann', rank: int = 0) [source]

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 list with one condition for each axis. For periodic axis, only periodic boundary conditions are allowed (indicated by ‘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.

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

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_image_data(data: numpy.ndarray) Dict[str, Any][source]

return a 2d-image of the data

Parameters

data (ndarray) – The values at the grid points

Returns

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

get_line_data(data: numpy.ndarray, extract: str = 'auto') Dict[str, Any][source]

return a line cut through the given data

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

• extract (str) –

Determines which cut is done through the grid. Possible choices are (default is cut_0):

• cut_#: return values along the axis specified by # and use the mid point along all other axes.

• project_#: average values for all axes, except axis #.

Here, # can either be a zero-based index (from 0 to dim-1) or a letter denoting the axis.

Returns

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

get_random_point(boundary_distance: float = 0, cartesian: bool = True, rng: = None) [source]

return a random point within the grid

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

• cartesian (bool) – Determines whether the point is returned in Cartesian coordinates or grid coordinates. This does not have any effect for Cartesian coordinate systems, but the argument is retained to have a unified interface for all grids.

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

Returns

The coordinates of the point

Return type

ndarray

iter_mirror_points(point: numpy.ndarray, with_self: bool = False, only_periodic: bool = True) [source]

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

plot(*args, title: str = None, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs)[source]

visualize the grid

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 figure. If the argument is set to show matplotlib.pyplot.show() will be called to show the plot, if the value is create, the figure will be created, but not shown, and the value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• 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 in 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. If None, a new figure with a single axes is created.

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

point_from_cartesian(coords: numpy.ndarray) [source]

convert points given in Cartesian coordinates to this grid

Parameters

coords (ndarray) – Points in Cartesian coordinates.

Returns

Points given in the coordinates of the grid

Return type

ndarray

point_to_cartesian(points: numpy.ndarray) [source]

convert coordinates of a point to Cartesian coordinates

Parameters

points (ndarray) – Points given in the coordinates of he grid

Returns

The Cartesian coordinates of the point

Return type

ndarray

polar_coordinates_real(origin: numpy.ndarray, *, ret_angle: bool = False) [source]

return polar coordinates associated with the grid

Parameters
• origin (ndarray) – Coordinates of the origin at which the polar coordinate system is anchored.

• ret_angle (bool) – Determines whether angles are returned alongside the distance. 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. For a 1d system system, the angle is defined as the sign of the difference between the point and the origin, so that angles can either be 1 or -1. For 2d systems and 3d systems, polar coordinates and spherical coordinates are used, respectively.

class UnitGrid(shape: , periodic: = False)[source]

d-dimensional Cartesian grid with unit discretization in all directions

The grids can be thought of as a collection of d-dimensional cells of unit length. The shape parameter determines how many boxes there are in each direction. The cells are enumerated starting with 0, so the last cell has index $$n-1$$ if there are $$n$$ cells along a dimension. A given cell $$i$$ extends from coordinates $$i$$ to $$i + 1$$, so the midpoint is at $$i + \frac12$$, which is the cell coordinate. Taken together, the cells covers the interval $$[0, n]$$ along this dimension.

Parameters
• shape (list) – The number of support points for each axis. The dimension of the grid is given by len(shape).

• periodic (bool or list) – Specifies which axes possess periodic boundary conditions. This is either a list of booleans defining periodicity for each individual axis or a single boolean value specifying the same periodicity for all axes.

axes: List[str]
cell_to_point(cells: numpy.ndarray, cartesian: bool = True) [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. This does not have any effect for Cartesian coordinate systems, but the argument is retained to have a unified interface for all grids.

Returns

The center points of the respective cells

Return type

ndarray

cuboid: pde.tools.cuboid.Cuboid
difference_vector_real(p1: numpy.ndarray, p2: numpy.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
classmethod from_state(state: Dict[str, Any]) [source]

create a field from a stored state.

Parameters

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

get_subgrid(indices: ) [source]

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

UnitGrid

num_axes: int
periodic: List[bool]
point_to_cell(points: numpy.ndarray) [source]

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

This function respects periodic boundary conditions, but it does not throw an error when coordinates lie outside the bcs (for non-periodic axes).

Parameters

points (ndarray) – Real coordinates

Returns

The indices of the respective cells

Return type

ndarray

property state: Dict[str, Any]

the state of the grid

Type

dict

to_cartesian() [source]

convert unit grid to CartesianGrid

property volume: float

total volume of the grid

Type

float