API Reference
This page contains the API reference for all modules in pydelt.
Automatic Differentiation
Functions for calculating derivatives using automatic differentiation with trained models.
Note: TensorFlow retracing warnings and general UserWarnings are suppressed in this module.
- pydelt.autodiff.neural_network_derivative(time: List[float] | ndarray, signal: List[float] | ndarray, framework: str = 'tensorflow', hidden_layers: List[int] = [128, 96, 64, 48, 32], epochs: int = 1000, holdout_fraction: float = 0.0, return_model: bool = False, order: int = 1, dropout: float = 0.1, learning_rate: float = 0.001, batch_size: int = 32, early_stopping: bool = True, patience: int = 50) Callable[[float | ndarray], ndarray] | Tuple[Callable[[float | ndarray], ndarray], Any][source]
Calculate derivatives using automatic differentiation with a neural network.
- Parameters:
time – Input array, shape (N,) for univariate or (N, n_in) for multivariate
signal – Output array, shape (N,) for univariate or (N, n_out) for multivariate
framework – Neural network framework (‘pytorch’ or ‘tensorflow’)
hidden_layers – List of hidden layer sizes
epochs – Number of training epochs
holdout_fraction – Fraction of data to use for validation
return_model – Whether to return the model along with the derivative function
order – Order of the derivative to compute
dropout – Dropout rate for regularization
learning_rate – Learning rate for optimizer
batch_size – Batch size for training
early_stopping – Whether to use early stopping
patience – Number of epochs with no improvement after which training will be stopped
- Returns:
Callable function that calculates the gradient (for scalar output) or Jacobian (for vector output) at any input point If return_model is True:
- Tuple containing:
Callable function that calculates derivatives
Trained neural network model
- Return type:
If return_model is False
Interpolation
Functions for interpolating time series data using various methods.
- class pydelt.interpolation.BaseInterpolator[source]
Bases:
objectAbstract base class for all interpolators with stochastic derivative support.
- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the interpolated function.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- set_stochastic_link(link_function: str | StochasticLinkFunction, method: str = 'ito', **kwargs)[source]
Set a stochastic link function for derivative transformations.
- Parameters:
link_function – Either a string name (‘normal’, ‘lognormal’, etc.) or StochasticLinkFunction instance
method – Either ‘ito’ or ‘stratonovich’ for stochastic integration method
**kwargs – Parameters for the link function if using string name
- class pydelt.interpolation.FdaInterpolator(smoothing: float | None = None, k: int = 3)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the FDA spline interpolation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.GllaInterpolator(embedding: int = 3, n: int = 2)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the GLLA Hermite interpolation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.GoldInterpolator(window_size: int = 5, normalization: str = 'min', zero_mean: bool = False)[source]
Bases:
BaseInterpolator
- class pydelt.interpolation.LlaInterpolator(window_size: int = 5, normalization: str = 'min', zero_mean: bool = False)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the LLA Hermite interpolation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.LoessInterpolator(degree: int = 2, frac: float = 0.1, it: int = 3)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the LOESS interpolation using numerical differentiation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.LowessInterpolator(frac: float = 0.1, it: int = 3)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the LOWESS interpolation using numerical differentiation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.NeuralNetworkInterpolator(framework: str = 'pytorch', hidden_layers: list = [64, 32], epochs: int = 1000, dropout: float = 0.1)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives using automatic differentiation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.PyTorchMLP(input_dim=1, output_dim=1, hidden_layers=[128, 96, 64, 48, 32], dropout=0.1)[source]
Bases:
ModulePyTorch Multi-Layer Perceptron for time series interpolation and autodiff. Supports arbitrary input and output dimensions for vector-valued signals. :param input_dim: Number of input features :type input_dim: int :param output_dim: Number of output features :type output_dim: int :param hidden_layers: Hidden layer sizes :type hidden_layers: list of int :param dropout: Dropout rate :type dropout: float
- forward(x)[source]
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- class pydelt.interpolation.SplineInterpolator(smoothing: float | None = None, k: int = 5)[source]
Bases:
BaseInterpolator- differentiate(order: int = 1, mask: ndarray | List[bool] | List[int] | None = None) Callable[source]
Return a callable function that computes derivatives of the spline interpolation.
- Parameters:
order – Order of derivative (1 for first derivative, 2 for second, etc.)
mask – Optional mask for partial derivatives (boolean array or indices) If provided, only compute derivatives for selected points
- Returns:
Callable function that takes input points and returns derivative values
- class pydelt.interpolation.TensorFlowModel(hidden_layers=[128, 96, 64, 48, 32], dropout=0.1, input_dim=1, output_dim=1)[source]
Bases:
objectTensorFlow model wrapper for time series interpolation.
- pydelt.interpolation.calculate_fit_quality(time: List[float] | ndarray, signal: List[float] | ndarray, interpolation_func: Callable[[float | ndarray], ndarray]) Dict[str, float][source]
Calculate the quality of fit for an interpolation function.
- Parameters:
time – Time points of the original signal
signal – Signal values
interpolation_func – Interpolation function to evaluate
- Returns:
Dictionary with quality metrics (r_squared, rmse)
- pydelt.interpolation.derivative_based_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, method: str = 'lla', **kwargs) Callable[[float | ndarray], ndarray][source]
Interpolate a time series using derivative estimation and signal reconstruction.
- Parameters:
time – Time points of the original signal
signal – Signal values
method – Derivative estimation method (‘lla’, ‘glla’, ‘gold’, ‘fda’)
**kwargs – Additional parameters for the derivative method
- Returns:
Callable function that interpolates the signal at any time point
- pydelt.interpolation.fda_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, smoothing: float | None = None, k: int = 3, return_model: bool = False) Callable[[float | ndarray], ndarray] | Tuple[Callable[[float | ndarray], ndarray], object][source]
Interpolate a time series using Functional Data Analysis (FDA) spline smoothing.
- Parameters:
time – Time points of the original signal
signal – Signal values
smoothing – Smoothing factor for the spline. If None, it is automatically determined.
k – Degree of the spline (default: 3, cubic)
return_model – If True, also return the fitted UnivariateSpline object for further predictions/interpolations.
- Returns:
Callable function (UnivariateSpline) that interpolates the signal at any time point - If return_model is True: (UnivariateSpline, UnivariateSpline) tuple (the spline is both the interpolator and the fitted object)
- Return type:
If return_model is False (default)
- pydelt.interpolation.get_best_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, methods: List[str] = ['linear', 'spline', 'lowess', 'loess', 'lla', 'glla', 'gold', 'fda'], metric: str = 'r_squared') Tuple[Callable[[float | ndarray], ndarray], str, float][source]
Find the best interpolation method based on fit quality.
- Parameters:
time – Time points of the original signal
signal – Signal values
methods – List of interpolation methods to try
metric – Metric to use for comparison (‘r_squared’ or ‘rmse’)
- Returns:
Best interpolation function
Name of the best method
Value of the quality metric for the best method
- Return type:
Tuple containing
- pydelt.interpolation.glla_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, embedding: int = 3, n: int = 2, r2_threshold: float | None = None, resample_method: str | None = None) Callable[[float | ndarray], ndarray][source]
Interpolate a time series using Generalized Local Linear Approximation (GLLA) with Hermite interpolation.
- Parameters:
time – Time points of the original signal
signal – Signal values
embedding – Number of points to consider for derivative calculation (default: 3)
n – Maximum order of derivative to calculate (default: 2)
r2_threshold – Optional R^2 threshold for filtering low-quality windows
resample_method – Method for resampling derivatives (‘spline’, ‘lowess’, ‘loess’, etc.)
- Returns:
Callable function that interpolates the signal at any time point
- pydelt.interpolation.gold_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, window_size: int = 5, normalization: str = 'min', zero_mean: bool = False, r2_threshold: float | None = None, resample_method: str | None = None) Callable[[float | ndarray], ndarray][source]
Interpolate a time series using Generalized Orthogonal Local Derivative (GOLD) with Hermite interpolation.
- Parameters:
time – Time points of the original signal
signal – Signal values
window_size – Size of the window for local regression (default: 5)
normalization – Normalization method for window (‘min’, ‘none’, etc.)
zero_mean – Whether to zero-mean center the window before regression
r2_threshold – Optional R^2 threshold for filtering low-quality windows
resample_method – Method for resampling derivatives (‘spline’, ‘lowess’, ‘loess’, etc.)
- Returns:
Callable function that interpolates the signal at any time point
- pydelt.interpolation.lla_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, window_size: int = 5, normalization: str = 'min', zero_mean: bool = False, r2_threshold: float | None = None, resample_method: str | None = None) Callable[[float | ndarray], ndarray][source]
Interpolate a time series using Local Linear Approximation (LLA) with Hermite interpolation.
- Parameters:
time – Time points of the original signal
signal – Signal values
window_size – Size of the window for local linear regression (default: 5)
normalization – Normalization method for window (‘min’, ‘none’, etc.)
zero_mean – Whether to zero-mean center the window before regression
r2_threshold – Optional R^2 threshold for filtering low-quality windows
resample_method – Method for resampling derivatives (‘spline’, ‘lowess’, ‘loess’, etc.)
- Returns:
Callable function that interpolates the signal at any time point
- pydelt.interpolation.local_segmented_linear(time: List[float] | ndarray, signal: List[float] | ndarray, window_size: int = 5, force_continuous: bool = True) Callable[[float | ndarray], ndarray][source]
Interpolate a time series using local segmented linear regression.
- Parameters:
time – Time points of the original signal
signal – Signal values
window_size – Size of the window for local linear regression
force_continuous – If True, ensures the interpolation is continuous at segment boundaries
- Returns:
Callable function that interpolates the signal at any time point
- pydelt.interpolation.loess_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, degree: int = 2, frac: float = 0.3, it: int = 3, return_model: bool = False) Callable[[float | ndarray], ndarray] | Tuple[Callable[[float | ndarray], ndarray], object][source]
Interpolate a time series using LOESS (LOcally Estimated Scatterplot Smoothing). This is similar to LOWESS but uses higher-degree local polynomials.
- Parameters:
time – Time points of the original signal
signal – Signal values
degree – Degree of local polynomials (1=linear, 2=quadratic)
frac – Between 0 and 1. The fraction of the data used when estimating each y-value
it – Number of robustifying iterations
return_model – If True, also return the smoothed data array used for interpolation (for further analysis or custom interpolators).
- Returns:
Callable function (interp1d) that interpolates the signal at any time point - If return_model is True: (interp1d, smoothed_data) tuple
- Return type:
If return_model is False (default)
- pydelt.interpolation.lowess_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, frac: float = 0.3, it: int = 3, return_model: bool = False) Callable[[float | ndarray], ndarray] | Tuple[Callable[[float | ndarray], ndarray], object][source]
Interpolate a time series using LOWESS (Locally Weighted Scatterplot Smoothing).
- Parameters:
time – Time points of the original signal
signal – Signal values
frac – Between 0 and 1. The fraction of the data used when estimating each y-value
it – Number of robustifying iterations
return_model – If True, also return the smoothed data array used for interpolation (for further analysis or custom interpolators).
- Returns:
Callable function (interp1d) that interpolates the signal at any time point - If return_model is True: (interp1d, smoothed_data) tuple
- Return type:
If return_model is False (default)
- pydelt.interpolation.neural_network_interpolation(time: list | ndarray, signal: list | ndarray, framework: str = 'pytorch', hidden_layers: list = [64, 32], epochs: int = 1000, holdout_fraction: float = 0.0, return_model: bool = False, **kwargs) callable | tuple[source]
- pydelt.interpolation.spline_interpolation(time: List[float] | ndarray, signal: List[float] | ndarray, smoothing: float | None = None, k: int = 5, return_model: bool = False) Callable[[float | ndarray], ndarray] | Tuple[Callable[[float | ndarray], ndarray], object][source]
Interpolate a time series using spline interpolation.
- Parameters:
time – Time points of the original signal
signal – Signal values
smoothing – Smoothing factor for the spline. If None, it’s automatically determined
k – Degree of the spline (1=linear, 2=quadratic, 3=cubic)
return_model – If True, also return the fitted UnivariateSpline object for further predictions/interpolations.
- Returns:
Callable function (UnivariateSpline) that interpolates the signal at any time point - If return_model is True: (UnivariateSpline, UnivariateSpline) tuple (the spline is both the interpolator and the fitted object)
- Return type:
If return_model is False (default)
Example
>>> interp, spline_obj = spline_interpolation(time, signal, return_model=True) >>> new_vals = interp(new_time) >>> # Or use spline_obj directly for further predictions: >>> spline_obj(new_time)
Derivatives
- pydelt.derivatives.fda(input_data: ndarray, output_data: ndarray, spar: float | None = None, r2_threshold: float | None = None, resample_method: str | None = None, signal: ndarray | None = None, time: ndarray | None = None) Dict[str, ndarray | float | None][source]
Calculate derivatives using the Functional Data Analysis (FDA) method. Supports vector-valued outputs (multiple columns).
- Parameters:
input_data – Array of input values, shape (N,) for univariate or (N, n_in) for multivariate
output_data – Array of output values, shape (N,) or (N, n_out)
spar – Smoothing parameter for the spline. If None, automatically determined
r2_threshold – If provided, only keep derivatives where local fit R² exceeds this value
resample_method – If provided with r2_threshold, resample filtered derivatives using this method (‘linear’, ‘spline’, ‘lowess’, ‘loess’, or ‘best’)
signal – DEPRECATED - use output_data instead
time – DEPRECATED - use input_data instead
- Returns:
dinput: Input values for derivatives
doutput: Matrix of derivatives (0th to 2nd order, shape (N, n_out, 3))
spar: Smoothing parameter used
r_squared: R² values for each point (if calculated)
- Return type:
Dictionary containing
- pydelt.derivatives.glla(input_data: ndarray, output_data: ndarray, embedding: int = 3, n: int = 2, r2_threshold: float | None = None, resample_method: str | None = None, signal: ndarray | None = None, time: ndarray | None = None) Dict[str, ndarray | int][source]
Calculate derivatives using the Generalized Local Linear Approximation (GLLA) method.
- Parameters:
input_data – Array of input values, shape (N,) for univariate or (N, n_in) for multivariate
output_data – Array of output values, shape (N,) for univariate or (N, n_out) for multivariate
embedding – Number of points to consider for derivative calculation
n – Maximum order of derivative to calculate
r2_threshold – If provided, only keep derivatives where local fit R² exceeds this value
resample_method – If provided with r2_threshold, resample filtered derivatives using this method (‘linear’, ‘spline’, ‘lowess’, ‘loess’, or ‘best’)
signal – DEPRECATED - use output_data instead
time – DEPRECATED - use input_data instead
- Returns:
dinput: Input values for derivatives
doutput: Matrix of derivatives (0th to nth order)
embedding: Embedding dimension used
n: Maximum order of derivatives calculated
r_squared: R² values for each point (if calculated)
- Return type:
Dictionary containing
- pydelt.derivatives.gold(input_data: ndarray, output_data: ndarray, embedding: int = 3, n: int = 2, r2_threshold: float | None = None, resample_method: str | None = None, signal: ndarray | None = None, time: ndarray | None = None) Dict[str, ndarray | int][source]
Calculate derivatives using the Generalized Orthogonal Local Derivative (GOLD) method.
- Parameters:
input_data – Array of input values, shape (N,) for univariate or (N, n_in) for multivariate
output_data – Array of output values, shape (N,) for univariate or (N, n_out) for multivariate
embedding – Number of points to consider for derivative calculation
n – Maximum order of derivative to estimate
r2_threshold – If provided, only keep derivatives where local fit R² exceeds this value
resample_method – If provided with r2_threshold, resample filtered derivatives using this method (‘linear’, ‘spline’, ‘lowess’, ‘loess’, or ‘best’)
signal – DEPRECATED - use output_data instead
time – DEPRECATED - use input_data instead
- Returns:
dinput: Input values for derivatives
doutput: Matrix of derivatives (0th to nth order)
embedding: Embedding dimension used
n: Maximum order of derivatives calculated
r_squared: R² values for each point (if calculated)
- Return type:
Dictionary containing
- pydelt.derivatives.lla(input_data: List[float] | ndarray, output_data: List[float] | ndarray, window_size: int | None = 5, normalization: str = 'min', zero_mean: bool = False, r2_threshold: float | None = None, resample_method: str | None = None, time_data: List[int] | ndarray | None = None, signal_data: List[float] | ndarray | None = None) Tuple[ndarray, ndarray][source]
Local Linear Approximation (LLA) method for estimating derivatives. Supports univariate and multivariate input/output data. Uses configurable normalization and linear regression within a sliding window.
- Parameters:
input_data – Array of input values, shape (N,) for univariate or (N, n_in) for multivariate
output_data – Array of output values, shape (N,) for univariate or (N, n_out) for multivariate
window_size – Number of points to consider for derivative calculation
normalization – Type of normalization to apply (‘min’, ‘none’)
zero_mean – Whether to center the data by subtracting the mean
r2_threshold – If provided, only keep derivatives where local fit R² exceeds this value
resample_method – If provided with r2_threshold, resample filtered derivatives using this method (‘linear’, ‘spline’, ‘lowess’, ‘loess’, or ‘best’)
time_data – DEPRECATED - use input_data instead
signal_data – DEPRECATED - use output_data instead
- Returns:
Array of derivative values, shape (N, n_out) for univariate input or (N, n_out, n_in) for multivariate
Array of step sizes used for each calculation
- Return type:
Tuple containing
Multivariate Derivatives
Multivariate derivative computation for pydelt.
This module provides classes for computing multivariate derivatives including: - Gradient (∇f): For scalar functions of multiple variables - Jacobian (∂f/∂x): For vector-valued functions - Hessian (∂²f/∂x²): Second derivatives for scalar functions - Laplacian (∇²f): Trace of Hessian for scalar functions
The module supports both traditional interpolation methods and neural networks with automatic differentiation for superior performance in high dimensions.
- class pydelt.multivariate.MultivariateDerivatives(interpolator_class: type = <class 'pydelt.interpolation.SplineInterpolator'>, **interpolator_kwargs)[source]
Bases:
objectCompute multivariate derivatives using traditional interpolation methods.
This class provides methods to compute gradient, Jacobian, Hessian, and Laplacian for multivariate functions using fitted interpolators. It works by fitting separate 1D interpolators for each output-input dimension pair and computing derivatives along each dimension independently.
- Key Features:
Gradient computation for scalar functions
Jacobian matrix computation for vector-valued functions
Hessian matrix computation for scalar functions (diagonal elements only)
Laplacian computation for scalar functions
Support for any interpolator from the pydelt library
- Limitations:
Mixed partial derivatives are approximated as zero
Assumes separable dependencies between input dimensions
Best suited for functions where each output depends primarily on one input
Critical Point Smoothing: Interpolation methods smooth out sharp mathematical features, leading to non-zero gradients at points where they should be zero
Boundary Effects: Edge artifacts can distort derivative calculations
Regularization Impact: Smoothing parameters blur sharp transitions and critical points
Finite Sampling: Cannot capture infinitely sharp transitions or discontinuities
- Example of Critical Point Issue:
For f(x,y) = (x-y)², the mathematical gradient is zero along x=y line, especially at corners like (-3,-3) and (3,3). However, numerical interpolation will give non-zero gradients everywhere due to smoothing effects.
- Mitigation Strategies:
Use higher resolution sampling near critical points
Reduce smoothing parameters (but beware of overfitting)
Validate against analytical solutions when available
Consider neural network methods with automatic differentiation for exact derivatives
For exact mixed partial derivatives and better handling of critical points, consider using NeuralNetworkMultivariateDerivatives with automatic differentiation.
Example
>>> from pydelt.interpolation import SplineInterpolator >>> mv = MultivariateDerivatives(SplineInterpolator, smoothing=0.1) >>> mv.fit(input_data, output_data) >>> gradient_func = mv.gradient() >>> grad = gradient_func(test_points)
- Parameters:
interpolator_class – The interpolation class to use (e.g., SplineInterpolator, LlaInterpolator)
**interpolator_kwargs – Keyword arguments to pass to the interpolator constructor
- fit(input_data: ndarray, output_data: ndarray)[source]
Fit interpolators for multivariate derivative computation.
This method fits separate 1D interpolators for each output-input dimension pair. For each combination of output dimension i and input dimension j, an interpolator is fitted using input_data[:, j] as x-values and output_data[:, i] as y-values.
The data is automatically sorted and duplicate x-values are handled by averaging the corresponding y-values to ensure proper interpolation.
- Parameters:
input_data – Input data of shape (n_samples, n_input_dims) Must be 2D array where each row is a sample and each column is an input dimension.
output_data – Output data of shape (n_samples,) for scalar functions or (n_samples, n_output_dims) for vector-valued functions. For scalar functions, can be 1D array.
- Returns:
Self for method chaining
- Raises:
ValueError – If input_data is not 2D or if input/output sample counts don’t match
Note
After fitting, the interpolators are stored in self.interpolators as a nested list where interpolators[i][j] contains the interpolator for output i, input j.
- gradient(eval_points: ndarray | None = None) Callable[source]
Compute the gradient (∇f) for scalar functions.
The gradient is computed by fitting separate 1D interpolators for each input dimension and evaluating their first derivatives. This approach works well for functions where each output depends primarily on one input dimension.
- Parameters:
eval_points – Points at which to evaluate the gradient. If None, uses training points.
- Returns:
Callable function that takes input points and returns gradient vectors.
- For single evaluation point:
Input: array of shape (n_input_dims,) or (1, n_input_dims)
Output: array of shape (n_input_dims,)
- For multiple evaluation points:
Input: array of shape (n_points, n_input_dims)
Output: array of shape (n_points, n_input_dims)
- Raises:
ValueError – If the function is not scalar (n_outputs != 1)
RuntimeError – If the model has not been fitted
Note
This method assumes that partial derivatives can be approximated by fitting 1D interpolators along each input dimension independently. Mixed partial derivatives are not computed with this approach.
- Critical Point Warning:
Numerical interpolation smooths out sharp mathematical features. For functions with critical points (where gradient should be zero), the computed gradient may be non-zero due to smoothing effects. Always validate against analytical solutions when possible, especially near minima, maxima, and saddle points.
- hessian(eval_points: ndarray | None = None) Callable[source]
Compute the Hessian matrix (∂²f/∂x²) for scalar functions.
The Hessian matrix contains all second-order partial derivatives of a scalar function. Element (i,j) represents ∂²f/∂x_i∂x_j. For traditional interpolation methods, only diagonal elements (pure second derivatives) are computed; off-diagonal elements (mixed partials) are approximated as zero.
- Parameters:
eval_points – Points at which to evaluate the Hessian. If None, uses training points.
- Returns:
Callable function that takes input points and returns Hessian matrices.
- For single evaluation point:
Input: array of shape (n_input_dims,) or (1, n_input_dims)
Output: array of shape (n_inputs, n_inputs)
- For multiple evaluation points:
Input: array of shape (n_points, n_input_dims)
Output: array of shape (n_points, n_inputs, n_inputs)
- Raises:
ValueError – If the function is not scalar (n_outputs != 1)
RuntimeError – If the model has not been fitted
Warning
Traditional interpolation methods cannot compute mixed partial derivatives (off-diagonal elements). These are set to zero, which may not be accurate for functions with significant cross-dependencies. Consider using neural network methods with automatic differentiation for exact mixed partials.
- jacobian(eval_points: ndarray | None = None) Callable[source]
Compute the Jacobian matrix (∂f/∂x) for vector-valued functions.
The Jacobian matrix contains all first-order partial derivatives of a vector-valued function. Element (i,j) represents ∂f_i/∂x_j. This is computed by fitting separate 1D interpolators for each output-input dimension pair.
- Parameters:
eval_points – Points at which to evaluate the Jacobian. If None, uses training points.
- Returns:
Callable function that takes input points and returns Jacobian matrices.
- For single evaluation point:
Input: array of shape (n_input_dims,) or (1, n_input_dims)
Output: array of shape (n_outputs, n_inputs)
- For multiple evaluation points:
Input: array of shape (n_points, n_input_dims)
Output: array of shape (n_points, n_outputs, n_inputs)
- Raises:
RuntimeError – If the model has not been fitted
Note
For scalar functions (n_outputs=1), the Jacobian is equivalent to the gradient transposed. Mixed partial derivatives are not computed with traditional interpolation methods.
- laplacian(eval_points: ndarray | None = None) Callable[source]
Compute the Laplacian (∇²f = tr(H)) for scalar functions.
The Laplacian is the trace (sum of diagonal elements) of the Hessian matrix, representing the sum of all pure second partial derivatives: ∇²f = ∂²f/∂x₁² + ∂²f/∂x₂² + … This is a scalar measure of the “curvature” of the function.
- Parameters:
eval_points – Points at which to evaluate the Laplacian. If None, uses training points.
- Returns:
Callable function that takes input points and returns Laplacian values.
- For single evaluation point:
Input: array of shape (n_input_dims,) or (1, n_input_dims)
Output: scalar value
- For multiple evaluation points:
Input: array of shape (n_points, n_input_dims)
Output: array of shape (n_points,)
- Raises:
ValueError – If the function is not scalar (n_outputs != 1)
RuntimeError – If the model has not been fitted
Note
Since mixed partial derivatives are not computed in traditional interpolation methods, this Laplacian only includes pure second derivatives. For functions with significant cross-dependencies, consider neural network methods.
- class pydelt.multivariate.NeuralNetworkMultivariateDerivatives(framework: str = 'pytorch', hidden_layers: List[int] = [64, 32], epochs: int = 1000, learning_rate: float = 0.01)[source]
Bases:
objectNeural network-based multivariate derivatives with automatic differentiation.
This class provides true multivariate derivative computation using automatic differentiation, which is superior to traditional methods for high-dimensional problems and can compute exact mixed partial derivatives.
- Parameters:
framework – Deep learning framework to use (‘pytorch’ or ‘tensorflow’)
hidden_layers – List of hidden layer sizes
epochs – Number of training epochs
learning_rate – Learning rate for optimization
- fit(input_data: ndarray, output_data: ndarray) NeuralNetworkMultivariateDerivatives[source]
Fit the neural network model.
- Parameters:
input_data – Input data of shape (n_samples, n_input_dims)
output_data – Output data of shape (n_samples,) for scalar functions or (n_samples, n_output_dims) for vector functions
- Returns:
Self for method chaining
- gradient() Callable[source]
Compute gradient using automatic differentiation.
- Returns:
Callable function that takes input points and returns gradient vectors
- hessian() Callable[source]
Compute Hessian using automatic differentiation.
- Returns:
Callable function that takes input points and returns Hessian matrices
Tensor Derivatives
Tensor derivatives computation for pydelt.
This module provides classes and functions for computing derivatives with respect to vectors and tensors, extending the multivariate derivatives functionality:
Directional derivatives: Derivative along a specific direction vector
Tensor gradients: Gradient of tensor-valued functions
Divergence: Divergence of vector fields
Curl: Curl of vector fields
Strain tensor: Symmetric part of the deformation gradient
Stress tensor: Based on strain tensor and material properties
These operations are particularly useful in continuum mechanics, fluid dynamics, and other physics applications requiring tensor calculus.
- class pydelt.tensor_derivatives.TensorDerivatives(interpolator_class=<class 'pydelt.interpolation.SplineInterpolator'>, **interpolator_kwargs)[source]
Bases:
objectCompute derivatives with respect to vectors and tensors.
This class extends the MultivariateDerivatives class to handle more complex tensor operations commonly used in continuum mechanics, fluid dynamics, and other physics applications.
- Key Features:
Directional derivatives: Derivative along a specific direction vector
Tensor gradients: Gradient of tensor-valued functions
Divergence: Divergence of vector fields
Curl: Curl of vector fields (3D only)
Strain tensor: Symmetric part of the deformation gradient
Stress tensor: Based on strain tensor and material properties
- Limitations:
Mixed partial derivatives are approximated as zero with traditional methods
Best suited for functions where each output depends primarily on one input
Critical point smoothing occurs due to interpolation methods
Example
>>> from pydelt.tensor_derivatives import TensorDerivatives >>> from pydelt.interpolation import SplineInterpolator >>> td = TensorDerivatives(SplineInterpolator, smoothing=0.1) >>> td.fit(input_data, output_data) >>> div_func = td.divergence() >>> div = div_func(test_points)
- curl(eval_points: ndarray | None = None) Callable[source]
Compute the curl of a 3D vector field.
The curl measures the “rotationality” of a vector field at each point. It is only defined for 3D vector fields (3 inputs, 3 outputs).
- Parameters:
eval_points – Optional points at which to evaluate the curl
- Returns:
Callable function that takes input points and returns curl vectors
- directional_derivative(direction: ndarray, normalize: bool = True) Callable[source]
Compute directional derivative along a specified direction.
The directional derivative represents the instantaneous rate of change of the function in the direction of the vector. It is computed as the dot product of the gradient with the direction vector.
- Parameters:
direction – Direction vector of shape (n_inputs,)
normalize – Whether to normalize the direction vector to unit length
- Returns:
Callable function that takes input points and returns directional derivatives
- divergence(eval_points: ndarray | None = None) Callable[source]
Compute the divergence of a vector field.
The divergence measures the “outgoingness” of a vector field at each point. Positive divergence indicates sources (expansion), while negative divergence indicates sinks (contraction).
- Parameters:
eval_points – Optional points at which to evaluate the divergence
- Returns:
Callable function that takes input points and returns divergence values
- fit(input_data: ndarray, output_data: ndarray)[source]
Fit interpolators for tensor derivative computation.
- Parameters:
input_data – Input data of shape (n_samples, n_inputs)
output_data – Output data of shape (n_samples, n_outputs) or (n_samples,)
- Returns:
The fitted instance
- Return type:
self
- strain_tensor(eval_points: ndarray | None = None) Callable[source]
Compute the strain tensor (symmetric part of the deformation gradient).
The strain tensor represents the symmetric part of the deformation gradient and is commonly used in continuum mechanics to describe deformation.
- Parameters:
eval_points – Optional points at which to evaluate the strain tensor
- Returns:
Callable function that takes input points and returns strain tensors
- stress_tensor(lambda_param: float = 1.0, mu_param: float = 0.5, eval_points: ndarray | None = None) Callable[source]
Compute the stress tensor based on strain tensor and Lamé parameters.
The stress tensor is computed using linear elasticity theory: σ = λ tr(ε) I + 2μ ε where: - λ and μ are Lamé parameters - ε is the strain tensor - I is the identity tensor - tr(ε) is the trace of the strain tensor
- Parameters:
lambda_param – First Lamé parameter (λ)
mu_param – Second Lamé parameter (μ, shear modulus)
eval_points – Optional points at which to evaluate the stress tensor
- Returns:
Callable function that takes input points and returns stress tensors
- tensor_gradient(eval_points: ndarray | None = None) Callable[source]
Compute the gradient of a tensor-valued function.
For a tensor-valued function, the gradient is a higher-order tensor. This method computes the gradient tensor by extending the Jacobian computation.
- Parameters:
eval_points – Optional points at which to evaluate the tensor gradient
- Returns:
Callable function that takes input points and returns tensor gradients
Integrals
Functions for integrating time series data using calculated derivatives.
- pydelt.integrals.integrate_derivative(time: List[float] | ndarray, derivative: List[float] | ndarray, initial_value: float | ndarray | List[float] | None = 0.0) ndarray[source]
Integrate a time series derivative to reconstruct the original signal. Supports vector-valued derivatives and initial values.
- Parameters:
time – Time points corresponding to the derivative values.
derivative – Derivative values at each time point, shape (N,) or (N, n_out)
initial_value – Initial value(s) of the integral at time[0]. Scalar or shape (n_out,). Defaults to 0.0.
- Returns:
Reconstructed signal through integration, shape (N, n_out) or (N,)
- Return type:
np.ndarray
Example
>>> time = np.linspace(0, 10, 500) >>> signal = np.stack([np.sin(time), np.cos(time)], axis=-1) >>> derivative, _ = lla(time, signal, window_size=5) >>> reconstructed = integrate_derivative(time, derivative, initial_value=signal[0]) >>> # reconstructed should be close to original signal
- pydelt.integrals.integrate_derivative_with_error(time: List[float] | ndarray, derivative: List[float] | ndarray, initial_value: float | ndarray | List[float] | None = 0.0) Tuple[ndarray, ndarray][source]
Integrate a time series derivative and estimate integration error. Supports vector-valued derivatives and initial values.
- Parameters:
time – Time points corresponding to the derivative values.
derivative – Derivative values at each time point, shape (N,) or (N, n_out)
initial_value – Initial value(s) of the integral at time[0]. Scalar or shape (n_out,). Defaults to 0.0.
- Returns:
(reconstructed signal, estimated error), each shape (N, n_out) or (N,)
- Return type:
Tuple[np.ndarray, np.ndarray]
Example
>>> time = np.linspace(0, 10, 500) >>> signal = np.stack([np.sin(time), np.cos(time)], axis=-1) >>> derivative, _ = lla(time, signal, window_size=5) >>> reconstructed, error = integrate_derivative_with_error(time, derivative, initial_value=signal[0])