4.2 pde.fields package

Package defining fields, which contain the actual data stored on discrete grids.

ScalarField

Scalar field discretized on a grid.

VectorField

Vector field discretized on a grid.

Tensor2Field

Tensor field of rank 2 discretized on a grid.

FieldCollection

Collection of fields defined on the same grid.

Inheritance structure of the classes:

Inheritance diagram of scalar.ScalarField, vectorial.VectorField, tensorial.Tensor2Field, collection.FieldCollection

The details of the classes are explained below:

class FieldCollection(fields: Sequence[DataFieldBase] | Mapping[str, DataFieldBase], *, label: str | None = None, labels: list[str | None] | _FieldLabels | None = None, dtype: DTypeLike | None = None, copy_fields: bool | None = None)[source]

Bases: FieldBase

Collection of fields defined on the same grid.

Note

Collections are initialized with a list of individual fields, whose data is copied into the collection, so that changing the original fields will not change the collection. All fields in a collection must have the same data type. This might lead to up-casting, where for instance a combination of a real-valued and a complex-valued field will be both stored as complex fields.

Parameters:
  • fields (sequence or mapping of DataFieldBase) – Sequence or mapping of the individual fields. If a mapping is used, the keys set the names of the individual fields.

  • label (str) – Label of the field collection

  • labels (list of str) – Labels of the individual fields. If omitted, the labels from the fields argument are used.

  • dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be automatically determined from the given fields.

  • copy_fields (bool) – Deprecated option.

append(*fields: DataFieldBase | FieldCollection, label: str | None = None) → FieldCollection[source]

Create new collection with appended field(s)

Warning

Appending fields requires a full copy of the data. Moreover, links to other fields will not be copied, but these links stay with the original collection.

Parameters:
  • *fields (FieldCollection or DataFieldBase) – A sequence of single fields or collection of fields that will be appended to the fields in the current collection. The data of all fields will be copied.

  • label (str) – Label of the new field collection. If omitted, the current label is used

Returns:

A new field collection, which combines the current one with fields given by fields.

Return type:

FieldCollection

apply(func: Callable | str, out: DataFieldBase | None = None, *, label: str | None = None, evaluate_args: dict[str, Any] | None = None) → DataFieldBase

Applies a function/expression to the data and returns it as a field.

Note

This function doesn’t support field collections very well. While collections can be passed as input (so this method can be called on collections), the output is expected to be a single field, i.e., an instance of DataFieldBase.

Parameters:
  • func (callable or str) – (Vectorized) function being applied to the data or an expression that can be parsed using sympy (evaluate() is used in this case). The local field values can be accessed using the field labels for a field collection and via the variable c otherwise.

  • out (DataFieldBase, optional) – Optional field into which the data is written

  • label (str, optional) – Name of the returned field

  • evaluate_args (dict) – Additional arguments passed to evaluate(). Only used when func is a string.

Returns:

Field with new data. Identical to out if given.

Return type:

DataFieldBase

assert_field_compatible(other: FieldBase, accept_scalar: bool = False)[source]

Checks whether other is compatible with the current field.

Parameters:
  • other (FieldBase) – Other field this is compared to

  • accept_scalar (bool, optional) – Determines whether it is acceptable that other is an instance of ScalarField.

property attributes: dict[str, Any]

describes the state of the instance (without the data)

Type:

dict

property attributes_serialized: dict[str, str]

serialized version of the attributes

Type:

dict

property averages: list

Averages of all fields.

conjugate() → Self

Returns complex conjugate of the field.

Returns:

the complex conjugated field

Return type:

FieldBase

copy(*, label: str | None = None, dtype: DTypeLike | None = None) → FieldCollection[source]

Return a copy of the data, but not of the grid.

Parameters:
  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

property data: NumericArray

discretized data at the support points.

Type:

ndarray

property dtype: DTypeLike

the numpy dtype of the underlying data.

Type:

DTypeLike

property fields: list[DataFieldBase]

the fields of this collection

Type:

list

classmethod from_data(field_classes, grid: GridBase, data: NumericArray, *, with_ghost_cells: bool = True, label: str | None = None, labels: list[str | None] | _FieldLabels | None = None, dtype: DTypeLike | None = None) → FieldCollection[source]

Create a field collection from classes and data.

Parameters:
  • field_classes (list) – List of the classes that define the individual fields

  • data (ndarray, optional) – Data values of all fields at support points of the grid

  • grid (GridBase) – Grid defining the space on which this field is defined.

  • with_ghost_cells (bool) – Indicates whether the ghost cells are included in data

  • label (str) – Label of the field collection

  • labels (list of str) – Labels of the individual fields. If omitted, the labels from the fields argument are used.

  • dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be determined from data automatically.

classmethod from_file(filename: str) → FieldBase

Create field from data stored in a file.

Field can be written to a file using FieldBase.to_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:

filename (str) – Path to the file being read

Returns:

The field with the appropriate sub-class

Return type:

FieldBase

classmethod from_scalar_expressions(grid: GridBase, expressions: Sequence[str], *, user_funcs: dict[str, Callable] | None = None, consts: dict[str, NumberOrArray] | None = None, label: str | None = None, labels: Sequence[str] | None = None, dtype: DTypeLike | None = None) → FieldCollection[source]

Create a field collection on a grid from given expressions.

Warning

This implementation uses exec() and should therefore not be used in a context where malicious input could occur.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • expressions (list of str) – A list of mathematical expression, one for each field in the collection. The expressions determine the values as a function of the position on the grid. The expressions may contain standard mathematical functions and they may depend on the axes labels of the grid. More information can be found in the expression documentation.

  • user_funcs (dict, optional) – A dictionary with user defined functions that can be used in the expression

  • consts (dict, optional) – A dictionary with user defined constants that can be used in the expression. The values of these constants should either be numbers or ndarray.

  • label (str, optional) – Name of the whole collection

  • labels (list of str, optional) – Names of the individual fields

  • dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be determined from data automatically.

classmethod from_state(attributes: dict[str, Any], data: NumericArray | Literal['empty', 'zeros', 'ones'] | None = None) → FieldCollection[source]

Create a field collection from given state.

Parameters:
  • attributes (dict) – The attributes that describe the current instance

  • data (ndarray, optional) – Data values at support points of the grid defining all fields

get_image_data(index: int = 0, **kwargs) → dict[str, Any][source]

Return data for plotting an image of the field.

Parameters:
  • index (int) – Index of the field whose data is returned

  • **kwargs – Arguments forwarded to the get_image_data method

Returns:

Information useful for plotting an image of the field

Return type:

dict

get_line_data(index: int = 0, scalar: str = 'auto', extract: str = 'auto') → dict[str, Any][source]

Return data for a line plot of the field.

Parameters:
  • index (int) – Index of the field whose data is returned

  • scalar (str or int) – The method for extracting scalars as described in DataFieldBase.to_scalar().

  • extract (str) – The method used for extracting the line data. See the docstring of the grid method get_line_data to find supported values.

Returns:

Information useful for performing a line plot of the field

Return type:

dict

property grid: GridBase

The grid on which the field is defined.

Type:

base,GridBase

property imag: Self

Imaginary part of the field.

Type:

FieldBase

property integrals: list

Integrals of all fields.

interpolate_to_grid(grid: GridBase, *, fill: Number | None = None, label: str | None = None) → FieldCollection[source]

Interpolate the data of this field collection to another grid.

Parameters:
  • grid (GridBase) – The grid of the new field onto which the current field is interpolated.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

  • label (str, optional) – Name of the returned field collection

Returns:

Interpolated data

Return type:

FieldCollection

property is_complex: bool

whether the field contains real or complex data

Type:

bool

property label: str | None

the name of the field

Type:

str

property labels: _FieldLabels

the labels of all fields.

Note

The attribute returns a special class _FieldLabels to allow specific manipulations of the field labels. The returned object behaves much like a list, but assigning values will modify the labels of the fields in the collection.

Type:

_FieldLabels

property magnitudes: NumericArray

scalar magnitudes of all fields.

Type:

ndarray

