Skip to main content

scivex_optim/
error.rs

1use core::fmt;
2
3/// All errors returned by `scivex-optim`.
4#[cfg_attr(
5    feature = "serde-support",
6    derive(serde::Serialize, serde::Deserialize)
7)]
8#[derive(Debug, Clone, PartialEq)]
9#[non_exhaustive]
10pub enum OptimError {
11    /// An iterative algorithm did not converge within the iteration budget.
12    ConvergenceFailure { iterations: usize },
13
14    /// A computation produced a non-finite value (NaN or infinity).
15    NonFiniteValue { context: &'static str },
16
17    /// A parameter has an invalid value.
18    InvalidParameter {
19        name: &'static str,
20        reason: &'static str,
21    },
22
23    /// The bracket does not contain a root (signs are not opposite).
24    BracketError,
25
26    /// An error propagated from `scivex-core`.
27    CoreError(scivex_core::CoreError),
28}
29
30impl fmt::Display for OptimError {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        match self {
33            Self::ConvergenceFailure { iterations } => {
34                write!(f, "convergence failure after {iterations} iterations")
35            }
36            Self::NonFiniteValue { context } => {
37                write!(f, "non-finite value encountered in {context}")
38            }
39            Self::InvalidParameter { name, reason } => {
40                write!(f, "invalid parameter `{name}`: {reason}")
41            }
42            Self::BracketError => {
43                write!(
44                    f,
45                    "bracket does not contain a root (f(a) and f(b) must have opposite signs)"
46                )
47            }
48            Self::CoreError(e) => write!(f, "core error: {e}"),
49        }
50    }
51}
52
53impl std::error::Error for OptimError {}
54
55impl From<scivex_core::CoreError> for OptimError {
56    fn from(e: scivex_core::CoreError) -> Self {
57        Self::CoreError(e)
58    }
59}
60
61/// Convenience alias used throughout `scivex-optim`.
62pub type Result<T> = std::result::Result<T, OptimError>;