Skip to main content

tpt_math_stats/
error.rs

1//! The error type shared by the checked (`try_*`) entry points of this crate.
2
3use std::error::Error;
4use std::fmt;
5
6/// Errors reported by the checked (`try_*`) entry points of this crate.
7///
8/// Every panicking convenience wrapper (for example [`mean`](crate::mean))
9/// simply unwraps its `try_*` twin, so a panic message is always the
10/// [`Display`](fmt::Display) text of one of these variants.
11///
12/// Degenerate — but well defined — results are *not* errors. A sample with
13/// zero variance, or a perfectly flat predictor, yields a documented
14/// `NaN`/infinite statistic rather than an `Err`; see the individual
15/// functions for the exact convention.
16#[derive(Clone, Copy, Debug, PartialEq)]
17#[non_exhaustive]
18pub enum StatsError {
19    /// The sample held fewer observations than the statistic requires.
20    NotEnoughData {
21        /// Name of the offending argument.
22        sample: &'static str,
23        /// Minimum number of observations the statistic needs.
24        required: usize,
25        /// Number of observations actually supplied.
26        found: usize,
27    },
28
29    /// Two paired inputs had different lengths.
30    LengthMismatch {
31        /// Length of the first argument.
32        first: usize,
33        /// Length of the second argument.
34        second: usize,
35    },
36
37    /// A quantile probability was outside `[0, 1]` (or `NaN`).
38    ProbabilityOutOfRange {
39        /// The offending probability.
40        value: f64,
41    },
42
43    /// An observation was `NaN` or infinite.
44    NotFinite {
45        /// Name of the offending argument.
46        sample: &'static str,
47        /// Index of the offending observation.
48        index: usize,
49        /// The offending value.
50        value: f64,
51    },
52
53    /// A scalar parameter (such as a hypothesised mean) was `NaN` or infinite.
54    ParameterNotFinite {
55        /// Name of the offending parameter.
56        parameter: &'static str,
57        /// The offending value.
58        value: f64,
59    },
60
61    /// An expected cell count was zero or negative, so the chi-squared
62    /// statistic would divide by zero.
63    NonPositiveExpected {
64        /// Index of the offending category.
65        index: usize,
66        /// The offending value.
67        value: f64,
68    },
69
70    /// The degrees of freedom implied by the inputs are not a usable
71    /// distribution parameter (not finite, or not strictly positive).
72    InvalidDegreesOfFreedom {
73        /// The rejected degrees-of-freedom value.
74        freedom: f64,
75    },
76
77    /// A scalar parameter that must be strictly positive (such as a kernel
78    /// bandwidth) was zero or negative.
79    NonPositiveParameter {
80        /// Name of the offending parameter.
81        parameter: &'static str,
82        /// The offending value.
83        value: f64,
84    },
85
86    /// The regression design matrix does not have full column rank, so the
87    /// coefficients are not identified.
88    RankDeficientDesign,
89
90    /// An iterative fit did not settle within its iteration budget.
91    DidNotConverge {
92        /// The number of iterations that were run.
93        iterations: usize,
94    },
95}
96
97impl fmt::Display for StatsError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            StatsError::ProbabilityOutOfRange { value } => {
101                write!(f, "probability {value} is outside [0, 1]")
102            }
103            StatsError::NotEnoughData {
104                sample,
105                required,
106                found,
107            } => write!(
108                f,
109                "`{sample}` needs at least {required} observation(s), found {found}"
110            ),
111            StatsError::LengthMismatch { first, second } => write!(
112                f,
113                "paired samples must have equal lengths, found {first} and {second}"
114            ),
115            StatsError::NotFinite {
116                sample,
117                index,
118                value,
119            } => write!(f, "`{sample}[{index}]` is {value}, expected a finite value"),
120            StatsError::ParameterNotFinite { parameter, value } => {
121                write!(f, "`{parameter}` is {value}, expected a finite value")
122            }
123            StatsError::NonPositiveExpected { index, value } => write!(
124                f,
125                "`expected[{index}]` is {value}, expected a strictly positive count"
126            ),
127            StatsError::InvalidDegreesOfFreedom { freedom } => write!(
128                f,
129                "{freedom} is not a valid number of degrees of freedom \
130                 (expected a finite value > 0)"
131            ),
132            StatsError::NonPositiveParameter { parameter, value } => {
133                write!(f, "`{parameter}` is {value}, expected a value > 0")
134            }
135            StatsError::RankDeficientDesign => write!(
136                f,
137                "the design matrix is rank-deficient; the coefficients are not identified"
138            ),
139            StatsError::DidNotConverge { iterations } => {
140                write!(f, "the fit did not converge within {iterations} iterations")
141            }
142        }
143    }
144}
145
146impl Error for StatsError {}
147
148/// Validate that `values` holds at least `required` observations.
149pub(crate) fn check_min_len(
150    sample: &'static str,
151    values: &[f64],
152    required: usize,
153) -> Result<(), StatsError> {
154    if values.len() >= required {
155        Ok(())
156    } else {
157        Err(StatsError::NotEnoughData {
158            sample,
159            required,
160            found: values.len(),
161        })
162    }
163}
164
165/// Validate that two paired inputs have the same length.
166pub(crate) fn check_equal_len(first: usize, second: usize) -> Result<(), StatsError> {
167    if first == second {
168        Ok(())
169    } else {
170        Err(StatsError::LengthMismatch { first, second })
171    }
172}
173
174/// Validate that every observation in `values` is finite.
175pub(crate) fn check_all_finite(sample: &'static str, values: &[f64]) -> Result<(), StatsError> {
176    match values.iter().position(|v| !v.is_finite()) {
177        None => Ok(()),
178        Some(index) => Err(StatsError::NotFinite {
179            sample,
180            index,
181            value: values[index],
182        }),
183    }
184}
185
186/// Validate that a scalar parameter is finite.
187pub(crate) fn check_parameter_finite(
188    parameter: &'static str,
189    value: f64,
190) -> Result<(), StatsError> {
191    if value.is_finite() {
192        Ok(())
193    } else {
194        Err(StatsError::ParameterNotFinite { parameter, value })
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    #[test]
203    fn display_mentions_the_offending_values() {
204        let msg = StatsError::NotEnoughData {
205            sample: "samples",
206            required: 2,
207            found: 1,
208        }
209        .to_string();
210        assert!(
211            msg.contains("samples") && msg.contains('2') && msg.contains('1'),
212            "{msg}"
213        );
214
215        let msg = StatsError::LengthMismatch {
216            first: 5,
217            second: 4,
218        }
219        .to_string();
220        assert!(msg.contains('5') && msg.contains('4'), "{msg}");
221
222        let msg = StatsError::NonPositiveExpected {
223            index: 2,
224            value: 0.0,
225        }
226        .to_string();
227        assert!(msg.contains("expected[2]"), "{msg}");
228
229        let msg = StatsError::InvalidDegreesOfFreedom { freedom: 0.0 }.to_string();
230        assert!(msg.contains("degrees of freedom"), "{msg}");
231    }
232
233    #[test]
234    fn validators_accept_good_input_and_reject_bad_input() {
235        assert!(check_min_len("x", &[1.0, 2.0], 2).is_ok());
236        assert_eq!(
237            check_min_len("x", &[1.0], 2),
238            Err(StatsError::NotEnoughData {
239                sample: "x",
240                required: 2,
241                found: 1
242            })
243        );
244
245        assert!(check_equal_len(3, 3).is_ok());
246        assert_eq!(
247            check_equal_len(3, 2),
248            Err(StatsError::LengthMismatch {
249                first: 3,
250                second: 2
251            })
252        );
253
254        assert!(check_all_finite("x", &[1.0, -2.0, 3.0]).is_ok());
255        assert!(matches!(
256            check_all_finite("x", &[1.0, f64::NAN]),
257            Err(StatsError::NotFinite {
258                sample: "x",
259                index: 1,
260                ..
261            })
262        ));
263        assert!(matches!(
264            check_all_finite("x", &[f64::INFINITY]),
265            Err(StatsError::NotFinite { index: 0, .. })
266        ));
267
268        assert!(check_parameter_finite("mu0", 1.5).is_ok());
269        assert!(matches!(
270            check_parameter_finite("mu0", f64::NAN),
271            Err(StatsError::ParameterNotFinite {
272                parameter: "mu0",
273                ..
274            })
275        ));
276    }
277
278    #[test]
279    fn is_a_std_error() {
280        fn assert_error<E: Error>(_: &E) {}
281        assert_error(&StatsError::LengthMismatch {
282            first: 1,
283            second: 2,
284        });
285    }
286}