use core::fmt;
use xingo_sparse::{KktError, LuError};
use crate::OperatorError;
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum StatlaError {
Dimension {
what: &'static str,
expected: usize,
found: usize,
},
InvalidArgument {
what: &'static str,
},
NonFinite {
what: &'static str,
index: usize,
},
NotPositiveDefinite {
column: usize,
},
DowndateIndefinite {
margin: f64,
},
RankDeficient {
column: usize,
},
NoConvergence {
requested: usize,
converged: usize,
restarts: usize,
},
Operator(OperatorError),
Lu(LuError),
Kkt(KktError),
}
pub(crate) fn op_err(e: OperatorError) -> StatlaError {
StatlaError::Operator(e)
}
impl fmt::Display for StatlaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Dimension {
what,
expected,
found,
} => write!(f, "{what}: expected length {expected}, found {found}"),
Self::InvalidArgument { what } => write!(f, "invalid argument: {what}"),
Self::NonFinite { what, index } => {
write!(f, "{what}: non-finite value at position {index}")
}
Self::NotPositiveDefinite { column } => {
write!(f, "matrix not positive definite (pivot of column {column})")
}
Self::DowndateIndefinite { margin } => write!(
f,
"downdate would leave the matrix indefinite (1 - |a|^2 = {margin:e})"
),
Self::RankDeficient { column } => {
write!(f, "rank deficient at column {column}")
}
Self::NoConvergence {
requested,
converged,
restarts,
} => write!(
f,
"no convergence: {converged} of {requested} values after {restarts} restarts"
),
Self::Operator(e) => write!(f, "operator error: {}", e.message),
Self::Lu(e) => write!(f, "LU of A - sigma I failed: {e}"),
Self::Kkt(e) => write!(f, "LDL^T of A - sigma I failed: {e}"),
}
}
}
impl std::error::Error for StatlaError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn messages_name_the_argument() {
let e = StatlaError::Dimension {
what: "x",
expected: 3,
found: 2,
};
assert_eq!(e.to_string(), "x: expected length 3, found 2");
assert!(
StatlaError::DowndateIndefinite { margin: -0.5 }
.to_string()
.contains("-5e-1")
);
assert!(
StatlaError::RankDeficient { column: 4 }
.to_string()
.contains('4')
);
assert!(
StatlaError::NonFinite {
what: "a",
index: 7
}
.to_string()
.contains("position 7")
);
assert!(
StatlaError::InvalidArgument { what: "ld < rows" }
.to_string()
.contains("ld < rows")
);
assert!(
StatlaError::NoConvergence {
requested: 5,
converged: 3,
restarts: 7
}
.to_string()
.contains("3 of 5")
);
assert!(
op_err(OperatorError {
message: "boom".into()
})
.to_string()
.contains("boom")
);
assert!(
StatlaError::Kkt(KktError::NotSymmetric)
.to_string()
.contains("LDL")
);
assert!(
StatlaError::Lu(LuError::NotFactorized)
.to_string()
.contains("LU")
);
assert!(
StatlaError::NotPositiveDefinite { column: 1 }
.to_string()
.contains("column 1")
);
}
}