Skip to main content

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