derivkit.utils.validate module#
Validation utilities for DerivativeKit.
- derivkit.utils.validate.check_scalar_valued(function, theta0: ndarray, i: int, n_workers: int)#
Helper used by
build_gradientandbuild_hessian.- Parameters:
function (callable) – The scalar-valued function to differentiate. It should accept a list or array of parameter values as input and return a scalar observable value.
theta0 – The points at which the derivative is evaluated. A 1D array or list of parameter values matching the expected input of the function.
i – Zero-based index of the parameter with respect to which to differentiate.
n_workers – Number of workers used inside
derivkit.derivative_kit.DerivativeKit.differentiate(). This does not parallelize across parameters.
- Raises:
TypeError – If
functiondoes not return a scalar value.
- derivkit.utils.validate.ensure_finite(arr: Any, *, msg: str) None#
Ensures that all values in an array are finite.
- Parameters:
arr – Input array-like to check.
msg – Error message for the exception if non-finite values are found.
- Raises:
FloatingPointError – If any value in
arris non-finite.
- derivkit.utils.validate.flatten_matrix_c_order(cov_function: Callable[[ndarray[tuple[Any, ...], dtype[float64]]], ndarray[tuple[Any, ...], dtype[float64]]], theta: ndarray[tuple[Any, ...], dtype[float64]], *, n_observables: int) ndarray[tuple[Any, ...], dtype[float64]]#
Validates the output of a covariance function and flattens it to 1D.
This function uses the convention of flattening 2D arrays in row-major (“C”) order. The flattening is necessary when computing derivatives of covariance matrices with respect to parameters, as the derivative routines typically operate on 1D arrays.
- Parameters:
cov_function – Callable that takes a parameter vector and returns a covariance matrix.
theta – Parameter vector at which to evaluate the covariance function.
n_observables – Number of observables, used to validate the shape of the covariance matrix.
- Returns:
A 1D NumPy array representing the flattened covariance matrix.
- Raises:
ValueError – If the output of
cov_functiondoes not have the expected shape.
- derivkit.utils.validate.is_finite_and_differentiable(function: Callable[[float], Any], x: float, delta: float = 1e-05) bool#
Check that
functionis finite atxandx + delta.Evaluates without exceptions and returns finite values at both points.
- Parameters:
function – Callable
f(x)returning a scalar or array-like.x – Probe point.
delta – Small forward step.
- Returns:
A boolean which is
Trueif the input is finite at both points andFalseotherwise.
- derivkit.utils.validate.normalize_theta(theta0: Any) ndarray[tuple[Any, ...], dtype[float64]]#
Ensures that data vector is a non-empty 1D float array.
- Parameters:
theta0 – Input array-like to validate and convert.
- Returns:
1D float array.
- Raises:
ValueError – if
theta0is empty.
- derivkit.utils.validate.require_callable(func: Callable[[...], Any] | None, *, name: str = 'function', context: str | None = None, hint: str | None = None) Callable[[...], Any]#
Ensures a required callable is provided.
This is a small helper to validate inputs. If
funcisNone, it raises aValueErrorwith a clear message (and an optional context/hint to make debugging easier). Iffuncis provided, it is returned unchanged so the caller can use it directly.- Parameters:
func – Callable to validate.
name – Name shown in the error message.
context – Optional context prefix (e.g. “ForecastKit.fisher”).
hint – Optional hint appended to the error message.
- Returns:
The input callable.
- Raises:
ValueError – If
funcis None.
- derivkit.utils.validate.resolve_covariance_input(cov: ndarray[tuple[Any, ...], dtype[float64]] | Callable[[ndarray[tuple[Any, ...], dtype[float64]]], ndarray[tuple[Any, ...], dtype[float64]]], *, theta0: ndarray[tuple[Any, ...], dtype[float64]], validate: Callable[[Any], ndarray[tuple[Any, ...], dtype[float64]]]) tuple[ndarray[tuple[Any, ...], dtype[float64]], Callable[[ndarray[tuple[Any, ...], dtype[float64]]], ndarray[tuple[Any, ...], dtype[float64]]] | None]#
Returns the covariance-like input after validation.
- Parameters:
cov –
Covariance input. You can pass:
A fixed square covariance array (constant covariance). In this case the returned callable is
None.A callable that takes
thetaand returns a square covariance array. In this case the function evaluates it attheta0to getcov0and returns the callable ascov_fn.
theta0 – Fiducial parameter vector. Only used when
covis a callable covariance function (or when a callable is provided in the tuple form). Ignored for fixed covariance arrays.validate – A function that converts a covariance-like input into a NumPy array and checks its basic shape (and any other rules the caller wants).
resolve_covariance_inputexists to handle the different input types forcov(array vs callable) and to consistently produce(cov0, cov_fn);validateis only used to check or coerce the arrays that come out of that process.
- Returns:
cov0: The validated covariance attheta0(or the provided fixed covariance).cov_fn: The callable covariance function if provided, otherwiseNone.
- Return type:
A tuple with two items
- derivkit.utils.validate.resolve_dali_assembled_multiplet(theta0: ndarray[tuple[Any, ...], dtype[floating]], dali: Any, *, forecast_order: int | None = None, check_finite: bool = False) tuple[int, tuple[ndarray[tuple[Any, ...], dtype[float64]], ...]]#
Return
(order, multiplet)where multiplet is assembled up toorder.- Accepted inputs (matching get_forecast_tensors):
dict[int, tuple[…]]: per-order “introduced-at-order” multiplets
tuple[…]: a single introduced-at-order multiplet
- Returned multiplets are assembled as:
order 1: (F,)
order 2: (F, D1, D2)
order 3: (F, D1, D2, T1, T2, T3)
Notes
Tuple inputs cannot be assembled for order>1 because they do not include F. For order>1 evaluation, pass the dict form from get_forecast_tensors.
- derivkit.utils.validate.resolve_dali_introduced_multiplet(theta0: ndarray[tuple[Any, ...], dtype[floating]], dali: Any, *, forecast_order: int | None = None, check_finite: bool = False) tuple[int, tuple[ndarray[tuple[Any, ...], dtype[float64]], ...]]#
“Returns
(order, multiplet)from any accepted forecast tensor output.- The accepted input forms match the conventions used by
derivkit.forecasting.get_forecast_tensors():
A dict mapping
order -> multipletfor consecutive orders starting at 1.A single multiplet tuple.
If
daliis a dict andforecast_orderis not provided, the highest available order is selected. Ifforecast_orderis provided, it must be present in the dict.If
daliis a tuple, the order is inferred from the tuple structure.- Parameters:
theta0 – Fiducial parameter vector with shape
(p,).dali – Forecast tensors in one of the accepted forms.
forecast_order – Optional order selector when
daliis a dict.check_finite – If
True, require all selected arrays to be finite.
- Returns:
Tuple
(order, multiplet)wheremultipletis a tuple of float64 arrays.- Raises:
TypeError/ValueError/FloatingPointError – If
daliis invalid, if the selected order does not exist, or if array shapes/values do not satisfy the validation rules.
- derivkit.utils.validate.validate_covariance_matrix_shape(cov: Any) ndarray[tuple[Any, ...], dtype[float64]]#
Validates covariance input shape: allows 0D/1D/2D; if 2D requires square.
- derivkit.utils.validate.validate_dali_shape(theta0: ndarray[tuple[Any, ...], dtype[floating]], dali: Any, *, check_finite: bool = False) None#
Validates forecast tensor shapes.
The accepted input forms match the conventions used by
derivkit.forecasting.get_forecast_tensors():A dict mapping
order -> multipletfor consecutive orders starting at 1.A single multiplet tuple.
With
p = len(theta0), the required shapes are:order 1 multiplet:
(F,)withFof shape(p, p).order 2 multiplet:
(D_{(2,1)}, D_{(2,2)})with shapes(p, p, p)and(p, p, p, p).order 3 multiplet:
(T_{(3,1)}, T_{(3,2)}, T_{(3,3)})with shapes(p, p, p, p),(p, p, p, p, p), and(p, p, p, p, p, p).
- Parameters:
theta0 – Fiducial parameter vector with shape
(p,).dali –
Forecast tensors to validate. Must be either:
dict[int, tuple[...]]where each value is a multiplet for that order, ortuple[...]which is a single multiplet.
check_finite – If
True, require all validated arrays to be finite.
- Raises:
TypeError – If
dalihas an unsupported type, if dict keys are not ints, or if any multiplet is not a tuple.ValueError – If dict keys are not consecutive starting at 1, if a multiplet has the wrong length for its order, or if any tensor has the wrong dimension/shape.
FloatingPointError – If
check_finite=Trueand any validated array contains non-finite values.
- derivkit.utils.validate.validate_fisher_shape(theta0: ndarray[tuple[Any, ...], dtype[floating]], fisher: Any, *, check_finite: bool = False) None#
Validates Fisher matrix shape (and optionally finiteness).
- Requirements:
theta0is a non-empty 1D array of lengthp.fisheris a 2D array with shape(p, p).
- Parameters:
theta0 – Fiducial parameter vector with shape
(p,).fisher – Fisher matrix with shape
(p, p).check_finite – If
True, require all entries offisherto be finite.
- Raises:
ValueError – If
theta0is empty or iffisherdoes not have shape(p, p).FloatingPointError – If
check_finite=Trueandfishercontains non-finite values.
- derivkit.utils.validate.validate_square_matrix(a: Any, *, name: str = 'matrix') ndarray[tuple[Any, ...], dtype[float64]]#
Validates that the input is a 2D square matrix and return it as float array.
- derivkit.utils.validate.validate_square_matrix_finite(a: Any, *, name: str = 'matrix') ndarray[tuple[Any, ...], dtype[float64]]#
Validates that
ais a finite 2D square matrix and returns it as a float64 NumPy array.- Parameters:
a – Array-like matrix.
name – Name used in error messages.
- Returns:
A 2D float64 NumPy array containing the validated square matrix.
- Raises:
ValueError – If
ais not 2D, is not square, or contains non-finite values.
- derivkit.utils.validate.validate_symmetric_psd(matrix: Any, *, sym_atol: float = 1e-12, psd_atol: float = 1e-12) ndarray[tuple[Any, ...], dtype[float64]]#
Validates that an input is a symmetric positive semidefinite (PSD) matrix.
This is intended for strict validation (e.g., inputs passed to GetDist, or any code path where an indefinite covariance-like matrix should hard-fail). This is an important validation because many algorithms assume PSD inputs, and invalid inputs can lead to silent failures or nonsensical results.
- Policy:
Requires 2D square shape.
Requires near-symmetry within
sym_atol(raises if violated).After the symmetry check passes, checks PSD by computing eigenvalues of the symmetrized matrix
S = 0.5 * (A + A.T)for numerical robustness, and requiresmin_eig(S) >= -psd_atol.
- Parameters:
matrix – Array-like input expected to be a covariance-like matrix.
sym_atol – Absolute tolerance for symmetry check.
psd_atol – Absolute tolerance for PSD check. Allows small negative eigenvalues down to
-psd_atol.
- Returns:
A NumPy array view/copy of the input, converted to
float(same values as input).
Note
The input must be symmetric within
sym_atol; this function does not modify or symmetrize the returned matrix. The positive semi-definite check uses the symmetrized form0.5*(A + A.T)only to reduce roundoff sensitivity after the symmetry check passes.- Raises:
ValueError – If
matrixis not 2D, square, is too asymmetric, contains non-finite values, is not PSD within tolerance, if max(|A - A.T|) > sym_atol`, ifmin_eig(0.5*(A + A.T)) < -psd_atol, or if eigenvalue computation fails.
- derivkit.utils.validate.validate_tabulated_xy(x: Any, y: Any) tuple[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]]]#
Validates and converts tabulated
xandyarrays into NumPy arrays.- Requirements:
xis 1D and strictly increasing.yhas at least 1 dimension.y.shape[0] == x.shape[0], butymay have arbitrary trailing dimensions (scalar, vector, or ND output).
- Parameters:
x – 1D array-like of x values (must be strictly increasing).
y – Array-like of y values with
y.shape[0] == len(x).
- Returns:
Tuple of (x_array, y_array) as NumPy arrays.
- Raises:
ValueError – If input arrays do not meet the required conditions.
- derivkit.utils.validate.validate_theta_1d_finite(theta: Any, *, name: str = 'theta') ndarray[tuple[Any, ...], dtype[float64]]#
Validates that
thetais a finite, non-empty 1D parameter vector and returns it as a float64 NumPy array.- Parameters:
theta – Array-like parameter vector.
name – Name used in error messages.
- Returns:
A 1D float64 NumPy array containing the validated parameter vector.
- Raises:
ValueError – If
thetais not 1D, is empty, or contains non-finite values.