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_gradient and build_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 function does 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 arr is 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_function does 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 function is finite at x and x + 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 True if the input is finite at both points and False otherwise.

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 theta0 is 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 func is None, it raises a ValueError with a clear message (and an optional context/hint to make debugging easier). If func is 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 func is 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 theta and returns a square covariance array. In this case the function evaluates it at theta0 to get cov0 and returns the callable as cov_fn.

  • theta0 – Fiducial parameter vector. Only used when cov is 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_input exists to handle the different input types for cov (array vs callable) and to consistently produce (cov0, cov_fn); validate is only used to check or coerce the arrays that come out of that process.

Returns:

  • cov0: The validated covariance at theta0 (or the provided fixed covariance).

  • cov_fn: The callable covariance function if provided, otherwise None.

Return type:

A tuple with two items

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_shapes(theta0: ndarray[tuple[Any, ...], dtype[floating]], fisher: ndarray[tuple[Any, ...], dtype[floating]], g_tensor: ndarray[tuple[Any, ...], dtype[floating]], h_tensor: ndarray[tuple[Any, ...], dtype[floating]] | None) None#

Validates shapes for DALI expansion inputs.

Checks that:

  • theta0 is a 1D parameter vector with shape (p,).

  • fisher has shape (p, p).

  • g_tensor (third-derivative tensor) has shape (p, p, p).

  • h_tensor (fourth-derivative tensor), if provided, has shape (p, p, p, p) with p being the number of parameters.

Parameters:
  • theta0 – Expansion point (fiducial parameters) as a 1D array of length p.

  • fisher – Fisher information matrix as a 2D array with shape (p, p).

  • g_tensor – DALI cubic tensor with shape (p, p, p).

  • h_tensor – Optional DALI quartic tensor with shape (p, p, p, p). If None, no quartic shape check is performed.

Raises:

ValueError – If any input does not have the expected dimensionality/shape.

derivkit.utils.validate.validate_fisher_shapes(theta0: ndarray[tuple[Any, ...], dtype[floating]], fisher: ndarray[tuple[Any, ...], dtype[floating]]) None#

Validates shapes for Fisher forecasting inputs.

Checks that:

  • theta0 is a 1D parameter vector with shape (p,).

  • fisher is a square matrix with shape (p, p), where p = len(theta0) with p being the number of parameters.

Parameters:
  • theta0 – Expansion point (fiducial parameters) as a 1D array of length p.

  • fisher – Fisher information matrix as a 2D array with shape (p, p).

Raises:

ValueError – If theta0 is not 1D, or if fisher does not have shape (p, p).

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 a is 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 a is 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 requires min_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 form 0.5*(A + A.T) only to reduce roundoff sensitivity after the symmetry check passes.

Raises:

ValueError – If matrix is not 2D, square, is too asymmetric, contains non-finite values, is not PSD within tolerance, if max(|A - A.T|) > sym_atol`, if min_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 x and y arrays into NumPy arrays.

Requirements:
  • x is 1D and strictly increasing.

  • y has at least 1 dimension.

  • y.shape[0] == x.shape[0], but y may 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 theta is 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 theta is not 1D, is empty, or contains non-finite values.