Debian Codegraph @

debian/rust-vendor/statrs/src/distribution/internal.rs

raw
1 use num_traits::Num;
2
3 /// Implements univariate function bisection searching for criteria
4 /// ```text
5 /// smallest k such that f(k) >= z
6 /// ```
7 /// Evaluates to `None` if
8 /// - provided interval has lower bound greater than upper bound
9 /// - function found not semi-monotone on the provided interval containing `z`
10 ///
11 /// Evaluates to `Some(k)`, where `k` satisfies the search criteria
12 pub fn integral_bisection_search<K: Num + Clone, T: Num + PartialOrd>(
13 f: impl Fn(&K) -> T,
14 z: T,
15 lb: K,
16 ub: K,
17 ) -> Option<K> {
18 if !(f(&lb)..=f(&ub)).contains(&z) {
19 return None;
20 }
21 let two = K::one() + K::one();
22 let mut lb = lb;
23 let mut ub = ub;
24 loop {
25 let mid = (lb.clone() + ub.clone()) / two.clone();
26 if !(f(&lb)..=f(&ub)).contains(&f(&mid)) {
27 return None; // f found not monotone on interval
28 } else if f(&lb) == z {
29 return Some(lb);
30 } else if f(&ub) == z || (lb.clone() + K::one()) == ub {
31 return Some(ub); // found or no more integers between
32 } else if f(&mid) >= z {
33 ub = mid;
34 } else {
35 lb = mid;
36 }
37 }
38 }
39
40 #[macro_use]
41 #[cfg(test)]
42 pub mod test {
43 use super::*;
44 use crate::distribution::{Continuous, ContinuousCDF, Discrete, DiscreteCDF};
45
46 #[macro_export]
47 macro_rules! testing_boiler {
48 ($($arg_name:ident: $arg_ty:ty),+; $dist:ty; $dist_err:ty) => {
49 fn make_param_text($($arg_name: $arg_ty),+) -> String {
50 // ""
51 let mut param_text = String::new();
52
53 // "shape=10.0, rate=NaN, "
54 $(
55 param_text.push_str(
56 &format!(
57 "{}={:?}, ",
58 stringify!($arg_name),
59 $arg_name,
60 )
61 );
62 )+
63
64 // "shape=10.0, rate=NaN" (removes trailing comma and whitespace)
65 param_text.pop();
66 param_text.pop();
67
68 param_text
69 }
70
71 /// Creates and returns a distribution with the given parameters,
72 /// panicking if `::new` fails.
73 fn create_ok($($arg_name: $arg_ty),+) -> $dist {
74 match <$dist>::new($($arg_name),+) {
75 Ok(d) => d,
76 Err(e) => panic!(
77 "{}::new was expected to succeed, but failed for {} with error: '{}'",
78 stringify!($dist),
79 make_param_text($($arg_name),+),
80 e
81 )
82 }
83 }
84
85 /// Returns the error when creating a distribution with the given parameters,
86 /// panicking if `::new` succeeds.
87 #[allow(dead_code)]
88 fn create_err($($arg_name: $arg_ty),+) -> $dist_err {
89 match <$dist>::new($($arg_name),+) {
90 Err(e) => e,
91 Ok(d) => panic!(
92 "{}::new was expected to fail, but succeeded for {} with result: {:?}",
93 stringify!($dist),
94 make_param_text($($arg_name),+),
95 d
96 )
97 }
98 }
99
100 /// Creates a distribution with the given parameters, calls the `get_fn`
101 /// function with the new distribution and returns the result of `get_fn`.
102 ///
103 /// Panics if `::new` fails.
104 fn create_and_get<F, T>($($arg_name: $arg_ty),+, get_fn: F) -> T
105 where
106 F: Fn($dist) -> T,
107 {
108 let n = create_ok($($arg_name),+);
109 get_fn(n)
110 }
111
112 /// Creates a distribution with the given parameters, calls the `get_fn`
113 /// function with the new distribution and compares the result of `get_fn`
114 /// to `expected` exactly.
115 ///
116 /// Panics if `::new` fails.
117 #[allow(dead_code)]
118 fn test_exact<F, T>($($arg_name: $arg_ty),+, expected: T, get_fn: F)
119 where
120 F: Fn($dist) -> T,
121 T: ::core::cmp::PartialEq + ::core::fmt::Debug
122 {
123 let x = create_and_get($($arg_name),+, get_fn);
124 if x != expected {
125 panic!(
126 "Expected {:?}, got {:?} for {}",
127 expected,
128 x,
129 make_param_text($($arg_name),+)
130 );
131 }
132 }
133
134 /// Gets a value for the given parameters by calling `create_and_get`
135 /// and compares it to `expected`.
136 ///
137 /// Allows relative error of up to [`crate::consts::ACC`].
138 ///
139 /// Panics if `::new` fails.
140 #[allow(dead_code)]
141 fn test_relative<F>($($arg_name: $arg_ty),+, expected: f64, get_fn: F)
142 where
143 F: Fn($dist) -> f64,
144 {
145 let x = create_and_get($($arg_name),+, get_fn);
146 let max_relative = $crate::consts::ACC;
147
148 if !::approx::relative_eq!(expected, x, max_relative = max_relative) {
149 panic!(
150 "Expected {:?} to be almost equal to {:?} (max. relative error of {:?}), but wasn't for {}",
151 x,
152 expected,
153 max_relative,
154 make_param_text($($arg_name),+)
155 );
156 }
157 }
158
159 /// Gets a value for the given parameters by calling `create_and_get`
160 /// and compares it to `expected`.
161 ///
162 /// Allows absolute error of up to `acc`.
163 ///
164 /// Panics if `::new` fails.
165 #[allow(dead_code)]
166 fn test_absolute<F>($($arg_name: $arg_ty),+, expected: f64, acc: f64, get_fn: F)
167 where
168 F: Fn($dist) -> f64,
169 {
170 let x = create_and_get($($arg_name),+, get_fn);
171
172 // abs_diff_eq! cannot handle infinities, so we manually accept them here
173 if expected.is_infinite() && x == expected {
174 return;
175 }
176
177 if !::approx::abs_diff_eq!(expected, x, epsilon = acc) {
178 panic!(
179 "Expected {:?} to be almost equal to {:?} (max. absolute error of {:?}), but wasn't for {}",
180 x,
181 expected,
182 acc,
183 make_param_text($($arg_name),+)
184 );
185 }
186 }
187
188 /// Purposely fails creating a distribution with the given
189 /// parameters and compares the returned error to `expected`.
190 ///
191 /// Panics if `::new` succeeds.
192 #[allow(dead_code)]
193 fn test_create_err($($arg_name: $arg_ty),+, expected: $dist_err)
194 {
195 let err = create_err($($arg_name),+);
196 if err != expected {
197 panic!(
198 "{}::new was expected to fail with error {:?}, but failed with error {:?} for {}",
199 stringify!($dist),
200 expected,
201 err,
202 make_param_text($($arg_name),+)
203 )
204 }
205 }
206
207 /// Gets a value for the given parameters by calling `create_and_get`
208 /// and asserts that it is [`NAN`].
209 ///
210 /// Panics if `::new` fails.
211 #[allow(dead_code)]
212 fn test_is_nan<F>($($arg_name: $arg_ty),+, get_fn: F)
213 where
214 F: Fn($dist) -> f64
215 {
216 let x = create_and_get($($arg_name),+, get_fn);
217 assert!(x.is_nan());
218 }
219
220 /// Gets a value for the given parameters by calling `create_and_get`
221 /// and asserts that it is [`None`].
222 ///
223 /// Panics if `::new` fails.
224 #[allow(dead_code)]
225 fn test_none<F, T>($($arg_name: $arg_ty),+, get_fn: F)
226 where
227 F: Fn($dist) -> Option<T>,
228 T: ::core::fmt::Debug,
229 {
230 let x = create_and_get($($arg_name),+, get_fn);
231
232 if let Some(inner) = x {
233 panic!(
234 "Expected None, got {:?} for {}",
235 inner,
236 make_param_text($($arg_name),+)
237 )
238 }
239 }
240
241 /// Asserts that associated error type is Send and Sync
242 #[test]
243 fn test_error_is_sync_send() {
244 fn assert_sync_send<T: Sync + Send>() {}
245 assert_sync_send::<$dist_err>();
246 }
247 };
248 }
249
250 pub mod boiler_tests {
251 use crate::distribution::{Beta, BetaError};
252 use crate::statistics::*;
253
254 testing_boiler!(shape_a: f64, shape_b: f64; Beta; BetaError);
255
256 #[test]
257 fn create_ok_success() {
258 let b = create_ok(0.8, 1.2);
259 assert_eq!(b.shape_a(), 0.8);
260 assert_eq!(b.shape_b(), 1.2);
261 }
262
263 #[test]
264 #[should_panic]
265 fn create_err_failure() {
266 create_err(0.8, 1.2);
267 }
268
269 #[test]
270 fn create_err_success() {
271 let err = create_err(-0.5, 1.2);
272 assert_eq!(err, BetaError::ShapeAInvalid);
273 }
274
275 #[test]
276 #[should_panic]
277 fn create_ok_failure() {
278 create_ok(-0.5, 1.2);
279 }
280
281 #[test]
282 fn test_exact_success() {
283 test_exact(1.5, 1.5, 0.5, |dist| dist.mode().unwrap());
284 }
285
286 #[test]
287 #[should_panic]
288 fn test_exact_failure() {
289 test_exact(1.2, 1.4, 0.333333333333, |dist| dist.mode().unwrap());
290 }
291
292 #[test]
293 fn test_relative_success() {
294 test_relative(1.2, 1.4, 0.333333333333, |dist| dist.mode().unwrap());
295 }
296
297 #[test]
298 #[should_panic]
299 fn test_relative_failure() {
300 test_relative(1.2, 1.4, 0.333, |dist| dist.mode().unwrap());
301 }
302
303 #[test]
304 fn test_absolute_success() {
305 test_absolute(1.2, 1.4, 0.333333333333, 1e-12, |dist| dist.mode().unwrap());
306 }
307
308 #[test]
309 #[should_panic]
310 fn test_absolute_failure() {
311 test_absolute(1.2, 1.4, 0.333333333333, 1e-15, |dist| dist.mode().unwrap());
312 }
313
314 #[test]
315 fn test_create_err_success() {
316 test_create_err(0.0, 0.5, BetaError::ShapeAInvalid);
317 }
318
319 #[test]
320 #[should_panic]
321 fn test_create_err_failure() {
322 test_create_err(0.0, 0.5, BetaError::ShapeBInvalid);
323 }
324
325 #[test]
326 fn test_is_nan_success() {
327 // Not sure that any Beta API can return a NaN, so we force the issue
328 test_is_nan(0.8, 1.2, |_| f64::NAN);
329 }
330
331 #[test]
332 #[should_panic]
333 fn test_is_nan_failure() {
334 test_is_nan(0.8, 1.2, |dist| dist.mean().unwrap());
335 }
336
337 #[test]
338 fn test_is_none_success() {
339 test_none(0.5, 1.2, |dist| dist.mode());
340 }
341
342 #[test]
343 #[should_panic]
344 fn test_is_none_failure() {
345 test_none(0.8, 1.2, |dist| dist.mean());
346 }
347 }
348
349 /// cdf should be the integral of the pdf
350 fn check_integrate_pdf_is_cdf<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>(
351 dist: &D,
352 x_min: f64,
353 x_max: f64,
354 step: f64,
355 ) {
356 let mut prev_x = x_min;
357 let mut prev_density = dist.pdf(x_min);
358 let mut sum = 0.0;
359
360 loop {
361 let x = prev_x + step;
362 let density = dist.pdf(x);
363
364 assert!(density >= 0.0);
365
366 let ln_density = dist.ln_pdf(x);
367
368 assert_almost_eq!(density.ln(), ln_density, 1e-10);
369
370 // triangle rule
371 sum += (prev_density + density) * step / 2.0;
372
373 let cdf = dist.cdf(x);
374 if (sum - cdf).abs() > 1e-3 {
375 println!("Integral of pdf doesn't equal cdf!");
376 println!("Integration from {x_min} by {step} to {x} = {sum}");
377 println!("cdf = {cdf}");
378 panic!();
379 }
380
381 if x >= x_max {
382 break;
383 } else {
384 prev_x = x;
385 prev_density = density;
386 }
387 }
388
389 assert!(sum > 0.99);
390 assert!(sum <= 1.001);
391 }
392
393 /// cdf should be the sum of the pmf
394 fn check_sum_pmf_is_cdf<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(dist: &D, x_max: u64) {
395 let mut sum = 0.0;
396
397 // go slightly beyond x_max to test for off-by-one errors
398 for i in 0..x_max + 3 {
399 let prob = dist.pmf(i);
400
401 assert!(prob >= 0.0);
402 assert!(prob <= 1.0);
403
404 sum += prob;
405
406 if i == x_max {
407 assert!(sum > 0.99);
408 }
409
410 assert_almost_eq!(sum, dist.cdf(i), 1e-10);
411 // assert_almost_eq!(sum, dist.cdf(i as f64), 1e-10);
412 // assert_almost_eq!(sum, dist.cdf(i as f64 + 0.1), 1e-10);
413 // assert_almost_eq!(sum, dist.cdf(i as f64 + 0.5), 1e-10);
414 // assert_almost_eq!(sum, dist.cdf(i as f64 + 0.9), 1e-10);
415 }
416
417 assert!(sum > 0.99);
418 assert!(sum <= 1.0 + 1e-10);
419 }
420
421 /// Does a series of checks that all continuous distributions must obey.
422 /// 99% of the probability mass should be between x_min and x_max.
423 pub fn check_continuous_distribution<D: ContinuousCDF<f64, f64> + Continuous<f64, f64>>(
424 dist: &D,
425 x_min: f64,
426 x_max: f64,
427 ) {
428 assert_eq!(dist.pdf(f64::NEG_INFINITY), 0.0);
429 assert_eq!(dist.pdf(f64::INFINITY), 0.0);
430 assert_eq!(dist.ln_pdf(f64::NEG_INFINITY), f64::NEG_INFINITY);
431 assert_eq!(dist.ln_pdf(f64::INFINITY), f64::NEG_INFINITY);
432 assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0);
433 assert_eq!(dist.cdf(f64::INFINITY), 1.0);
434
435 check_integrate_pdf_is_cdf(dist, x_min, x_max, (x_max - x_min) / 100000.0);
436 }
437
438 /// Does a series of checks that all positive discrete distributions must
439 /// obey.
440 /// 99% of the probability mass should be between 0 and x_max (inclusive).
441 pub fn check_discrete_distribution<D: DiscreteCDF<u64, f64> + Discrete<u64, f64>>(
442 dist: &D,
443 x_max: u64,
444 ) {
445 // assert_eq!(dist.cdf(f64::NEG_INFINITY), 0.0);
446 // assert_eq!(dist.cdf(-10.0), 0.0);
447 // assert_eq!(dist.cdf(-1.0), 0.0);
448 // assert_eq!(dist.cdf(-0.01), 0.0);
449 // assert_eq!(dist.cdf(f64::INFINITY), 1.0);
450
451 check_sum_pmf_is_cdf(dist, x_max);
452 }
453
454 #[test]
455 fn test_integer_bisection() {
456 fn search(z: usize, data: &[usize]) -> Option<usize> {
457 integral_bisection_search(|idx: &usize| data[*idx], z, 0, data.len() - 1)
458 }
459
460 let needle = 3;
461 let data = (0..5)
462 .map(|n| if n >= needle { n + 1 } else { n })
463 .collect::<Vec<_>>();
464
465 for i in 0..(data.len()) {
466 assert_eq!(search(data[i], &data), Some(i),)
467 }
468 {
469 let infimum = search(needle, &data);
470 let found_element = search(needle + 1, &data); // 4 > needle && member of range
471 assert_eq!(found_element, Some(needle));
472 assert_eq!(infimum, found_element)
473 }
474 }
475 }