plot(kind: str | Sequence[str] = 'auto', figsize: Literal['auto'] | tuple[float, float] = 'auto', arrangement: Literal['horizontal', 'vertical', 'square'] | tuple[int, int] = 'horizontal', subplot_args=None, *args, title: str | None = None, constrained_layout: bool = True, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', fig_style: dict[str, Any] | None = None, fig=None, **kwargs) → list[PlotReference][source]

Visualize all the fields in the collection.

Parameters:
  • kind (str or list of str) – Determines the kind of the visualizations. Supported values are image, line, vector, interactive, or merged. Alternatively, auto determines the best visualization based on each field itself. Instead of a single value for all fields, a list with individual values can be given, unless merged is chosen.

  • figsize (str or tuple of numbers) – Determines the figure size. The figure size is unchanged if the string default is passed. Conversely, the size is adjusted automatically when auto is passed. Finally, a specific figure size can be specified using two values, using matplotlib.figure.Figure.set_size_inches().

  • arrangement (str or tuple of int) – Determines how the sub panels will be arranged. The default value horizontal places all subplots next to each other, whereas vertical puts them below each other. Alternatively, an exact number of rows and columns can be specified by the tuple (nrows, ncols). Negative values will be replaced by suitable values that ensure enough panels.

  • subplot_args (list) – Additional arguments for the specific subplots. Should be a list with a dictionary of arguments for each subplot. Supplying an empty dict allows to keep the default setting of specific subplots.

  • title (str) – Title of the plot. If omitted, the title might be chosen automatically. This is shown above all panels.

  • constrained_layout (bool) – Whether to use constrained_layout in matplotlib.pyplot.figure() call to create a figure. This affects the layout of all plot elements. Generally, spacing might be better with this flag enabled, but it can also lead to problems when plotting multiple plots successively, e.g., when creating a movie.

  • filename (str, optional) – If given, the figure 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.

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

  • fig (matplotlib.figures.Figure) – Figure that is used for plotting. If omitted, a new figure is created.

  • **kwargs – All additional keyword arguments are forwarded to the actual plotting function of all subplots.

Returns:

Instances that contain information to update all the plots with new data later.

Return type:

List of PlotReference

plot_interactive(viewer_args: dict[str, Any] | None = None, **kwargs) → None

Create an interactive plot of the field using napari

For a detailed description of the launched program, see the napari webpage.

Parameters:
  • viewer_args (dict) – Arguments passed to napari.viewer.Viewer to affect the viewer.

  • **kwargs – Extra arguments passed to the plotting function

project(axes: str | Sequence[str], *, label: str | None = None, **kwargs) → FieldCollection[source]

Project fields along given axes.

This is currently only implemented for scalar fields. If any field in the collection has higher rank, the entire process fails.

Parameters:
  • axes (list of str) – The names of the axes that are removed by the projection operation. The valid names for a given grid are the ones in the GridBase.axes attribute.

  • label (str, optional) – Name of the returned collection. If omitted, the current label is used.

  • **kwargs – Additional arguments forwarded to the projection method. In particular, this allows selecting a projection method.

Returns:

The projected data of all fields on a subgrid of the original grid.

Return type:

FieldCollection

property real: Self

Real part of the field.

Type:

FieldBase

classmethod scalar_random_normal(num_fields: int, grid: GridBase, mean: float = 0, std: float = 1, *, label: str | None = None, labels: Sequence[str] | None = None, **kwargs) → FieldCollection[source]

Creates Gaussian random fields with normal distributed random values.

Details of methods and additional options are described in random_normal().

Parameters:
  • num_fields (int) – The number of fields to create

  • grid (GridBase) – Grid defining the space on which this field is defined

  • mean (float) – Mean of the Gaussian distribution

  • std (float) – Standard deviation of the Gaussian distribution

  • label (str, optional) – Name of the returned field

  • labels (list of str, optional) – Names of the individual fields

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

  • **kwargs – Additional parameters can affect details of the correlation function.

classmethod scalar_random_uniform(num_fields: int, grid: GridBase, vmin: float = 0, vmax: float = 1, *, label: str | None = None, labels: Sequence[str] | None = None, rng: np.random.Generator | None = None) → FieldCollection[source]

Create scalar fields with random values between vmin and vmax

Parameters:
  • num_fields (int) – The number of fields to create

  • grid (GridBase) – Grid defining the space on which the fields are defined

  • vmin (float) – Lower bound. Can be complex to create complex fields

  • vmax (float) – Upper bound. Can be complex to create complex fields

  • label (str, optional) – Name of the field collection

  • labels (list of str, optional) – Names of the individual fields

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

slice(position: dict[str, float], *, label: str | None = None, **kwargs) → FieldCollection[source]

Slice all fields at a given position.

This is currently only implemented for scalar fields. If any field in the collection has higher rank, the entire process fails.

Parameters:
  • position (dict) – Determines the location of the slice using a dictionary supplying coordinate values for a subset of axes. Axes not mentioned in the dictionary are retained and form the slice. For instance, in a 2d Cartesian grid, position = {‘x’: 1} slices along the y-direction at x=1. Additionally, the special positions ‘low’, ‘mid’, and ‘high’ are supported to reference relative positions along the axis.

  • label (str, optional) – Name of the returned collection. If omitted, the current label is used.

  • **kwargs – Additional arguments forwarded to the slicing method (e.g., method).

Returns:

The projected data of all fields on a subgrid of the original grid.

Return type:

FieldCollection

smooth(sigma: float = 1, *, out: FieldCollection | None = None, label: str | None = None) → FieldCollection[source]

Applies Gaussian smoothing with the given standard deviation.

This function respects periodic boundary conditions of the underlying grid, using reflection when no periodicity is specified.

Parameters:
  • sigma (float) – Gives the standard deviation of the smoothing in real length units (default: 1)

  • out (FieldCollection, optional) – Optional field into which the smoothed data is stored

  • label (str, optional) – Name of the returned field

Returns:

Smoothed data, stored at out if given.

Return type:

FieldCollection

split_mpi(decomposition: Literal['auto'] | int | list[int] = 'auto') → Self

Splits the field onto subgrids in an MPI run.

In a normal serial simulation, the method simply returns the field itself. In contrast, in an MPI simulation, the field provided on the main node is split onto all nodes using the given decomposition. The field data provided on all other nodes is not used.

Parameters:

decomposition (list of ints) – Number of subdivision in each direction. Should be a list of length grid.num_axes specifying the number of nodes for this axis. If one value is -1, its value will be determined from the number of available nodes. The default value auto tries to determine an optimal decomposition by minimizing communication between nodes.

Returns:

The part of the field that corresponds to the subgrid associated with the current MPI node.

Return type:

FieldBase

to_file(filename: str, **kwargs) → None

Store field in a file.

The extension of the filename determines what format is being used. If it ends in .h5 or .hdf, the Hierarchical Data Format is used. The other supported format are images, where only the most typical formats are supported.

To load the field back from the file, you may use FieldBase.from_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:
  • filename (str) – Path where the data is stored

  • **kwargs – Additional parameters may be supported for some formats

classmethod unserialize_attributes(attributes: dict[str, str]) → dict[str, Any][source]

Unserializes the given attributes.

Parameters:

attributes (dict) – The serialized attributes

Returns:

The unserialized attributes

Return type:

dict

property writeable: bool

whether the field data can be changed or not

Type:

bool

class ScalarField(grid: GridBase, data: ArrayLike | Literal['empty', 'zeros', 'ones'] | None = 'zeros', *, label: str | None = None, dtype: DTypeLike | None = None, with_ghost_cells: bool = False)[source]

Bases: DataFieldBase

Scalar field discretized on a grid.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined.

  • data (Number or ndarray, optional) – Field values at the support points of the grid. The flag with_ghost_cells determines whether this data array contains values for the ghost cells, too. The resulting field will contain real data unless the data argument contains complex values. Special values are “zeros” or None, initializing the field with zeros, and “empty”, just allocating memory with unspecified values.

  • label (str, optional) – Name of the field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

  • with_ghost_cells (bool) – Indicates whether the ghost cells are included in data

apply(func: Callable | str, out: DataFieldBase | None = None, *, label: str | None = None, evaluate_args: dict[str, Any] | None = None) → DataFieldBase

Applies a function/expression to the data and returns it as a field.

Note

This function doesn’t support field collections very well. While collections can be passed as input (so this method can be called on collections), the output is expected to be a single field, i.e., an instance of DataFieldBase.

Parameters:
  • func (callable or str) – (Vectorized) function being applied to the data or an expression that can be parsed using sympy (evaluate() is used in this case). The local field values can be accessed using the field labels for a field collection and via the variable c otherwise.

  • out (DataFieldBase, optional) – Optional field into which the data is written

  • label (str, optional) – Name of the returned field

  • evaluate_args (dict) – Additional arguments passed to evaluate(). Only used when func is a string.

Returns:

Field with new data. Identical to out if given.

Return type:

DataFieldBase

apply_operator(operator: str, bc: BoundariesData | None, out: DataFieldBase | None = None, *, label: str | None = None, backend: str | pde.backends.base.BackendBase = 'default', args: dict[str, Any] | None = None, **kwargs) → DataFieldBase

Apply a (differential) operator and return result as a field.

Parameters:
  • operator (str) – An identifier determining the operator. Note that not all grids support the same operators.

  • bc – Boundary conditions applied to the field before applying the operator. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (DataFieldBase, optional) – Optional field to which the result is written.

  • label (str, optional) – Name of the returned field

  • backend (str) – Backend (e.g., numba or numpy) for constructing the operator

  • args (dict) – Additional arguments for the boundary conditions

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

Field data after applying the operator. This field is identical to out if this argument was specified.

Return type:

DataFieldBase

assert_field_compatible(other: FieldBase, *, accept_scalar: bool = False) → None

Checks whether other is compatible with the current field.

Parameters:
  • other (FieldBase) – The other field this one is compared to

  • accept_scalar (bool, optional) – Determines whether it is acceptable that other is an instance of ScalarField.

property attributes: dict[str, Any]

describes the state of the instance (without the data)

Type:

dict

property attributes_serialized: dict[str, str]

serialized version of the attributes

Type:

dict

property average: NumberOrArray

the average of data.

This is calculated by integrating each component of the field over space and dividing by the grid volume

Type:

Float or ndarray

conjugate() → Self

Returns complex conjugate of the field.

Returns:

the complex conjugated field

Return type:

FieldBase

copy(*, label: str | None = None, dtype: DTypeLike | None = None) → Self

Return a copy of the field.

This method creates a new instance of the field with the same grid and data. Optionally, a new label and/or data type can be specified for the copy.

Parameters:
  • label (str, optional) – Name of the copied field. If omitted, the label of the original field is used.

  • dtype (numpy dtype, optional) – Data type of the copied field. If omitted, the data type of the original field is used.

Returns:

A copy of the current field instance.

Return type:

DataFieldBase

property data: NumericArray

discretized data at the support points.

Type:

ndarray

property data_shape: tuple[int, ...]

the shape of the data at each grid point

Type:

tuple

property dtype: DTypeLike

the numpy dtype of the underlying data.

Type:

DTypeLike

property fluctuations: NumberOrArray

quantification of the average fluctuations.

The fluctuations are defined as the standard deviation of the data scaled by the cell volume. This definition makes the fluctuations independent of the discretization. It corresponds to the physical scaling available in the random_normal().

Returns:

A tensor with the same rank of the field, specifying the fluctuations of each component of the tensor field individually. Consequently, a simple scalar is returned for a ScalarField.

Return type:

ndarray

Type:

Float or ndarray

classmethod from_expression(grid: GridBase, expression: str, *, user_funcs: dict[str, Callable] | None = None, consts: dict[str, NumberOrArray] | None = None, label: str | None = None, dtype: DTypeLike | None = None) → pde.fields.scalar.ScalarField[source]

Create a scalar field on a grid from a given expression.

Warning

This implementation uses exec() and should therefore not be used in a context where malicious input could occur.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • expression (str) – Mathematical expression for the scalar value as a function of the position on the grid. The expression may contain standard mathematical functions and it may depend on the axes labels of the grid. More information can be found in the expression documentation.

  • user_funcs (dict, optional) – A dictionary with user defined functions that can be used in the expression

  • consts (dict, optional) – A dictionary with user defined constants that can be used in the expression. The values of these constants should either be numbers or ndarray.

  • label (str, optional) – Name of the field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

classmethod from_file(filename: str) → FieldBase

Create field from data stored in a file.

Field can be written to a file using FieldBase.to_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:

filename (str) – Path to the file being read

Returns:

The field with the appropriate sub-class

Return type:

FieldBase

classmethod from_image(path: Path | str, bounds: Sequence[tuple[float, float]] | None = None, periodic: bool | Sequence[bool] = False, *, label: str | None = None) → pde.fields.scalar.ScalarField[source]

Create a scalar field from an image.

Parameters:
  • path (Path or str) – The path to the image file

  • bounds (tuple, optional) – Gives the coordinate range for each axis. This should be two tuples of two numbers each, which mark the lower and upper bound for each axis.

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

  • label (str, optional) – Name of the field

classmethod from_state(attributes: dict[str, Any], data: NumericArray | Literal['empty', 'zeros', 'ones'] | None = None) → Self

Create a field from given state.

Parameters:
  • attributes (dict) – The attributes that describe the current instance

  • data (ndarray, optional) – Data values at the support points of the grid defining the field

Returns:

The instance created from the stored state

Return type:

DataFieldBase

get_boundary_field(index: str | tuple[int, bool], bc: BoundariesData | None = None, *, label: str | None = None) → pde.fields.scalar.ScalarField[source]

Get the field on the specified boundary.

Parameters:
  • index (str or tuple) – Index specifying the boundary. Can be either a string given in boundary_names, like "left", or a tuple of the axis index perpendicular to the boundary and a boolean specifying whether the boundary is at the upper side of the axis or not, e.g., (1, True).

  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • label (str) – Label of the returned field

Returns:

The field on the boundary

Return type:

ScalarField

get_boundary_values(axis: int, upper: bool, bc: BoundariesData | None) → NumberOrArray

Get the field values directly on the specified boundary.

Parameters:
  • axis (int) – The axis perpendicular to the boundary

  • upper (bool) – Whether the boundary is at the upper side of the axis

  • bc – The boundary conditions applied to the field. If this is None, it is assumed that boundary conditions have been set beforehand, e.g., using set_ghost_cells(). 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

Returns:

The discretized values on the boundary

Return type:

ndarray

classmethod get_class_by_rank(rank: int) → type[DataFieldBase]

Return a DataFieldBase subclass describing a field with a given rank.

Parameters:

rank (int) – The rank of the tensor field

Returns:

The DataField class that corresponds to the rank

get_image_data(scalar: str = 'auto', transpose: bool = False, **kwargs) → dict[str, Any]

Return data for visualizing the field as an image.

Parameters:
  • scalar (str) – Method used for extracting a scalar representation; see DataFieldBase.to_scalar().

  • transpose (bool) – Determines whether the transpose of the data should be returned.

  • **kwargs – Additional keyword arguments are forwarded to get_image_data().

Returns:

Information useful for plotting an image representation of the field.

Return type:

dict

get_line_data(scalar: str = 'auto', extract: str = 'auto') → dict[str, Any]

Return data for visualizing the field in a line plot.

Parameters:
  • scalar (str) – Method used for extracting a scalar representation; see DataFieldBase.to_scalar().

  • extract (str) – Method used for extracting one-dimensional line data from the grid.

Returns:

Information useful for plotting a line representation of the field.

Return type:

dict

get_nematic_data(transpose: bool = False, **kwargs) → dict[str, Any]

Return data for a nematic plot of the field.

Parameters:
  • transpose (bool) – Determines whether the transpose of the data should be plotted.

  • **kwargs – Additional parameters are forwarded to grid.get_image_data

Returns:

Information useful for plotting a nematic field

Return type:

dict

get_vector_data(transpose: bool = False, **kwargs) → dict[str, Any]

Return data for a vector plot of the field.

Parameters:
  • transpose (bool) – Determines whether the transpose of the data should be plotted.

  • **kwargs – Additional parameters are forwarded to grid.get_image_data

Returns:

Information useful for plotting an vector field

Return type:

dict

gradient(bc: BoundariesData | None, out: pde.fields.vectorial.VectorField | None = None, **kwargs) → pde.fields.vectorial.VectorField[source]

Apply gradient operator and return result as a field.

Parameters:
  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.vectorial.VectorField, optional) – Optional vector field to which the result is written.

  • **kwargs – Additional keyword arguments (e.g., label)

