# 4.2.4. pde.grids.cartesian module¶

Cartesian grids of arbitrary dimension.

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

Bases: GridBase

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

property cell_volume_data

size associated with each cell

cuboid: Cuboid
from_polar_coordinates(distance: ndarray, angle: ndarray, origin: Optional[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

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_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’ 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.

• 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: 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: 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, coords: str = 'cartesian', rng: Optional[Generator] = None, cartesian: Optional[bool] = None) [source]

return a random point within the grid

Parameters
Returns

The coordinates of the point

Return type

ndarray

get_subgrid(indices: Sequence[int]) [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

iter_mirror_points(point: ndarray, with_self: bool = False, only_periodic: bool = True) Generator[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 final figure. If the argument is set to show, matplotlib.pyplot.show() will be called to show the plot. If the value is 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. 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. 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(coords: 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: ndarray, *, full: bool = False) [source]

convert coordinates of a point to Cartesian coordinates

Parameters
• points (ndarray) – Points given in grid coordinates

• full (bool) – Compatibility option not used in this method

Returns

The Cartesian coordinates of the point

Return type

ndarray

polar_coordinates_real(origin: ndarray, *, ret_angle: bool = False) Union[ndarray, Tuple[ndarray, ndarray, ndarray]][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.

property state: Dict[str, Any]

the state of the grid

Type

dict

property volume: float

total volume of the grid

Type

float

CartesianGridBase

alias of CartesianGrid

class UnitGrid(shape: Sequence[int], periodic: Union[Sequence[bool], bool] = False)[source]

Bases: CartesianGrid

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]
cuboid: Cuboid
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: Sequence[int]) [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]
property state: Dict[str, Any]

the state of the grid

Type

dict

to_cartesian() [source]

convert unit grid to CartesianGrid