4.1.6.2 pde.backends.torch.backend module
Defines the torch backend.
This backend prefers functional internal operator implementations. Raw operators are
expected to follow operator_raw(arr_full, *[, args]) -> result and return new data.
The public interface remains functional-first and rejects out for differential
operators on this backend.
- class TorchBackend(config: ConfigLike | None = None, *, name: str | None = None, device: str = 'config')[source]
Bases:
BackendBase[Tensor]Defines
torchbackend.Initialize the torch backend.
- Parameters:
- compile_function(func: TFunc, *, to_device: bool = False, **kwargs) TFunc[source]
General method that compiles a user function.
- Parameters:
func (callable) – The function that needs to be compiled for this backend
to_device (bool) – Moves (compiled) function to device
**kwargs – Additional keyword arguments forwarded to
torch.compile()
- classmethod from_args(config: ConfigLike | None, args: str = '', *, name: str | None = None) Self[source]
Initialize backend with extra arguments.
- get_numpy_dtype(dtype: DTypeLike) np.dtype[source]
Determine numpy dtype suitable for the torch backend.
- Parameters:
dtype – numpy dtype to convert to supported dtype
- Returns:
A numpy dtype that is compatible with the torch backend
- Return type:
- get_operator_info(grid: GridBase, operator: str | OperatorInfo) OperatorInfo
Return an operator for a particular grid.
- Parameters:
grid (
GridBase) – Grid for which the operator is neededoperator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the
operatorsattribute.
- Returns:
information for the operator
- Return type:
OperatorInfo
- get_registered_operators(grid_id: GridBase | type[GridBase]) set[str]
Returns all operators defined for a grid.
- Parameters:
grid_id (
GridBaseor its type) – Grid or grid class for which the operators need to be returned
- get_torch_dtype(dtype: DTypeLike) torch.dtype[source]
Convert dtype to torch dtype.
The torch dtype might be narrower than the corresponding numpy dtype if the configuration parameter dtype_downcasting is enabled.
- Parameters:
dtype – numpy dtype to convert to corresponding torch dtype
- Returns:
A proper dtype for torch
- Return type:
- make_data_setter(grid: GridBase, rank: int, bcs: BoundariesBase | None = None) DataSetter
Create a function to set the valid part of a full data array.
- Parameters:
grid (
GridBase) – Grid for which the data setter is definedrank (int) – Rank of the data represented on the grid
bcs (
BoundariesBase, optional) – If supplied, the returned function also enforces boundary conditions by setting the ghost cells to the correct values
- Returns:
Takes two numpy arrays, setting the valid data in the first one, using the second array. The arrays need to be allocated already and they need to have the correct dimensions, which are not checked. If bcs are given, a third argument is allowed, which sets arguments for the BCs.
- Return type:
callable
- make_expression_function(expression: ExpressionBase, *, single_arg: bool = False, user_funcs: dict[str, Callable] | None = None) Callable[..., NumberOrArray][source]
Return a function evaluating an expression.
- Parameters:
expression (
ExpressionBase) – The expression that is converted to a functionsingle_arg (bool) – Determines whether the returned function accepts all variables in a single argument as an array or whether all variables need to be supplied separately.
user_funcs (dict) – Additional functions that can be used in the expression.
- Returns:
the function
- Return type:
function
- make_full_data_setter(bcs: BoundariesBase) DataSetter
Create a function to set the valid part of a full data array.
- Parameters:
bcs (
BoundariesBase, optional) – If supplied, the returned function also enforces boundary conditions by setting the ghost cells to the correct values- Returns:
Takes two numpy arrays, setting the valid data in the first one, using the second array. The arrays need to be allocated already and they need to have the correct dimensions, which are not checked. If bcs are given, a third argument is allowed, which sets arguments for the BCs.
- Return type:
callable
- make_gaussian_noise(field: TField, *, rng: np.random.Generator) Callable[[], torch.Tensor][source]
Create a function generating Gaussian white noise.
- Parameters:
field (
FieldBase) – An example for the state from which the grid and other information can be extractedrng (
Generator) – Random number generator (default:default_rng()) used to initialize the seed.
- make_ghost_cell_setter(bcs: BoundariesBase) GhostCellSetter
Return function that sets the ghost cells on a full array.
- Parameters:
bcs (
BoundariesBase) – Defines the boundary conditions for a particular grid, for which the setter should be defined.- Returns:
Callable with signature
(data_full: NumericArray, args=None), which sets the ghost cells of the full data, potentially using additional information in args (e.g., the time t during solving a PDE)
- make_inner_prod_operator(field: DataFieldBase, *, conjugate: bool = True) Callable[[torch.Tensor, torch.Tensor, torch.Tensor | None], torch.Tensor][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:
field (
DataFieldBase) – Field for which the inner product is definedconjugate (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_integrator(grid: GridBase, *, dtype: DTypeLike = <class 'numpy.float64'>) Callable[[torch.Tensor], torch.Tensor][source]
Return function that integrates discretized data over a grid.
- Parameters:
grid (
GridBase) – Grid for which the integrator is defineddtype – The data type of the field that is being integrated
- Returns:
A function that takes a numpy array and returns the integral with the correct weights given by the cell volumes.
- make_interpolator(field: DataFieldBase, *, fill: Number | None = None, with_ghost_cells: bool = False) Callable[[FloatingArray, NumericArray], NumberOrArray]
Returns a function that can be used to interpolate values.
- Parameters:
field (
DataFieldBase) – Field for which the interpolator is definedfill (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.
- make_mpi_synchronizer(operator: int | str = 'MAX') Callable[[float], float]
Return function that synchronizes values between multiple MPI processes.
Warning
The default implementation does not synchronize anything. This is simply a hook, which can be used by backends that support MPI
- make_operator(grid: GridBase, operator: str | OperatorInfo, *, bcs: BoundariesBase, dtype: DTypeLike | None = None, **kwargs) OperatorType[source]
Return a torch function applying an operator with boundary conditions.
- Parameters:
grid (
GridBase) – Grid for which the operator is neededoperator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the
operatorsattribute.bcs (
BoundariesBase, optional) – The boundary conditions used before the operator is applieddtype (numpy dtype) – The data type of the field.
**kwargs – Specifies extra arguments influencing how the operator is created.
Warning
The same operator should not be assigned to different variables that are used in the same code, because
torchhas problems compiling the resulting code. This particularly precludes caching the operators, since they then might be reused, e.g., if boundary conditions agree between different operators.- Returns:
the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray = None, args=None).
- Return type:
callable
Internally, raw operator implementations are expected to use the functional signature
operator_raw(arr_full[, args]) -> result.
- make_operator_no_bc(grid: GridBase, operator: str | OperatorInfo, *, dtype: DTypeLike | None = None, **kwargs) OperatorType[source]
Return a compiled function applying an operator without boundary conditions.
A function that takes the discretized full data as an input and an array of valid data points to which the result of applying the operator is written.
Note
The resulting function does not check whether the ghost cells of the input array have been supplied with sensible values. It is the responsibility of the user to set the values of the ghost cells beforehand. Use this function only if you absolutely know what you’re doing. In all other cases,
make_operator()is probably the better choice.- Parameters:
grid (
GridBase) – Grid for which the operator is neededoperator (str) – Identifier for the operator. Some examples are ‘laplace’, ‘gradient’, or ‘divergence’. The registered operators for this grid can be obtained from the
operatorsattribute.dtype (numpy dtype) – The data type of the field.
**kwargs – Specifies extra arguments influencing how the operator is created.
- Returns:
the function that applies the operator. This function has the signature (arr: NumericArray, out: NumericArray=None, args=None). Since torch arrays are immutable in this context, supplying out raises an error.
- Return type:
callable
Internally, raw operator implementations are expected to use the functional signature
operator_raw(arr_full[, args]) -> result.
- make_outer_prod_operator(field: DataFieldBase) Callable[[torch.Tensor, torch.Tensor, torch.Tensor | None], torch.Tensor][source]
Return operator calculating the outer product between two fields.
This supports typically only supports products between two vector fields.
- Parameters:
field (
DataFieldBase) – Field for which the outer product is defined- 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_pde_rhs(eq: PDEBase, state: TField) TorchRHSType[source]
Return a function for evaluating the right hand side of the PDE.
- Parameters:
eq (
PDEBase) – The object describing the differential equationstate (
FieldBase) – An example for the state from which information can be extracted
- Returns:
Function returning deterministic part of the right hand side of the PDE.
- make_stepper(solver: SolverBase, state: TField) StepperType[source]
Create a field-based stepping function for a given solver.
- Parameters:
solver (
SolverBase) – The solver instance, which determines how the stepper is constructedstate (
FieldBase) – An example for the state from which the grid and other information can be extracted
- Returns:
Function that can be called to advance the state from time t_start to time t_end. The function call signature is (state: numpy.ndarray, t_start: float, t_end: float)
- make_valid_data_setter(grid: GridBase, rank: int) DataSetter
Create a function to set the valid part of a full data array.
- Parameters:
grid (
GridBase) – Grid for which the data setter is definedrank (int) – Rank of the data represented on the grid
- Returns:
Takes two numpy arrays, setting the valid data in the first one, using the second array. The arrays need to be allocated already and they need to have the correct dimensions, which are not checked. If bcs are given, a third argument is allowed, which sets arguments for the BCs.
- Return type:
callable
- numpy_to_native(value: Any) Tensor[source]
Convert values from numpy to torch representation.
This method also ensures that the value is copied to the selected device.
- classmethod register_operator(grid_cls: type[GridBase], name: str, factory_func: OperatorFactory | None = None, *, rank_in: int = 0, rank_out: int = 0)
Register an operator for a particular grid.
Example
The method can either be used directly:
BackendClass.register_operator(grid_class, "operator", make_operator)
or as a decorator for the factory function:
@BackendClass.register_operator(grid_class, "operator") def make_operator(grid: GridBase): ...
- Parameters:
grid_cls (
GridBase) – Grid class for which the operator is definedname (str) – The name of the operator to register
factory_func (callable) – A function with signature
(grid: GridBase, **kwargs), which takes a grid object and optional keyword arguments and returns an implementation of the given operator. This implementation is a function that takes andarrayof discretized values as arguments and returns the resulting discretized data in andarrayafter applying the operator.rank_in (int) – The rank of the input field for the operator
rank_out (int) – The rank of the field that is returned by the operator