# 4.1.1. pde.fields.base module

Defines base classes of fields, which are discretized on grids

class DataFieldBase(grid, data='zeros', *, label=None, dtype=None, with_ghost_cells=False)[source]

Bases: FieldBase

abstract base class for describing fields of single entities

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_operator(operator, bc, out=None, *, label=None, args=None, **kwargs)[source]

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 (Dict[str, Dict | str | BCBase] | Dict | str | BCBase | Tuple[Dict | str | BCBase, Dict | str | BCBase] | BoundaryAxisBase | Sequence[Dict[str, Dict | str | BCBase] | Dict | str | BCBase | Tuple[Dict | str | BCBase, Dict | str | BCBase] | BoundaryAxisBase] | None) – Boundary conditions applied to the field before applying the operator. Boundary conditions are generally given as a list with one condition for each axis. 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 a tuple of two conditions). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation. 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

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

• args (Dict[str, Any] | None) –

Returns:

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

Return type:

DataFieldBase

property average: int | float | complex | ndarray

determine the average of data

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

copy(*, label=None, dtype=None)[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 or the dtype of the current field is used.

• self (TDataField) –

Return type:

TDataField

property data_shape: Tuple[int, ...]

the shape of the data at each grid point

Type:

tuple

property fluctuations: int | float | complex | ndarray

fluctuations over the entire space.

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:

ndarray

classmethod from_state(attributes, data=None)[source]

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

Return type:

TDataField

get_boundary_values(axis, upper, bc=None)[source]

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 (Dict[str, Dict | str | BCBase] | Dict | str | BCBase | Tuple[Dict | str | BCBase, Dict | str | BCBase] | BoundaryAxisBase | Sequence[Dict[str, Dict | str | BCBase] | Dict | str | BCBase | Tuple[Dict | str | BCBase, Dict | str | BCBase] | BoundaryAxisBase] | None) – The boundary conditions applied to the field. Boundary conditions are generally given as a list with one condition for each axis. 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 a tuple of two conditions). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation. 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)[source]

return a DataFieldBase subclass describing a field with a given rank

Parameters:

rank (int) – The rank of the tensor field

Return type:
get_image_data(scalar='auto', transpose=False, **kwargs)[source]

return data for plotting an image of the field

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

• transpose (bool) – Determines whether the transpose of the data should is plotted

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

Returns:

Information useful for plotting an image of the field

Return type:

dict

get_line_data(scalar='auto', extract='auto')[source]

return data for a line plot of the field

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

get_vector_data(**kwargs)[source]

return data for a vector plot of the field

Parameters:

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

Returns:

Information useful for plotting an vector field

Return type:

dict

insert(point, amount)[source]

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.

Return type:

None

abstract property integral: int | float | complex | ndarray
interpolate(point, *, bc=None, fill=None, **kwargs)[source]

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 (Dict[str, Dict | str | BCBase] | Dict | str | BCBase | Tuple[Dict | str | BCBase, Dict | str | BCBase] | BoundaryAxisBase | Sequence[Dict[str, Dict | str | BCBase] | Dict | str | BCBase | Tuple[Dict | str | BCBase, Dict | str | BCBase] | BoundaryAxisBase] | None) – The boundary conditions applied to the field, which affects values close to the boundary. If omitted, the argument fill is used. Boundary conditions are generally given as a list with one condition for each axis. 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 a tuple of two conditions). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation. 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.

• **kwargs – Additional keyword arguments are forwarded to the method DataFieldBase.make_interpolator().

Returns:

the values of the field

Return type:

ndarray

interpolate_to_grid(grid, *, fill=None, label=None)[source]

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.

• 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

• self (TDataField) –

Returns:

Field of the same rank as the current one.

Return type:

TDataField

property magnitude: float

determine the 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='numba', *, conjugate=True)[source]

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) – Can be numba or numpy, deciding how the function is constructed

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

Return type:

Callable[[ndarray, ndarray, ndarray | None], ndarray]

make_interpolator(*, fill=None, with_ghost_cells=False)[source]

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.

Returns:

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

Return type:
plot(kind='auto', *args, title=None, filename=None, action='auto', ax_style=None, fig_style=None, ax=None, **kwargs)[source]

visualize the field

Parameters:
• kind (str) – Determines the visualizations. Supported values are image, line, vector, 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 none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.

• ax_style (dict) – Dictionary with properties that will be changed on the axis after the plot has been drawn by calling matplotlib.pyplot.setp(). A special item 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

classmethod random_colored(grid, exponent=0, scale=1, *, label=None, dtype=None, rng=None)[source]

