use crate::StatsError;
use deep_causality_algebra::RealField;
use deep_causality_num::{FromPrimitive, ToPrimitive};
use deep_causality_rand::{Distribution, Xoshiro256};
pub const SUITE_SEED: u64 = 0x5EED_2026;
pub fn draws<T, D>(d: &D, n: u64, seed: u64) -> Vec<f64>
where
T: ToPrimitive,
D: Distribution<T>,
{
let mut g = Xoshiro256::from_seed(seed);
(0..n)
.map(|_| {
d.sample(&mut g)
.to_f64()
.expect("every supported scalar lowers to f64")
})
.collect()
}
pub fn moments<T, D>(d: &D, n: u64, seed: u64) -> (f64, f64)
where
T: ToPrimitive,
D: Distribution<T>,
{
let xs = draws::<T, D>(d, n, seed);
let mean = xs.iter().sum::<f64>() / xs.len() as f64;
let var = xs.iter().map(|x| (x - mean) * (x - mean)).sum::<f64>() / xs.len() as f64;
(mean, var)
}
pub fn sorted_draws<T, D>(d: &D, n: u64, seed: u64) -> Vec<f64>
where
T: ToPrimitive,
D: Distribution<T>,
{
let mut xs = draws::<T, D>(d, n, seed);
xs.sort_by(|a, b| a.partial_cmp(b).expect("no draw is NaN"));
xs
}
pub fn quantile(sorted: &[f64], q: f64) -> f64 {
assert!((0.0..=1.0).contains(&q), "a quantile lies in [0, 1]");
let idx = ((sorted.len() as f64 - 1.0) * q).round() as usize;
sorted[idx]
}
pub fn assert_near(got: f64, want: f64, tol: f64, what: &str) {
let rel = if want == 0.0 {
got.abs()
} else {
(got - want).abs() / want.abs()
};
assert!(
rel <= tol,
"{what}: got {got}, closed form {want}, relative error {rel} exceeds {tol}"
);
}
pub fn expect_refused<T>(got: Result<T, StatsError>, what: &str) {
assert!(
got.is_err(),
"{what}: the constructor accepted a parameter the distribution is not defined for"
);
}
pub fn expect_accepted<T>(got: Result<T, StatsError>, what: &str) -> T {
match got {
Ok(v) => v,
Err(e) => panic!("{what}: the constructor refused a valid parameter: {e}"),
}
}
pub fn lift<T: FromPrimitive + RealField>(v: f64) -> T {
T::from_f64(v).expect("a configuration literal converts to every supported scalar")
}
#[derive(Clone, Copy, Debug, Default)]
pub struct ZeroRng;
impl deep_causality_rand::RngCore for ZeroRng {
fn next_u32(&mut self) -> u32 {
0
}
fn next_u64(&mut self) -> u64 {
0
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
dest.fill(0);
}
}
impl deep_causality_rand::Rng for ZeroRng {}
pub fn assert_guards_against_zero<F>(draw: F, what: &str)
where
F: FnOnce() + Send + 'static,
{
let handle = std::thread::spawn(draw);
std::thread::sleep(std::time::Duration::from_millis(200));
assert!(
!handle.is_finished(),
"{what}: the sampler returned a value from an all-zero generator, so it admits a zero \
into a logarithm"
);
}
#[derive(Clone, Copy, Debug, Default)]
pub struct MaxRng;
impl deep_causality_rand::RngCore for MaxRng {
fn next_u32(&mut self) -> u32 {
u32::MAX
}
fn next_u64(&mut self) -> u64 {
u64::MAX
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
dest.fill(0xFF);
}
}
impl deep_causality_rand::Rng for MaxRng {}