Returns:

result of applying the operator

Return type:

VectorField

gradient_squared(bc: BoundariesData | None, out: pde.fields.scalar.ScalarField | None = None, **kwargs) → pde.fields.scalar.ScalarField[source]

Apply squared gradient operator and return result as a field.

This evaluates \(|\nabla \phi|^2\) for the scalar field \(\phi\)

Parameters:
  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.scalar.ScalarField, optional) – Optional vector field to which the result is written.

  • **kwargs – Extra arguments are forwarded to apply_operator()

Returns:

the squared gradient of the field

Return type:

ScalarField

property grid: GridBase

The grid on which the field is defined.

Type:

base,GridBase

property imag: Self

Imaginary part of the field.

Type:

FieldBase

insert(point: FloatingArray, amount: ArrayLike) → None

Adds an (integrated) value to the field at an interpolated position.

Parameters:
  • point (ndarray) – The point inside the grid where the value is added. This is given in grid coordinates.

  • amount (Number or ndarray) – The amount that will be added to the field. The value describes an integrated quantity (given by the field value times the discretization volume). This is important for consistency with different discretizations and in particular grids with non-uniform discretizations.

property integral: NumericArray

integral of each component over space.

Type:

ndarray

interpolate(point: FloatingArray, *, bc: BoundariesData | None = None, fill: Number | None = None) → NumericArray

Interpolate the field to points between support points.

Parameters:
  • point (ndarray) – The points at which the values should be obtained. This is given in grid coordinates.

  • bc – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used to determine values outside the domain. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

Returns:

the values of the field

Return type:

ndarray

interpolate_to_grid(grid: GridBase, *, bc: BoundariesData | None = None, fill: Number | None = None, label: str | None = None) → pde.fields.scalar.ScalarField[source]

Interpolate the data of this scalar field to another grid.

Parameters:
  • grid (GridBase) – The grid of the new field onto which the current field is interpolated.

  • bc – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used to determine values outside the domain. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

  • label (str, optional) – Name of the returned field

Returns:

Field of the same rank as the current one.

property is_complex: bool

whether the field contains real or complex data

Type:

bool

property label: str | None

the name of the field

Type:

str

laplace(bc: BoundariesData | None, out: pde.fields.scalar.ScalarField | None = None, **kwargs) → pde.fields.scalar.ScalarField[source]

Apply Laplace operator and return result as a field.

Parameters:
  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.scalar.ScalarField, optional) – Optional scalar field to which the result is written.

  • **kwargs – Additional keyword arguments (e.g., label)

Returns:

the Laplacian of the field

Return type:

ScalarField

property magnitude: float

determine the (scalar) magnitude of the field

This is calculated by getting a scalar field using the default arguments of the to_scalar() method, averaging the result over the whole grid, and taking the absolute value.

Type:

float

make_dot_operator(backend: str | pde.backends.base.BackendBase = 'default', *, conjugate: bool = True) → _BinaryOperatorImplType

Return operator calculating the dot product between two fields.

This supports both products between two vectors as well as products between a vector and a tensor.

Parameters:
  • backend (str) – Backend (e.g., numba or numpy) for constructing the operator

  • conjugate (bool) – Whether to use the complex conjugate for the second operand

Returns:

function that takes two instance of ndarray, which contain the discretized data of the two operands. An optional third argument can specify the output array to which the result is written.

make_interpolator(*, fill: Number | None = None, with_ghost_cells: bool = False, backend: str | pde.backends.base.BackendBase = 'default') → Callable[[FloatingArray, NumericArray], NumberOrArray]

Returns a function that can be used to interpolate values.

Parameters:
  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

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

  • backend (str) – The name of the backend to use to implement this operator.

Returns:

A function which returns interpolated values when called with arbitrary positions within the space of the grid.

plot(kind: str = 'auto', *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) → PlotReference

Visualize the field.

Parameters:
  • kind (str) – Determines the visualizations. Supported values are image, line, vector, nematic, or interactive. Alternatively, auto determines the best visualization based on the field itself.

  • 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 – All additional keyword arguments are forwarded to the actual plotting function determined by kind.

Returns:

Instance that contains information to update the plot with new data later.

Return type:

PlotReference

Tip

Typical additional arguments for the various plot kinds include

  • kind == "line":

    • scalar: Sets method for extracting scalars as described in DataFieldBase.to_scalar().

    • extract: Method used for extracting the line data.

    • ylabel: Label of the y-axis.

    • ylim: Data limits of the y-axis.

    • Additional arguments are passed to matplotlib.pyplot.plot()

  • kind == "image":

    • colorbar: Determines whether a colorbar is shown

    • scalar: Sets method for extracting scalars as described in

      DataFieldBase.to_scalar().

    • transpose Determines whether the transpose of the data is plotted

    • Most remaining arguments are passed to matplotlib.pyplot.imshow()

  • kind == "vector":

  • kind == "nematic":

    • transpose Determines whether the transpose of the data is plotted

    • max_points Sets max. number of points along each axis

    • Additional arguments are passed to matplotlib.pyplot.quiver()

plot_interactive(viewer_args: dict[str, Any] | None = None, **kwargs) → None

Create an interactive plot of the field using napari

For a detailed description of the launched program, see the napari webpage.

Parameters:
  • viewer_args (dict) – Arguments passed to napari.viewer.Viewer to affect the viewer.

  • **kwargs – Extra arguments passed to the plotting function

project(axes: str | Sequence[str], *, method: Literal['integral', 'average', 'mean', 'maximum', 'max', 'minimum', 'min'] = 'integral', label: str | None = None) → pde.fields.scalar.ScalarField[source]

Project scalar field along given axes.

Parameters:
  • axes (list of str) – The names of the axes that are removed by the projection operation. The valid names for a given grid are the ones in the GridBase.axes attribute.

  • method (str) –

    The projection method. Supported values are:

    • "integral": Integrate over the removed axes.

    • "average" or "mean": Return the average over the removed axes.

    • "maximum" or "max": Return the maximum over the removed axes.

    • "minimum" or "min": Return the minimum over the removed axes.

  • label (str, optional) – The label of the returned field

Returns:

The projected data is a scalar field defined on a subgrid of the original grid.

Return type:

ScalarField

classmethod random_harmonic(grid: GridBase, modes: int = 3, harmonic=<ufunc 'cos'>, axis_combination=<ufunc 'multiply'>, *, label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None) → Self

Create a random field build from harmonics.

The resulting fields will be highly correlated in space and can thus serve for testing differential operators.

With the default settings, the resulting field \(c_i(\mathbf{x})\) is given by

\[c_i(\mathbf{x}) = \prod_{\alpha=1}^N \sum_{j=1}^M a_{ij\alpha} \cos\left(\frac{2 \pi x_\alpha}{j L_\alpha}\right) \;,\]

where \(N\) is the number of spatial dimensions, each with length \(L_\alpha\), \(M\) is the number of modes given by modes, and \(a_{ij\alpha}\) are random amplitudes, chosen from a uniform distribution over the interval [0, 1].

Note that the product could be replaced by a sum when axis_combination = numpy.add and the \(\cos()\) could be any other function given by the parameter harmonic.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • modes (int) – Number \(M\) of harmonic modes

  • harmonic (callable) – Determines which harmonic function is used. Typical values are numpy.sin() and numpy.cos(), which basically relate to different boundary conditions applied at the grid boundaries.

  • axis_combination (callable) – Determines how values from different axis are combined. Typical choices are numpy.multiply() and numpy.add() resulting in products and sums of the values along axes, respectively.

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to double.

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

classmethod random_normal(grid: GridBase, mean: float = 0, std: float = 1, *, scaling: Literal['none', 'physical'] = 'none', correlation: CorrelationType = 'none', label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None, **kwargs) → Self

Creates Gaussian random field with normal distributed random values.

