Skip to main content

sparse_ir_core/
error.rs

1//! Error type of the public API
2//!
3//! The public functions of this crate that return a `Result` use [`Error`]
4//! as the error type. Each variant carries the values that caused it, so
5//! that its message locates the problem. [`Error::kind`] sorts the variants
6//! into the categories that the C API reports as status codes.
7
8use crate::gemm::GemmError;
9use crate::traits::Statistics;
10
11/// Which array of an operation has the wrong shape, in
12/// [`Error::ShapeMismatch`]
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ArrayRole {
15    /// An array that the operation reads, e.g. the coefficients of an
16    /// evaluation or a given sampling matrix
17    Input,
18    /// The array that the operation writes to, e.g. `out` of `evaluate_nd_to`
19    Output,
20}
21
22impl std::fmt::Display for ArrayRole {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        f.write_str(match self {
25            ArrayRole::Input => "input",
26            ArrayRole::Output => "output",
27        })
28    }
29}
30
31/// Error returned by the fallible public functions of this crate
32///
33/// More variants may be added without a major version bump. To handle a category of
34/// errors rather than one variant, match on [`Error::kind`].
35///
36/// Errors compare equal when all their fields do. An error that holds a NaN
37/// value is therefore not equal to itself; match on the variant instead.
38#[derive(Debug, Clone, PartialEq, thiserror::Error)]
39#[non_exhaustive]
40pub enum Error {
41    /// A parameter is outside its valid range.
42    #[error("invalid {name} = {value}: {reason}")]
43    InvalidParameter {
44        /// Name of the parameter, as in the documentation of the function
45        name: &'static str,
46        /// The rejected value, formatted for the message
47        value: String,
48        /// The condition that the value violates, e.g. "must be in (0, 1)"
49        reason: String,
50    },
51    /// A point lies outside the domain of a function, e.g. τ outside [-β, β]
52    /// or x outside the knots of a polynomial. NaN lies outside every domain.
53    #[error("{name} = {value:?} is outside the domain [{:?}, {:?}]", .domain.0, .domain.1)]
54    OutOfDomain {
55        /// Name of the argument, as in the documentation of the function
56        name: &'static str,
57        /// The rejected point
58        value: f64,
59        /// The closed interval `(lower, upper)` of valid points
60        domain: (f64, f64),
61    },
62    /// A Matsubara frequency index is not allowed: `n` must be odd for
63    /// fermionic and even for bosonic statistics, and non-negative for a
64    /// positive-only sampling. The message says which: a wrong parity, or a
65    /// negative `n` of the right parity.
66    #[error("{}", invalid_matsubara_index_message(.n, .statistics))]
67    InvalidMatsubaraIndex {
68        /// The rejected index
69        n: i64,
70        /// The statistics that `n` was checked against
71        statistics: Statistics,
72    },
73    /// An input that must not be empty is empty.
74    #[error("{name} must not be empty")]
75    EmptyInput {
76        /// Name of the input, as in the documentation of the function
77        name: &'static str,
78    },
79    /// An input contains NaN or an infinity.
80    #[error("{name} has the non-finite entry {value} at index {index:?}")]
81    NonFiniteInput {
82        /// Name of the input, as in the documentation of the function
83        name: &'static str,
84        /// Index of the first non-finite entry (`[row, column]` for a matrix)
85        index: Vec<usize>,
86        /// That entry, converted to `f64`
87        value: f64,
88    },
89    /// The kernel does not support the requested statistics, e.g.
90    /// `RegularizedBoseKernel` with fermionic statistics.
91    #[error(
92        "kernel does not support the requested statistics: kernels with ypower = 1 \
93         (e.g. RegularizedBoseKernel) require bosonic statistics"
94    )]
95    KernelStatisticsMismatch,
96    /// The basis has fewer default poles than functions, so its default poles
97    /// cannot define a DLR. This can happen with certain kernels (e.g.
98    /// `RegularizedBoseKernel`) because of the limited precision of the root
99    /// finding.
100    #[error("number of default poles ({n_poles}) is less than the basis size ({basis_size})")]
101    InsufficientDefaultPoles {
102        /// Basis size
103        basis_size: usize,
104        /// Number of default poles found
105        n_poles: usize,
106    },
107    /// An axis argument is not an axis of the array, e.g. `dim` of
108    /// `evaluate_nd` for an array of rank `dim` or less.
109    #[error("axis {axis} is out of range for an array of rank {rank}")]
110    AxisOutOfRange {
111        /// The rejected axis
112        axis: usize,
113        /// The rank of the array
114        rank: usize,
115    },
116    /// An array has the wrong shape. For a slice, the shapes have one entry,
117    /// its length.
118    #[error("{which} has the shape {actual:?}, expected {expected:?}")]
119    ShapeMismatch {
120        /// Which array: an input, or the output
121        which: ArrayRole,
122        /// The shape the operation needs
123        expected: Vec<usize>,
124        /// The shape of the array
125        actual: Vec<usize>,
126    },
127    /// The operation is not defined for this input, e.g. the even/odd SVE of
128    /// a kernel that is not centrosymmetric.
129    #[error("not supported: {what}")]
130    NotSupported {
131        /// What is not supported, and why
132        what: String,
133    },
134    /// A matrix decomposition failed, e.g. the SVD iteration did not converge.
135    #[error("decomposition failed: {reason}")]
136    DecompositionFailed {
137        /// What failed, with the values involved
138        reason: String,
139    },
140    /// The GEMM backend rejected a call, e.g. a dimension exceeds the integer
141    /// range of an injected BLAS.
142    #[error(transparent)]
143    Gemm(#[from] GemmError),
144    /// A tenferro tensor operation failed.
145    #[error("tensor operation failed: {reason}")]
146    Tensor {
147        /// The message of the tenferro error
148        reason: String,
149    },
150}
151
152impl From<tenferro_tensor::Error> for Error {
153    fn from(e: tenferro_tensor::Error) -> Self {
154        Error::Tensor {
155            reason: e.to_string(),
156        }
157    }
158}
159
160/// Each variant of the SVE error becomes the variant of the same name.
161impl From<sparse_ir_sve::Error> for Error {
162    fn from(e: sparse_ir_sve::Error) -> Self {
163        use sparse_ir_sve::Error as Sve;
164        match e {
165            Sve::InvalidParameter {
166                name,
167                value,
168                reason,
169            } => Error::InvalidParameter {
170                name,
171                value,
172                reason,
173            },
174            Sve::OutOfDomain {
175                name,
176                value,
177                domain,
178            } => Error::OutOfDomain {
179                name,
180                value,
181                domain,
182            },
183            Sve::EmptyInput { name } => Error::EmptyInput { name },
184            Sve::NonFiniteInput { name, index, value } => {
185                Error::NonFiniteInput { name, index, value }
186            }
187            Sve::NotSupported { what } => Error::NotSupported { what },
188            Sve::DecompositionFailed { reason } => Error::DecompositionFailed { reason },
189            // sparse-ir-sve is released together with this crate, which maps
190            // every variant it has; one added there without a counterpart
191            // here keeps its category (and so its C status code) and message.
192            other => match other.kind() {
193                sparse_ir_sve::ErrorKind::InvalidArgument => Error::InvalidParameter {
194                    name: "argument",
195                    value: "?".to_string(),
196                    reason: other.to_string(),
197                },
198                sparse_ir_sve::ErrorKind::NotSupported => Error::NotSupported {
199                    what: other.to_string(),
200                },
201                _ => Error::DecompositionFailed {
202                    reason: other.to_string(),
203                },
204            },
205        }
206    }
207}
208
209/// Category of an [`Error`]
210///
211/// Each category corresponds to one failure status code of the C API, shown
212/// in parentheses.
213///
214/// Unlike [`Error`], this enum is exhaustive: a new category would need a new
215/// C status code, so adding one is a breaking change.
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
217pub enum ErrorKind {
218    /// An argument has an invalid value (`SPIR_INVALID_ARGUMENT`).
219    InvalidArgument,
220    /// An axis or a rank is invalid (`SPIR_INVALID_DIMENSION`).
221    InvalidDimension,
222    /// An input array has the wrong shape (`SPIR_INPUT_DIMENSION_MISMATCH`).
223    InputDimensionMismatch,
224    /// An output array has the wrong shape (`SPIR_OUTPUT_DIMENSION_MISMATCH`).
225    OutputDimensionMismatch,
226    /// The operation is not supported for these arguments
227    /// (`SPIR_NOT_SUPPORTED`).
228    NotSupported,
229    /// A failure that invalid input does not explain
230    /// (`SPIR_INTERNAL_ERROR`).
231    Internal,
232}
233
234impl Error {
235    /// Category of the error
236    pub fn kind(&self) -> ErrorKind {
237        match self {
238            Error::InvalidParameter { .. }
239            | Error::OutOfDomain { .. }
240            | Error::InvalidMatsubaraIndex { .. }
241            | Error::EmptyInput { .. }
242            | Error::NonFiniteInput { .. }
243            | Error::InsufficientDefaultPoles { .. } => ErrorKind::InvalidArgument,
244            Error::KernelStatisticsMismatch | Error::NotSupported { .. } => ErrorKind::NotSupported,
245            Error::AxisOutOfRange { .. } => ErrorKind::InvalidDimension,
246            Error::ShapeMismatch {
247                which: ArrayRole::Input,
248                ..
249            } => ErrorKind::InputDimensionMismatch,
250            Error::ShapeMismatch {
251                which: ArrayRole::Output,
252                ..
253            } => ErrorKind::OutputDimensionMismatch,
254            Error::Gemm(GemmError::DimensionOverflow { .. }) => ErrorKind::InvalidArgument,
255            Error::DecompositionFailed { .. }
256            | Error::Gemm(GemmError::InvalidArgument(_))
257            | Error::Tensor { .. } => ErrorKind::Internal,
258        }
259    }
260}
261
262/// Message of [`Error::InvalidMatsubaraIndex`]: an `n` of the parity of
263/// `statistics` can only have been rejected for being negative (in a
264/// positive-only sampling)
265fn invalid_matsubara_index_message(n: &i64, statistics: &Statistics) -> String {
266    let parity_ok = match statistics {
267        Statistics::Fermionic => n.rem_euclid(2) == 1,
268        Statistics::Bosonic => n.rem_euclid(2) == 0,
269    };
270    if parity_ok && *n < 0 {
271        format!(
272            "Matsubara frequency n = {n} is negative, but only non-negative frequencies are \
273             allowed here (positive-only sampling)"
274        )
275    } else {
276        format!(
277            "Matsubara frequency n = {n} is not allowed for {} statistics",
278            statistics.as_str()
279        )
280    }
281}
282
283/// `Ok` if `value` is positive and finite
284#[doc(hidden)]
285pub fn require_positive_finite(name: &'static str, value: f64) -> Result<(), Error> {
286    Ok(sparse_ir_sve::unstable::require_positive_finite(
287        name, value,
288    )?)
289}
290
291/// `Ok` if `value` is finite
292#[doc(hidden)]
293pub fn require_finite(name: &'static str, value: f64) -> Result<(), Error> {
294    Ok(sparse_ir_sve::unstable::require_finite(name, value)?)
295}
296
297/// `Ok` for an accuracy that selects the SVE: `None` (automatic) or a value
298/// in (0, 1)
299#[doc(hidden)]
300pub fn require_accuracy(name: &'static str, epsilon: Option<f64>) -> Result<(), Error> {
301    Ok(sparse_ir_sve::unstable::require_accuracy(name, epsilon)?)
302}
303
304/// `Ok` for a relative truncation threshold: `None` or a value in [0, 1),
305/// where 0 keeps every singular value
306#[doc(hidden)]
307pub fn require_threshold(name: &'static str, epsilon: Option<f64>) -> Result<(), Error> {
308    Ok(sparse_ir_sve::unstable::require_threshold(name, epsilon)?)
309}
310
311/// `Ok` unless `size` is `Some(0)`
312#[doc(hidden)]
313pub fn require_nonzero_size(name: &'static str, size: Option<usize>) -> Result<(), Error> {
314    Ok(sparse_ir_sve::unstable::require_nonzero_size(name, size)?)
315}
316
317/// Result type of the fallible public functions of this crate
318pub type Result<T, E = Error> = std::result::Result<T, E>;
319
320#[cfg(test)]
321#[path = "error_tests.rs"]
322mod error_tests;