backend.base#

AbstractBackend ABC, @passthrough decorator, and BackendCapabilityError.

Kramer Harrison, 2025

Functions

passthrough(*func_names)

Inject concrete passthrough methods into the decorated class.

Classes

AbstractBackend()

Abstract base class that defines the full backend contract.

Exceptions

BackendCapabilityError

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 (numpy or torch).

abs(*args: Any, **kwargs: Any) Any#
abstractmethod all(x: Any) bool[source]#

Return True if all elements of x are True.

allclose(*args: Any, **kwargs: Any) Any#
abstractmethod any(x: Any) bool[source]#

Return True if any element of x is True.

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.

arccos(*args: Any, **kwargs: Any) Any#
arcsin(*args: Any, **kwargs: Any) Any#
arctan(*args: Any, **kwargs: Any) Any#
arctan2(*args: Any, **kwargs: Any) Any#
abstractmethod argmin(x: Any, axis: int | None = None) Any[source]#

Return indices of the minimum values along an axis.

abstractmethod argwhere(x: Any) Any[source]#

Return indices of non-zero elements.

abstractmethod array(x: Any) Any[source]#

Create a backend array/tensor from x.

abstractmethod as_array_1d(data: Any) Any[source]#

Force conversion to a 1D array.

abstractmethod asarray(x: Any, **kwargs: Any) Any[source]#

Convert x to a backend array without copying if possible.

abstractmethod atleast_1d(x: Any) Any[source]#

Return x as an array with at least one dimension.

abstractmethod atleast_2d(x: Any) Any[source]#

Return x as an array with at least two dimensions.

property autograd: Any#

The autograd submodule (torch only).

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 cast(x: Any) Any[source]#

Cast x to the current floating-point precision.

ceil(*args: Any, **kwargs: Any) Any#
abstractmethod clip(x: Any, a_min: Any, a_max: Any) Any[source]#

Clip the values in x to [a_min, a_max].

column_stack(*args: Any, **kwargs: Any) Any#
abstractmethod 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#
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.

deg2rad(*args: Any, **kwargs: Any) Any#
abstractmethod degrees(x: Any) Any[source]#

Convert angles from radians to degrees.

abstractmethod 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#
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 erfinv(x: Any) Any[source]#

Inverse error function.

abstractmethod errstate(**kwargs: Any) Any[source]#

Context manager for floating-point error state.

exp(*args: Any, **kwargs: Any) Any#
abstractmethod expand_dims(x: Any, axis: int) Any[source]#

Expand the shape of x by inserting a new axis.

abstractmethod eye(n: int) Any[source]#

Return a 2D identity matrix of size n.

abstractmethod factorial(n: Any) Any[source]#

Compute the factorial of n.

property fft: Any#

Expose the FFT submodule of the underlying library.

abstractmethod fftconvolve(in1: Any, in2: Any, mode: str = 'full') Any[source]#

FFT-based convolution.

finfo(*args: Any, **kwargs: Any) Any#
abstractmethod flip(x: Any) Any[source]#

Reverse the order of elements in x along axis 0.

floor(*args: Any, **kwargs: Any) Any#
abstractmethod fmax(a: Any, b: Any) Any[source]#

Element-wise maximum, ignoring NaNs.

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 get_precision() int[source]#

Return the current precision as an integer (32 or 64).

property grad_mode: Any#

Control object for gradient computation (torch only).

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 histogram(x: Any, bins: Any = 10) tuple[Any, Any][source]#

Compute a histogram of x.

abstractmethod 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#
abstractmethod interp(x: Any, xp: Any, fp: Any) Any[source]#

1-D linear interpolation.

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.

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.

abstractmethod 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#
abstractmethod lstsq(a: Any, b: Any) Any[source]#

Return the least-squares solution to a @ x = b.

abstractmethod matmul(a: Any, b: Any) Any[source]#

Matrix product of two arrays.

abstractmethod matrix_vector_multiply_and_squeeze(p: Any, E: Any) Any[source]#

Multiply p @ E[…, newaxis] and squeeze the trailing dimension.

abstractmethod max(x: Any) Any[source]#

Return the maximum value of x.

abstractmethod maximum(a: Any, b: Any) Any[source]#

Element-wise maximum of a and b.

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 min(x: Any) Any[source]#

Return the minimum value of x.

abstractmethod minimum(a: Any, b: Any) Any[source]#

Element-wise minimum of a and b.

abstractmethod 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’).

abstractmethod 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#
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.

outer(*args: Any, **kwargs: Any) Any#
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 polyfit(x: Any, y: Any, degree: int) Any[source]#

Least-squares polynomial fit.

abstractmethod polyval(coeffs: Any, x: Any) Any[source]#

Evaluate a polynomial at specific values.

abstractmethod power(x: Any, y: Any) Any[source]#

Return x raised to the power y.

rad2deg(*args: Any, **kwargs: Any) Any#
abstractmethod radians(x: Any) Any[source]#

Convert angles from degrees to radians.

abstractmethod rand(*size: int) Any[source]#

Random values from a uniform distribution on [0, 1).

property random: Any#

Expose the random submodule of the underlying library.

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 ravel(x: Any) Any[source]#

Return a 1D float array of x.

real(*args: Any, **kwargs: Any) Any#
abstractmethod repeat(x: Any, repeats: int) Any[source]#

Repeat elements of x.

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.

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.

abstractmethod 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#
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 sort(x: Any, axis: int = -1) Any[source]#

Return a sorted copy of x.

sqrt(*args: Any, **kwargs: Any) Any#
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.

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#
abstractmethod tile(x: Any, dims: Any) Any[source]#

Construct an array by tiling x.

abstractmethod to_complex(x: Any) Any[source]#

Cast x to complex128.

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 unsqueeze_last(x: Any) Any[source]#

Add a trailing dimension to x.

abstractmethod vectorize(pyfunc: Callable[..., Any]) Callable[..., Any][source]#

Vectorize a scalar function over array inputs.

vstack(*args: Any, **kwargs: Any) Any#
abstractmethod where(condition: Any, x: Any, y: Any) Any[source]#

Return elements chosen from x or y depending on condition.

abstractmethod zeros(shape: Sequence[int], dtype: Any = None) Any[source]#

Return a new array of the given shape filled with zeros.

abstractmethod zeros_like(x: Any) Any[source]#

Return an array of zeros with the same shape and type as x.

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.