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.- _lib
The underlying library module (
numpyortorch).- Type:
ModuleType
- abs(*args: Any, **kwargs: Any) Any
- allclose(*args: Any, **kwargs: Any) Any
- abstract arange(*args: Any, **kwargs: Any) Any[source]
Return evenly spaced values within a given interval.
- abstract arange_indices(start: Any, stop: Any = None, step: int = 1) Any[source]
Return an integer array of indices.
- arccos(*args: Any, **kwargs: Any) Any
- arcsin(*args: Any, **kwargs: Any) Any
- arctan(*args: Any, **kwargs: Any) Any
- arctan2(*args: Any, **kwargs: Any) Any
- abstract argmin(x: Any, axis: int | None = None) Any[source]
Return indices of the minimum values along an axis.
- abstract asarray(x: Any, **kwargs: Any) Any[source]
Convert x to a backend array without copying if possible.
- property autograd: Any
The autograd submodule (torch only).
- abstract batched_chain_matmul3(a: Any, b: Any, c: Any) Any[source]
Compute a @ b @ c with promoted dtype.
- ceil(*args: Any, **kwargs: Any) Any
- column_stack(*args: Any, **kwargs: Any) Any
- abstract concatenate(arrays: Sequence[Any], axis: int = 0) Any[source]
Join arrays along an existing axis.
- conj(*args: Any, **kwargs: Any) Any
- copy(*args: Any, **kwargs: Any) Any
- copysign(*args: Any, **kwargs: Any) Any
- cos(*args: Any, **kwargs: Any) Any
- cosh(*args: Any, **kwargs: Any) Any
- abstract 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.
- abstract default_rng(seed: int | None = None) Any[source]
Return a random number generator seeded with seed.
- deg2rad(*args: Any, **kwargs: Any) Any
- abstract diff(x: Any, n: int = 1, axis: int = -1, **kwargs: Any) Any[source]
Calculate the n-th discrete difference along the given axis.
- dot(*args: Any, **kwargs: Any) Any
- einsum(*args: Any, **kwargs: Any) Any
- abstract empty(shape: Sequence[int]) Any[source]
Return a new uninitialized array of the given shape.
- exp(*args: Any, **kwargs: Any) Any
- property fft: Any
Expose the FFT submodule of the underlying library.
- finfo(*args: Any, **kwargs: Any) Any
- floor(*args: Any, **kwargs: Any) Any
- abstract full(shape: Sequence[int], fill_value: Any, dtype: Any = None) Any[source]
Return a new array of the given shape filled with fill_value.
- abstract 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.
- property grad_mode: Any
Control object for gradient computation (torch only).
- abstract 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.
- abstract histogram2d(x: Any, y: Any, bins: Any, weights: Any = None) tuple[Any, Any, Any][source]
Compute a 2-D histogram.
- hypot(*args: Any, **kwargs: Any) Any
- imag(*args: Any, **kwargs: Any) Any
- abstract isclose(a: Any, b: Any, rtol: float = 1e-05, atol: float = 1e-08) Any[source]
Return a boolean array where elements are close.
- isfinite(*args: Any, **kwargs: Any) Any
- isinf(*args: Any, **kwargs: Any) Any
- isnan(*args: Any, **kwargs: Any) Any
- isscalar(*args: Any, **kwargs: Any) Any
- property linalg: Any
Expose the linear-algebra submodule of the underlying library.
- abstract linspace(start: float, stop: float, num: int = 50) Any[source]
Return evenly spaced numbers over the specified interval.
- load(*args: Any, **kwargs: Any) Any
- log(*args: Any, **kwargs: Any) Any
- log10(*args: Any, **kwargs: Any) Any
- log2(*args: Any, **kwargs: Any) Any
- logical_and(*args: Any, **kwargs: Any) Any
- logical_not(*args: Any, **kwargs: Any) Any
- logical_or(*args: Any, **kwargs: Any) Any
- abstract matrix_vector_multiply_and_squeeze(p: Any, E: Any) Any[source]
Multiply p @ E[…, newaxis] and squeeze the trailing dimension.
- abstract mean(x: Any, axis: int | None = None, keepdims: bool = False) Any[source]
Compute the arithmetic mean, ignoring NaNs.
- abstract meshgrid(*arrays: Any) tuple[Any, ...][source]
Return coordinate matrices from coordinate vectors.
- abstract mult_p_E(p: Any, E: Any) Any[source]
Complex matrix-vector multiply used for polarized fields.
- abstract property name: str
Return the backend name (e.g. ‘numpy’ or ‘torch’).
- abstract nanmax(x: Any, axis: int | None = None, keepdim: bool = False) Any[source]
Return the maximum, ignoring NaNs.
- nanmean(*args: Any, **kwargs: Any) Any
- nansum(*args: Any, **kwargs: Any) Any
- abstract nearest_nd_interpolator(points: Any, values: Any, x: Any, y: Any) Any[source]
Nearest-neighbour interpolation on an N-D dataset.
- abstract ones(shape: Sequence[int], dtype: Any = None) Any[source]
Return a new array of the given shape filled with ones.
- outer(*args: Any, **kwargs: Any) Any
- abstract pad(tensor: Any, pad_width: Any, mode: str = 'constant', constant_values: float | None = 0) Any[source]
Pad an array.
- abstract path_contains_points(vertices: Any, points: Any) Any[source]
Return a boolean mask of points inside the polygon.
- rad2deg(*args: Any, **kwargs: Any) Any
- property random: Any
Expose the random submodule of the underlying library.
- abstract 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.
- abstract random_uniform(low: float = 0.0, high: float = 1.0, size: Any = None, generator: Any = None) Any[source]
Uniform random samples in [low, high).
- real(*args: Any, **kwargs: Any) Any
- abstract roll(x: Any, shift: Any, axis: Any = ()) Any[source]
Roll x elements along the given axis.
- round(*args: Any, **kwargs: Any) Any
- searchsorted(*args: Any, **kwargs: Any) Any
- 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.
- abstract set_precision(precision: Literal['float32', 'float64']) None[source]
Set the floating-point precision used by this backend.
- Parameters:
precision – Either
'float32'or'float64'.
- shape(*args: Any, **kwargs: Any) Any
- sign(*args: Any, **kwargs: Any) Any
- sin(*args: Any, **kwargs: Any) Any
- sinh(*args: Any, **kwargs: Any) Any
- size(*args: Any, **kwargs: Any) Any
- abstract sobol_sampler(dim: int, num_samples: int, scramble: bool = True, seed: int | None = None) Any[source]
Generate quasi-random samples using Sobol sequences.
- sqrt(*args: Any, **kwargs: Any) Any
- abstract stack(xs: Sequence[Any], axis: int = 0) Any[source]
Join a sequence of arrays along a new axis.
- abstract std(x: Any, axis: int | None = None) Any[source]
Compute the standard deviation along the given axis.
- property supports_gpu: bool
Return True if this backend can use GPU acceleration.
- property supports_gradients: bool
Return True if this backend supports automatic differentiation.
- tan(*args: Any, **kwargs: Any) Any
- tanh(*args: Any, **kwargs: Any) Any
- 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.
- abstract transpose(x: Any, axes: Sequence[int] | None = None) Any[source]
Permute the dimensions of x.
- abstract vectorize(pyfunc: Callable[..., Any]) Callable[..., Any][source]
Vectorize a scalar function over array inputs.
- vstack(*args: Any, **kwargs: Any) Any
- abstract 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')
- add_note()
Exception.add_note(note) – add a note to the exception
- args
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- 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.