Skip to main content

tpt_math_prob_dist/
lib.rs

1#![no_std]
2#![forbid(unsafe_code)]
3#![warn(missing_docs, missing_debug_implementations)]
4//! Standard probability distributions, bridging [`rand_distr`] into the
5//! [`tpt_math_prob_core`] trait ecosystem.
6//!
7//! This crate wraps the [`rand_distr`] distributions and makes them sampleable
8//! through the minimal [`tpt_math_prob_core::Rng`]/[`Distribution`](`tpt_math_prob_core::Distribution`)
9//! traits used across the `tpt-math-prob-*` family. Because our [`Rng`] is far
10//! smaller than [`rand`]'s [`RngCore`], we provide [`CoreRng`]: a thin adapter
11//! that turns any of our RNGs into a [`rand::RngCore`] so that every
12//! [`rand_distr`] distribution can be sampled without pulling in `rand`'s own
13//! generators.
14//!
15//! The distributions themselves are *not* directly re-implemented. Instead the
16//! local [`Dist`] wrapper (and the small [`AsU64`] helper for counts) adapts a
17//! `rand_distr` distribution to our [`Distribution`](`tpt_math_prob_core::Distribution`)
18//! trait. Constructor functions ([`normal`], [`uniform`], [`poisson`], …) give
19//! ergonomic, documented entry points, and the raw [`rand_distr`] module is
20//! re-exported so advanced users can reach under the bridge.
21//!
22//! The crate is `no_std`-compatible; all float math is delegated to
23//! `rand_distr` (which uses `num-traits`'s `libm` fallback), and `std`-only
24//! conveniences are gated behind the default `std` feature.
25//!
26//! # Examples
27//!
28//! ```
29//! use tpt_math_prob_core::{Distribution, Rng, SplitMix64};
30//! use tpt_math_prob_dist::{normal, Dist};
31//!
32//! let mut rng = SplitMix64::seed_from_u64(0);
33//! let gauss = normal((0.0, 1.0)).unwrap();
34//! let x: f64 = Dist::new(gauss).sample(&mut rng);
35//! // or, equivalently, with the explicit bridge type:
36//! let y: f64 = Dist::new(normal((2.0, 3.0)).unwrap()).sample(&mut rng);
37//! let _ = x + y;
38//! ```
39
40extern crate alloc;
41
42#[cfg(feature = "std")]
43extern crate std;
44
45/// Densities, probability mass functions, CDFs and quantiles. Needs `std`
46/// (the default) for the special functions in `tpt-math-prob-core`.
47#[cfg(feature = "std")]
48pub mod density;
49#[cfg(feature = "multivariate")]
50pub mod multivariate;
51
52// Re-export the core randomness traits/types so consumers can depend on this
53// crate alone. We deliberately re-export `rand_distr` verbatim as well.
54pub use tpt_math_prob_core::{Distribution, Rng, Sampler, SplitMix64, Standard};
55
56/// The raw [`rand_distr`] distributions, re-exported for direct use.
57///
58/// Everything in this module is the unmodified `rand_distr` API, which samples
59/// through [`rand::RngCore`]. To sample through our [`Rng`], wrap a value in
60/// [`Dist`] (or use the constructor functions like [`normal`]).
61pub use rand_distr;
62
63use rand::distr::Distribution as RandDistribution;
64use rand::rand_core::RngCore;
65
66/// Adapter turning one of our [`Rng`]s into a [`rand::RngCore`].
67///
68/// `rand_distr` distributions are generic over [`rand::RngCore`]; our
69/// [`tpt_math_prob_core::Rng`] is deliberately much smaller (it only promises
70/// [`next_u64`](`Rng::next_u64`)). `CoreRng` supplies the missing methods in
71/// terms of `next_u64`, so a distribution can be sampled as
72/// `dist.sample(&mut CoreRng(&mut our_rng))`.
73///
74/// The adapter is zero-cost and owns no state of its own.
75///
76/// # Examples
77///
78/// ```
79/// use rand::RngCore;
80/// use tpt_math_prob_core::SplitMix64;
81/// use tpt_math_prob_dist::CoreRng;
82///
83/// let mut rng = SplitMix64::seed_from_u64(1);
84/// let mut core = CoreRng(&mut rng);
85/// let word: u32 = core.next_u32();
86/// let quad: u64 = core.next_u64();
87/// let _ = (word, quad);
88/// ```
89#[derive(Debug)]
90pub struct CoreRng<R: ?Sized>(pub R);
91impl<R: Rng + ?Sized> RngCore for CoreRng<R> {
92    #[inline]
93    fn next_u32(&mut self) -> u32 {
94        (self.0.next_u64() >> 32) as u32
95    }
96
97    #[inline]
98    fn next_u64(&mut self) -> u64 {
99        self.0.next_u64()
100    }
101
102    #[inline]
103    fn fill_bytes(&mut self, dst: &mut [u8]) {
104        let mut chunks = dst.chunks_exact_mut(8);
105        for chunk in chunks.by_ref() {
106            chunk.copy_from_slice(&self.next_u64().to_le_bytes());
107        }
108        let rem = chunks.into_remainder();
109        if !rem.is_empty() {
110            let bits = self.next_u64().to_le_bytes();
111            rem.copy_from_slice(&bits[..rem.len()]);
112        }
113    }
114}
115
116/// A `rand_distr` distribution adapted to our [`Distribution`](`tpt_math_prob_core::Distribution`)
117/// trait.
118///
119/// Given a `rand_distr` distribution `D` that produces values of type `T`
120/// (i.e. `rand_distr::Distribution<T>` is implemented for `D`), [`Dist::new`]
121/// wraps it so it can be sampled through any of our [`Rng`]s:
122///
123/// ```
124/// use tpt_math_prob_core::{Distribution, SplitMix64};
125/// use tpt_math_prob_dist::{normal, Dist};
126///
127/// let mut rng = SplitMix64::seed_from_u64(5);
128/// let dist = Dist::new(normal((0.0, 1.0)).unwrap());
129/// let x: f64 = dist.sample(&mut rng);
130/// assert!(x.is_finite());
131/// ```
132///
133/// The blanket [`Distribution`](`tpt_math_prob_core::Distribution) impl below
134/// means [`Dist`] works for *every* `rand_distr` distribution, not just the
135/// ones with dedicated constructors in this crate.
136#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
137pub struct Dist<D>(pub D);
138
139impl<D> Dist<D> {
140    /// Wrap a `rand_distr` distribution so it can be sampled through our [`Rng`].
141    #[inline]
142    pub fn new(dist: D) -> Self {
143        Dist(dist)
144    }
145
146    /// Borrow the wrapped distribution.
147    #[inline]
148    pub fn inner(&self) -> &D {
149        &self.0
150    }
151
152    /// Mutably borrow the wrapped distribution.
153    #[inline]
154    pub fn inner_mut(&mut self) -> &mut D {
155        &mut self.0
156    }
157
158    /// Consume the adapter and return the wrapped distribution.
159    #[inline]
160    pub fn into_inner(self) -> D {
161        self.0
162    }
163}
164
165/// Bridge any `rand_distr` distribution into our [`Distribution`](`tpt_math_prob_core::Distribution`)
166/// trait.
167///
168/// Because [`Dist`] is a local type, this `impl` is allowed (the orphan rule
169/// forbids implementing our foreign [`Distribution`](`tpt_math_prob_core::Distribution)
170/// directly for the foreign `rand_distr` distributions). Sampling simply
171/// forwards to the `rand_distr` `Distribution::sample` through [`CoreRng`].
172impl<D, T> Distribution<T> for Dist<D>
173where
174    D: RandDistribution<T>,
175{
176    #[inline]
177    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T {
178        let mut r = CoreRng(rng);
179        self.0.sample(&mut r)
180    }
181}
182
183/// Wrap a *float*-producing `rand_distr` distribution and emit integer counts.
184///
185/// Some `rand_distr` distributions are defined to return an `f64` even though
186/// they model integer quantities (most notably [`Poisson`](`rand_distr::Poisson`),
187/// which yields a `f64` number of occurrences). [`AsU64`] adapts such a
188/// distribution to our [`Distribution<u64>`](`tpt_math_prob_core::Distribution),
189/// truncating the (non-negative, whole) `f64` value to `u64`.
190///
191/// # Examples
192///
193/// ```
194/// use tpt_math_prob_core::{Distribution, SplitMix64};
195/// use tpt_math_prob_dist::{poisson, AsU64};
196///
197/// let mut rng = SplitMix64::seed_from_u64(9);
198/// let dist = AsU64(poisson(4.0).unwrap());
199/// let n: u64 = dist.sample(&mut rng);
200/// assert_eq!(n, n as f64 as u64);
201/// ```
202#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
203pub struct AsU64<D>(pub D);
204
205impl<D> AsU64<D> {
206    /// Wrap a float-producing `rand_distr` distribution as a `u64` source.
207    #[inline]
208    pub fn new(dist: D) -> Self {
209        AsU64(dist)
210    }
211
212    /// Consume the adapter and return the wrapped distribution.
213    #[inline]
214    pub fn into_inner(self) -> D {
215        self.0
216    }
217}
218
219impl<D> Distribution<u64> for AsU64<D>
220where
221    D: RandDistribution<f64>,
222{
223    #[inline]
224    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> u64 {
225        let mut r = CoreRng(rng);
226        let x: f64 = self.0.sample(&mut r);
227        if x <= 0.0 {
228            0
229        } else if x >= u64::MAX as f64 {
230            u64::MAX
231        } else {
232            x as u64
233        }
234    }
235}
236
237/// Generate a re-exported `rand_distr` distribution type alias plus an
238/// ergonomic constructor function.
239///
240/// The alias keeps the canonical `rand_distr` name (so `use` sites read
241/// naturally), and the constructor forwards to `rand_distr`'s `new`, mapping
242/// the `rand_distr` error to a plain `&'static str` so the public surface is
243/// allocation-free and `no_std`-friendly. A `const`-assertion documents the
244/// `Output` type the distribution actually produces.
245macro_rules! dist {
246    (
247        $(#[$meta:meta])*
248        $func:ident, $name:ident, $inner:ident, $args:ty, $output:ty
249    ) => {
250        $(#[$meta])*
251        #[allow(missing_docs)]
252        pub type $name<F = f64> = rand_distr::$inner<F>;
253
254        $(#[$meta])*
255        ///
256        /// # Errors
257        ///
258        /// Returns `Err(&str)` if the parameters are invalid for this
259        /// distribution (e.g. non-positive scale, zero variance).
260        pub fn $func(args: $args) -> Result<$name<f64>, &'static str> {
261            const _: () = {
262                // Verify the output type at compile time.
263                fn _assert(_: $output) {}
264            };
265            <rand_distr::$inner<f64> as DistConstructable>::construct(args)
266                .map_err(|_| "invalid parameters for distribution")
267        }
268    };
269}
270
271/// Helper trait used solely to give the [`dist!`] macro a uniform constructor
272/// signature across the various `rand_distr` `new` argument shapes.
273trait DistConstructable: Sized {
274    /// Constructor argument tuple type (mirrors `rand_distr::*::new`).
275    type Args;
276    /// Error type returned by the underlying `rand_distr` constructor.
277    type Error;
278    /// Build the distribution, returning the `rand_distr` error on bad input.
279    fn construct(args: Self::Args) -> Result<Self, Self::Error>;
280}
281
282impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::Normal<F>
283where
284    rand_distr::StandardNormal: RandDistribution<F>,
285    rand_distr::Exp1: RandDistribution<F>,
286{
287    type Args = (F, F);
288    type Error = rand_distr::NormalError;
289    fn construct((m, s): (F, F)) -> Result<Self, Self::Error> {
290        rand_distr::Normal::new(m, s)
291    }
292}
293
294impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::LogNormal<F>
295where
296    rand_distr::StandardNormal: RandDistribution<F>,
297    rand_distr::Exp1: RandDistribution<F>,
298{
299    type Args = (F, F);
300    type Error = rand_distr::NormalError;
301    fn construct((m, s): (F, F)) -> Result<Self, Self::Error> {
302        rand_distr::LogNormal::new(m, s)
303    }
304}
305
306impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::Exp<F>
307where
308    rand_distr::Exp1: RandDistribution<F>,
309{
310    type Args = F;
311    type Error = rand_distr::ExpError;
312    fn construct(lambda: F) -> Result<Self, Self::Error> {
313        rand_distr::Exp::new(lambda)
314    }
315}
316
317impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::Gamma<F>
318where
319    rand_distr::StandardNormal: RandDistribution<F>,
320    rand_distr::Exp1: RandDistribution<F>,
321    rand_distr::Open01: RandDistribution<F>,
322{
323    type Args = (F, F);
324    type Error = rand_distr::GammaError;
325    fn construct((shape, scale): (F, F)) -> Result<Self, Self::Error> {
326        rand_distr::Gamma::new(shape, scale)
327    }
328}
329
330impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::Beta<F>
331where
332    rand_distr::StandardNormal: RandDistribution<F>,
333    rand_distr::Exp1: RandDistribution<F>,
334    rand_distr::Open01: RandDistribution<F>,
335{
336    type Args = (F, F);
337    type Error = rand_distr::BetaError;
338    fn construct((a, b): (F, F)) -> Result<Self, Self::Error> {
339        rand_distr::Beta::new(a, b)
340    }
341}
342
343impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::ChiSquared<F>
344where
345    rand_distr::StandardNormal: RandDistribution<F>,
346    rand_distr::Exp1: RandDistribution<F>,
347    rand_distr::Open01: RandDistribution<F>,
348{
349    type Args = F;
350    type Error = rand_distr::ChiSquaredError;
351    fn construct(k: F) -> Result<Self, Self::Error> {
352        rand_distr::ChiSquared::new(k)
353    }
354}
355
356impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::StudentT<F>
357where
358    rand_distr::StandardNormal: RandDistribution<F>,
359    rand_distr::Exp1: RandDistribution<F>,
360    rand_distr::Open01: RandDistribution<F>,
361    rand_distr::ChiSquared<F>: RandDistribution<F>,
362{
363    type Args = F;
364    type Error = rand_distr::ChiSquaredError;
365    fn construct(nu: F) -> Result<Self, Self::Error> {
366        rand_distr::StudentT::new(nu)
367    }
368}
369
370impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::Cauchy<F>
371where
372    rand_distr::StandardNormal: RandDistribution<F>,
373    rand_distr::Exp1: RandDistribution<F>,
374    rand_distr::Open01: RandDistribution<F>,
375    rand_distr::StandardUniform: RandDistribution<F>,
376    F: rand_distr::num_traits::FloatConst,
377{
378    type Args = (F, F);
379    type Error = rand_distr::CauchyError;
380    fn construct((median, scale): (F, F)) -> Result<Self, Self::Error> {
381        rand_distr::Cauchy::new(median, scale)
382    }
383}
384
385impl<F: rand_distr::num_traits::Float> DistConstructable for rand_distr::Poisson<F>
386where
387    rand_distr::StandardUniform: RandDistribution<F>,
388    F: rand_distr::num_traits::FloatConst,
389{
390    type Args = F;
391    type Error = rand_distr::PoissonError;
392    fn construct(lambda: F) -> Result<Self, Self::Error> {
393        rand_distr::Poisson::new(lambda)
394    }
395}
396
397dist!(
398    /// `Normal` (Gaussian) distribution, `N(mean, std_dev)`.
399    normal, Normal, Normal, (f64, f64), f64
400);
401dist!(
402    /// `LogNormal` distribution.
403    lognormal, LogNormal, LogNormal, (f64, f64), f64
404);
405dist!(
406    /// `Exp` (exponential) distribution with rate `lambda`.
407    exp, Exp, Exp, f64, f64
408);
409dist!(
410    /// `Gamma` distribution with shape and scale.
411    gamma, Gamma, Gamma, (f64, f64), f64
412);
413dist!(
414    /// `Beta` distribution with shape parameters `alpha`, `beta`.
415    beta, Beta, Beta, (f64, f64), f64
416);
417dist!(
418    /// `ChiSquared` distribution with `k` degrees of freedom.
419    chi_squared, ChiSquared, ChiSquared, f64, f64
420);
421dist!(
422    /// Student's `t` distribution with `nu` degrees of freedom.
423    student_t, StudentT, StudentT, f64, f64
424);
425dist!(
426    /// `Cauchy` distribution with `median` and `scale`.
427    cauchy, Cauchy, Cauchy, (f64, f64), f64
428);
429dist!(
430    /// `Poisson` distribution with rate `lambda` (samples returned as `u64`).
431    poisson, Poisson, Poisson, f64, u64
432);
433
434/// `Uniform` distribution over an inclusive-exclusive range `[low, high)`.
435///
436/// Produces values of the sampled type `T` (e.g. `f64` or `u64`). The
437/// constructor uses `rand_distr`'s `Uniform::new`.
438///
439/// # Examples
440///
441/// ```
442/// use tpt_math_prob_core::{Distribution, SplitMix64};
443/// use tpt_math_prob_dist::{uniform, Dist};
444///
445/// let mut rng = SplitMix64::seed_from_u64(2);
446/// let dist = Dist::new(uniform(0.0_f64, 1.0).unwrap());
447/// let x: f64 = dist.sample(&mut rng);
448/// assert!((0.0..1.0).contains(&x));
449/// ```
450///
451/// # Errors
452///
453/// Returns `Err(&str)` if `low >= high`.
454pub fn uniform<T>(low: T, high: T) -> Result<rand_distr::Uniform<T>, &'static str>
455where
456    T: rand_distr::uniform::SampleUniform,
457{
458    rand_distr::Uniform::new(low, high)
459        .map_err(|_| "invalid parameters for Uniform (require low < high)")
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use tpt_math_prob_core::{Distribution as CoreDist, Rng as CoreRngTrait, SplitMix64};
466
467    /// Sample `n` values from `dist` via our [`Rng`] and return the mean.
468    fn mean_f64<D: CoreDist<f64>>(dist: &D, n: u64) -> f64 {
469        let mut rng = SplitMix64::seed_from_u64(0xDEAD_BEEF);
470        let mut sum = 0.0;
471        for _ in 0..n {
472            sum += dist.sample(&mut rng);
473        }
474        sum / (n as f64)
475    }
476
477    /// Sample `n` values from `dist` via our [`Rng`] and return the mean.
478    fn mean_u64<D: CoreDist<u64>>(dist: &D, n: u64) -> f64 {
479        let mut rng = SplitMix64::seed_from_u64(0xDEAD_BEEF);
480        let mut sum = 0.0;
481        for _ in 0..n {
482            sum += dist.sample(&mut rng) as f64;
483        }
484        sum / (n as f64)
485    }
486
487    #[test]
488    fn normal_mean_and_variance() {
489        let n = 200_000u64;
490        let dist = Dist::new(normal((3.0, 2.0)).unwrap());
491        let mut rng = SplitMix64::seed_from_u64(1234);
492        let mut sum = 0.0;
493        let mut sum_sq = 0.0;
494        for _ in 0..n {
495            let x: f64 = dist.sample(&mut rng);
496            sum += x;
497            sum_sq += x * x;
498        }
499        let mean = sum / (n as f64);
500        let var = sum_sq / (n as f64) - mean * mean;
501        assert!((mean - 3.0).abs() < 0.05, "mean={mean}");
502        assert!((var - 4.0).abs() < 0.1, "var={var}");
503    }
504
505    #[test]
506    fn uniform_float_mean() {
507        let dist = Dist::new(uniform(0.0_f64, 1.0).unwrap());
508        let m = mean_f64(&dist, 100_000);
509        assert!((m - 0.5).abs() < 0.01, "mean={m}");
510    }
511
512    #[test]
513    fn uniform_u64_range() {
514        let dist = Dist::new(uniform(10u64, 20u64).unwrap());
515        let mut rng = SplitMix64::seed_from_u64(7);
516        for _ in 0..1000 {
517            let x: u64 = dist.sample(&mut rng);
518            assert!((10..20).contains(&x), "x={x}");
519        }
520    }
521
522    #[test]
523    fn exp_mean() {
524        // exp(rate=2) has mean 0.5.
525        let dist = Dist::new(exp(2.0).unwrap());
526        let m = mean_f64(&dist, 100_000);
527        assert!((m - 0.5).abs() < 0.02, "mean={m}");
528    }
529
530    #[test]
531    fn poisson_mean() {
532        // poisson(lambda=4) has mean lambda=4.
533        let dist = AsU64(poisson(4.0).unwrap());
534        let m = mean_u64(&dist, 100_000);
535        assert!((m - 4.0).abs() < 0.05, "mean={m}");
536    }
537
538    #[test]
539    fn lognormal_positive() {
540        let dist = Dist::new(lognormal((0.0, 1.0)).unwrap());
541        let mut rng = SplitMix64::seed_from_u64(11);
542        for _ in 0..1000 {
543            let x: f64 = dist.sample(&mut rng);
544            assert!(x > 0.0);
545        }
546    }
547
548    #[test]
549    fn gamma_beta_positive() {
550        let g = Dist::new(gamma((2.0, 1.0)).unwrap());
551        let b = Dist::new(beta((2.0, 3.0)).unwrap());
552        let mut rng = SplitMix64::seed_from_u64(13);
553        for _ in 0..1000 {
554            assert!(g.sample(&mut rng) >= 0.0);
555            let x: f64 = b.sample(&mut rng);
556            assert!((0.0..=1.0).contains(&x));
557        }
558    }
559
560    #[test]
561    fn chi_squared_studentt_cauchy_finite() {
562        let chi = Dist::new(chi_squared(3.0).unwrap());
563        let st = Dist::new(student_t(5.0).unwrap());
564        let ca = Dist::new(cauchy((0.0, 1.0)).unwrap());
565        let mut rng = SplitMix64::seed_from_u64(17);
566        for _ in 0..1000 {
567            assert!(chi.sample(&mut rng).is_finite());
568            assert!(st.sample(&mut rng).is_finite());
569            assert!(ca.sample(&mut rng).is_finite());
570        }
571    }
572
573    #[test]
574    fn core_rng_adapter_forwards_bits() {
575        // Sampling through `CoreRng` must match sampling `rand_distr` directly
576        // with the same seed, proving the adapter forwards bits faithfully.
577        let gauss = rand_distr::Normal::new(0.0, 1.0).unwrap();
578        let mut a = SplitMix64::seed_from_u64(42);
579        let mut b = SplitMix64::seed_from_u64(42);
580        for _ in 0..1000 {
581            let via_adapter: f64 = Dist::new(&gauss).sample(&mut a);
582            let direct: f64 = {
583                let mut r = CoreRng(&mut b);
584                gauss.sample(&mut r)
585            };
586            assert_eq!(via_adapter, direct);
587        }
588    }
589
590    #[test]
591    fn core_rng_next_u64_matches_inner() {
592        // `CoreRng` must delegate `next_u64`/`next_u32` to the wrapped `Rng`.
593        let mut a = SplitMix64::seed_from_u64(7);
594        let mut b = SplitMix64::seed_from_u64(7);
595        let mut core = CoreRng(&mut a);
596        for _ in 0..1000 {
597            assert_eq!(core.next_u64(), b.next_u64());
598            assert_eq!(core.next_u32(), (b.next_u64() >> 32) as u32);
599        }
600    }
601
602    #[test]
603    fn direct_rand_distr_usage() {
604        // A plain `rand_distr` usage example, bridged via `CoreRng`.
605        let gauss = rand_distr::Normal::new(1.0, 0.5).unwrap();
606        let mut rng = SplitMix64::seed_from_u64(2024);
607        let mut core = CoreRng(&mut rng);
608        let x: f64 = gauss.sample(&mut core);
609        assert!(x.is_finite());
610    }
611}