derivkit.adaptive_fit module¶
Provides the AdaptiveFitDerivative class.
The user must specify the function to differentiate and the central value at which the derivative should be evaluated. More details about available options can be found in the documentation of the methods.
Typical usage example:
>>> derivative = AdaptiveFitDerivative(function_to_differentiate, 1).compute()
derivative is the derivative of function_to_differerentiate at value 1.
- class derivkit.adaptive_fit.AdaptiveFitDerivative(function, central_value)¶
Bases:
object
Computes derivatives using an adaptive polynomial fitting approach.
This method evaluates a function at symmetrically spaced points around a central value, fits a polynomial of specified degree (equal to the derivative order), and computes the derivative by evaluating the derivative of the polynomial at the central point.
If the polynomial fit fails to meet a specified residual tolerance, the method adaptively removes points with the largest relative residuals (optionally in symmetric pairs) and refits until the tolerance is met or the minimum sample count is reached.
- function¶
The function to be differentiated. Must return scalar or vector output.
- Type:
callable
- central_value¶
The point at which the derivative is evaluated.
- Type:
float
- diagnostics_data¶
The diagnostic data collected during the fitting process, if requested. Defaults to None.
- Type:
dict, optional
- min_used_points¶
The default minimum number of samples required for fitting. This is used to ensure that the polynomial fit has enough data points to be meaningful.
- Type:
int
Initialises the class based on the function and central value.
- Parameters:
function (callable) – The function to be differentiated. Must return scalar or vector output.
central_value (float) – The point at which the derivative is evaluated.
- compute(include_zero=True, derivative_order=1, min_samples=7, diagnostics=False, fallback_mode: str = 'finite_difference', fit_tolerance=0.05, floor_accept_multiplier: float = 2.0, n_workers: int = 1)¶
Computes class derivative using adaptive polynomial fitting.
This method evaluates the target function at symmetric points around a central value, fits a polynomial of the specified order, and computes the derivative from that fit. If the fit quality does not meet the specified tolerance, it adaptively prunes the worst residual points and refits. If all attempts fail, it falls back to a finite difference estimate or accepts a fit based on a looser criterion.
- Parameters:
derivative_order (int, optional) – The order of the derivative to compute (default is 1). Must be 1, 2, 3, or 4.
min_samples (int, optional) – Minimum number of total samples to start with. Must be at least equal to the larger value of derivative_order + 2, self.min_used_points, to have an effect. Smaller values are ignored. Default is 7.
fit_tolerance (float, optional) – Maximum acceptable relative residual for the polynomial fit. Default is 0.05, i.e 5%.
include_zero (bool, optional) – Whether to include the central point in the sampling grid. Default is True.
fallback_mode –
Strategy if the fit fails to meet the tolerance at the minimum sample count. Options are:
”finite_difference”: always reject and use finite difference fallback.
”poly_at_floor”: always accept the polynomial fit at floor regardless of residuals.
”auto”: accept the polynomial at floor if both of the following conditions hold:
(max_residual < floor_accept_multiplier × fit_tolerance)
(median_residual < fit_tolerance);
otherwise fall back to finite differences.
Default is “finite_difference”.
floor_accept_multiplier – Tolerance multiplier used in “auto” fallback mode. Default is 2.0.
diagnostics (bool, optional) – Whether to return diagnostic information such as residuals, fit values, and pruning status. Default is False.
n_workers – Number of worker to use in multiprocessing. Default is 1 (no multiprocessing).
- Returns:
- The estimated
derivative(s). If diagnostics is True, returns a tuple with the derivative array and a dictionary of diagnostic data.
- Return type:
np.ndarray
, (np.ndarray
, dict)- Raises:
ValueError – An error occurred attempting to comput derivatives of order higher than 4.
- get_adaptive_offsets(central_value=None, base_rel=0.01, base_abs=1e-06, factor=1.5, num_offsets=10, max_rel=0.05, max_abs=0.01, step_mode='auto', x_small_threshold=0.001)¶
Returns an array of absolute step sizes to use for adaptive sampling.
- Parameters:
central_value (float_optional) – The central value around which to generate offsets. If None, uses self.central_value.
base_rel (float, optional) – Base relative step size as a fraction of the central value. Default is 1%.
base_abs (float, optional) – Base absolute step size for small central values. Default is 1e-6.
factor (float, optional) – Factor by which to increase the step size for each offset. Default is 1.5.
num_offsets (int, optional) – Number of offsets to generate. Default is 10.
max_rel (float, optional) – Maximum relative step size as a fraction of the central value. Default is 5%.
max_abs (float, optional) – Maximum absolute step size. Default is 1e-2.
step_mode (str, optional) – Mode for determining step sizes: “auto”, “relative”, or “absolute”. Defaults to “auto”.
x_small_threshold (float, optional) – Threshold below which the central value is considered small. Default is 1e-3.
- Returns:
- An array with absolute step sizes (positive
only), not including the central 0 step.
- Return type:
np.ndarray
- recommend_fit_tolerance(dx=0.001, verbose=True)¶
Suggests a fit_tolerance value based on local function variation.
- Parameters:
dx (float, optional) – Offset used to probe nearby values. Default value is 1e-3.
verbose (bool, optional) – Whether to print out the suggested value. Default value is True.
- Returns:
Recommended fit_tolerance.
- Return type:
float