| 1 | mod cone; |
| 2 | |
| 3 | pub(crate) use self::cone::*; |
| 4 | |
| 5 | #[cfg(test)] |
| 6 | pub(crate) mod test_utils { |
| 7 | pub(crate) const BINS: usize = 10; |
| 8 | pub(crate) const SAMPLES: usize = 20_000; |
| 9 | |
| 10 | /// Perform a Chi-squared goodness-of-fit test to check if the bins are |
| 11 | /// uniformly distributed. Returns the p-value. |
| 12 | pub(crate) fn uniform_distribution_test(bins: &[usize]) -> f64 { |
| 13 | let sum = bins.iter().sum::<usize>() as f64; |
| 14 | let expected = sum / bins.len() as f64; |
| 15 | let critical_value = bins |
| 16 | .iter() |
| 17 | .map(|&bin| { |
| 18 | let difference = bin as f64 - expected; |
| 19 | difference * difference / expected |
| 20 | }) |
| 21 | .sum::<f64>(); |
| 22 | |
| 23 | chi_square(bins.len() - 1, critical_value) |
| 24 | } |
| 25 | |
| 26 | // Shamelessly taken from https://www.codeproject.com/Articles/432194/How-to-Calculate-the-Chi-Squared-P-Value |
| 27 | fn chi_square(dof: usize, critical_value: f64) -> f64 { |
| 28 | if critical_value < 0.0 || dof < 1 { |
| 29 | return 0.0; |
| 30 | } |
| 31 | let k = dof as f64 * 0.5; |
| 32 | let x = critical_value * 0.5; |
| 33 | if dof == 2 { |
| 34 | return (-x).exp(); |
| 35 | } |
| 36 | |
| 37 | let mut p_value = incomplete_gamma_function(k, x); |
| 38 | if p_value.is_nan() || p_value.is_infinite() || p_value <= 1e-8 { |
| 39 | return 1e-14; |
| 40 | } |
| 41 | |
| 42 | p_value /= approximate_gamma(k); |
| 43 | |
| 44 | 1.0 - p_value |
| 45 | } |
| 46 | |
| 47 | fn incomplete_gamma_function(mut s: f64, z: f64) -> f64 { |
| 48 | if z < 0.0 { |
| 49 | return 0.0; |
| 50 | } |
| 51 | let mut sc = 1.0 / s; |
| 52 | sc *= z.powf(s); |
| 53 | sc *= (-z).exp(); |
| 54 | |
| 55 | let mut sum = 1.0; |
| 56 | let mut nom = 1.0; |
| 57 | let mut denom = 1.0; |
| 58 | |
| 59 | for _ in 0..200 { |
| 60 | nom *= z; |
| 61 | s += 1.0; |
| 62 | denom *= s; |
| 63 | sum += nom / denom; |
| 64 | } |
| 65 | |
| 66 | sum * sc |
| 67 | } |
| 68 | |
| 69 | fn approximate_gamma(z: f64) -> f64 { |
| 70 | #[allow(clippy::excessive_precision)] |
| 71 | const RECIP_E: f64 = 0.36787944117144232159552377016147; // RECIP_E = (E^-1) = (1.0 / E) |
| 72 | const TWOPI: f64 = core::f64::consts::TAU; |
| 73 | |
| 74 | let mut d = 1.0 / (10.0 * z); |
| 75 | d = 1.0 / ((12.0 * z) - d); |
| 76 | d = (d + z) * RECIP_E; |
| 77 | d = d.powf(z); |
| 78 | d *= (TWOPI / z).sqrt(); |
| 79 | |
| 80 | d |
| 81 | } |
| 82 | } |