1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use std::{marker::PhantomData, ops::RangeInclusive};

use fastrand::Rng;

use crate::{
    constants::{ConstDoubleSqrt3, ConstSqrt3},
    kernel::Kernel,
    traits::{
        loopback::{SelfAdd, SelfDiv, SelfMul, SelfMulAdd, SelfNeg},
        shortcuts::Additive,
    },
    Density,
    Sample,
};

/// [Uniform][1] kernel, also known as «boxcar function», with normalized density.
///
/// [1]: https://en.wikipedia.org/wiki/Continuous_uniform_distribution#Probability_density_function
#[derive(Copy, Clone, Debug)]
pub struct Uniform<P, D> {
    min: P,
    max: P,
    _density: PhantomData<D>,
}

impl<P, D> Uniform<P, D>
where
    P: PartialOrd,
{
    /// Construct the kernel with specified **inclusive** bounds.
    pub fn with_bounds(range: RangeInclusive<P>) -> Self {
        let (min, max) = range.into_inner();
        Self {
            min,
            max,
            _density: PhantomData,
        }
    }
}

impl<P, D> Density for Uniform<P, D>
where
    P: Copy + Into<D> + PartialOrd + Additive,
    D: SelfDiv + num_traits::Zero + ConstDoubleSqrt3,
{
    type Param = P;
    type Output = D;

    fn density(&self, at: Self::Param) -> Self::Output {
        if (self.min..=self.max).contains(&at) {
            (self.max - self.min).into() / D::DOUBLE_SQRT_3
        } else {
            D::zero()
        }
    }
}

macro_rules! impl_sample_discrete {
    ($type:ident) => {
        impl<D> Sample for Uniform<$type, D> {
            type Param = $type;

            fn sample(&self, rng: &mut Rng) -> Self::Param {
                rng.$type(self.min..=self.max)
            }
        }
    };
}

impl_sample_discrete!(isize);
impl_sample_discrete!(usize);
impl_sample_discrete!(i8);
impl_sample_discrete!(u8);
impl_sample_discrete!(i16);
impl_sample_discrete!(u16);
impl_sample_discrete!(i32);
impl_sample_discrete!(u32);
impl_sample_discrete!(i64);
impl_sample_discrete!(u64);
impl_sample_discrete!(i128);
impl_sample_discrete!(u128);

macro_rules! impl_sample_continuous {
    ($type:ident) => {
        impl<D> Sample for Uniform<$type, D> {
            type Param = $type;

            fn sample(&self, rng: &mut Rng) -> Self::Param {
                rng.$type().mul_add(self.max - self.min, self.min)
            }
        }

        #[cfg(feature = "ordered-float")]
        impl<D> Sample for Uniform<ordered_float::OrderedFloat<$type>, D> {
            type Param = ordered_float::OrderedFloat<$type>;

            fn sample(&self, rng: &mut Rng) -> ordered_float::OrderedFloat<$type> {
                use num_traits::Float;
                ordered_float::OrderedFloat(rng.$type()).mul_add(self.max - self.min, self.min)
            }
        }

        #[cfg(feature = "ordered-float")]
        impl<D> Sample for Uniform<ordered_float::NotNan<$type>, D> {
            type Param = ordered_float::NotNan<$type>;

            fn sample(&self, rng: &mut Rng) -> ordered_float::NotNan<$type> {
                let normalized = unsafe { ordered_float::NotNan::new_unchecked(rng.$type()) };
                normalized * (self.max - self.min) + self.min
            }
        }
    };
}

impl_sample_continuous!(f32);
impl_sample_continuous!(f64);

impl<P, D> Kernel for Uniform<P, D>
where
    Self: Density<Param = P, Output = D> + Sample<Param = P>,
    P: Copy + SelfAdd + SelfMul + PartialOrd + num_traits::Zero + ConstSqrt3 + SelfNeg + SelfMulAdd,
{
    type Param = P;

    fn new(location: P, std: P) -> Self {
        assert!(std > P::zero());
        Self {
            min: std.mul_add(-P::SQRT_3, location),
            max: std.mul_add(P::SQRT_3, location),
            _density: PhantomData,
        }
    }
}