4.1.1. pde.fields.base module

Defines base classes of fields, which are discretized on grids

class DataFieldBase(grid: GridBase, data: Optional[Union[int, float, complex, ndarray, Sequence[Union[int, float, complex, ndarray]], Sequence[Sequence[Any]], str]] = 'zeros', *, label: str = None, dtype=None, with_ghost_cells: bool = 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

add_interpolated(point: ndarray, amount: Union[int, float, complex, ndarray, Sequence[Union[int, float, complex, ndarray]], Sequence[Sequence[Any]]]) None[source]

deprecated alias of method insert

property average: Union[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: str = None, dtype=None) TDataField[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.

property data_shape: Tuple[int, ...]

the shape of the data at each grid point

Type

tuple

property fluctuations: Union[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: Dict[str, Any], data: Optional[ndarray] = None) TDataField[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

get_boundary_values(axis: int, upper: bool, bc: Optional[Union[Dict[str, Union[Dict, str, BCBase]], Dict, str, BCBase, Tuple[Union[Dict, str, BCBase], Union[Dict, str, BCBase]], Sequence[Union[Dict[str, Union[Dict, str, BCBase]], Dict, str, BCBase, Tuple[Union[Dict, str, BCBase], Union[Dict, str, BCBase]]]]]] = None) Union[int, float, complex, ndarray][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 – The boundary conditions applied to the field. Boundary conditions are generally given as a list with one condition for each axis. For periodic axis, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using a tuple of two conditions). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation. 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][source]

return a DataFieldBase subclass describing a field with a given rank

Parameters

rank (int) – The rank of the tensor field

get_image_data(scalar: str = 'auto', transpose: bool = False, **kwargs) Dict[str, Any][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: str = 'auto', extract: str = 'auto') Dict[str, Any][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) Dict[str, Any][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: ndarray, amount: Union[int, float, complex, ndarray, Sequence[Union[int, float, complex, ndarray]], Sequence[Sequence[Any]]]) None[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.

abstract property integral: Union[int, float, complex, ndarray]
interpolate(point: ndarray, *, backend: str = 'numba', method: str = 'linear', fill: Optional[Number] = None, **kwargs) Union[int, float, complex, ndarray][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.

  • backend (str) – The accepted values “scipy” and “numba” determine the backend that is used for the interpolation.

  • method (str) – Determines the method being used for interpolation. Typical values that are “nearest” and “linear”, but the supported values depend on the chosen backend.

  • 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: GridBase, *, backend: str = 'numba', method: str = 'linear', fill: Optional[Number] = None, label: str = None) TDataField[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.

  • backend (str) – The accepted values “scipy” and “numba” determine the backend that is used for the interpolation.

  • method (str) – Determines the method being used for interpolation. Typical values that are “nearest” and “linear”, but the supported values depend on the chosen backend.

  • 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 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_interpolator(method: str = 'linear', *, fill: Number = None, backend: str = 'numba', **kwargs) Callable[[ndarray, ndarray], Union[int, float, complex, ndarray]][source]

returns a function that can be used to interpolate values.

Parameters
  • backend (str) – The accepted values scipy and numba determine the backend that is used for the interpolation.

  • method (str) – Determines the method being used for interpolation. Typical values that are “nearest” and “linear”, but the supported values depend on the chosen backend.

  • 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 passed to the individual interpolator methods and can be used to further affect the behavior.

The scipy implementations use scipy.interpolate.RegularGridInterpolator and thus do not respect boundary conditions. Additional keyword arguments are directly forwarded to the constructor of RegularGridInterpolator.

The numba implementation respect boundary conditions, which can be set using the bc keywords argument. Supported values are the same as for the operators, e.g., the Laplacian. If no boundary conditions are specified, natural boundary conditions are assumed, which are periodic conditions for periodic axes and Neumann conditions otherwise.

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, filename: str = None, action: str = 'auto', ax_style: Optional[Dict[str, Any]] = None, fig_style: Optional[Dict[str, Any]] = None, ax=None, **kwargs) PlotReference[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 in this dictionary is use_offset, which is flag that can be used to control whether offset are shown along the axes of the plot.

  • fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.

  • ax (matplotlib.axes.Axes) – Figure axes to be used for plotting. The special value “create” creates a new figure, while “reuse” attempts to reuse an existing figure, which is the default.

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

Returns

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

Return type

PlotReference

classmethod random_colored(grid: GridBase, exponent: float = 0, scale: float = 1, *, label: str = None, dtype=None, rng: Optional[Generator] = None) TDataField[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 components of vector or 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())

classmethod random_harmonic(grid: ~GridBase, modes: int = 3, harmonic=<ufunc 'cos'>, axis_combination=<ufunc 'multiply'>, *, label: ~str = None, dtype=None, rng: ~Optional[~numpy.random._generator.Generator] = None) TDataField[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())

classmethod random_normal(grid: GridBase, mean: float = 0, std: float = 1, *, scaling: str = 'none', label: str = None, dtype=None, rng: Optional[Generator] = None) TDataField[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())

classmethod random_uniform(grid: GridBase, vmin: float = 0, vmax: float = 1, *, label: str = None, dtype=None, rng: Optional[Generator] = None) TDataField[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())

rank: int
set_ghost_cells(bc: Union[Dict[str, Union[Dict, str, BCBase]], Dict, str, BCBase, Tuple[Union[Dict, str, BCBase], Union[Dict, str, BCBase]], Sequence[Union[Dict[str, Union[Dict, str, BCBase]], Dict, str, BCBase, Tuple[Union[Dict, str, BCBase], Union[Dict, str, BCBase]]]]], *, normal: bool = False, args=None) 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 axis, only periodic boundary conditions are allowed (indicated by ‘periodic’ and ‘anti-periodic’). For non-periodic axes, different boundary conditions can be specified for the lower and upper end (using a tuple of two conditions). For instance, Dirichlet conditions enforcing a value NUM (specified by {‘value’: NUM}) and Neumann conditions enforcing the value DERIV for the derivative in the normal direction (specified by {‘derivative’: DERIV}) are supported. Note that the special value ‘natural’ imposes periodic boundary conditions for periodic axis and a vanishing derivative otherwise. More information can be found in the boundaries documentation.

  • normal (bool) – Flag indicating whether the condition is only applied in the normal direction.

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

smooth(sigma: float = 1, *, out: Optional[TDataField] = None, label: str = None) TDataField[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.

abstract to_scalar(scalar: str = 'auto', *, label: str = None) ScalarField[source]
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

class FieldBase(grid: GridBase, data: ndarray, *, label: str = 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: Callable, out: Optional[TField] = None, label: str = None) TField[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

Returns

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

assert_field_compatible(other: FieldBase, accept_scalar: bool = 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() TField[source]

returns complex conjugate of the field

abstract copy(*, label: str = None, dtype=None) TField[source]
property data: ndarray

discretized data at the support points

Type

ndarray

property dtype

returns the numpy dtype of the underlying data

classmethod from_file(filename: str) FieldBase[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: Dict[str, Any], data: Optional[ndarray] = None) FieldBase[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

abstract get_image_data() Dict[str, Any][source]
abstract get_line_data(scalar: str = 'auto', extract: str = 'auto') Dict[str, Any][source]
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: Optional[str]

the name of the field

Type

str

abstract plot(*args, **kwargs)[source]
plot_interactive(viewer_args: Optional[Dict[str, Any]] = 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
  • viewer_args (dict) – Arguments passed to napari.viewer.Viewer to affect the viewer.

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

property real: TField

Real part of the field

Type

FieldBase

to_file(filename: str, **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: 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

exception RankError[source]

Bases: TypeError

error indicating that the field has the wrong rank