Skip to main content

lib_jsl_linalg/
error.rs

1//! Errors and the triangle and diagonal selectors shared by the decompositions.
2
3use std::fmt;
4
5/// Why a decomposition or solve failed. Converts into the library-wide
6/// [`ErrorsJSL`](lib_jsl_core::ErrorsJSL) with `?`.
7#[derive(Debug, Clone, PartialEq)]
8#[non_exhaustive]
9pub enum LinalgError {
10    /// The operation needs a square matrix but got `rows × cols`.
11    NotSquare { rows: usize, cols: usize },
12    /// Operand shapes do not fit together.
13    Shape(String),
14    /// The matrix is singular (an exact or numerically zero pivot at this step).
15    Singular(usize),
16    /// Cholesky found a non-positive pivot: the matrix is not positive definite.
17    NotPositiveDefinite(usize),
18    /// An iterative algorithm did not converge within its iteration budget.
19    NoConvergence(&'static str),
20    /// The matrix contains NaN or infinity.
21    NonFinite,
22}
23
24impl fmt::Display for LinalgError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            LinalgError::NotSquare { rows, cols } => write!(f, "expected a square matrix, got {rows} × {cols}"),
28            LinalgError::Shape(s) => write!(f, "incompatible shapes: {s}"),
29            LinalgError::Singular(k) => write!(f, "the matrix is singular (zero pivot at step {k})"),
30            LinalgError::NotPositiveDefinite(k) => write!(f, "the matrix is not positive definite (pivot {k})"),
31            LinalgError::NoConvergence(what) => write!(f, "{what} did not converge"),
32            LinalgError::NonFinite => write!(f, "the matrix contains NaN or infinite entries"),
33        }
34    }
35}
36
37impl std::error::Error for LinalgError {}
38
39impl From<LinalgError> for lib_jsl_core::ErrorsJSL {
40    fn from(e: LinalgError) -> Self {
41        lib_jsl_core::ErrorsJSL::LinearAlgebra(e.to_string())
42    }
43}
44
45/// Which triangle of a matrix to use (or produce).
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum UPLO {
48    Upper,
49    Lower,
50}
51
52/// Whether a triangular matrix has an implicit unit diagonal.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub enum Diag {
55    Unit,
56    NonUnit,
57}
58
59pub type Result<T> = std::result::Result<T, LinalgError>;