A complex field is returned when either mean or std is a complex number. In this case, the real and imaginary parts of these arguments are used to determine the distribution of the real and imaginary parts of the resulting field. Consequently, pde.fields.scalar.ScalarField.random_normal(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard normal distribution.

Real and imaginary parts of fields, as well as all components of vector and tensor fields, are always uncorrelated. Correlations in spatial positions are supported through the correlation argument. If set, the returned field \(f\) obeys the selected correlation function \(C(k)\) (see table below for details). In Fourier space, we thus have

\[\langle f(\boldsymbol k) f(\boldsymbol k’) \rangle = C(|\boldsymbol k|) \delta(\boldsymbol k-\boldsymbol k’)\]

For simplicity, the correlations respect periodic boundary conditions.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • mean (float) – Mean of the Gaussian distribution

  • std (float) – Standard deviation of the Gaussian distribution

  • scaling (str) – Determines how the values are scaled. Possible choices are ‘none’ (values are drawn from a normal distribution with given mean and standard deviation) or ‘physical’ (the variance of the random number is scaled by the inverse volume of the grid cell; this is for instance useful for concentration fields, which vary less in larger cells).

  • correlation (str) – Selects the autocorrelation function to create spatially correlated noise. Many of the options (described below) support additional parameters that can be supplied as keyword arguments.

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to float if both mean and std are real, otherwise it is complex. Note that if a complex dtype is supplied, the mean and std are also assumed to be complex, so that specifying them as real will lead to a vanishing imaginary part of the returned field.

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

  • **kwargs – Additional parameters can affect details of the correlation function. Examples include length_scale, exponent, and sharpness, which are described in the table below.

Supported correlation functions

Identifier

Correlation function

none

No correlation, \(C(k) = \delta(k)\)

gaussian

\(C(k) = \exp(-\frac12 k^2 \lambda^2)\) with the length scale \(\lambda\) set by argument length_scale

power law

\(C(k) = k^{\nu/2}\) with exponent \(\nu\) set by argument exponent.

cosine

\(C(k) = \exp\bigl(-s^2(\lambda k - 1)^2\bigr)\) with the length scale \(\lambda\) set by argument length_scale, whereas the sharpness parameter \(s\) is set by sharpness and defaults to 10.

Note

The returned field only has the correct standard deviation (set by std) for correlation functions that decrease monotonously. In other cases (i.e., for cosine correlation), the variance depends on details, like the resolution of the grid.

classmethod random_uniform(grid: GridBase, vmin: float = 0, vmax: float = 1, *, label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None) → Self

Create field with uncorrelated uniform distributed random values.

A complex field is returned when vmin or vmax is a complex number. In this case, the real and imaginary parts of these arguments are used to determine the distribution of the real and imaginary parts of the resulting field. Consequently, pde.fields.scalar.ScalarField.random_uniform(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard uniform distribution.

Real and imaginary parts of fields, all components of vector and tensor fields, as well as all spatial positions are always uncorrelated.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • vmin (float) – Lower bound for the random values

  • vmax (float) – Upper bound for the random values

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to double if both vmin and vmax are real, otherwise it is complex.

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

property real: Self

Real part of the field.

Type:

FieldBase

set_ghost_cells(bc: BoundariesData, *, args=None, **kwargs) → None

Set the boundary values on virtual points for all boundaries.

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.

  • args – Additional arguments that might be supported by special boundary conditions.

  • **kwargs – Some boundary conditions might provide additional control via keyword arguments, e.g., set_corners to control whether corner cells are set using interpolation.

slice(position: dict[str, float], *, method: Literal['nearest'] = 'nearest', label: str | None = None) → ScalarField[source]

Slice data at a given position.

Note

This method should not be used to evaluate fields right at the boundary since it does not respect boundary conditions. Use get_boundary_field() to obtain the values directly on the boundary.

Parameters:
  • position (dict) – Determines the location of the slice using a dictionary supplying coordinate values for a subset of axes. Axes not mentioned in the dictionary are retained and form the slice. For instance, in a 2d Cartesian grid, position = {‘x’: 1} slices along the y-direction at x=1. Additionally, the special positions ‘low’, ‘mid’, and ‘high’ are supported to reference relative positions along the axis.

  • method (str) – The method used for slicing. Currently, we only support nearest, which takes data from cells defined on the grid.

  • label (str, optional) – The label of the returned field

Returns:

The sliced data is a scalar field defined on a subgrid of the original grid.

Return type:

ScalarField

smooth(sigma: float = 1, *, out: Self | None = None, label: str | None = None) → Self

Applies Gaussian smoothing with the given standard deviation.

This function respects periodic boundary conditions of the underlying grid, using reflection when no periodicity is specified.

Parameters:
  • sigma (float) – Gives the standard deviation of the smoothing in real length units (default: 1)

  • out (FieldBase, optional) – Optional field into which the smoothed data is stored. Setting this to the input field enables in-place smoothing.

  • label (str, optional) – Name of the returned field

Returns:

Field with smoothed data. This is stored at out if given.

split_mpi(decomposition: Literal['auto'] | int | list[int] = 'auto') → Self

Splits the field onto subgrids in an MPI run.

In a normal serial simulation, the method simply returns the field itself. In contrast, in an MPI simulation, the field provided on the main node is split onto all nodes using the given decomposition. The field data provided on all other nodes is not used.

Parameters:

decomposition (list of ints) – Number of subdivision in each direction. Should be a list of length grid.num_axes specifying the number of nodes for this axis. If one value is -1, its value will be determined from the number of available nodes. The default value auto tries to determine an optimal decomposition by minimizing communication between nodes.

Returns:

The part of the field that corresponds to the subgrid associated with the current MPI node.

Return type:

FieldBase

to_file(filename: str, **kwargs) → None

Store field in a file.

The extension of the filename determines what format is being used. If it ends in .h5 or .hdf, the Hierarchical Data Format is used. The other supported format are images, where only the most typical formats are supported.

To load the field back from the file, you may use FieldBase.from_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:
  • filename (str) – Path where the data is stored

  • **kwargs – Additional parameters may be supported for some formats

to_scalar(scalar: str | Callable = 'auto', *, label: str | None = None) → pde.fields.scalar.ScalarField[source]

Return a modified scalar field by applying method scalar

Parameters:
  • scalar (str or callable) – Determines the method used for obtaining the scalar. If this is a callable, it is simply applied to self.data and a new scalar field with this data is returned. Alternatively, pre-defined methods can be selected using strings. Here, abs and norm denote the norm of each entry of the field, while norm_squared returns the squared norm. The default auto is to return a (unchanged) copy of a real field and the norm of a complex field.

  • label (str, optional) – Name of the returned field

Returns:

Scalar field after applying the operation

Return type:

ScalarField

classmethod unserialize_attributes(attributes: dict[str, str]) → dict[str, Any]

Unserializes the given attributes.

Parameters:

attributes (dict) – The serialized attributes

Returns:

The unserialized attributes

Return type:

dict

property writeable: bool

whether the field data can be changed or not

Type:

bool

class Tensor2Field(grid: GridBase, data: ArrayLike | Literal['empty', 'zeros', 'ones'] | None = 'zeros', *, label: str | None = None, dtype: DTypeLike | None = None, with_ghost_cells: bool = False)[source]

Bases: DataFieldBase

Tensor field of rank 2 discretized on a grid.

Warning

Components of the tensor field are given in the local basis. While the local basis is identical to the global basis in Cartesian coordinates, the local basis depends on position in curvilinear coordinate systems. Moreover, the field always contains all components, even if the underlying grid assumes symmetries.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined.

  • data (Number or ndarray, optional) – Field values at the support points of the grid. The flag with_ghost_cells determines whether this data array contains values for the ghost cells, too. The resulting field will contain real data unless the data argument contains complex values. Special values are “zeros” or None, initializing the field with zeros, and “empty”, just allocating memory with unspecified values.

  • label (str, optional) – Name of the field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

  • with_ghost_cells (bool) – Indicates whether the ghost cells are included in data

apply(func: Callable | str, out: DataFieldBase | None = None, *, label: str | None = None, evaluate_args: dict[str, Any] | None = None) → DataFieldBase

Applies a function/expression to the data and returns it as a field.

Note

This function doesn’t support field collections very well. While collections can be passed as input (so this method can be called on collections), the output is expected to be a single field, i.e., an instance of DataFieldBase.

Parameters:
  • func (callable or str) – (Vectorized) function being applied to the data or an expression that can be parsed using sympy (evaluate() is used in this case). The local field values can be accessed using the field labels for a field collection and via the variable c otherwise.

  • out (DataFieldBase, optional) – Optional field into which the data is written

  • label (str, optional) – Name of the returned field

  • evaluate_args (dict) – Additional arguments passed to evaluate(). Only used when func is a string.

Returns:

Field with new data. Identical to out if given.

Return type:

DataFieldBase

apply_operator(operator: str, bc: BoundariesData | None, out: DataFieldBase | None = None, *, label: str | None = None, backend: str | pde.backends.base.BackendBase = 'default', args: dict[str, Any] | None = None, **kwargs) → DataFieldBase

Apply a (differential) operator and return result as a field.

Parameters:
  • operator (str) – An identifier determining the operator. Note that not all grids support the same operators.

  • bc – Boundary conditions applied to the field before applying the operator. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (DataFieldBase, optional) – Optional field to which the result is written.

  • label (str, optional) – Name of the returned field

  • backend (str) – Backend (e.g., numba or numpy) for constructing the operator

  • args (dict) – Additional arguments for the boundary conditions

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

Field data after applying the operator. This field is identical to out if this argument was specified.

Return type:

DataFieldBase

assert_field_compatible(other: FieldBase, *, accept_scalar: bool = False) → None

Checks whether other is compatible with the current field.

Parameters:
  • other (FieldBase) – The other field this one is compared to

  • accept_scalar (bool, optional) – Determines whether it is acceptable that other is an instance of ScalarField.

property attributes: dict[str, Any]

describes the state of the instance (without the data)

Type:

dict

property attributes_serialized: dict[str, str]

serialized version of the attributes

Type:

dict

property average: NumberOrArray

the average of data.

This is calculated by integrating each component of the field over space and dividing by the grid volume

Type:

Float or ndarray

conjugate() → Self

Returns complex conjugate of the field.

Returns:

the complex conjugated field

Return type:

FieldBase

convert(form: Literal['symmetric', 'anti-symmetric', 'transposed', 'traceless'], inplace: bool = False, *, label: str | None = None) → Tensor2Field[source]

Convert tensor to a specific form in each point in space.

Parameters:
  • form (str) – Determines the form (symmetric, anti-symmetric, transposed, or traceless) that the converted tensors should have.

  • inplace (bool) – Overwrites current field if True

  • label (str, optional) – Name of the returned field

Returns:

converted tensor field

Return type:

Tensor2Field

copy(*, label: str | None = None, dtype: DTypeLike | None = None) → Self

Return a copy of the field.

This method creates a new instance of the field with the same grid and data. Optionally, a new label and/or data type can be specified for the copy.

Parameters:
  • label (str, optional) – Name of the copied field. If omitted, the label of the original field is used.

  • dtype (numpy dtype, optional) – Data type of the copied field. If omitted, the data type of the original field is used.

Returns:

A copy of the current field instance.

Return type:

DataFieldBase

property data: NumericArray

discretized data at the support points.

Type:

ndarray

property data_shape: tuple[int, ...]

the shape of the data at each grid point

Type:

tuple

divergence(bc: BoundariesData | None, out: pde.fields.vectorial.VectorField | None = None, **kwargs) → pde.fields.vectorial.VectorField[source]

Apply tensor divergence and return result as a field.

The tensor divergence is a vector field \(v_\alpha\) resulting from a contracting of the derivative of the tensor field \(t_{\alpha\beta}\):

\[v_\alpha = \sum_\beta \frac{\partial t_{\alpha\beta}}{\partial x_\beta}\]
Parameters:
  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.vectorial.VectorField, optional) – Optional scalar field to which the result is written.

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

result of applying the operator

Return type:

VectorField

dot(other: VectorField, out: VectorField | None = None, *, conjugate: bool = True, label: str = 'dot product') → VectorField[source]
dot(other: Tensor2Field, out: Tensor2Field | None = None, *, conjugate: bool = True, label: str = 'dot product') → Tensor2Field

Calculate the dot product involving a tensor field.

This supports the dot product between two tensor fields as well as the product between a tensor and a vector. The resulting fields will be a tensor or vector, respectively.

Parameters:
Returns:

VectorField or Tensor2Field: result of applying dot operator

property dtype: DTypeLike

the numpy dtype of the underlying data.

Type:

DTypeLike

property fluctuations: NumberOrArray

quantification of the average fluctuations.

The fluctuations are defined as the standard deviation of the data scaled by the cell volume. This definition makes the fluctuations independent of the discretization. It corresponds to the physical scaling available in the random_normal().

Returns:

A tensor with the same rank of the field, specifying the fluctuations of each component of the tensor field individually. Consequently, a simple scalar is returned for a ScalarField.

Return type:

ndarray

Type:

Float or ndarray

classmethod from_expression(grid: GridBase, expressions: Sequence[Sequence[str]], *, user_funcs: dict[str, Callable] | None = None, consts: dict[str, NumberOrArray] | None = None, label: str | None = None, dtype: DTypeLike | None = None) → pde.fields.tensorial.Tensor2Field[source]

Create a tensor field on a grid from given expressions.

Warning

This implementation uses exec() and should therefore not be used in a context where malicious input could occur.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • expressions (list of str) – A 2d list of mathematical expression, one for each component of the tensor field. The expressions determine the values as a function of the position on the grid. The expressions may contain standard mathematical functions and they may depend on the axes labels of the grid. More information can be found in the expression documentation.

  • user_funcs (dict, optional) – A dictionary with user defined functions that can be used in the expression

  • consts (dict, optional) – A dictionary with user defined constants that can be used in the expression. The values of these constants should either be numbers or ndarray.

  • label (str, optional) – Name of the field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

classmethod from_file(filename: str) → FieldBase

Create field from data stored in a file.

Field can be written to a file using FieldBase.to_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:

filename (str) – Path to the file being read

Returns:

The field with the appropriate sub-class

Return type:

FieldBase

classmethod from_state(attributes: dict[str, Any], data: NumericArray | Literal['empty', 'zeros', 'ones'] | None = None) → Self

Create a field from given state.

Parameters:
  • attributes (dict) – The attributes that describe the current instance

  • data (ndarray, optional) – Data values at the support points of the grid defining the field

Returns:

The instance created from the stored state

Return type:

DataFieldBase

get_boundary_values(axis: int, upper: bool, bc: BoundariesData | None) → NumberOrArray

Get the field values directly on the specified boundary.

Parameters:
  • axis (int) – The axis perpendicular to the boundary

  • upper (bool) – Whether the boundary is at the upper side of the axis

  • bc – The boundary conditions applied to the field. If this is None, it is assumed that boundary conditions have been set beforehand, e.g., using set_ghost_cells(). 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

Returns:

The discretized values on the boundary

Return type:

ndarray

classmethod get_class_by_rank(rank: int) → type[DataFieldBase]

Return a DataFieldBase subclass describing a field with a given rank.

Parameters:

rank (int) – The rank of the tensor field

Returns:

The DataField class that corresponds to the rank

get_image_data(scalar: str = 'auto', transpose: bool = False, **kwargs) → dict[str, Any]

Return data for visualizing the field as an image.

Parameters:
  • scalar (str) – Method used for extracting a scalar representation; see DataFieldBase.to_scalar().

  • transpose (bool) – Determines whether the transpose of the data should be returned.

  • **kwargs – Additional keyword arguments are forwarded to get_image_data().

Returns:

Information useful for plotting an image representation of the field.

Return type:

dict

get_line_data(scalar: str = 'auto', extract: str = 'auto') → dict[str, Any]

Return data for visualizing the field in a line plot.

Parameters:
  • scalar (str) – Method used for extracting a scalar representation; see DataFieldBase.to_scalar().

  • extract (str) – Method used for extracting one-dimensional line data from the grid.

Returns:

Information useful for plotting a line representation of the field.

Return type:

dict

get_nematic_data(transpose: bool = False, max_points: int | None = None, **kwargs) → dict[str, Any][source]

Return data for a nematic plot of the field.

The tensor field is interpreted as a nematic order parameter, i.e., only the symmetric, traceless part \(\boldsymbol{Q}\) of the tensor is used. In two dimensions, this part can be written as

\[\boldsymbol{Q} = S \left( \boldsymbol{n} \otimes \boldsymbol{n} - \frac{\mathbb{1}}{2} \right)\]

where the director \(\boldsymbol{n}\) is a unit vector and the nematic order \(S \ge 0\) is the difference of the two eigenvalues of \(\boldsymbol{Q}\). The returned vectors are aligned with the director and their length is given by the nematic order.

Note that the director is only defined up to its sign, so the returned vectors should be plotted without arrow heads; see the nematic plot kind of plot().

Parameters:
  • transpose (bool) – Determines whether the transpose of the data should be plotted.

  • max_points (int) – The maximal number of points that is used along each axis. This option can be used to sub-sample the data.

  • **kwargs – Additional parameters forwarded to grid.get_image_data

Returns:

Information useful for plotting a nematic field

Return type:

dict

get_vector_data(transpose: bool = False, **kwargs) → dict[str, Any]

Return data for a vector plot of the field.

Parameters:
  • transpose (bool) – Determines whether the transpose of the data should be plotted.

  • **kwargs – Additional parameters are forwarded to grid.get_image_data

Returns:

Information useful for plotting an vector field

Return type:

dict

property grid: GridBase

The grid on which the field is defined.

Type:

base,GridBase

property imag: Self

Imaginary part of the field.

Type:

FieldBase

insert(point: FloatingArray, amount: ArrayLike) → None

Adds an (integrated) value to the field at an interpolated position.

Parameters:
  • point (ndarray) – The point inside the grid where the value is added. This is given in grid coordinates.

  • amount (Number or ndarray) – The amount that will be added to the field. The value describes an integrated quantity (given by the field value times the discretization volume). This is important for consistency with different discretizations and in particular grids with non-uniform discretizations.

property integral: NumericArray

integral of each component over space.

Type:

ndarray

interpolate(point: FloatingArray, *, bc: BoundariesData | None = None, fill: Number | None = None) → NumericArray

Interpolate the field to points between support points.

Parameters:
  • point (ndarray) – The points at which the values should be obtained. This is given in grid coordinates.

  • bc – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used to determine values outside the domain. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

Returns:

the values of the field

Return type:

ndarray

interpolate_to_grid(grid: GridBase, *, bc: BoundariesData | None = None, fill: Number | None = None, label: str | None = None) → Self

Interpolate the data of this field to another grid.

Parameters:
  • grid (GridBase) – The grid of the new field onto which the current field is interpolated.

  • bc – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used to determine values outside the domain. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

  • label (str, optional) – Name of the returned field

Returns:

Field of the same rank as the current one.

property is_complex: bool

whether the field contains real or complex data

Type:

bool

is_symmetric(rtol=1e-05, atol=1e-08) → bool[source]

Returns whether the tensor is symmetric.

Parameters:
property label: str | None

the name of the field

Type:

str

property magnitude: float

determine the (scalar) magnitude of the field

This is calculated by getting a scalar field using the default arguments of the to_scalar() method, averaging the result over the whole grid, and taking the absolute value.

Type:

float

make_dot_operator(backend: str | pde.backends.base.BackendBase = 'default', *, conjugate: bool = True) → _BinaryOperatorImplType

Return operator calculating the dot product between two fields.

This supports both products between two vectors as well as products between a vector and a tensor.

Parameters:
  • backend (str) – Backend (e.g., numba or numpy) for constructing the operator

  • conjugate (bool) – Whether to use the complex conjugate for the second operand

Returns:

function that takes two instance of ndarray, which contain the discretized data of the two operands. An optional third argument can specify the output array to which the result is written.

make_interpolator(*, fill: Number | None = None, with_ghost_cells: bool = False, backend: str | pde.backends.base.BackendBase = 'default') → Callable[[FloatingArray, NumericArray], NumberOrArray]

Returns a function that can be used to interpolate values.

Parameters:
  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

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

  • backend (str) – The name of the backend to use to implement this operator.

Returns:

A function which returns interpolated values when called with arbitrary positions within the space of the grid.

plot(kind: str = 'auto', *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) → PlotReference

Visualize the field.

Parameters:
  • kind (str) – Determines the visualizations. Supported values are image, line, vector, nematic, or interactive. Alternatively, auto determines the best visualization based on the field itself.

  • 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 – All additional keyword arguments are forwarded to the actual plotting function determined by kind.

Returns:

Instance that contains information to update the plot with new data later.

Return type:

PlotReference

Tip

Typical additional arguments for the various plot kinds include

  • kind == "line":

    • scalar: Sets method for extracting scalars as described in DataFieldBase.to_scalar().

    • extract: Method used for extracting the line data.

    • ylabel: Label of the y-axis.

    • ylim: Data limits of the y-axis.

    • Additional arguments are passed to matplotlib.pyplot.plot()

  • kind == "image":

    • colorbar: Determines whether a colorbar is shown

    • scalar: Sets method for extracting scalars as described in

      DataFieldBase.to_scalar().

    • transpose Determines whether the transpose of the data is plotted

    • Most remaining arguments are passed to matplotlib.pyplot.imshow()

  • kind == "vector":

  • kind == "nematic":

    • transpose Determines whether the transpose of the data is plotted

    • max_points Sets max. number of points along each axis

    • Additional arguments are passed to matplotlib.pyplot.quiver()

plot_components(kind: str = 'auto', *args, title: str | None = None, constrained_layout: bool = True, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', fig_style: dict[str, Any] | None = None, fig=None, **kwargs) → list[list[PlotReference]][source]

Visualize all the components of this tensor field.

Parameters:
  • kind (str or list of str) – Determines the kind of the visualizations. Supported values are image or line. Alternatively, auto determines the best visualization based on the grid.

  • title (str) – Title of the plot. If omitted, the title might be chosen automatically. This is shown above all panels.

  • constrained_layout (bool) – Whether to use constrained_layout in matplotlib.pyplot.figure() call to create a figure. This affects the layout of all plot elements. Generally, spacing might be better with this flag enabled, but it can also lead to problems when plotting multiple plots successively, e.g., when creating a movie.

  • filename (str, optional) – If given, the figure 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.

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

  • fig (matplotlib.figures.Figure) – Figure that is used for plotting. If omitted, a new figure is created.

  • **kwargs – All additional keyword arguments are forwarded to the actual plotting function of all subplots.

Returns:

Instances that contain information to update all the plots with new data later.

Return type:

2d list of PlotReference

plot_interactive(viewer_args: dict[str, Any] | None = None, **kwargs) → None

Create an interactive plot of the field using napari

For a detailed description of the launched program, see the napari webpage.

Parameters:
  • viewer_args (dict) – Arguments passed to napari.viewer.Viewer to affect the viewer.

  • **kwargs – Extra arguments passed to the plotting function

classmethod random_harmonic(grid: GridBase, modes: int = 3, harmonic=<ufunc 'cos'>, axis_combination=<ufunc 'multiply'>, *, label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None) → Self

Create a random field build from harmonics.

The resulting fields will be highly correlated in space and can thus serve for testing differential operators.

With the default settings, the resulting field \(c_i(\mathbf{x})\) is given by

\[c_i(\mathbf{x}) = \prod_{\alpha=1}^N \sum_{j=1}^M a_{ij\alpha} \cos\left(\frac{2 \pi x_\alpha}{j L_\alpha}\right) \;,\]

where \(N\) is the number of spatial dimensions, each with length \(L_\alpha\), \(M\) is the number of modes given by modes, and \(a_{ij\alpha}\) are random amplitudes, chosen from a uniform distribution over the interval [0, 1].

Note that the product could be replaced by a sum when axis_combination = numpy.add and the \(\cos()\) could be any other function given by the parameter harmonic.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • modes (int) – Number \(M\) of harmonic modes

  • harmonic (callable) – Determines which harmonic function is used. Typical values are numpy.sin() and numpy.cos(), which basically relate to different boundary conditions applied at the grid boundaries.

  • axis_combination (callable) – Determines how values from different axis are combined. Typical choices are numpy.multiply() and numpy.add() resulting in products and sums of the values along axes, respectively.

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to double.

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

classmethod random_normal(grid: GridBase, mean: float = 0, std: float = 1, *, scaling: Literal['none', 'physical'] = 'none', correlation: CorrelationType = 'none', label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None, **kwargs) → Self

Creates Gaussian random field with normal distributed random values.

A complex field is returned when either mean or std is a complex number. In this case, the real and imaginary parts of these arguments are used to determine the distribution of the real and imaginary parts of the resulting field. Consequently, pde.fields.scalar.ScalarField.random_normal(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard normal distribution.

Real and imaginary parts of fields, as well as all components of vector and tensor fields, are always uncorrelated. Correlations in spatial positions are supported through the correlation argument. If set, the returned field \(f\) obeys the selected correlation function \(C(k)\) (see table below for details). In Fourier space, we thus have

\[\langle f(\boldsymbol k) f(\boldsymbol k’) \rangle = C(|\boldsymbol k|) \delta(\boldsymbol k-\boldsymbol k’)\]

For simplicity, the correlations respect periodic boundary conditions.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • mean (float) – Mean of the Gaussian distribution

  • std (float) – Standard deviation of the Gaussian distribution

  • scaling (str) – Determines how the values are scaled. Possible choices are ‘none’ (values are drawn from a normal distribution with given mean and standard deviation) or ‘physical’ (the variance of the random number is scaled by the inverse volume of the grid cell; this is for instance useful for concentration fields, which vary less in larger cells).

  • correlation (str) – Selects the autocorrelation function to create spatially correlated noise. Many of the options (described below) support additional parameters that can be supplied as keyword arguments.

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to float if both mean and std are real, otherwise it is complex. Note that if a complex dtype is supplied, the mean and std are also assumed to be complex, so that specifying them as real will lead to a vanishing imaginary part of the returned field.

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

  • **kwargs – Additional parameters can affect details of the correlation function. Examples include length_scale, exponent, and sharpness, which are described in the table below.

Supported correlation functions

Identifier

Correlation function

none

No correlation, \(C(k) = \delta(k)\)

gaussian

\(C(k) = \exp(-\frac12 k^2 \lambda^2)\) with the length scale \(\lambda\) set by argument length_scale

power law

\(C(k) = k^{\nu/2}\) with exponent \(\nu\) set by argument exponent.

cosine

\(C(k) = \exp\bigl(-s^2(\lambda k - 1)^2\bigr)\) with the length scale \(\lambda\) set by argument length_scale, whereas the sharpness parameter \(s\) is set by sharpness and defaults to 10.

Note

The returned field only has the correct standard deviation (set by std) for correlation functions that decrease monotonously. In other cases (i.e., for cosine correlation), the variance depends on details, like the resolution of the grid.

classmethod random_uniform(grid: GridBase, vmin: float = 0, vmax: float = 1, *, label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None) → Self

Create field with uncorrelated uniform distributed random values.

A complex field is returned when vmin or vmax is a complex number. In this case, the real and imaginary parts of these arguments are used to determine the distribution of the real and imaginary parts of the resulting field. Consequently, pde.fields.scalar.ScalarField.random_uniform(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard uniform distribution.

Real and imaginary parts of fields, all components of vector and tensor fields, as well as all spatial positions are always uncorrelated.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • vmin (float) – Lower bound for the random values

  • vmax (float) – Upper bound for the random values

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to double if both vmin and vmax are real, otherwise it is complex.

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

property real: Self

Real part of the field.

Type:

FieldBase

set_ghost_cells(bc: BoundariesData, *, args=None, **kwargs) → None

Set the boundary values on virtual points for all boundaries.

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.

  • args – Additional arguments that might be supported by special boundary conditions.

  • **kwargs – Some boundary conditions might provide additional control via keyword arguments, e.g., set_corners to control whether corner cells are set using interpolation.

smooth(sigma: float = 1, *, out: Self | None = None, label: str | None = None) → Self

Applies Gaussian smoothing with the given standard deviation.

This function respects periodic boundary conditions of the underlying grid, using reflection when no periodicity is specified.

Parameters:
  • sigma (float) – Gives the standard deviation of the smoothing in real length units (default: 1)

  • out (FieldBase, optional) – Optional field into which the smoothed data is stored. Setting this to the input field enables in-place smoothing.

  • label (str, optional) – Name of the returned field

Returns:

Field with smoothed data. This is stored at out if given.

split_mpi(decomposition: Literal['auto'] | int | list[int] = 'auto') → Self

Splits the field onto subgrids in an MPI run.

In a normal serial simulation, the method simply returns the field itself. In contrast, in an MPI simulation, the field provided on the main node is split onto all nodes using the given decomposition. The field data provided on all other nodes is not used.

Parameters:

decomposition (list of ints) – Number of subdivision in each direction. Should be a list of length grid.num_axes specifying the number of nodes for this axis. If one value is -1, its value will be determined from the number of available nodes. The default value auto tries to determine an optimal decomposition by minimizing communication between nodes.

Returns:

The part of the field that corresponds to the subgrid associated with the current MPI node.

Return type:

FieldBase

symmetrize(make_traceless: bool = False, inplace: bool = False, *, label: str | None = None) → Tensor2Field[source]

Symmetrize the tensor field.

Parameters:
  • make_traceless (bool) – Determines whether the result is also traceless

  • inplace (bool) – Overwrites current field if True

  • label (str, optional) – Name of the returned field

Returns:

result of the operation

Return type:

Tensor2Field

to_file(filename: str, **kwargs) → None

Store field in a file.

The extension of the filename determines what format is being used. If it ends in .h5 or .hdf, the Hierarchical Data Format is used. The other supported format are images, where only the most typical formats are supported.

To load the field back from the file, you may use FieldBase.from_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:
  • filename (str) – Path where the data is stored

  • **kwargs – Additional parameters may be supported for some formats

to_scalar(scalar: str = 'auto', *, label: str | None = 'scalar `{scalar}`') → ScalarField[source]

Return scalar variant of the field.

The invariants of the tensor field \(\boldsymbol{A}\) are

\[\begin{split}I_1 &= \mathrm{tr}(\boldsymbol{A}) \\ I_2 &= \frac12 \left[ (\mathrm{tr}(\boldsymbol{A})^2 - \mathrm{tr}(\boldsymbol{A}^2) \right] \\ I_3 &= \det(A)\end{split}\]

where tr denotes the trace and det denotes the determinant. Note that the three invariants can only be distinct and non-zero in three dimensions. In two dimensional spaces, we have the identity \(I_2 = I_3\) and in one-dimensional spaces, we have \(I_1 = I_3\) as well as \(I_2 = 0\).

Parameters:
  • scalar (str) – The method to calculate the scalar. Possible choices include norm (the default chosen when the value is auto), min, max, squared_sum, norm_squared, trace (or invariant1), invariant2, and determinant (or invariant3)

  • label (str, optional) – Name of the returned field

Returns:

the scalar field after applying the operation

Return type:

ScalarField

trace(*, label: str | None = 'trace') → ScalarField[source]

Return the trace of the tensor field as a scalar field.

Parameters:

label (str, optional) – Name of the returned field

Returns:

scalar field of traces

Return type:

ScalarField

transpose(inplace: bool = False, *, label: str = 'transpose') → Tensor2Field[source]

Return the transpose of the tensor field.

Parameters:
  • inplace (bool) – Overwrites current field if True

  • label (str, optional) – Name of the returned field

Returns:

transpose of the tensor field

Return type:

Tensor2Field

classmethod unserialize_attributes(attributes: dict[str, str]) → dict[str, Any]

Unserializes the given attributes.

Parameters:

attributes (dict) – The serialized attributes

Returns:

The unserialized attributes

Return type:

dict

property writeable: bool

whether the field data can be changed or not

Type:

bool

class VectorField(grid: GridBase, data: ArrayLike | Literal['empty', 'zeros', 'ones'] | None = 'zeros', *, label: str | None = None, dtype: DTypeLike | None = None, with_ghost_cells: bool = False)[source]

Bases: DataFieldBase

Vector field discretized on a grid.

Warning

Components of the vector field are given in the local basis. While the local basis is identical to the global basis in Cartesian coordinates, the local basis depends on position in curvilinear coordinate systems. Moreover, the field always contains all components, even if the underlying grid assumes symmetries.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined.

  • data (Number or ndarray, optional) – Field values at the support points of the grid. The flag with_ghost_cells determines whether this data array contains values for the ghost cells, too. The resulting field will contain real data unless the data argument contains complex values. Special values are “zeros” or None, initializing the field with zeros, and “empty”, just allocating memory with unspecified values.

  • label (str, optional) – Name of the field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

  • with_ghost_cells (bool) – Indicates whether the ghost cells are included in data

apply(func: Callable | str, out: DataFieldBase | None = None, *, label: str | None = None, evaluate_args: dict[str, Any] | None = None) → DataFieldBase

Applies a function/expression to the data and returns it as a field.

Note

This function doesn’t support field collections very well. While collections can be passed as input (so this method can be called on collections), the output is expected to be a single field, i.e., an instance of DataFieldBase.

Parameters:
  • func (callable or str) – (Vectorized) function being applied to the data or an expression that can be parsed using sympy (evaluate() is used in this case). The local field values can be accessed using the field labels for a field collection and via the variable c otherwise.

  • out (DataFieldBase, optional) – Optional field into which the data is written

  • label (str, optional) – Name of the returned field

  • evaluate_args (dict) – Additional arguments passed to evaluate(). Only used when func is a string.

Returns:

Field with new data. Identical to out if given.

Return type:

DataFieldBase

apply_operator(operator: str, bc: BoundariesData | None, out: DataFieldBase | None = None, *, label: str | None = None, backend: str | pde.backends.base.BackendBase = 'default', args: dict[str, Any] | None = None, **kwargs) → DataFieldBase

Apply a (differential) operator and return result as a field.

Parameters:
  • operator (str) – An identifier determining the operator. Note that not all grids support the same operators.

  • bc – Boundary conditions applied to the field before applying the operator. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (DataFieldBase, optional) – Optional field to which the result is written.

  • label (str, optional) – Name of the returned field

  • backend (str) – Backend (e.g., numba or numpy) for constructing the operator

  • args (dict) – Additional arguments for the boundary conditions

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

Field data after applying the operator. This field is identical to out if this argument was specified.

Return type:

DataFieldBase

assert_field_compatible(other: FieldBase, *, accept_scalar: bool = False) → None

Checks whether other is compatible with the current field.

Parameters:
  • other (FieldBase) – The other field this one is compared to

  • accept_scalar (bool, optional) – Determines whether it is acceptable that other is an instance of ScalarField.

property attributes: dict[str, Any]

describes the state of the instance (without the data)

Type:

dict

property attributes_serialized: dict[str, str]

serialized version of the attributes

Type:

dict

property average: NumberOrArray

the average of data.

This is calculated by integrating each component of the field over space and dividing by the grid volume

Type:

Float or ndarray

conjugate() → Self

Returns complex conjugate of the field.

Returns:

the complex conjugated field

Return type:

FieldBase

copy(*, label: str | None = None, dtype: DTypeLike | None = None) → Self

Return a copy of the field.

This method creates a new instance of the field with the same grid and data. Optionally, a new label and/or data type can be specified for the copy.

Parameters:
  • label (str, optional) – Name of the copied field. If omitted, the label of the original field is used.

  • dtype (numpy dtype, optional) – Data type of the copied field. If omitted, the data type of the original field is used.

Returns:

A copy of the current field instance.

Return type:

DataFieldBase

property data: NumericArray

discretized data at the support points.

Type:

ndarray

property data_shape: tuple[int, ...]

the shape of the data at each grid point

Type:

tuple

divergence(bc: BoundariesData | None, out: pde.fields.scalar.ScalarField | None = None, **kwargs) → pde.fields.scalar.ScalarField[source]

Apply divergence operator and return result as a field.

Parameters:
  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.scalar.ScalarField, optional) – Optional scalar field to which the result is written.

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

Divergence of the field

Return type:

ScalarField

dot(other: VectorField, out: ScalarField | None = None, *, conjugate: bool = True, label: str = 'dot product') → ScalarField[source]
dot(other: Tensor2Field, out: VectorField | None = None, *, conjugate: bool = True, label: str = 'dot product') → VectorField

Calculate the dot product involving a vector field.

This supports the dot product between two vectors fields as well as the product between a vector and a tensor. The resulting fields will be a scalar or vector, respectively.

Parameters:
Returns:

ScalarField or VectorField: result of applying the operator

property dtype: DTypeLike

the numpy dtype of the underlying data.

Type:

DTypeLike

property fluctuations: NumberOrArray

quantification of the average fluctuations.

The fluctuations are defined as the standard deviation of the data scaled by the cell volume. This definition makes the fluctuations independent of the discretization. It corresponds to the physical scaling available in the random_normal().

Returns:

A tensor with the same rank of the field, specifying the fluctuations of each component of the tensor field individually. Consequently, a simple scalar is returned for a ScalarField.

Return type:

ndarray

Type:

Float or ndarray

classmethod from_expression(grid: GridBase, expressions: Sequence[str], *, user_funcs: dict[str, Callable] | None = None, consts: dict[str, NumberOrArray] | None = None, label: str | None = None, dtype: DTypeLike | None = None) → pde.fields.vectorial.VectorField[source]

Create a vector field on a grid from given expressions.

Warning

This implementation uses exec() and should therefore not be used in a context where malicious input could occur.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • expressions (list of str) – A list of mathematical expression, one for each component of the vector field. The expressions determine the values as a function of the position on the grid. The expressions may contain standard mathematical functions and they may depend on the axes labels of the grid. More information can be found in the expression documentation.

  • user_funcs (dict, optional) – A dictionary with user defined functions that can be used in the expression

  • consts (dict, optional) – A dictionary with user defined constants that can be used in the expression. The values of these constants should either be numbers or ndarray.

  • label (str, optional) – Name of the field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

classmethod from_file(filename: str) → FieldBase

Create field from data stored in a file.

Field can be written to a file using FieldBase.to_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:

filename (str) – Path to the file being read

Returns:

The field with the appropriate sub-class

Return type:

FieldBase

classmethod from_scalars(fields: list[pde.fields.scalar.ScalarField], *, label: str | None = None, dtype: DTypeLike | None = None) → pde.fields.vectorial.VectorField[source]

Create a vector field from a list of ScalarFields.

Note that the data of the scalar fields is copied in the process

Parameters:
  • fields (list) – The list of (compatible) scalar fields

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.

Returns:

the resulting vector field

Return type:

pde.fields.vectorial.VectorField

classmethod from_state(attributes: dict[str, Any], data: NumericArray | Literal['empty', 'zeros', 'ones'] | None = None) → Self

Create a field from given state.

Parameters:
  • attributes (dict) – The attributes that describe the current instance

  • data (ndarray, optional) – Data values at the support points of the grid defining the field

Returns:

The instance created from the stored state

Return type:

DataFieldBase

get_boundary_values(axis: int, upper: bool, bc: BoundariesData | None) → NumberOrArray

Get the field values directly on the specified boundary.

Parameters:
  • axis (int) – The axis perpendicular to the boundary

  • upper (bool) – Whether the boundary is at the upper side of the axis

  • bc – The boundary conditions applied to the field. If this is None, it is assumed that boundary conditions have been set beforehand, e.g., using set_ghost_cells(). 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

Returns:

The discretized values on the boundary

Return type:

ndarray

classmethod get_class_by_rank(rank: int) → type[DataFieldBase]

Return a DataFieldBase subclass describing a field with a given rank.

Parameters:

rank (int) – The rank of the tensor field

Returns:

The DataField class that corresponds to the rank

get_image_data(scalar: str = 'auto', transpose: bool = False, **kwargs) → dict[str, Any]

Return data for visualizing the field as an image.

Parameters:
  • scalar (str) – Method used for extracting a scalar representation; see DataFieldBase.to_scalar().

  • transpose (bool) – Determines whether the transpose of the data should be returned.

  • **kwargs – Additional keyword arguments are forwarded to get_image_data().

Returns:

Information useful for plotting an image representation of the field.

Return type:

dict

get_line_data(scalar: str = 'auto', extract: str = 'auto') → dict[str, Any]

Return data for visualizing the field in a line plot.

Parameters:
  • scalar (str) – Method used for extracting a scalar representation; see DataFieldBase.to_scalar().

  • extract (str) – Method used for extracting one-dimensional line data from the grid.

Returns:

Information useful for plotting a line representation of the field.

Return type:

dict

get_nematic_data(transpose: bool = False, **kwargs) → dict[str, Any]

Return data for a nematic plot of the field.

Parameters:
  • transpose (bool) – Determines whether the transpose of the data should be plotted.

  • **kwargs – Additional parameters are forwarded to grid.get_image_data

Returns:

Information useful for plotting a nematic field

Return type:

dict

get_vector_data(transpose: bool = False, max_points: int | None = None, **kwargs) → dict[str, Any][source]

Return data for a vector plot of the field.

Parameters:
  • transpose (bool) – Determines whether the transpose of the data should be plotted.

  • max_points (int) – The maximal number of points that is used along each axis. This option can be used to sub-sample the data.

  • **kwargs – Additional parameters forwarded to grid.get_image_data

Returns:

Information useful for plotting an vector field

Return type:

dict

gradient(bc: BoundariesData | None, out: pde.fields.tensorial.Tensor2Field | None = None, **kwargs) → pde.fields.tensorial.Tensor2Field[source]

Apply vector gradient operator and return result as a field.

The vector gradient field is a tensor field \(t_{\alpha\beta}\) that specifies the derivatives of the vector field \(v_\alpha\) with respect to all coordinates \(x_\beta\).

Parameters:
  • bc – The boundary conditions applied to the field. Boundary conditions need to determine all components of the vector 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.vectorial.VectorField, optional) – Optional vector field to which the result is written.

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

Gradient of the field

Return type:

Tensor2Field

property grid: GridBase

The grid on which the field is defined.

Type:

base,GridBase

property imag: Self

Imaginary part of the field.

Type:

FieldBase

insert(point: FloatingArray, amount: ArrayLike) → None

Adds an (integrated) value to the field at an interpolated position.

Parameters:
  • point (ndarray) – The point inside the grid where the value is added. This is given in grid coordinates.

  • amount (Number or ndarray) – The amount that will be added to the field. The value describes an integrated quantity (given by the field value times the discretization volume). This is important for consistency with different discretizations and in particular grids with non-uniform discretizations.

property integral: NumericArray

integral of each component over space.

Type:

ndarray

interpolate(point: FloatingArray, *, bc: BoundariesData | None = None, fill: Number | None = None) → NumericArray

Interpolate the field to points between support points.

Parameters:
  • point (ndarray) – The points at which the values should be obtained. This is given in grid coordinates.

  • bc – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used to determine values outside the domain. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

Returns:

the values of the field

Return type:

ndarray

interpolate_to_grid(grid: GridBase, *, bc: BoundariesData | None = None, fill: Number | None = None, label: str | None = None) → pde.fields.vectorial.VectorField[source]

Interpolate the data of this vector field to another grid.

Parameters:
  • grid (GridBase) – The grid of the new field onto which the current field is interpolated.

  • bc – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used to determine values outside the domain. 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

  • label (str, optional) – Name of the returned field

Returns:

Field of the same rank as the current one.

property is_complex: bool

whether the field contains real or complex data

Type:

bool

property label: str | None

the name of the field

Type:

str

laplace(bc: BoundariesData | None, out: pde.fields.vectorial.VectorField | None = None, **kwargs) → pde.fields.vectorial.VectorField[source]

Apply vector Laplace operator and return result as a field.

The vector Laplacian is a vector field \(L_\alpha\) containing the second derivatives of the vector field \(v_\alpha\) with respect to the coordinates \(x_\beta\):

\[L_\alpha = \sum_\beta \frac{\partial^2 v_\alpha}{\partial x_\beta \partial x_\beta}\]
Parameters:
  • bc – 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. If the special value None is given, no boundary conditions are enforced. The user then needs to ensure that the ghost cells are set accordingly.

  • out (pde.fields.vectorial.VectorField, optional) – Optional vector field to which the result is written.

  • **kwargs – Additional arguments affecting how the operator behaves.

Returns:

Laplacian of the field

Return type:

VectorField

property magnitude: float

determine the (scalar) magnitude of the field

This is calculated by getting a scalar field using the default arguments of the to_scalar() method, averaging the result over the whole grid, and taking the absolute value.

Type:

float

make_dot_operator(backend: str | pde.backends.base.BackendBase = 'default', *, conjugate: bool = True) → _BinaryOperatorImplType

Return operator calculating the dot product between two fields.

This supports both products between two vectors as well as products between a vector and a tensor.

Parameters:
  • backend (str) – Backend (e.g., numba or numpy) for constructing the operator

  • conjugate (bool) – Whether to use the complex conjugate for the second operand

Returns:

function that takes two instance of ndarray, which contain the discretized data of the two operands. An optional third argument can specify the output array to which the result is written.

make_interpolator(*, fill: Number | None = None, with_ghost_cells: bool = False, backend: str | pde.backends.base.BackendBase = 'default') → Callable[[FloatingArray, NumericArray], NumberOrArray]

Returns a function that can be used to interpolate values.

Parameters:
  • fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.

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

  • backend (str) – The name of the backend to use to implement this operator.

Returns:

A function which returns interpolated values when called with arbitrary positions within the space of the grid.

make_outer_prod_operator(backend: str | pde.backends.base.BackendBase = 'numba') → _BinaryOperatorImplType[source]

Return operator calculating the outer product of two vector fields.

Warning

This function does not check types or dimensions.

Parameters:

backend (str) – The backend (e.g., ‘numba’ or ‘numba_mpi’) used for this operator.

Returns:

function that takes two instance of ndarray, which contain the discretized data of the two operands. An optional third argument can specify the output array to which the result is written.

outer_product(other: pde.fields.vectorial.VectorField, out: pde.fields.tensorial.Tensor2Field | None = None, *, label: str | None = None) → pde.fields.tensorial.Tensor2Field[source]

Calculate the outer product of this vector field with another.

Parameters:
  • other (VectorField) – The second vector field

  • out (Tensor2Field, optional) – Optional tensorial field to which the result is written.

  • label (str, optional) – Name of the returned field

Returns:

result of the operation

Return type:

Tensor2Field

plot(kind: str = 'auto', *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) → PlotReference

Visualize the field.

Parameters:
  • kind (str) – Determines the visualizations. Supported values are image, line, vector, nematic, or interactive. Alternatively, auto determines the best visualization based on the field itself.

  • 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 – All additional keyword arguments are forwarded to the actual plotting function determined by kind.

Returns:

Instance that contains information to update the plot with new data later.

Return type:

PlotReference

Tip

Typical additional arguments for the various plot kinds include

  • kind == "line":

    • scalar: Sets method for extracting scalars as described in DataFieldBase.to_scalar().

    • extract: Method used for extracting the line data.

    • ylabel: Label of the y-axis.

    • ylim: Data limits of the y-axis.

    • Additional arguments are passed to matplotlib.pyplot.plot()

  • kind == "image":

    • colorbar: Determines whether a colorbar is shown

    • scalar: Sets method for extracting scalars as described in

      DataFieldBase.to_scalar().

    • transpose Determines whether the transpose of the data is plotted

    • Most remaining arguments are passed to matplotlib.pyplot.imshow()

  • kind == "vector":

  • kind == "nematic":

    • transpose Determines whether the transpose of the data is plotted

    • max_points Sets max. number of points along each axis

    • Additional arguments are passed to matplotlib.pyplot.quiver()

plot_components(kind: str = 'auto', *args, title: str | None = None, constrained_layout: bool = True, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', fig_style: dict[str, Any] | None = None, fig=None, **kwargs) → list[PlotReference][source]

Visualize all the components of this vector field.

Parameters:
  • kind (str or list of str) – Determines the kind of the visualizations. Supported values are image or line. Alternatively, auto determines the best visualization based on the grid.

  • title (str) – Title of the plot. If omitted, the title might be chosen automatically. This is shown above all panels.

  • constrained_layout (bool) – Whether to use constrained_layout in matplotlib.pyplot.figure() call to create a figure. This affects the layout of all plot elements. Generally, spacing might be better with this flag enabled, but it can also lead to problems when plotting multiple plots successively, e.g., when creating a movie.

  • filename (str, optional) – If given, the figure 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.

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

  • fig (matplotlib.figures.Figure) – Figure that is used for plotting. If omitted, a new figure is created.

  • **kwargs – All additional keyword arguments are forwarded to the actual plotting function of all subplots.

Returns:

Instances that contain information to update all the plots with new data later.

Return type:

list of PlotReference

plot_interactive(viewer_args: dict[str, Any] | None = None, **kwargs) → None

Create an interactive plot of the field using napari

For a detailed description of the launched program, see the napari webpage.

Parameters:
  • viewer_args (dict) – Arguments passed to napari.viewer.Viewer to affect the viewer.

  • **kwargs – Extra arguments passed to the plotting function

classmethod random_harmonic(grid: GridBase, modes: int = 3, harmonic=<ufunc 'cos'>, axis_combination=<ufunc 'multiply'>, *, label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None) → Self

Create a random field build from harmonics.

The resulting fields will be highly correlated in space and can thus serve for testing differential operators.

With the default settings, the resulting field \(c_i(\mathbf{x})\) is given by

\[c_i(\mathbf{x}) = \prod_{\alpha=1}^N \sum_{j=1}^M a_{ij\alpha} \cos\left(\frac{2 \pi x_\alpha}{j L_\alpha}\right) \;,\]

where \(N\) is the number of spatial dimensions, each with length \(L_\alpha\), \(M\) is the number of modes given by modes, and \(a_{ij\alpha}\) are random amplitudes, chosen from a uniform distribution over the interval [0, 1].

Note that the product could be replaced by a sum when axis_combination = numpy.add and the \(\cos()\) could be any other function given by the parameter harmonic.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • modes (int) – Number \(M\) of harmonic modes

  • harmonic (callable) – Determines which harmonic function is used. Typical values are numpy.sin() and numpy.cos(), which basically relate to different boundary conditions applied at the grid boundaries.

  • axis_combination (callable) – Determines how values from different axis are combined. Typical choices are numpy.multiply() and numpy.add() resulting in products and sums of the values along axes, respectively.

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to double.

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

classmethod random_normal(grid: GridBase, mean: float = 0, std: float = 1, *, scaling: Literal['none', 'physical'] = 'none', correlation: CorrelationType = 'none', label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None, **kwargs) → Self

Creates Gaussian random field with normal distributed random values.

A complex field is returned when either mean or std is a complex number. In this case, the real and imaginary parts of these arguments are used to determine the distribution of the real and imaginary parts of the resulting field. Consequently, pde.fields.scalar.ScalarField.random_normal(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard normal distribution.

Real and imaginary parts of fields, as well as all components of vector and tensor fields, are always uncorrelated. Correlations in spatial positions are supported through the correlation argument. If set, the returned field \(f\) obeys the selected correlation function \(C(k)\) (see table below for details). In Fourier space, we thus have

\[\langle f(\boldsymbol k) f(\boldsymbol k’) \rangle = C(|\boldsymbol k|) \delta(\boldsymbol k-\boldsymbol k’)\]

For simplicity, the correlations respect periodic boundary conditions.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • mean (float) – Mean of the Gaussian distribution

  • std (float) – Standard deviation of the Gaussian distribution

  • scaling (str) – Determines how the values are scaled. Possible choices are ‘none’ (values are drawn from a normal distribution with given mean and standard deviation) or ‘physical’ (the variance of the random number is scaled by the inverse volume of the grid cell; this is for instance useful for concentration fields, which vary less in larger cells).

  • correlation (str) – Selects the autocorrelation function to create spatially correlated noise. Many of the options (described below) support additional parameters that can be supplied as keyword arguments.

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to float if both mean and std are real, otherwise it is complex. Note that if a complex dtype is supplied, the mean and std are also assumed to be complex, so that specifying them as real will lead to a vanishing imaginary part of the returned field.

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

  • **kwargs – Additional parameters can affect details of the correlation function. Examples include length_scale, exponent, and sharpness, which are described in the table below.

Supported correlation functions

Identifier

Correlation function

none

No correlation, \(C(k) = \delta(k)\)

gaussian

\(C(k) = \exp(-\frac12 k^2 \lambda^2)\) with the length scale \(\lambda\) set by argument length_scale

power law

\(C(k) = k^{\nu/2}\) with exponent \(\nu\) set by argument exponent.

cosine

\(C(k) = \exp\bigl(-s^2(\lambda k - 1)^2\bigr)\) with the length scale \(\lambda\) set by argument length_scale, whereas the sharpness parameter \(s\) is set by sharpness and defaults to 10.

Note

The returned field only has the correct standard deviation (set by std) for correlation functions that decrease monotonously. In other cases (i.e., for cosine correlation), the variance depends on details, like the resolution of the grid.

classmethod random_uniform(grid: GridBase, vmin: float = 0, vmax: float = 1, *, label: str | None = None, dtype: DTypeLike | None = None, rng: np.random.Generator | None = None) → Self

Create field with uncorrelated uniform distributed random values.

A complex field is returned when vmin or vmax is a complex number. In this case, the real and imaginary parts of these arguments are used to determine the distribution of the real and imaginary parts of the resulting field. Consequently, pde.fields.scalar.ScalarField.random_uniform(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard uniform distribution.

Real and imaginary parts of fields, all components of vector and tensor fields, as well as all spatial positions are always uncorrelated.

Parameters:
  • grid (GridBase) – Grid defining the space on which this field is defined

  • vmin (float) – Lower bound for the random values

  • vmax (float) – Upper bound for the random values

  • label (str, optional) – Name of the returned field

  • dtype (numpy dtype) – The data type of the field. If omitted, it defaults to double if both vmin and vmax are real, otherwise it is complex.

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

property real: Self

Real part of the field.

Type:

FieldBase

set_ghost_cells(bc: BoundariesData, *, args=None, **kwargs) → None

Set the boundary values on virtual points for all boundaries.

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.

  • args – Additional arguments that might be supported by special boundary conditions.

  • **kwargs – Some boundary conditions might provide additional control via keyword arguments, e.g., set_corners to control whether corner cells are set using interpolation.

smooth(sigma: float = 1, *, out: Self | None = None, label: str | None = None) → Self

Applies Gaussian smoothing with the given standard deviation.

This function respects periodic boundary conditions of the underlying grid, using reflection when no periodicity is specified.

Parameters:
  • sigma (float) – Gives the standard deviation of the smoothing in real length units (default: 1)

  • out (FieldBase, optional) – Optional field into which the smoothed data is stored. Setting this to the input field enables in-place smoothing.

  • label (str, optional) – Name of the returned field

Returns:

Field with smoothed data. This is stored at out if given.

split_mpi(decomposition: Literal['auto'] | int | list[int] = 'auto') → Self

Splits the field onto subgrids in an MPI run.

In a normal serial simulation, the method simply returns the field itself. In contrast, in an MPI simulation, the field provided on the main node is split onto all nodes using the given decomposition. The field data provided on all other nodes is not used.

Parameters:

decomposition (list of ints) – Number of subdivision in each direction. Should be a list of length grid.num_axes specifying the number of nodes for this axis. If one value is -1, its value will be determined from the number of available nodes. The default value auto tries to determine an optimal decomposition by minimizing communication between nodes.

Returns:

The part of the field that corresponds to the subgrid associated with the current MPI node.

Return type:

FieldBase

to_file(filename: str, **kwargs) → None

Store field in a file.

The extension of the filename determines what format is being used. If it ends in .h5 or .hdf, the Hierarchical Data Format is used. The other supported format are images, where only the most typical formats are supported.

To load the field back from the file, you may use FieldBase.from_file().

Example

Write a field to a file and then read it back:

field = pde.ScalarField(...)
field.write_to("test.hdf5")

field_copy = pde.FieldBase.from_file("test.hdf5")
Parameters:
  • filename (str) – Path where the data is stored

  • **kwargs – Additional parameters may be supported for some formats

to_scalar(scalar: str | int = 'auto', *, label: str | None = 'scalar `{scalar}`') → ScalarField[source]

Return scalar variant of the field.

Parameters:
  • scalar (str) – Choose the method to use. Possible choices are norm, max, min, squared_sum, norm_squared, or an integer specifying which component is returned (indexing starts at 0). The default value auto picks the method automatically: The first (and only) component is returned for real fields on one-dimensional spaces, while the norm of the vector is returned otherwise.

  • label (str, optional) – Name of the returned field

Returns:

The scalar field after applying the operation

Return type:

pde.fields.scalar.ScalarField

classmethod unserialize_attributes(attributes: dict[str, str]) → dict[str, Any]

Unserializes the given attributes.

Parameters:

attributes (dict) – The serialized attributes

Returns:

The unserialized attributes

Return type:

dict

property writeable: bool

whether the field data can be changed or not

Type:

bool