1use std::error::Error;
4use std::fmt;
5
6#[derive(Clone, Copy, Debug, PartialEq)]
17#[non_exhaustive]
18pub enum StatsError {
19 NotEnoughData {
21 sample: &'static str,
23 required: usize,
25 found: usize,
27 },
28
29 LengthMismatch {
31 first: usize,
33 second: usize,
35 },
36
37 ProbabilityOutOfRange {
39 value: f64,
41 },
42
43 NotFinite {
45 sample: &'static str,
47 index: usize,
49 value: f64,
51 },
52
53 ParameterNotFinite {
55 parameter: &'static str,
57 value: f64,
59 },
60
61 NonPositiveExpected {
64 index: usize,
66 value: f64,
68 },
69
70 InvalidDegreesOfFreedom {
73 freedom: f64,
75 },
76
77 NonPositiveParameter {
80 parameter: &'static str,
82 value: f64,
84 },
85
86 RankDeficientDesign,
89
90 DidNotConverge {
92 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
148pub(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
165pub(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
174pub(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
186pub(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}