backend.numpy_backend#
NumPy backend — implements AbstractBackend using NumPy and SciPy.
The implementation is split across same-package modules by operation
category (creation, indexing, math, conic, linalg, interpolation, random,
misc); this module composes them into the concrete NumpyBackend
class. See creation.py etc. for the actual method bodies.
The private modules are not mixins. They hold the compiled Numba code of
NumPy-only fast paths: _trace_kernel.py (the compiled trace plan),
_aim.py (the paraxial aim directions) and _compiled_math.py (the
scalar math that both share). See the developer page “Performance
Internals”.
Kramer Harrison, 2024, 2025
Classes
Backend implementation using NumPy and SciPy. |
- class NumpyBackend[source]#
Backend implementation using NumPy and SciPy.
- Variables:
_lib – The NumPy module (used by passthrough methods).
_precision (Literal['float32', 'float64']) – Current floating-point precision string.
- all(x: Any, axis: int | tuple[int, ...] | None = None) bool | NDArray#
Return True if all elements of x are True.
- Parameters:
x – Input array.
axis – Axis or axes to reduce. None reduces the whole array.
- Returns:
Python bool for a whole-array reduction; otherwise a boolean NumPy array with the unreduced dimensions (0D if none remain).
- any(x: Any) bool#
Return True if any element of x is True.
- Parameters:
x – Input array.
- Returns:
Whether any element is True.
- Return type:
- arange(*args: Any, **kwargs: Any) NDArray#
Return evenly spaced values within a given interval.
- Parameters:
*args – start, stop, step (same as np.arange).
**kwargs – Additional keyword arguments passed to np.arange.
- Returns:
Array of evenly spaced values.
- Return type:
NDArray
- arange_indices(start: Any, stop: Any = None, step: int = 1) NDArray#
Create an integer array of indices.
- Parameters:
start – Start index (or stop if stop is None).
stop – Stop index.
step – Step size.
- Returns:
Integer index array.
- Return type:
NDArray
- argmin(x: ArrayLike, axis: int | None = None) NDArray#
Return indices of the minimum values along an axis.
- Parameters:
x – Input array.
axis – Axis along which to find the minimum.
- Returns:
Index array.
- Return type:
NDArray
- argwhere(x: ArrayLike) NDArray#
Return indices of non-zero elements.
- Parameters:
x – Input array.
- Returns:
Index array of shape (N, ndim).
- Return type:
NDArray
- array(x: ArrayLike) NDArray#
Create a NumPy array cast to the current precision.
- Parameters:
x – Input data.
- Returns:
- NumPy array with dtype matching current precision.
Boolean inputs are returned as bool arrays (dtype preserved).
- Return type:
NDArray
- as_array_1d(data: Any) NDArray#
Force conversion to a 1-D array.
- Parameters:
data – Scalar, list, tuple, or array.
- Returns:
1-D array.
- Return type:
NDArray
- Raises:
ValueError – If data type is not supported.
- asarray(x: ArrayLike, **kwargs: Any) NDArray#
Convert x to a NumPy array without copying if possible.
- Parameters:
x – Input data.
**kwargs – Keyword arguments forwarded to
np.asarray(e.g.dtype).
- Returns:
NumPy array view (or copy if necessary).
- Return type:
NDArray
- atleast_1d(x: ArrayLike) NDArray#
Convert x to an array with at least one dimension.
- Parameters:
x – Input data.
- Returns:
Array with at least 1 dimension, cast to float.
- Return type:
NDArray
- atleast_2d(x: ArrayLike) NDArray#
Convert x to an array with at least two dimensions.
- Parameters:
x – Input data.
- Returns:
Array with at least 2 dimensions.
- Return type:
NDArray
- batched_chain_matmul3(a: ArrayLike, b: ArrayLike, c: ArrayLike) NDArray#
Compute a @ b @ c with promoted dtype.
- Parameters:
a – First matrix.
b – Second matrix.
c – Third matrix.
- Returns:
Result of a @ b @ c.
- Return type:
NDArray
- broadcast_to(x: ArrayLike, shape: Sequence[int]) NDArray#
Broadcast x to the given shape.
- Parameters:
x – Input array.
shape – Target shape.
- Returns:
Broadcast view.
- Return type:
NDArray
- cast(x: ArrayLike) NDArray#
Cast x to the current floating-point dtype.
- Parameters:
x – Input data.
- Returns:
Array cast to current precision.
- Return type:
NDArray
- clip(x: ArrayLike, a_min: Any, a_max: Any) NDArray#
Clip values in x to [a_min, a_max].
- Parameters:
x – Input array.
a_min – Minimum value.
a_max – Maximum value.
- Returns:
Clipped array.
- Return type:
NDArray
- concatenate(arrays: Sequence[ArrayLike], axis: int = 0) NDArray#
Join arrays along an existing axis.
- Parameters:
arrays – Sequence of arrays to concatenate.
axis – Axis along which to concatenate.
- Returns:
Concatenated array.
- Return type:
NDArray
- conic_intersection(x: Any, y: Any, z: Any, L: Any, M: Any, N: Any, radius: Any, conic: Any, contains: Callable | None = None) Any#
Select a finite-conic intersection using compiled or native arrays.
See
AbstractBackend.conic_intersectionfor the numerical contract.
- copy_to(source: NDArray, destination: NDArray) None#
Copy source array into destination in-place.
- Parameters:
source – Source array.
destination – Destination array (modified in place).
- cross(a: ArrayLike, b: ArrayLike, axisa: int = -1, axisb: int = -1, axisc: int = -1, axis: int | None = None) NDArray#
Return the cross product of two vectors.
- Parameters:
a – First vector array.
b – Second vector array.
axisa – Axis of a that defines the vector(s).
axisb – Axis of b that defines the vector(s).
axisc – Axis of c that contains the cross product vector.
axis – If defined, the axis of a, b and c that defines the vectors.
- Returns:
Cross product.
- Return type:
NDArray
- default_rng(seed: int | None = None) NpGenerator#
Return a NumPy random number generator.
- Parameters:
seed – Optional seed.
- Returns:
NumPy random generator.
- Return type:
Generator
- degrees(x: ArrayLike) NDArray#
Convert angles from radians to degrees.
- Parameters:
x – Angle in radians.
- Returns:
Angle in degrees.
- Return type:
NDArray
- diff(x: ArrayLike, n: int = 1, axis: int = -1, **kwargs: Any) NDArray#
Calculate the n-th discrete difference along the given axis.
- Parameters:
x – Input array.
n – Number of times to apply the difference.
axis – Axis along which to compute differences.
**kwargs – Additional keyword arguments forwarded to
np.diff(e.g.prepend,append).
- Returns:
Differences array.
- Return type:
NDArray
- empty(shape: Sequence[int]) NDArray#
Return an uninitialized array of the given shape.
- Parameters:
shape – Shape of the output array.
- Returns:
Uninitialized array.
- Return type:
NDArray
- empty_like(x: ArrayLike) NDArray#
Return an uninitialized array with the same shape as x.
- Parameters:
x – Reference array.
- Returns:
Uninitialized array.
- Return type:
NDArray
- erfinv(x: ArrayLike) NDArray#
Inverse error function.
- Parameters:
x – Input array.
- Returns:
Inverse error function of x.
- Return type:
NDArray
- errstate(**kwargs: Any) Generator[None, None, None]#
Context manager for NumPy floating-point error state.
- Parameters:
**kwargs – Keyword arguments forwarded to
np.errstate.- Yields:
None
- expand_dims(x: ArrayLike, axis: int) NDArray#
Insert a new axis into x.
- Parameters:
x – Input array.
axis – Position of the new axis.
- Returns:
Expanded array.
- Return type:
NDArray
- eye(n: int) NDArray#
Return a 2D identity matrix.
- Parameters:
n – Size of the identity matrix.
- Returns:
Identity matrix.
- Return type:
NDArray
- factorial(n: Any) NDArray#
Compute the factorial of n using the gamma function.
- Parameters:
n – Non-negative integer or array of integers.
- Returns:
Factorial values.
- Return type:
NDArray
- fftconvolve(in1: ArrayLike, in2: ArrayLike, mode: Literal['full', 'valid', 'same'] = 'full') NDArray#
FFT-based convolution using SciPy.
- Parameters:
in1 – First input array.
in2 – Second input array.
mode – Convolution mode (
'full','valid','same').
- Returns:
Convolved array.
- Return type:
NDArray
- flip(x: ArrayLike) NDArray#
Reverse the order of elements along axis 0.
- Parameters:
x – Input array.
- Returns:
Flipped array.
- Return type:
NDArray
- fmax(a: ArrayLike, b: ArrayLike) NDArray#
Element-wise maximum, ignoring NaNs.
- Parameters:
a – First input array.
b – Second input array.
- Returns:
Element-wise maximum ignoring NaN.
- Return type:
NDArray
- from_euler(euler: NDArray) R#
Create a SciPy Rotation from Euler angles.
- Parameters:
euler – Euler angles in the ‘xyz’ convention.
- Returns:
SciPy Rotation object.
- Return type:
Rotation
- from_matrix(matrix: NDArray) R#
Create a SciPy Rotation from a rotation matrix.
- Parameters:
matrix – Rotation matrix.
- Returns:
SciPy Rotation object.
- Return type:
Rotation
- full(shape: Sequence[int], fill_value: Any, dtype: Any = None) NDArray#
Return a constant-filled array with current precision dtype.
- Parameters:
shape – Shape of the output array.
fill_value – Fill value.
dtype – Optional dtype override.
- Returns:
Filled array.
- Return type:
NDArray
- full_like(x: ArrayLike, fill_value: Any) NDArray#
Return a full array with the same shape as x.
- Parameters:
x – Reference array.
fill_value – Fill value.
- Returns:
Filled array.
- Return type:
NDArray
- get_complex_precision() Any#
Return the complex dtype matching the current precision (torch only).
- Raises:
BackendCapabilityError – Always, on non-torch backends.
- get_device() str#
Return the current compute device (torch only).
- Raises:
BackendCapabilityError – Always, on non-torch backends.
- grid_sample(input: NDArray, grid: NDArray, mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: bool = False) NDArray#
Sample input using bilinear/nearest interpolation on a grid.
NumPy/SciPy implementation of
torch.nn.functional.grid_sample.- Parameters:
input – Input array of shape (N, C, H_in, W_in).
grid – Grid of shape (N, H_out, W_out, 2). Coordinates in [-1, 1].
mode – Interpolation mode (
'bilinear'or'nearest').padding_mode – Padding mode (
'zeros','border','reflection').align_corners – Whether to align corners.
- Returns:
Output array of shape (N, C, H_out, W_out).
- Return type:
NDArray
- histogram(x: ArrayLike, bins: Any = 10) tuple[NDArray, NDArray]#
Compute a histogram of x.
- Parameters:
x – Input data.
bins – Number of bins or bin edges.
- Returns:
Bin counts and bin edges.
- Return type:
tuple[NDArray, NDArray]
- histogram2d(x: ArrayLike, y: ArrayLike, bins: Any, weights: NDArray | None = None) tuple[NDArray, NDArray, NDArray]#
Compute a 2-D histogram.
- Parameters:
x – x-coordinates of the sample points.
y – y-coordinates of the sample points.
bins – Bin specification (list of two edge arrays).
weights – Optional weights for each sample.
- Returns:
Histogram, x edges, y edges.
- Return type:
tuple[NDArray, NDArray, NDArray]
- index_add(target: NDArray, dim: int, index: NDArray, source: NDArray) NDArray#
Scatter-add: result[index[i]] += source[i] along dim=0.
- Parameters:
target – Accumulation buffer, shape (N, …).
dim – Must be 0 (only 0 supported for NumPy path).
index – Integer indices, shape (K,).
source – Values to add, shape (K, …).
- Returns:
New array with scattered values added.
- Return type:
NDArray
- interp(x: ArrayLike, xp: ArrayLike, fp: ArrayLike) NDArray#
1-D linear interpolation.
- Parameters:
x – x-coordinates of the interpolated values.
xp – x-coordinates of the data points.
fp – y-coordinates of the data points.
- Returns:
Interpolated values.
- Return type:
NDArray
- is_array_like(x: Any) bool#
Return True if x is a list, tuple, or ndarray.
- Parameters:
x – Object to check.
- Returns:
True if x is array-like.
- Return type:
- isclose(a: Any, b: Any, rtol: float = 1e-05, atol: float = 1e-08) NDArray#
Return a boolean array where elements are close.
- Parameters:
a – First input.
b – Second input.
rtol – Relative tolerance.
atol – Absolute tolerance.
- Returns:
Boolean array.
- Return type:
NDArray
- linspace(start: float, stop: float, num: int = 50) NDArray#
Return evenly spaced numbers over an interval.
- Parameters:
start – Start of the interval.
stop – End of the interval.
num – Number of samples.
- Returns:
Evenly spaced samples.
- Return type:
NDArray
- lstsq(a: ArrayLike, b: ArrayLike) NDArray#
Compute the least-squares solution to a @ x = b.
- Parameters:
a – Left-hand side matrix (M, N).
b – Right-hand side matrix (M,) or (M, K).
- Returns:
Least-squares solution (N,) or (N, K).
- Return type:
NDArray
- matmul(a: ArrayLike, b: ArrayLike) NDArray#
Matrix product of two arrays.
- Parameters:
a – First matrix.
b – Second matrix.
- Returns:
Matrix product.
- Return type:
NDArray
- matrix_vector_multiply_and_squeeze(p: NDArray, E: NDArray, backend: Literal['numpy'] = 'numpy') NDArray#
Multiply p @ E[…, newaxis] and squeeze trailing dimension.
- Parameters:
p – Matrix array.
E – Vector array.
backend – Unused; kept for backward compatibility.
- Returns:
Result with trailing dimension squeezed.
- Return type:
NDArray
- max(x: ArrayLike) Any#
Return the maximum value of x.
- Parameters:
x – Input array.
- Returns:
Maximum value.
- Return type:
float or NDArray
- maximum(a: ArrayLike, b: ArrayLike) NDArray#
Element-wise maximum of a and b.
- Parameters:
a – First input array.
b – Second input array.
- Returns:
Element-wise maximum.
- Return type:
NDArray
- mean(x: ArrayLike, axis: int | None = None, keepdims: bool = False) NDArray#
Compute the arithmetic mean along an axis.
- Parameters:
x – Input array.
axis – Axis along which to compute the mean.
keepdims – Whether to keep reduced dimensions.
- Returns:
Mean of x.
- Return type:
NDArray
- meshgrid(*arrays: ArrayLike) tuple[NDArray, ...]#
Return coordinate matrices from coordinate vectors (xy indexing).
- Parameters:
*arrays – 1-D arrays representing grid coordinates.
- Returns:
Coordinate matrices.
- Return type:
tuple[NDArray, …]
- min(x: ArrayLike) Any#
Return the minimum value of x.
- Parameters:
x – Input array.
- Returns:
Minimum value.
- Return type:
float or NDArray
- minimum(a: ArrayLike, b: ArrayLike) NDArray#
Element-wise minimum of a and b.
- Parameters:
a – First input array.
b – Second input array.
- Returns:
Element-wise minimum.
- Return type:
NDArray
- mult_p_E(p: NDArray, E: NDArray) NDArray#
Complex matrix-vector multiply used for polarized fields.
- Parameters:
p – Jones matrix array.
E – Electric field array.
- Returns:
Result of complex matrix-vector multiplication.
- Return type:
NDArray
- nanmax(x: ArrayLike, axis: int | None = None, keepdim: bool = False) NDArray#
Return the maximum value, ignoring NaNs.
- Parameters:
x – Input array.
axis – Axis along which to compute the maximum.
keepdim – Whether to keep reduced dimensions.
- Returns:
Maximum value ignoring NaN.
- Return type:
NDArray
- nearest_nd_interpolator(points: NDArray, values: NDArray, x: Any, y: Any) NDArray#
Nearest-neighbour interpolation on an N-D dataset.
- Parameters:
points – Known sample points.
values – Values at the sample points.
x – Query x coordinates.
y – Query y coordinates.
- Returns:
Interpolated values.
- Return type:
NDArray
- no_grad_unless_enabled() Generator[None, None, None]#
Context in which gradient bookkeeping may be suppressed.
A no-op for backends without gradient support. The torch backend runs the context under
torch.no_gradunless gradients were globally requested viagrad_mode, sparing per-op autograd dispatch during plain forward computations.
- ones(shape: Sequence[int], dtype: Any = None) NDArray#
Return an array of ones with current precision dtype.
- Parameters:
shape – Shape of the output array.
dtype – Optional dtype override.
- Returns:
Ones array.
- Return type:
NDArray
- ones_like(x: ArrayLike) NDArray#
Return an array of ones with the same shape as x.
- Parameters:
x – Reference array.
- Returns:
Ones array.
- Return type:
NDArray
- pad(tensor: NDArray, pad_width: Any, mode: str = 'constant', constant_values: float | None = 0) NDArray#
Pad an array.
- Parameters:
tensor – Input array.
pad_width – Number of values padded per axis.
mode – Padding mode (only
'constant'is supported).constant_values – Value used for constant padding.
- Returns:
Padded array.
- Return type:
NDArray
- path_contains_points(vertices: NDArray, points: NDArray) NDArray#
Return a boolean mask of points inside the polygon.
- Parameters:
vertices – Polygon vertices as (N, 2) array.
points – Query points as (M, 2) array.
- Returns:
Boolean mask of shape (M,).
- Return type:
NDArray
- polyfit(x: ArrayLike, y: ArrayLike, degree: int) NDArray#
Least-squares polynomial fit.
- Parameters:
x – x-coordinates of the sample points.
y – y-coordinates of the sample points.
degree – Degree of the polynomial.
- Returns:
Polynomial coefficients, highest power first.
- Return type:
NDArray
- polyval(coeffs: ArrayLike, x: ArrayLike) NDArray#
Evaluate a polynomial at specific values.
- Parameters:
coeffs – Polynomial coefficients, highest power first.
x – Values at which to evaluate the polynomial.
- Returns:
Evaluated polynomial.
- Return type:
NDArray
- power(x: ArrayLike, y: ArrayLike) NDArray#
Return x raised to the power y.
- Parameters:
x – Base array.
y – Exponent array.
- Returns:
x ** y.
- Return type:
NDArray
- radians(x: ArrayLike) NDArray#
Convert angles from degrees to radians.
- Parameters:
x – Angle in degrees.
- Returns:
Angle in radians.
- Return type:
NDArray
- rand(*size: int) NDArray#
Random values from a uniform distribution on [0, 1).
- Parameters:
*size – Shape of the output array.
- Returns:
Random values.
- Return type:
NDArray
- random_normal(loc: float = 0.0, scale: float = 1.0, size: Any = None, generator: NpGenerator | None = None) NDArray#
Random samples from a Gaussian distribution.
- Parameters:
loc – Mean of the distribution.
scale – Standard deviation.
size – Output shape.
generator – Optional NumPy random generator.
- Returns:
Normal random samples.
- Return type:
NDArray
- random_uniform(low: float = 0.0, high: float = 1.0, size: Any = None, generator: NpGenerator | None = None) NDArray#
Uniform random samples in [low, high).
- Parameters:
low – Lower boundary.
high – Upper boundary.
size – Output shape.
generator – Optional NumPy random generator.
- Returns:
Uniform random samples.
- Return type:
NDArray
- ravel(x: ArrayLike) NDArray#
Return a contiguous flattened array cast to float.
- Parameters:
x – Input array.
- Returns:
1-D float array.
- Return type:
NDArray
- repeat(x: ArrayLike, repeats: int) NDArray#
Repeat elements of x.
- Parameters:
x – Input array.
repeats – Number of repetitions.
- Returns:
Repeated array.
- Return type:
NDArray
- reshape(x: ArrayLike, shape: Sequence[int]) NDArray#
Return x with a new shape.
- Parameters:
x – Input array.
shape – New shape.
- Returns:
Reshaped array.
- Return type:
NDArray
- roll(x: ArrayLike, shift: Any, axis: Any = ()) NDArray#
Roll x elements along the given axis.
- Parameters:
x – Input array.
shift – Number of places to shift.
axis – Axis or axes along which to roll.
- Returns:
Rolled array.
- Return type:
NDArray
- set_device(device: str) None#
Set the compute device (torch only).
- Parameters:
device – Device string (e.g.
'cpu'or'cuda').- Raises:
BackendCapabilityError – Always, on non-torch backends.
- set_precision(precision: Literal['float32', 'float64']) None#
Set the floating-point precision.
- Parameters:
precision – Either
'float32'or'float64'.
- sobol_sampler(dim: int, num_samples: int, scramble: bool = True, seed: int | None = None) NDArray#
Generate quasi-random samples using Sobol sequences.
- Parameters:
dim – Dimension of the samples.
num_samples – Number of samples to generate.
scramble – Whether to scramble the sequence.
seed – Random seed for scrambling.
- Returns:
Samples of shape (num_samples_pow2, dim).
- Return type:
NDArray
- sort(x: ArrayLike, axis: int = -1) NDArray#
Return a sorted copy of x.
- Parameters:
x – Input array.
axis – Axis along which to sort.
- Returns:
Sorted array.
- Return type:
NDArray
- stack(xs: Sequence[ArrayLike], axis: int = 0) NDArray#
Join a sequence of arrays along a new axis.
- Parameters:
xs – Sequence of arrays.
axis – Axis along which to stack.
- Returns:
Stacked array.
- Return type:
NDArray
- std(x: ArrayLike, axis: int | None = None) NDArray#
Compute the standard deviation along an axis.
- Parameters:
x – Input array.
axis – Axis along which to compute the std.
- Returns:
Standard deviation.
- Return type:
NDArray
- sum(x: ArrayLike, axis: int | None = None) NDArray#
Sum array elements over a given axis.
- Parameters:
x – Input array.
axis – Axis along which to sum.
- Returns:
Sum of x.
- Return type:
NDArray
- tile(x: ArrayLike, dims: Any) NDArray#
Construct an array by tiling x.
- Parameters:
x – Input array.
dims – Number of repetitions per dimension.
- Returns:
Tiled array.
- Return type:
NDArray
- to_complex(x: NDArray) NDArray#
Cast x to complex128.
- Parameters:
x – Input array.
- Returns:
Complex128 array.
- Return type:
NDArray
- to_tensor(data: Any, device: Any = None) Any#
Convert data to a backend tensor with current precision (torch only).
- Raises:
BackendCapabilityError – Always, on non-torch backends.
- transpose(x: ArrayLike, axes: Sequence[int] | None = None) NDArray#
Permute the dimensions of x.
- Parameters:
x – Input array.
axes – Permutation of dimensions.
- Returns:
Transposed array.
- Return type:
NDArray
- unsqueeze_last(x: ArrayLike) NDArray#
Add a trailing dimension to x.
- Parameters:
x – Input array.
- Returns:
Array with an extra trailing dimension.
- Return type:
NDArray
- vectorize(pyfunc: Callable[..., Any]) Callable[..., Any]#
Vectorize a scalar Python function.
- Parameters:
pyfunc – The scalar function to vectorize.
- Returns:
Vectorized function.
- Return type:
Callable
- where(condition: Any, x: Any, y: Any) NDArray#
Return elements from x or y depending on condition.
- Parameters:
condition – Boolean array.
x – Values where condition is True.
y – Values where condition is False.
- Returns:
Output array.
- Return type:
NDArray
- zeros(shape: Sequence[int], dtype: Any = None) NDArray#
Return a zero array of given shape with current precision dtype.
- Parameters:
shape – Shape of the output array.
dtype – Optional dtype override.
- Returns:
Zero array.
- Return type:
NDArray
- zeros_like(x: ArrayLike) NDArray#
Return a zero array with the same shape as x.
- Parameters:
x – Reference array.
- Returns:
Zero array.
- Return type:
NDArray