create a field of random values with colored noise

The spatially correlated values obey

$\langle c_i(\boldsymbol k) c_j(\boldsymbol k’) \rangle = \Gamma^2 |\boldsymbol k|^\nu \delta_{ij} \delta(\boldsymbol k - \boldsymbol k’)$

in spectral space, where $$\boldsymbol k$$ is the wave vector. The special case $$\nu = 0$$ corresponds to white noise. Note that the spatial correlations always assume periodic boundary conditions (even if the underlying grid does not) and that the components of tensor fields are uncorrelated.

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

• exponent (float) – Exponent $$\nu$$ of the power spectrum

• scale (float) – Scaling factor $$\Gamma$$ determining noise strength

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

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

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

Return type:

TDataField

classmethod random_harmonic(grid, modes=3, harmonic=<ufunc 'cos'>, axis_combination=<ufunc 'multiply'>, *, label=None, dtype=None, rng=None)[source]

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 field

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

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

Return type:

TDataField

classmethod random_normal(grid, mean=0, std=1, *, scaling='none', label=None, dtype=None, rng=None)[source]

create field with normal distributed random values

These values are uncorrelated in space. 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, ScalarField.random_normal(grid, 0, 1 + 1j) creates a complex field where the real and imaginary parts are chosen from a standard normal distribution.

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 volumes).

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

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

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

Return type:

TDataField

classmethod random_uniform(grid, vmin=0, vmax=1, *, label=None, dtype=None, rng=None)[source]

create field with uniform distributed random values

These values are uncorrelated in space.

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

• vmin (float) – Smallest possible random value

• vmax (float) – Largest random value

• label (str, optional) – Name of the 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())

Return type:

TDataField

rank: int
set_ghost_cells(bc, *, args=None)[source]

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 list with one condition for each axis. 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 a tuple of two conditions). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

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

Return type:

None

smooth(sigma=1, *, out=None, label=None)[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.

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.

Parameters:
• self (TDataField) –

• sigma (float) –

• out (TDataField | None) –

• label (str | None) –

Return type:

TDataField

abstract to_scalar(scalar='auto', *, label=None)[source]
Parameters:
• scalar (str) –

• label (str | None) –

Return type:

ScalarField

classmethod unserialize_attributes(attributes)[source]

unserializes the given attributes

Parameters:

attributes (dict) – The serialized attributes

Returns:

The unserialized attributes

Return type:

dict

class FieldBase(grid, data, *, label=None)[source]

Bases: object

abstract base class for describing (discretized) fields

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

• data (ndarray, optional) – Field values at the support points of the grid and the ghost cells

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

apply(func, out=None, label=None)[source]

applies a function to the data and returns it as a field

Parameters:
• func (callable or str) – The (vectorized) function being applied to the data or the name of an operator that is defined for the grid of this field.

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

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

• self (TField) –

Returns:

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

Return type:

TField

assert_field_compatible(other, accept_scalar=False)[source]

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

conjugate()[source]

returns complex conjugate of the field

Parameters:

self (TField) –

Return type:

TField

abstract copy(*, label=None, dtype=None)[source]
Parameters:
Return type:

TField

property data: ndarray

discretized data at the support points

Type:

ndarray

property dtype: dtype[Any] | None | Type[Any] | _SupportsDType[dtype[Any]] | str | Tuple[Any, int] | Tuple[Any, SupportsIndex | Sequence[SupportsIndex]] | List[Any] | _DTypeDict | Tuple[Any, Any]

the numpy dtype of the underlying data

Type:

DTypeLike

classmethod from_file(filename)[source]

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, data=None)[source]

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

Return type:

FieldBase

abstract get_image_data()[source]
Return type:

Dict[str, Any]

abstract get_line_data(scalar='auto', extract='auto')[source]
Parameters:
• scalar (str) –

• extract (str) –

Return type:

Dict[str, Any]

property grid: GridBase

The grid on which the field is defined

Type:

GridBase

property imag: TField

Imaginary part of the field

Type:

FieldBase

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

abstract plot(*args, **kwargs)[source]
plot_interactive(viewer_args=None, **kwargs)[source]

create an interactive plot of the field using napari

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

Parameters:
property real: TField

Real part of the field

Type:

FieldBase

split_mpi(decomposition=-1)[source]

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 field.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 decomposed the first axis using all available nodes

• self (TField) –

Returns:

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

Return type:

FieldBase

to_file(filename, **kwargs)[source]

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)[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

exception RankError[source]

Bases: TypeError

error indicating that the field has the wrong rank