Backends¶
Backend abstraction layer for JAX/NumPy array operations with device management and I/O boundary adapters.
Overview¶
The backends module provides a unified interface for array computations that can run on either JAX (with GPU support) or NumPy (CPU fallback). The backend is selected automatically based on JAX availability, or explicitly via environment variables.
Quick Start¶
from xpcsviewer.backends import get_backend, ensure_numpy
backend = get_backend() # Auto-detects JAX or NumPy
print(f"Using {backend.name} backend")
# Use backend for array operations
x = backend.linspace(0, 1, 100)
y = backend.sin(x)
# Convert to NumPy at I/O boundaries
import matplotlib.pyplot as plt
plt.plot(ensure_numpy(x), ensure_numpy(y))
Environment Variables¶
Variable |
Default |
Description |
|---|---|---|
|
|
|
|
|
Enable GPU computation |
|
|
Fall back to CPU if GPU unavailable |
|
|
Maximum GPU memory fraction (0.0-1.0) |
Backend Functions¶
- xpcsviewer.backends.get_backend()[source]¶
Get the current computation backend.
Returns the JAX backend if available and configured, otherwise falls back to NumPy.
- Returns:
The active backend instance.
- Return type:
BackendProtocol
- xpcsviewer.backends.set_backend(name)[source]¶
Set the computation backend.
- Parameters:
name (str) – Backend name: ‘jax’ or ‘numpy’
- Raises:
ValueError – If backend name is not recognized.
ImportError – If JAX backend is requested but not available.
- Return type:
None
Backend Protocol¶
- class xpcsviewer.backends.BackendProtocol(*args, **kwargs)[source]
Bases:
ProtocolProtocol defining the backend interface for array operations.
Both NumPyBackend and JAXBackend implement this protocol, providing a unified API for array computations that can run on CPU or GPU.
- name
Backend identifier (“numpy” or “jax”)
- Type:
- supports_gpu
Whether backend supports GPU computation
- Type:
- supports_jit
Whether backend supports JIT compilation
- Type:
- supports_grad
Whether backend supports automatic differentiation
- Type:
- pi
Mathematical constant π
- Type:
- property name: str
Backend identifier (‘numpy’ or ‘jax’).
- property supports_gpu: bool
Whether backend supports GPU computation.
- property supports_jit: bool
Whether backend supports JIT compilation.
- property supports_grad: bool
Whether backend supports automatic differentiation.
- property pi: float
Mathematical constant π.
- zeros(shape, dtype=None)[source]
Create array filled with zeros.
- ones(shape, dtype=None)[source]
Create array filled with ones.
- arange(start, stop=None, step=1, dtype=None)[source]
Create array with evenly spaced values.
- linspace(start, stop, num)[source]
Create array with linearly spaced values.
- logspace(start, stop, num)[source]
Create array with logarithmically spaced values.
- meshgrid(*xi, indexing='xy')[source]
Create coordinate matrices from coordinate vectors.
- zeros_like(x, dtype=None)[source]
Create zero-filled array with same shape as input.
- Parameters:
x (ArrayType)
dtype (Any)
- Return type:
ArrayType
- ones_like(x, dtype=None)[source]
Create ones-filled array with same shape as input.
- Parameters:
x (ArrayType)
dtype (Any)
- Return type:
ArrayType
- full(shape, fill_value, dtype=None)[source]
Create array filled with specified value.
- array(data, dtype=None)[source]
Create array from data.
- sin(x)[source]
Element-wise sine.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- cos(x)[source]
Element-wise cosine.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- arctan(x)[source]
Element-wise arctangent.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- arctan2(y, x)[source]
Element-wise arctangent of y/x, handling quadrants.
- Parameters:
y (ArrayType)
x (ArrayType)
- Return type:
ArrayType
- hypot(x, y)[source]
Element-wise sqrt(x^2 + y^2).
- Parameters:
x (ArrayType)
y (ArrayType)
- Return type:
ArrayType
- deg2rad(x)[source]
Convert degrees to radians.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- rad2deg(x)[source]
Convert radians to degrees.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- mod(x, y)[source]
Element-wise modulo.
- Parameters:
x (ArrayType)
y (ArrayType | float)
- Return type:
ArrayType
- floor(x)[source]
Element-wise floor.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- ceil(x)[source]
Element-wise ceiling.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- round(x, decimals=0)[source]
Round to given number of decimals.
- Parameters:
x (ArrayType)
decimals (int)
- Return type:
ArrayType
- mean(x, axis=None)[source]
Compute mean along axis.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- std(x, axis=None)[source]
Compute standard deviation along axis.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- nanmean(x, axis=None)[source]
Compute mean, ignoring NaN values.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- nanmin(x, axis=None)[source]
Compute minimum, ignoring NaN values.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- nanmax(x, axis=None)[source]
Compute maximum, ignoring NaN values.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- percentile(x, q, axis=None)[source]
Compute percentile along axis.
- sum(x, axis=None)[source]
Compute sum along axis.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- min(x, axis=None)[source]
Compute minimum along axis.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- max(x, axis=None)[source]
Compute maximum along axis.
- Parameters:
x (ArrayType)
axis (int | None)
- Return type:
ArrayType
- digitize(x, bins)[source]
Return indices of bins to which each value belongs.
- Parameters:
x (ArrayType)
bins (ArrayType)
- Return type:
ArrayType
- bincount(x, weights=None, minlength=0)[source]
Count number of occurrences of each value.
- Parameters:
x (ArrayType)
weights (ArrayType | None)
minlength (int)
- Return type:
ArrayType
- unique(x, return_inverse=False, size=None)[source]
Find unique elements of array.
- logical_and(x, y)[source]
Element-wise logical AND.
- Parameters:
x (ArrayType)
y (ArrayType)
- Return type:
ArrayType
- logical_or(x, y)[source]
Element-wise logical OR.
- Parameters:
x (ArrayType)
y (ArrayType)
- Return type:
ArrayType
- logical_not(x)[source]
Element-wise logical NOT.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- where(condition, x, y)[source]
Return elements chosen from x or y depending on condition.
- Parameters:
condition (ArrayType)
x (ArrayType)
y (ArrayType)
- Return type:
ArrayType
- nonzero(x, size=None)[source]
Return indices of non-zero elements.
- isnan(x)[source]
Test element-wise for NaN.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- isfinite(x)[source]
Test element-wise for finite values.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- clip(x, a_min, a_max)[source]
Clip array values to specified range.
- stack(arrays, axis=0)[source]
Stack arrays along new axis.
- concatenate(arrays, axis=0)[source]
Concatenate arrays along existing axis.
- copy(x)[source]
Return copy of array.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- reshape(x, shape)[source]
Reshape array to specified shape.
- transpose(x, axes=None)[source]
Permute array dimensions.
- flatten(x)[source]
Flatten array to 1D.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- exp(x)[source]
Element-wise exponential.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- log(x)[source]
Element-wise natural logarithm.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- log10(x)[source]
Element-wise base-10 logarithm.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- sqrt(x)[source]
Element-wise square root.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- abs(x)[source]
Element-wise absolute value.
- Parameters:
x (ArrayType)
- Return type:
ArrayType
- power(x, y)[source]
Element-wise power.
- Parameters:
x (ArrayType)
y (float | ArrayType)
- Return type:
ArrayType
- to_numpy(x)[source]
Convert array to NumPy ndarray.
- Parameters:
x (ArrayType)
- Return type:
np.ndarray
- from_numpy(x)[source]
Convert NumPy ndarray to backend array.
- Parameters:
x (np.ndarray)
- Return type:
ArrayType
- astype(x, dtype)[source]
Cast array to specified dtype.
- Parameters:
x (ArrayType)
dtype (Any)
- Return type:
ArrayType
- jit(func, static_argnums=None)[source]
JIT compile function (no-op for NumPy).
- grad(func, argnums=0)[source]
Return gradient function (raises for NumPy).
- value_and_grad(func, argnums=0)[source]
Return function computing both value and gradient.
- vmap(func, in_axes=0, out_axes=0)[source]
Vectorize function over batch dimension.
- scan(func, init, xs, length=None)[source]
Scan over leading array dimension while carrying along state.
- fori_loop(lower, upper, body_fun, init_val)[source]
Execute body function in a loop from lower to upper.
- __init__(*args, **kwargs)
Array Conversions¶
Utilities for converting between array types at I/O boundaries.
Array conversion utilities for I/O boundaries.
This module provides functions for converting between NumPy arrays and backend-specific arrays at I/O boundaries (file I/O, visualization, etc.).
- xpcsviewer.backends._conversions.ensure_numpy(array)[source]
Convert any array type to NumPy for I/O boundaries.
Use this function at boundaries where NumPy arrays are required: - HDF5 file I/O (h5py) - PyQtGraph visualization - Matplotlib plotting - Pandas DataFrame operations
- Parameters:
array (array-like) – JAX array, NumPy array, list, or any array-like object
- Returns:
NumPy array
- Return type:
np.ndarray
Examples
>>> import jax.numpy as jnp >>> x = jnp.array([1, 2, 3]) >>> np_x = ensure_numpy(x) >>> isinstance(np_x, np.ndarray) True
>>> # Works with lists too >>> ensure_numpy([1, 2, 3]) array([1, 2, 3])
- xpcsviewer.backends._conversions.ensure_backend_array(array, backend=None)[source]
Convert array to the backend’s array type.
Use this function when receiving external data that needs to be converted to the current backend’s array format.
- Parameters:
array (array-like) – NumPy array, JAX array, list, or any array-like object
backend (BackendProtocol, optional) – Backend to convert to. If None, uses the current backend.
- Returns:
Array in the backend’s native format
- Return type:
ArrayType
Examples
>>> from xpcsviewer.backends import get_backend, ensure_backend_array >>> import numpy as np >>> x = np.array([1, 2, 3]) >>> backend = get_backend() >>> bx = ensure_backend_array(x, backend)
- xpcsviewer.backends._conversions.is_jax_array(array)[source]
Check if array is a JAX array.
- Parameters:
array (Any) – Object to check
- Returns:
True if array is a JAX array
- Return type:
- xpcsviewer.backends._conversions.is_numpy_array(array)[source]
Check if array is a NumPy array.
- Parameters:
array (Any) – Object to check
- Returns:
True if array is a NumPy array
- Return type:
- xpcsviewer.backends._conversions.get_array_backend(array)[source]
Determine which backend an array belongs to.
- Parameters:
array (Any) – Array to check
- Returns:
‘numpy’, ‘jax’, or ‘unknown’
- Return type:
- xpcsviewer.backends._conversions.arrays_compatible(a, b)[source]
Check if two arrays are from the same backend.
- Parameters:
a (Any) – Arrays to compare
b (Any) – Arrays to compare
- Returns:
True if both arrays are from the same backend
- Return type:
Note
Always use ensure_numpy() at I/O boundaries (HDF5, PyQtGraph,
Matplotlib) to avoid passing JAX arrays to libraries that expect NumPy.
I/O Adapters¶
Centralized adapters for array conversion at I/O boundaries with optional performance monitoring.
Device Management¶
Singleton manager for compute device selection and GPU/CPU placement.
- class xpcsviewer.backends.DeviceType(*values)[source]
Bases:
EnumEnumeration of supported device types.
- CPU = 'cpu'
- GPU = 'gpu'
- class xpcsviewer.backends.DeviceConfig(preferred_device=DeviceType.CPU, allow_gpu_fallback=True, memory_fraction=0.9)[source]
Bases:
objectConfiguration for device selection.
- preferred_device
Preferred compute device (default: CPU)
- Type:
DeviceType
- allow_gpu_fallback
Allow fallback to CPU if GPU is unavailable (default: True)
- Type:
- memory_fraction
Maximum fraction of GPU memory to use (default: 0.9)
- Type:
- preferred_device: DeviceType = 'cpu'
- allow_gpu_fallback: bool = True
- memory_fraction: float = 0.9
- __post_init__()[source]
Validate configuration values.
- Return type:
None
- classmethod from_environment()[source]
Create configuration from environment variables.
Environment Variables¶
- XPCS_USE_GPUstr
‘true’ or ‘false’ (default: ‘false’)
- XPCS_GPU_FALLBACKstr
‘true’ or ‘false’ (default: ‘true’)
- XPCS_GPU_MEMORY_FRACTIONstr
Float value 0.0-1.0 (default: ‘0.9’)
- Return type:
DeviceConfig
- class xpcsviewer.backends.DeviceManager[source]
Bases:
objectSingleton manager for compute device selection and placement.
This class provides centralized management of device selection, including automatic fallback from GPU to CPU when needed.
Examples
>>> manager = DeviceManager() >>> manager.configure(DeviceConfig(preferred_device=DeviceType.GPU)) >>> if manager.is_gpu_enabled: ... print("Using GPU")
- Return type:
DeviceManager
- static __new__(cls)[source]
Create singleton instance.
- Return type:
DeviceManager
- __init__()[source]
Initialize device manager (only runs once).
- Return type:
None
- configure(config)[source]
Configure device manager with specified settings.
- Parameters:
config (DeviceConfig) – Device configuration
- Raises:
RuntimeError – If GPU is requested but unavailable and fallback is disabled
- Return type:
None
- property jax_available: bool
Check if JAX is installed and available.
- property gpu_available: bool
Check if GPU devices are available.
- property is_gpu_enabled: bool
Check if GPU is currently enabled.
- property has_gpu: bool
Check if GPU is available (alias for gpu_available).
- property available_devices: list
Get list of available compute devices.
- Returns:
List of JAX device objects, or empty list if JAX unavailable
- Return type:
- property config: DeviceConfig
Get current device configuration.
- property current_device: DeviceInfo | None
Get current device info.
- get_device()[source]
Get the current JAX device object.
- Returns:
JAX device object, or None if JAX is not available
- Return type:
jax.Device or None
- place_on_device(array)[source]
Place array on the current device.
- Parameters:
array (array-like) – Array to place on device
- Returns:
Array on the appropriate device
- Return type:
array
- get_memory_info()[source]
Get GPU memory information.
- Returns:
Dictionary with ‘total’ and ‘available’ memory in bytes, or None values if not on GPU
- Return type:
- classmethod reset()[source]
Reset the singleton instance (for testing).
- Return type:
None
SciPy Replacements¶
JAX-compatible replacements for SciPy functions using interpax, optimistix, and optax. Used by the SimpleMask module for GPU-accelerated operations.
JAX replacements for SciPy functions using interpax, optimistix, and optax.
This module provides JAX-compatible implementations of SciPy functions that are used in the SimpleMask module: - interpax for interpolation - optimistix for optimization and root-finding - optax for gradient-based optimization
- Available modules:
ndimage: gaussian_filter, gaussian_filter1d, zoom, etc. interpolate: interp1d, interp2d_jax, etc. optimize: minimize, curve_fit, least_squares, root
- class xpcsviewer.backends.scipy_replacements.Interp1d(x, y, kind='linear', bounds_error=True, fill_value=nan)[source]
Bases:
object1D interpolation class compatible with scipy.interpolate.interp1d.
This class provides JAX-compatible 1D interpolation using interpax. It stores the interpolation data and provides a callable interface.
- Parameters:
x (array-like) – 1D array of x coordinates (must be monotonically increasing)
y (array-like) – 1D or ND array of y values. If ND, interpolation is performed along the last axis.
kind (str) – Interpolation method: ‘linear’, ‘nearest’, ‘quadratic’, ‘cubic’. Default is ‘linear’.
bounds_error (bool) – If True, raise ValueError for out-of-bounds values. If False, use fill_value for out-of-bounds. Default: True.
fill_value (float or tuple) – Value for out-of-bounds points. Can be ‘extrapolate’ for linear extrapolation, or a tuple (below, above) for different values below and above the range.
Examples
>>> x = np.array([0, 1, 2, 3]) >>> y = np.array([0, 1, 4, 9]) >>> f = Interp1d(x, y, kind='linear') >>> f(1.5) 2.5
- __init__(x, y, kind='linear', bounds_error=True, fill_value=nan)[source]
Initialize interpolator.
- __call__(x_new)[source]
Evaluate interpolation at new x values.
- Parameters:
x_new (array-like) – New x values at which to interpolate
- Returns:
Interpolated y values
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.interp1d(x, y, kind='linear', bounds_error=True, fill_value=nan)[source]
Create 1D interpolation function.
Factory function that returns an Interp1d instance using interpax when JAX is available.
- Parameters:
x (array-like) – 1D array of x coordinates (must be monotonically increasing)
y (array-like) – Array of y values
kind (str) – Interpolation method: ‘linear’, ‘nearest’, ‘cubic’, etc.
bounds_error (bool) – If True, raise ValueError for out-of-bounds values
fill_value (float or tuple or 'extrapolate') – Value for out-of-bounds points
- Returns:
Callable interpolation function
- Return type:
Interp1d
- xpcsviewer.backends.scipy_replacements.interp2d_jax(xq, yq, x, y, f, method='linear', extrap=False, fill_value=nan)[source]
2D interpolation using interpax.
- Parameters:
xq (array-like) – Query points for interpolation
yq (array-like) – Query points for interpolation
x (array-like) – Original grid coordinates (1D arrays)
y (array-like) – Original grid coordinates (1D arrays)
f (array-like) – Values on original grid (2D array)
method (str) – Interpolation method: ‘linear’, ‘cubic’, etc.
extrap (bool) – Whether to extrapolate outside bounds
fill_value (float) – Value for out-of-bounds points when extrap=False
- Returns:
Interpolated values at query points
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.gaussian_filter(input_array, sigma, mode='reflect', truncate=4.0)[source]
Apply Gaussian filter to array.
This is a JAX-compatible implementation that uses convolution with a Gaussian kernel. Falls back to scipy.ndimage.gaussian_filter when JAX is not available.
- Parameters:
input_array (array-like) – Input array to filter
sigma (float or tuple of floats) – Standard deviation for Gaussian kernel. Can be a single value for isotropic filtering or a tuple for anisotropic filtering.
mode (str) – Boundary mode: ‘reflect’, ‘constant’, ‘nearest’, ‘wrap’ (default: ‘reflect’)
truncate (float) – Truncate filter at this many standard deviations (default: 4.0)
- Returns:
Filtered array
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.gaussian_filter1d(input_array, sigma, axis=-1, mode='reflect', truncate=4.0)[source]
Apply 1D Gaussian filter along specified axis.
This is a JAX-compatible implementation that uses convolution with a 1D Gaussian kernel. Falls back to scipy.ndimage.gaussian_filter1d when JAX is not available.
- Parameters:
input_array (array-like) – Input array to filter
sigma (float) – Standard deviation for Gaussian kernel
axis (int) – Axis along which to apply filter (default: -1)
mode (str) – Boundary mode: ‘reflect’, ‘constant’, ‘nearest’, ‘wrap’ (default: ‘reflect’)
truncate (float) – Truncate filter at this many standard deviations (default: 4.0)
- Returns:
Filtered array
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.zoom(input_array, zoom_factor, order=1, mode='constant', cval=0.0)[source]
Zoom (resize) array using interpolation.
This is a JAX-compatible implementation using interpax for interpolation. Falls back to scipy.ndimage.zoom when JAX is not available.
- Parameters:
input_array (array-like) – Input array to zoom
zoom_factor (float or tuple of floats) – Zoom factor for each axis. If scalar, applied uniformly.
order (int) – Interpolation order (0=nearest, 1=linear, 3=cubic). Default: 1.
mode (str) – Boundary mode (default: ‘constant’)
cval (float) – Fill value for constant mode (default: 0.0)
- Returns:
Zoomed array
- Return type:
ndarray
- class xpcsviewer.backends.scipy_replacements.OptimizeResult(x, fun, success, message, nfev=0, nit=0, jac=None)[source]
Bases:
objectContainer for optimization result.
Compatible with scipy.optimize.OptimizeResult.
- Parameters:
- x
Solution vector
- Type:
ndarray
- fun
Function value at solution
- Type:
- success
Whether optimization converged
- Type:
- message
Description of termination
- Type:
- nfev
Number of function evaluations
- Type:
- nit
Number of iterations
- Type:
- jac
Jacobian at solution (if available)
- Type:
ndarray, optional
- x: ndarray
- fun: float
- success: bool
- message: str
- nfev: int = 0
- nit: int = 0
- xpcsviewer.backends.scipy_replacements.minimize(fun, x0, args=(), method=None, jac=None, bounds=None, tol=None, options=None)[source]
Minimize a scalar function using optimistix/optax.
- Parameters:
fun (callable) – Objective function to minimize
x0 (array-like) – Initial guess
args (tuple) – Extra arguments passed to fun
method (str, optional) – Optimization method: ‘BFGS’, ‘L-BFGS-B’, ‘CG’, ‘Adam’, ‘SGD’
jac (callable or bool, optional) – Jacobian function or True for auto-diff
tol (float, optional) – Tolerance for termination
options (dict, optional) – Solver-specific options
- Returns:
Optimization result container
- Return type:
OptimizeResult
- xpcsviewer.backends.scipy_replacements.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, bounds=None, maxfev=1000, **kwargs)[source]
Nonlinear least squares curve fitting using optimistix.
- Parameters:
f (callable) – Model function:
f(x, *params)xdata (array-like) – Independent variable
ydata (array-like) – Dependent variable (data to fit)
p0 (array-like, optional) – Initial guess for parameters
sigma (array-like, optional) – Uncertainties in ydata
absolute_sigma (bool) – If True, sigma is used in absolute sense
bounds (tuple, optional) – Bounds (lower, upper) for parameters
maxfev (int) – Maximum function evaluations
- Returns:
popt (ndarray) – Optimal parameters
pcov (ndarray) – Covariance matrix of parameters
- Return type:
tuple[np.ndarray, np.ndarray]
- xpcsviewer.backends.scipy_replacements.least_squares(fun, x0, bounds=(-inf, inf), method='trf', ftol=1e-08, xtol=1e-08, gtol=1e-08, max_nfev=None, **kwargs)[source]
Solve nonlinear least squares using optimistix.
- Parameters:
fun (callable) – Function returning residuals: fun(x) -> residuals
x0 (array-like) – Initial guess
bounds (tuple) – Lower and upper bounds
method (str) – Method: ‘trf’, ‘dogbox’, ‘lm’
ftol (float) – Tolerances
xtol (float) – Tolerances
gtol (float) – Tolerances
max_nfev (int, optional) – Maximum function evaluations
- Returns:
Optimization result
- Return type:
OptimizeResult
- xpcsviewer.backends.scipy_replacements.root(fun, x0, args=(), method='hybr', jac=None, tol=None, options=None)[source]
Find roots of a function using optimistix.
- Parameters:
- Returns:
Root finding result
- Return type:
OptimizeResult
JAX replacements for scipy.interpolate functions using interpax.
This module provides JAX-compatible implementations of scipy.interpolate functions used in SimpleMask for interpolation operations, using the interpax library for GPU-accelerated interpolation.
- class xpcsviewer.backends.scipy_replacements.interpolate.Interp1d(x, y, kind='linear', bounds_error=True, fill_value=nan)[source]
Bases:
object1D interpolation class compatible with scipy.interpolate.interp1d.
This class provides JAX-compatible 1D interpolation using interpax. It stores the interpolation data and provides a callable interface.
- Parameters:
x (array-like) – 1D array of x coordinates (must be monotonically increasing)
y (array-like) – 1D or ND array of y values. If ND, interpolation is performed along the last axis.
kind (str) – Interpolation method: ‘linear’, ‘nearest’, ‘quadratic’, ‘cubic’. Default is ‘linear’.
bounds_error (bool) – If True, raise ValueError for out-of-bounds values. If False, use fill_value for out-of-bounds. Default: True.
fill_value (float or tuple) – Value for out-of-bounds points. Can be ‘extrapolate’ for linear extrapolation, or a tuple (below, above) for different values below and above the range.
Examples
>>> x = np.array([0, 1, 2, 3]) >>> y = np.array([0, 1, 4, 9]) >>> f = Interp1d(x, y, kind='linear') >>> f(1.5) 2.5
- __init__(x, y, kind='linear', bounds_error=True, fill_value=nan)[source]
Initialize interpolator.
- __call__(x_new)[source]
Evaluate interpolation at new x values.
- Parameters:
x_new (array-like) – New x values at which to interpolate
- Returns:
Interpolated y values
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.interpolate.interp1d(x, y, kind='linear', bounds_error=True, fill_value=nan)[source]
Create 1D interpolation function.
Factory function that returns an Interp1d instance using interpax when JAX is available.
- Parameters:
x (array-like) – 1D array of x coordinates (must be monotonically increasing)
y (array-like) – Array of y values
kind (str) – Interpolation method: ‘linear’, ‘nearest’, ‘cubic’, etc.
bounds_error (bool) – If True, raise ValueError for out-of-bounds values
fill_value (float or tuple or 'extrapolate') – Value for out-of-bounds points
- Returns:
Callable interpolation function
- Return type:
Interp1d
- xpcsviewer.backends.scipy_replacements.interpolate.interp2d_jax(xq, yq, x, y, f, method='linear', extrap=False, fill_value=nan)[source]
2D interpolation using interpax.
- Parameters:
xq (array-like) – Query points for interpolation
yq (array-like) – Query points for interpolation
x (array-like) – Original grid coordinates (1D arrays)
y (array-like) – Original grid coordinates (1D arrays)
f (array-like) – Values on original grid (2D array)
method (str) – Interpolation method: ‘linear’, ‘cubic’, etc.
extrap (bool) – Whether to extrapolate outside bounds
fill_value (float) – Value for out-of-bounds points when extrap=False
- Returns:
Interpolated values at query points
- Return type:
ndarray
JAX replacements for scipy.ndimage functions.
This module provides JAX-compatible implementations of scipy.ndimage functions used in SimpleMask for smoothing and filtering.
- xpcsviewer.backends.scipy_replacements.ndimage.gaussian_filter(input_array, sigma, mode='reflect', truncate=4.0)[source]
Apply Gaussian filter to array.
This is a JAX-compatible implementation that uses convolution with a Gaussian kernel. Falls back to scipy.ndimage.gaussian_filter when JAX is not available.
- Parameters:
input_array (array-like) – Input array to filter
sigma (float or tuple of floats) – Standard deviation for Gaussian kernel. Can be a single value for isotropic filtering or a tuple for anisotropic filtering.
mode (str) – Boundary mode: ‘reflect’, ‘constant’, ‘nearest’, ‘wrap’ (default: ‘reflect’)
truncate (float) – Truncate filter at this many standard deviations (default: 4.0)
- Returns:
Filtered array
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.ndimage.gaussian_filter1d(input_array, sigma, axis=-1, mode='reflect', truncate=4.0)[source]
Apply 1D Gaussian filter along specified axis.
This is a JAX-compatible implementation that uses convolution with a 1D Gaussian kernel. Falls back to scipy.ndimage.gaussian_filter1d when JAX is not available.
- Parameters:
input_array (array-like) – Input array to filter
sigma (float) – Standard deviation for Gaussian kernel
axis (int) – Axis along which to apply filter (default: -1)
mode (str) – Boundary mode: ‘reflect’, ‘constant’, ‘nearest’, ‘wrap’ (default: ‘reflect’)
truncate (float) – Truncate filter at this many standard deviations (default: 4.0)
- Returns:
Filtered array
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.ndimage.zoom(input_array, zoom_factor, order=1, mode='constant', cval=0.0)[source]
Zoom (resize) array using interpolation.
This is a JAX-compatible implementation using interpax for interpolation. Falls back to scipy.ndimage.zoom when JAX is not available.
- Parameters:
input_array (array-like) – Input array to zoom
zoom_factor (float or tuple of floats) – Zoom factor for each axis. If scalar, applied uniformly.
order (int) – Interpolation order (0=nearest, 1=linear, 3=cubic). Default: 1.
mode (str) – Boundary mode (default: ‘constant’)
cval (float) – Fill value for constant mode (default: 0.0)
- Returns:
Zoomed array
- Return type:
ndarray
- xpcsviewer.backends.scipy_replacements.ndimage.uniform_filter(input_array, size=3, mode='reflect')[source]
Apply uniform (box) filter to array.
JAX replacements for scipy.optimize functions using optimistix and optax.
This module provides JAX-compatible implementations of scipy.optimize functions, using optimistix for root-finding and minimization, and optax for gradient-based optimization.
- class xpcsviewer.backends.scipy_replacements.optimize.OptimizeResult(x, fun, success, message, nfev=0, nit=0, jac=None)[source]
Bases:
objectContainer for optimization result.
Compatible with scipy.optimize.OptimizeResult.
- Parameters:
- x
Solution vector
- Type:
ndarray
- fun
Function value at solution
- Type:
- success
Whether optimization converged
- Type:
- message
Description of termination
- Type:
- nfev
Number of function evaluations
- Type:
- nit
Number of iterations
- Type:
- jac
Jacobian at solution (if available)
- Type:
ndarray, optional
- x: ndarray
- fun: float
- success: bool
- message: str
- nfev: int = 0
- nit: int = 0
- xpcsviewer.backends.scipy_replacements.optimize.minimize(fun, x0, args=(), method=None, jac=None, bounds=None, tol=None, options=None)[source]
Minimize a scalar function using optimistix/optax.
- Parameters:
fun (callable) – Objective function to minimize
x0 (array-like) – Initial guess
args (tuple) – Extra arguments passed to fun
method (str, optional) – Optimization method: ‘BFGS’, ‘L-BFGS-B’, ‘CG’, ‘Adam’, ‘SGD’
jac (callable or bool, optional) – Jacobian function or True for auto-diff
tol (float, optional) – Tolerance for termination
options (dict, optional) – Solver-specific options
- Returns:
Optimization result container
- Return type:
OptimizeResult
- xpcsviewer.backends.scipy_replacements.optimize.curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False, bounds=None, maxfev=1000, **kwargs)[source]
Nonlinear least squares curve fitting using optimistix.
- Parameters:
f (callable) – Model function:
f(x, *params)xdata (array-like) – Independent variable
ydata (array-like) – Dependent variable (data to fit)
p0 (array-like, optional) – Initial guess for parameters
sigma (array-like, optional) – Uncertainties in ydata
absolute_sigma (bool) – If True, sigma is used in absolute sense
bounds (tuple, optional) – Bounds (lower, upper) for parameters
maxfev (int) – Maximum function evaluations
- Returns:
popt (ndarray) – Optimal parameters
pcov (ndarray) – Covariance matrix of parameters
- Return type:
tuple[np.ndarray, np.ndarray]
- xpcsviewer.backends.scipy_replacements.optimize.least_squares(fun, x0, bounds=(-inf, inf), method='trf', ftol=1e-08, xtol=1e-08, gtol=1e-08, max_nfev=None, **kwargs)[source]
Solve nonlinear least squares using optimistix.
- Parameters:
fun (callable) – Function returning residuals: fun(x) -> residuals
x0 (array-like) – Initial guess
bounds (tuple) – Lower and upper bounds
method (str) – Method: ‘trf’, ‘dogbox’, ‘lm’
ftol (float) – Tolerances
xtol (float) – Tolerances
gtol (float) – Tolerances
max_nfev (int, optional) – Maximum function evaluations
- Returns:
Optimization result
- Return type:
OptimizeResult
- xpcsviewer.backends.scipy_replacements.optimize.root(fun, x0, args=(), method='hybr', jac=None, tol=None, options=None)[source]
Find roots of a function using optimistix.
- Parameters:
- Returns:
Root finding result
- Return type:
OptimizeResult
See Also¶
Schemas - Type-safe data structures using backend arrays
I/O Facade - HDF5 facade with backend-aware I/O
Fitting Module - Fitting module using JAX backend for acceleration