backend.base#
AbstractBackend ABC, @passthrough decorator, and BackendCapabilityError.
Kramer Harrison, 2025
Functions
|
Inject concrete passthrough methods into the decorated class. |
Classes
Abstract base class that defines the full backend contract. |
Exceptions
Raised when an operation is not supported by the current backend. |
- class AbstractBackend[source]#
Abstract base class that defines the full backend contract.
All backends must subclass this class and implement every abstract method. Concrete passthrough methods (injected by @passthrough) delegate to
self._lib.<name>(...); subclasses may override them.- Variables:
_lib (ModuleType) – The underlying library module (
numpyortorch).
- abstractmethod arange(*args: Any, **kwargs: Any) Any[source]#
Return evenly spaced values within a given interval.
- abstractmethod arange_indices(start: Any, stop: Any = None, step: int = 1) Any[source]#
Return an integer array of indices.
- abstractmethod argmin(x: Any, axis: int | None = None) Any[source]#
Return indices of the minimum values along an axis.
- abstractmethod asarray(x: Any, **kwargs: Any) Any[source]#
Convert x to a backend array without copying if possible.
- abstractmethod batched_chain_matmul3(a: Any, b: Any, c: Any) Any[source]#
Compute a @ b @ c with promoted dtype.
- abstractmethod broadcast_to(x: Any, shape: Sequence[int]) Any[source]#
Broadcast x to the given shape.
- abstractmethod clip(x: Any, a_min: Any, a_max: Any) Any[source]#
Clip the values in x to [a_min, a_max].
- abstractmethod concatenate(arrays: Sequence[Any], axis: int = 0) Any[source]#
Join arrays along an existing axis.
- abstractmethod cross(a: Any, b: Any, axisa: int = -1, axisb: int = -1, axisc: int = -1, axis: int | None = None) Any[source]#
Return the cross product of two vectors.
- abstractmethod default_rng(seed: int | None = None) Any[source]#
Return a random number generator seeded with seed.
- abstractmethod diff(x: Any, n: int = 1, axis: int = -1, **kwargs: Any) Any[source]#
Calculate the n-th discrete difference along the given axis.
- abstractmethod empty(shape: Sequence[int]) Any[source]#
Return a new uninitialized array of the given shape.
- abstractmethod empty_like(x: Any) Any[source]#
Return an uninitialized array with the same shape as x.
- abstractmethod expand_dims(x: Any, axis: int) Any[source]#
Expand the shape of x by inserting a new axis.
- abstractmethod fftconvolve(in1: Any, in2: Any, mode: str = 'full') Any[source]#
FFT-based convolution.
- abstractmethod full(shape: Sequence[int], fill_value: Any, dtype: Any = None) Any[source]#
Return a new array of the given shape filled with fill_value.
- abstractmethod full_like(x: Any, fill_value: Any) Any[source]#
Return a full array with the same shape as x.
- get_complex_precision() Any[source]#
Return the complex dtype matching the current precision (torch only).
- Raises:
BackendCapabilityError – Always, on non-torch backends.
- get_device() str[source]#
Return the current compute device (torch only).
- Raises:
BackendCapabilityError – Always, on non-torch backends.
- abstractmethod grid_sample(input: Any, grid: Any, mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: bool = False) Any[source]#
Sample input using bilinear/nearest interpolation on a grid.
- abstractmethod histogram2d(x: Any, y: Any, bins: Any, weights: Any = None) tuple[Any, Any, Any][source]#
Compute a 2-D histogram.
- abstractmethod is_array_like(x: Any) bool[source]#
Return True if x is a list, tuple, or backend array.
- abstractmethod isclose(a: Any, b: Any, rtol: float = 1e-05, atol: float = 1e-08) Any[source]#
Return a boolean array where elements are close.
- abstractmethod linspace(start: float, stop: float, num: int = 50) Any[source]#
Return evenly spaced numbers over the specified interval.
- abstractmethod matrix_vector_multiply_and_squeeze(p: Any, E: Any) Any[source]#
Multiply p @ E[…, newaxis] and squeeze the trailing dimension.
- abstractmethod mean(x: Any, axis: int | None = None, keepdims: bool = False) Any[source]#
Compute the arithmetic mean, ignoring NaNs.
- abstractmethod meshgrid(*arrays: Any) tuple[Any, ...][source]#
Return coordinate matrices from coordinate vectors.
- abstractmethod mult_p_E(p: Any, E: Any) Any[source]#
Complex matrix-vector multiply used for polarized fields.
- abstractmethod nanmax(x: Any, axis: int | None = None, keepdim: bool = False) Any[source]#
Return the maximum, ignoring NaNs.
- abstractmethod nearest_nd_interpolator(points: Any, values: Any, x: Any, y: Any) Any[source]#
Nearest-neighbour interpolation on an N-D dataset.
- abstractmethod ones(shape: Sequence[int], dtype: Any = None) Any[source]#
Return a new array of the given shape filled with ones.
- abstractmethod ones_like(x: Any) Any[source]#
Return an array of ones with the same shape and type as x.
- abstractmethod pad(tensor: Any, pad_width: Any, mode: str = 'constant', constant_values: float | None = 0) Any[source]#
Pad an array.
- abstractmethod path_contains_points(vertices: Any, points: Any) Any[source]#
Return a boolean mask of points inside the polygon.
- abstractmethod random_normal(loc: float = 0.0, scale: float = 1.0, size: Any = None, generator: Any = None) Any[source]#
Random samples from a normal (Gaussian) distribution.
- abstractmethod random_uniform(low: float = 0.0, high: float = 1.0, size: Any = None, generator: Any = None) Any[source]#
Uniform random samples in [low, high).
- abstractmethod reshape(x: Any, shape: Sequence[int]) Any[source]#
Return x reshaped to the given shape.
- abstractmethod roll(x: Any, shift: Any, axis: Any = ()) Any[source]#
Roll x elements along the given axis.
- set_device(device: str) None[source]#
Set the compute device (torch only).
- Parameters:
device – Device string (e.g.
'cpu'or'cuda').- Raises:
BackendCapabilityError – Always, on non-torch backends.
- abstractmethod set_precision(precision: Literal['float32', 'float64']) None[source]#
Set the floating-point precision used by this backend.
- Parameters:
precision – Either
'float32'or'float64'.
- abstractmethod sobol_sampler(dim: int, num_samples: int, scramble: bool = True, seed: int | None = None) Any[source]#
Generate quasi-random samples using Sobol sequences.
- abstractmethod stack(xs: Sequence[Any], axis: int = 0) Any[source]#
Join a sequence of arrays along a new axis.
- abstractmethod std(x: Any, axis: int | None = None) Any[source]#
Compute the standard deviation along the given axis.
- abstractmethod sum(x: Any, axis: int | None = None) Any[source]#
Sum array elements over a given axis.
- to_tensor(data: Any, device: Any = None) Any[source]#
Convert data to a backend tensor with current precision (torch only).
- Raises:
BackendCapabilityError – Always, on non-torch backends.
- abstractmethod transpose(x: Any, axes: Sequence[int] | None = None) Any[source]#
Permute the dimensions of x.
- abstractmethod vectorize(pyfunc: Callable[..., Any]) Callable[..., Any][source]#
Vectorize a scalar function over array inputs.
- abstractmethod where(condition: Any, x: Any, y: Any) Any[source]#
Return elements chosen from x or y depending on condition.
- exception BackendCapabilityError[source]#
Raised when an operation is not supported by the current backend.
Example
>>> be.grad_mode.enable() # on numpy backend BackendCapabilityError: grad_mode requires a backend that supports gradients. Current backend: 'numpy'. Try: be.set_backend('torch')
- passthrough(*func_names: str)[source]#
Inject concrete passthrough methods into the decorated class.
For each name in func_names, adds a method that calls
self._lib.<name>(*args, **kwargs). Only injected if the class does not already define the method — explicit overrides always take priority.- Parameters:
*func_names – Names of functions to inject from the backend library.
- Returns:
A class decorator that injects the passthrough methods.