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 (BoundariesData | 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
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:
- property average: int | float | complex | ndarray
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
- copy(*, label=None, dtype=None)[source]
return a new field with the data (but not the grid) copied
- 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) –
- Returns:
A copy of the current field
- Return type:
- property fluctuations: int | float | complex | ndarray
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:
- Type:
float or
ndarray
- classmethod from_state(attributes, data=None)[source]
create a field from given state.
- Parameters:
- Returns:
The instance created from the stored state
- Return type:
- 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 (BoundariesData | 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:
- 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
- Returns:
The DataField class that corresponds to the rank
- 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:
- 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:
- 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
integral of the scalar field over space
- interpolate(point, *, bc=None, fill=None)[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 (BoundariesData | None) – 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 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.
- Returns:
the values of the field
- Return type:
- interpolate_to_grid(grid, *, bc=None, 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.bc (BoundariesData | None) – 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 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.
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 (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:
- 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:
- 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:
- 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:
Callable[[ndarray, ndarray], int | float | complex | ndarray]
- 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:
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
transpose Determines whether the transpose of the data is plotted
Most remaining arguments are passed to
matplotlib.pyplot.imshow()
kind == `"vector"
:method Can be either quiver or streamplot
transpose Determines whether the transpose of the data is plotted
max_points Sets max. number of points along each axis in quiver plots
Additional arguments are passed to
matplotlib.pyplot.quiver()
ormatplotlib.pyplot.streamplot()
.
- 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 definedexponent (float) – Exponent \(\nu\) of the power spectrum
scale (float) – Scaling factor \(\Gamma\) determining noise strength
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()
)
- 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 definedmodes (int) – Number \(M\) of harmonic modes
harmonic (callable) – Determines which harmonic function is used. Typical values are
numpy.sin()
andnumpy.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()
andnumpy.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()
)
- 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 definedmean (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 returned 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 definedvmin (float) – Smallest possible random value
vmax (float) – Largest random value
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()
)
- Return type:
TDataField
- 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.
- 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
self (TDataField) –
- Returns:
Field with smoothed data. This is stored at out if given.
- Return type:
TDataField
- class FieldBase(grid, data, *, label=None)[source]
Bases:
object
abstract base class for describing (discretized) fields
- Parameters:
- apply(func, out=None, *, label=None, evaluate_args=None)[source]
applies a function/expression to the data and returns it as a field
- Parameters:
func (callable or str) – The (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 (FieldBase, 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.self (TField) –
- Returns:
Field with new data. Identical to out if given.
- Return type:
- assert_field_compatible(other, accept_scalar=False)[source]
checks whether other is compatible with the current field
- conjugate()[source]
returns complex conjugate of the field
- Returns:
the complex conjugated field
- Return type:
- Parameters:
self (TField) –
- abstract copy(*, label=None, dtype=None)[source]
return a new field with the data (but not the grid) copied
- 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 (TField) –
- Returns:
A copy of the current field
- Return type:
- 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")
- abstract get_image_data()[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:
- abstract 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:
- 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:
viewer_args (dict) – Arguments passed to
napari.viewer.Viewer
to affect the viewer.**kwargs – Extra arguments passed to the plotting function
- Return type:
None
- 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:
- 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
- Return type:
None