4.2.2 pde.fields.collection module
Defines a collection of fields to represent multiple fields defined on a common grid.
- class FieldCollection(fields: Sequence[DataFieldBase] | Mapping[str, DataFieldBase], *, label: str | None = None, labels: list[str | None] | _FieldLabels | None = None, dtype: DTypeLike | None = None, copy_fields: bool | None = None)[source]
Bases:
FieldBaseCollection of fields defined on the same grid.
Note
Collections are initialized with a list of individual fields, whose data is copied into the collection, so that changing the original fields will not change the collection. All fields in a collection must have the same data type. This might lead to up-casting, where for instance a combination of a real-valued and a complex-valued field will be both stored as complex fields.
- Parameters:
fields (sequence or mapping of
DataFieldBase) – Sequence or mapping of the individual fields. If a mapping is used, the keys set the names of the individual fields.label (str) – Label of the field collection
labels (list of str) – Labels of the individual fields. If omitted, the labels from the fields argument are used.
dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be automatically determined from the given fields.
copy_fields (bool) – Deprecated option.
- append(*fields: DataFieldBase | FieldCollection, label: str | None = None) FieldCollection[source]
Create new collection with appended field(s)
Warning
Appending fields requires a full copy of the data. Moreover, links to other fields will not be copied, but these links stay with the original collection.
- Parameters:
*fields (FieldCollection or DataFieldBase) – A sequence of single fields or collection of fields that will be appended to the fields in the current collection. The data of all fields will be copied.
label (str) – Label of the new field collection. If omitted, the current label is used
- Returns:
A new field collection, which combines the current one with fields given by fields.
- Return type:
- 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 writtenlabel (str, optional) – Name of the returned field
evaluate_args (dict) – Additional arguments passed to
evaluate(). Only used when func is a string.
- Returns:
Field with new data. Identical to out if given.
- Return type:
DataFieldBase
- assert_field_compatible(other: FieldBase, accept_scalar: bool = False)[source]
Checks whether other is compatible with the current field.
- Parameters:
other (FieldBase) – Other field this is compared to
accept_scalar (bool, optional) – Determines whether it is acceptable that other is an instance of
ScalarField.
- conjugate() Self
Returns complex conjugate of the field.
- Returns:
the complex conjugated field
- Return type:
FieldBase
- copy(*, label: str | None = None, dtype: DTypeLike | None = None) FieldCollection[source]
Return a copy of the data, but not of the grid.
- Parameters:
label (str, optional) – Name of the returned field
dtype (numpy dtype) – The data type of the field. If omitted, it will be determined from data automatically.
- property dtype: DTypeLike
the numpy dtype of the underlying data.
- Type:
DTypeLike
- property fields: list[DataFieldBase]
the fields of this collection
- Type:
- classmethod from_data(field_classes, grid: GridBase, data: NumericArray, *, with_ghost_cells: bool = True, label: str | None = None, labels: list[str | None] | _FieldLabels | None = None, dtype: DTypeLike | None = None) FieldCollection[source]
Create a field collection from classes and data.
- Parameters:
field_classes (list) – List of the classes that define the individual fields
data (
ndarray, optional) – Data values of all fields at support points of the gridgrid (
GridBase) – Grid defining the space on which this field is defined.with_ghost_cells (bool) – Indicates whether the ghost cells are included in data
label (str) – Label of the field collection
labels (list of str) – Labels of the individual fields. If omitted, the labels from the fields argument are used.
dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be determined from data automatically.
- classmethod from_file(filename: str) FieldBase
Create field from data stored in a file.
Field can be written to a file using
FieldBase.to_file().Example
Write a field to a file and then read it back:
field = pde.ScalarField(...) field.write_to("test.hdf5") field_copy = pde.FieldBase.from_file("test.hdf5")
- Parameters:
filename (str) – Path to the file being read
- Returns:
The field with the appropriate sub-class
- Return type:
FieldBase
- classmethod from_scalar_expressions(grid: GridBase, expressions: Sequence[str], *, user_funcs: dict[str, Callable] | None = None, consts: dict[str, NumberOrArray] | None = None, label: str | None = None, labels: Sequence[str] | None = None, dtype: DTypeLike | None = None) FieldCollection[source]
Create a field collection on a grid from given expressions.
Warning
This implementation uses
exec()and should therefore not be used in a context where malicious input could occur.- Parameters:
grid (
GridBase) – Grid defining the space on which this field is definedexpressions (list of str) – A list of mathematical expression, one for each field in the collection. The expressions determine the values as a function of the position on the grid. The expressions may contain standard mathematical functions and they may depend on the axes labels of the grid. More information can be found in the expression documentation.
user_funcs (dict, optional) – A dictionary with user defined functions that can be used in the expression
consts (dict, optional) – A dictionary with user defined constants that can be used in the expression. The values of these constants should either be numbers or
ndarray.label (str, optional) – Name of the whole collection
labels (list of str, optional) – Names of the individual fields
dtype (numpy dtype) – The data type of the field. All the numpy dtypes are supported. If omitted, it will be determined from data automatically.
- classmethod from_state(attributes: dict[str, Any], data: NumericArray | Literal['empty', 'zeros', 'ones'] | None = None) FieldCollection[source]
Create a field collection from given state.
- get_image_data(index: int = 0, **kwargs) dict[str, Any][source]
Return data for plotting an image of the field.
- get_line_data(index: int = 0, scalar: str = 'auto', extract: str = 'auto') dict[str, Any][source]
Return data for a line plot of the field.
- Parameters:
- Returns:
Information useful for performing a line plot of the field
- Return type:
- interpolate_to_grid(grid: GridBase, *, fill: Number | None = None, label: str | None = None) FieldCollection[source]
Interpolate the data of this field collection to another grid.
- Parameters:
grid (
GridBase) – The grid of the new field onto which the current field is interpolated.fill (Number, optional) – Determines how values out of bounds are handled. If None, a ValueError is raised when out-of-bounds points are requested. Otherwise, the given value is returned.
label (str, optional) – Name of the returned field collection
- Returns:
Interpolated data
- Return type:
- property labels: _FieldLabels
the labels of all fields.
Note
The attribute returns a special class
_FieldLabelsto allow specific manipulations of the field labels. The returned object behaves much like a list, but assigning values will modify the labels of the fields in the collection.- Type:
_FieldLabels
- plot(kind: str | Sequence[str] = 'auto', figsize: Literal['auto'] | tuple[float, float] = 'auto', arrangement: Literal['horizontal', 'vertical', 'square'] | tuple[int, int] = 'horizontal', subplot_args=None, *args, title: str | None = None, constrained_layout: bool = True, filename: str | None = None, action: Literal['auto', 'close', 'none', 'sca', 'show'] = 'auto', fig_style: dict[str, Any] | None = None, fig=None, **kwargs) list[PlotReference][source]
Visualize all the fields in the collection.
- Parameters:
kind (str or list of str) – Determines the kind of the visualizations. Supported values are image, line, vector, interactive, or merged. Alternatively, auto determines the best visualization based on each field itself. Instead of a single value for all fields, a list with individual values can be given, unless merged is chosen.
figsize (str or tuple of numbers) – Determines the figure size. The figure size is unchanged if the string default is passed. Conversely, the size is adjusted automatically when auto is passed. Finally, a specific figure size can be specified using two values, using
matplotlib.figure.Figure.set_size_inches().arrangement (str or tuple of int) – Determines how the sub panels will be arranged. The default value horizontal places all subplots next to each other, whereas vertical puts them below each other. Alternatively, an exact number of rows and columns can be specified by the tuple
(nrows, ncols). Negative values will be replaced by suitable values that ensure enough panels.subplot_args (list) – Additional arguments for the specific subplots. Should be a list with a dictionary of arguments for each subplot. Supplying an empty dict allows to keep the default setting of specific subplots.
title (str) – Title of the plot. If omitted, the title might be chosen automatically. This is shown above all panels.
constrained_layout (bool) – Whether to use constrained_layout in
matplotlib.pyplot.figure()call to create a figure. This affects the layout of all plot elements. Generally, spacing might be better with this flag enabled, but it can also lead to problems when plotting multiple plots successively, e.g., when creating a movie.filename (str, optional) – If given, the figure is written to the specified file.
action (str) – Decides what to do with the final figure. If the argument is set to show,
matplotlib.pyplot.show()will be called to show the plot. If the value is none, the figure will be created, but not necessarily shown. The value close closes the figure, after saving it to a file when filename is given. The default value auto implies that the plot is shown if it is not a nested plot call.fig_style (dict) – Dictionary with properties that will be changed on the figure after the plot has been drawn by calling
matplotlib.pyplot.setp(). For instance, using fig_style={‘dpi’: 200} increases the resolution of the figure.fig (
matplotlib.figures.Figure) – Figure that is used for plotting. If omitted, a new figure is created.**kwargs – All additional keyword arguments are forwarded to the actual plotting function of all subplots.
- Returns:
Instances that contain information to update all the plots with new data later.
- Return type:
List of
PlotReference
- plot_interactive(viewer_args: dict[str, Any] | None = None, **kwargs) None
Create an interactive plot of the field using
napariFor a detailed description of the launched program, see the napari webpage.
- Parameters:
viewer_args (dict) – Arguments passed to
napari.viewer.Viewerto affect the viewer.**kwargs – Extra arguments passed to the plotting function
- project(axes: str | Sequence[str], *, label: str | None = None, **kwargs) FieldCollection[source]
Project fields along given axes.
This is currently only implemented for scalar fields. If any field in the collection has higher rank, the entire process fails.
- Parameters:
axes (list of str) – The names of the axes that are removed by the projection operation. The valid names for a given grid are the ones in the
GridBase.axesattribute.label (str, optional) – Name of the returned collection. If omitted, the current label is used.
**kwargs – Additional arguments forwarded to the projection method. In particular, this allows selecting a projection method.
- Returns:
The projected data of all fields on a subgrid of the original grid.
- Return type:
- classmethod scalar_random_normal(num_fields: int, grid: GridBase, mean: float = 0, std: float = 1, *, label: str | None = None, labels: Sequence[str] | None = None, **kwargs) FieldCollection[source]
Creates Gaussian random fields with normal distributed random values.
Details of methods and additional options are described in
random_normal().- Parameters:
num_fields (int) – The number of fields to create
grid (
GridBase) – Grid defining the space on which this field is definedmean (float) – Mean of the Gaussian distribution
std (float) – Standard deviation of the Gaussian distribution
label (str, optional) – Name of the returned field
labels (list of str, optional) – Names of the individual fields
rng (
Generator) – Random number generator (default:default_rng())**kwargs – Additional parameters can affect details of the correlation function.
- classmethod scalar_random_uniform(num_fields: int, grid: GridBase, vmin: float = 0, vmax: float = 1, *, label: str | None = None, labels: Sequence[str] | None = None, rng: np.random.Generator | None = None) FieldCollection[source]
Create scalar fields with random values between vmin and vmax
- Parameters:
num_fields (int) – The number of fields to create
grid (
GridBase) – Grid defining the space on which the fields are definedvmin (float) – Lower bound. Can be complex to create complex fields
vmax (float) – Upper bound. Can be complex to create complex fields
label (str, optional) – Name of the field collection
labels (list of str, optional) – Names of the individual fields
rng (
Generator) – Random number generator (default:default_rng())
- slice(position: dict[str, float], *, label: str | None = None, **kwargs) FieldCollection[source]
Slice all fields at a given position.
This is currently only implemented for scalar fields. If any field in the collection has higher rank, the entire process fails.
- Parameters:
position (dict) – Determines the location of the slice using a dictionary supplying coordinate values for a subset of axes. Axes not mentioned in the dictionary are retained and form the slice. For instance, in a 2d Cartesian grid, position = {‘x’: 1} slices along the y-direction at x=1. Additionally, the special positions ‘low’, ‘mid’, and ‘high’ are supported to reference relative positions along the axis.
label (str, optional) – Name of the returned collection. If omitted, the current label is used.
**kwargs – Additional arguments forwarded to the slicing method (e.g., method).
- Returns:
The projected data of all fields on a subgrid of the original grid.
- Return type:
- smooth(sigma: float = 1, *, out: FieldCollection | None = None, label: str | None = None) FieldCollection[source]
Applies Gaussian smoothing with the given standard deviation.
This function respects periodic boundary conditions of the underlying grid, using reflection when no periodicity is specified.
- Parameters:
sigma (float) – Gives the standard deviation of the smoothing in real length units (default: 1)
out (FieldCollection, optional) – Optional field into which the smoothed data is stored
label (str, optional) – Name of the returned field
- Returns:
Smoothed data, stored at out if given.
- Return type:
- 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