xingo_statla/error.rs
1//! # Chapter 12.0.1 — Errors
2//!
3//! ## Purpose
4//! One error type for every function of the crate (decision S10 of
5//! D-0127), so that `xingo-ffi` maps one enum to R conditions and Python
6//! exceptions. **No function of the crate panics on bad input**: wrong
7//! lengths, bad indices, non-finite data and invalid options come back as
8//! a [`StatlaError`]; a panic is a bug.
9//!
10//! ## Variants of this edition
11//! The enum is `#[non_exhaustive]`. Task L3.2 has the six variants its
12//! operations can return, with the names of the contract: `Dimension`,
13//! `InvalidArgument`, `NonFinite`, `NotPositiveDefinite`,
14//! `DowndateIndefinite`, `RankDeficient`. Task L3.3 adds `NoConvergence`
15//! ([`crate::svds()`]) and `Operator` (every driver over a
16//! [`crate::LinearOperator`]). The contract's `Lu` and `Kkt` arrive with
17//! shift-invert (L3.4); adding a variant to a non-exhaustive enum is not
18//! breaking.
19//!
20//! ## Conventions
21//! 1. Lengths are checked before indices, indices before values, values
22//! (finiteness) before any arithmetic: the first violation found in that
23//! order is the one reported.
24//! 2. `NonFinite::index` is the position in the argument, column-major for
25//! matrices (`i + j·rows`, independent of the leading dimension).
26//! 3. Every error of an updating operation leaves the factorization bit for
27//! bit as it was (invariants H3, Q3).
28
29use core::fmt;
30
31use xingo_sparse::{KktError, LuError};
32
33use crate::OperatorError;
34
35/// Everything that can go wrong, for every function of the crate (decision
36/// S10: one error type). No function of the crate panics on bad input;
37/// panics are bugs.
38#[derive(Clone, Debug, PartialEq)]
39#[non_exhaustive]
40pub enum StatlaError {
41 /// Two lengths that must agree do not.
42 Dimension {
43 /// Which argument has the wrong length.
44 what: &'static str,
45 /// Expected length.
46 expected: usize,
47 /// Actual length.
48 found: usize,
49 },
50 /// An argument outside its domain: an index out of range, a view whose
51 /// `ld < rows`, a matrix that is not square, an option out of its
52 /// range, …
53 InvalidArgument {
54 /// What is wrong, in a few words.
55 what: &'static str,
56 },
57 /// A NaN or an infinity in the input.
58 NonFinite {
59 /// Which argument.
60 what: &'static str,
61 /// Position (column-major for matrices).
62 index: usize,
63 },
64 /// Cholesky factorization met a nonpositive pivot at `column` (the
65 /// matrix is not positive definite within [`CholOptions::pivot_tol`]).
66 ///
67 /// [`CholOptions::pivot_tol`]: crate::CholOptions::pivot_tol
68 NotPositiveDefinite {
69 /// The column of the failing pivot.
70 column: usize,
71 },
72 /// A downdate `A − x xᵀ` would not be positive definite: with `Rᵀa =
73 /// x`, `1 − ‖a‖² ≤ CholOptions::downdate_tol` (step C2 of 12.2). The
74 /// factor is unchanged (H3).
75 DowndateIndefinite {
76 /// `1 − ‖a‖²` as computed (≤ the tolerance; may be negative;
77 /// `−∞` if it overflowed).
78 margin: f64,
79 },
80 /// `Qr` met a column (or, in `delete_row`, a complement vector) whose
81 /// norm fell below [`QrOptions::rank_tol`] after reorthogonalization.
82 ///
83 /// [`QrOptions::rank_tol`]: crate::QrOptions::rank_tol
84 RankDeficient {
85 /// The column concerned (for `delete_row`, the index of the row
86 /// that could not be deleted).
87 column: usize,
88 },
89 /// Fewer than `requested` values converged within the restart limit
90 /// (and `allow_partial` of the options is off).
91 NoConvergence {
92 /// `k`.
93 requested: usize,
94 /// How many satisfied the convergence test.
95 converged: usize,
96 /// Restarts performed.
97 restarts: usize,
98 },
99 /// The caller's operator reported an error.
100 Operator(OperatorError),
101 /// The LU of `A − σI` failed (shift-invert, [`crate::ShiftInvert`]); `σ`
102 /// is probably an eigenvalue.
103 Lu(LuError),
104 /// The LDLᵀ of `A − σI` failed ([`crate::SymShiftInvert`]); a
105 /// [`KktError::WrongInertia`] with zero pivots means `σ` is
106 /// (numerically) an eigenvalue.
107 Kkt(KktError),
108}
109
110/// `StatlaError::Operator` (a function, not a public `From` impl: the
111/// contract has none).
112pub(crate) fn op_err(e: OperatorError) -> StatlaError {
113 StatlaError::Operator(e)
114}
115
116impl fmt::Display for StatlaError {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 match self {
119 Self::Dimension {
120 what,
121 expected,
122 found,
123 } => write!(f, "{what}: expected length {expected}, found {found}"),
124 Self::InvalidArgument { what } => write!(f, "invalid argument: {what}"),
125 Self::NonFinite { what, index } => {
126 write!(f, "{what}: non-finite value at position {index}")
127 }
128 Self::NotPositiveDefinite { column } => {
129 write!(f, "matrix not positive definite (pivot of column {column})")
130 }
131 Self::DowndateIndefinite { margin } => write!(
132 f,
133 "downdate would leave the matrix indefinite (1 - |a|^2 = {margin:e})"
134 ),
135 Self::RankDeficient { column } => {
136 write!(f, "rank deficient at column {column}")
137 }
138 Self::NoConvergence {
139 requested,
140 converged,
141 restarts,
142 } => write!(
143 f,
144 "no convergence: {converged} of {requested} values after {restarts} restarts"
145 ),
146 Self::Operator(e) => write!(f, "operator error: {}", e.message),
147 Self::Lu(e) => write!(f, "LU of A - sigma I failed: {e}"),
148 Self::Kkt(e) => write!(f, "LDL^T of A - sigma I failed: {e}"),
149 }
150 }
151}
152
153impl std::error::Error for StatlaError {}
154
155#[cfg(test)]
156mod tests {
157 use super::*;
158
159 #[test]
160 fn messages_name_the_argument() {
161 let e = StatlaError::Dimension {
162 what: "x",
163 expected: 3,
164 found: 2,
165 };
166 assert_eq!(e.to_string(), "x: expected length 3, found 2");
167 assert!(
168 StatlaError::DowndateIndefinite { margin: -0.5 }
169 .to_string()
170 .contains("-5e-1")
171 );
172 assert!(
173 StatlaError::RankDeficient { column: 4 }
174 .to_string()
175 .contains('4')
176 );
177 assert!(
178 StatlaError::NonFinite {
179 what: "a",
180 index: 7
181 }
182 .to_string()
183 .contains("position 7")
184 );
185 assert!(
186 StatlaError::InvalidArgument { what: "ld < rows" }
187 .to_string()
188 .contains("ld < rows")
189 );
190 assert!(
191 StatlaError::NoConvergence {
192 requested: 5,
193 converged: 3,
194 restarts: 7
195 }
196 .to_string()
197 .contains("3 of 5")
198 );
199 assert!(
200 op_err(OperatorError {
201 message: "boom".into()
202 })
203 .to_string()
204 .contains("boom")
205 );
206 assert!(
207 StatlaError::Kkt(KktError::NotSymmetric)
208 .to_string()
209 .contains("LDL")
210 );
211 assert!(
212 StatlaError::Lu(LuError::NotFactorized)
213 .to_string()
214 .contains("LU")
215 );
216 assert!(
217 StatlaError::NotPositiveDefinite { column: 1 }
218 .to_string()
219 .contains("column 1")
220 );
221 }
222}