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.

_lib

The underlying library module (numpy or torch).

Type:

ModuleType

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

Return True if all elements of x are True.

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

Return True if any element of x is True.

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

Return indices of non-zero elements.

abstract array(x: Any) Any[source]

Create a backend array/tensor from x.

abstract as_array_1d(data: Any) Any[source]

Force conversion to a 1D array.

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

Convert x to a backend array without copying if possible.

abstract atleast_1d(x: Any) Any[source]

Return x as an array with at least one dimension.

abstract atleast_2d(x: Any) Any[source]

Return x as an array with at least two dimensions.

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.

abstract broadcast_to(x: Any, shape: Sequence[int]) Any[source]

Broadcast x to the given shape.

abstract cast(x: Any) Any[source]

Cast x to the current floating-point precision.

ceil(*args: Any, **kwargs: Any) Any
abstract 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
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 degrees(x: Any) Any[source]

Convert angles from radians to degrees.

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.

abstract empty_like(x: Any) Any[source]

Return an uninitialized array with the same shape as x.

abstract erfinv(x: Any) Any[source]

Inverse error function.

abstract errstate(**kwargs: Any) Any[source]

Context manager for floating-point error state.

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

Expand the shape of x by inserting a new axis.

abstract eye(n: int) Any[source]

Return a 2D identity matrix of size n.

abstract factorial(n: Any) Any[source]

Compute the factorial of n.

property fft: Any

Expose the FFT submodule of the underlying library.

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

FFT-based convolution.

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

Reverse the order of elements in x along axis 0.

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

Element-wise maximum, ignoring NaNs.

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.

abstract 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).

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

Compute a histogram of x.

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

1-D linear interpolation.

abstract is_array_like(x: Any) bool[source]

Return True if x is a list, tuple, or backend array.

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

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

abstract matmul(a: Any, b: Any) Any[source]

Matrix product of two arrays.

abstract matrix_vector_multiply_and_squeeze(p: Any, E: Any) Any[source]

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

abstract max(x: Any) Any[source]

Return the maximum value of x.

abstract maximum(a: Any, b: Any) Any[source]

Element-wise maximum of a and b.

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

Return the minimum value of x.

abstract minimum(a: Any, b: Any) Any[source]

Element-wise minimum of a and b.

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.

abstract 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
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.

abstract polyfit(x: Any, y: Any, degree: int) Any[source]

Least-squares polynomial fit.

abstract polyval(coeffs: Any, x: Any) Any[source]

Evaluate a polynomial at specific values.

abstract power(x: Any, y: Any) Any[source]

Return x raised to the power y.

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

Convert angles from degrees to radians.

abstract 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.

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

abstract ravel(x: Any) Any[source]

Return a 1D float array of x.

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

Repeat elements of x.

abstract reshape(x: Any, shape: Sequence[int]) Any[source]

Return x reshaped to the given shape.

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.

abstract sort(x: Any, axis: int = -1) Any[source]

Return a sorted copy of x.

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.

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

Construct an array by tiling x.

abstract 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.

abstract transpose(x: Any, axes: Sequence[int] | None = None) Any[source]

Permute the dimensions of x.

abstract unsqueeze_last(x: Any) Any[source]

Add a trailing dimension to 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.

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

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

abstract 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')
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.