4.2.4 pde.fields.scalar module

Defines a scalar field over a grid.

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