Skip to main content

numra_fit/
error.rs

1//! Error types for curve fitting.
2//!
3//! Author: Moussa Leblouba
4//! Date: 9 February 2026
5//! Modified: 2 May 2026
6
7use core::fmt;
8use numra_core::NumraError;
9
10/// Error type for curve fitting operations.
11#[derive(Clone, Debug, PartialEq)]
12pub enum FitError {
13    /// Not enough data points.
14    InsufficientData { need: usize, got: usize },
15    /// More parameters than data points.
16    Underdetermined { n_params: usize, n_data: usize },
17    /// Optimization failed to converge.
18    OptimizationFailed(String),
19    /// Dimension mismatch between x and y data.
20    LengthMismatch { expected: usize, got: usize },
21    /// Invalid parameter (e.g., negative polynomial degree).
22    InvalidParameter(String),
23    /// Singular or near-singular Jacobian (covariance unreliable).
24    SingularJacobian,
25}
26
27impl fmt::Display for FitError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            Self::InsufficientData { need, got } => {
31                write!(f, "insufficient data: need at least {need}, got {got}")
32            }
33            Self::Underdetermined { n_params, n_data } => {
34                write!(
35                    f,
36                    "underdetermined: {n_params} parameters but only {n_data} data points"
37                )
38            }
39            Self::OptimizationFailed(msg) => write!(f, "optimization failed: {msg}"),
40            Self::LengthMismatch { expected, got } => {
41                write!(f, "length mismatch: expected {expected}, got {got}")
42            }
43            Self::InvalidParameter(msg) => write!(f, "invalid parameter: {msg}"),
44            Self::SingularJacobian => write!(f, "singular Jacobian: covariance unreliable"),
45        }
46    }
47}
48
49impl std::error::Error for FitError {}
50
51impl From<FitError> for NumraError {
52    fn from(e: FitError) -> Self {
53        NumraError::Fit(e.to_string())
54    }
55}