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
134
135
136
137
138
139
140
141
use crate::{ProbabilityDistribution, StrError};
use rand::Rng;
use rand_distr::{Distribution, Uniform};

/// Defines the Uniform / Type II Extreme Value Distribution (largest value)
pub struct DistributionUniform {
    xmin: f64, // min x value
    xmax: f64, // max x value

    sampler: Uniform<f64>, // sampler
}

impl DistributionUniform {
    /// Creates a new Uniform distribution
    ///
    /// # Input
    ///
    /// * `xmin` -- min x value
    /// * `xmax` -- max x value
    pub fn new(xmin: f64, xmax: f64) -> Result<Self, StrError> {
        if xmax < xmin {
            return Err("invalid parameters");
        }
        Ok(DistributionUniform {
            xmin,
            xmax,
            sampler: Uniform::new(xmin, xmax),
        })
    }
}

impl ProbabilityDistribution for DistributionUniform {
    /// Implements the Probability Density Function (CDF)
    fn pdf(&self, x: f64) -> f64 {
        if x < self.xmin {
            return 0.0;
        }
        if x > self.xmax {
            return 0.0;
        }
        1.0 / (self.xmax - self.xmin)
    }

    /// Implements the Cumulative Density Function (CDF)
    fn cdf(&self, x: f64) -> f64 {
        if x < self.xmin {
            return 0.0;
        }
        if x > self.xmax {
            return 1.0;
        }
        (x - self.xmin) / (self.xmax - self.xmin)
    }

    /// Returns the Mean
    fn mean(&self) -> f64 {
        (self.xmin + self.xmax) / 2.0
    }

    /// Returns the Variance
    fn variance(&self) -> f64 {
        (self.xmax - self.xmin) * (self.xmax - self.xmin) / 12.0
    }

    /// Generates a pseudo-random number belonging to this probability distribution
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
        self.sampler.sample(rng)
    }
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use crate::{DistributionUniform, ProbabilityDistribution, StrError};
    use rand::prelude::StdRng;
    use rand::SeedableRng;
    use russell_chk::assert_approx_eq;

    // Data from the following R-code (run with Rscript uniform.R):
    /*
    a <- 1.5 # xmin
    b <- 2.5 # xmax
    X <- seq(0.5, 3.0, 0.5)
    Y <- matrix(ncol=5)
    first <- TRUE
    pdf <- dunif(X, a, b)
    cdf <- punif(X, a, b)
    for (i in 1:length(X)) {
        if (first) {
            Y <- rbind(c(X[i], a, b, pdf[i], cdf[i]))
            first <- FALSE
        } else {
            Y <- rbind(Y, c(X[i], a, b, pdf[i], cdf[i]))
        }
    }
    write.table(format(Y, digits=15), "/tmp/uniform.dat", row.names=FALSE, col.names=c("x","xmin","xmax","pdf","cdf"), quote=FALSE)
    print("file </tmp/uniform.dat> written")
    */

    #[test]
    fn uniform_works() -> Result<(), StrError> {
        #[rustfmt::skip]
        // x, xmin, xmax, pdf, cdf
        let data = [
            [0.5, 1.5, 2.5, 0.0, 0.0],
            [1.0, 1.5, 2.5, 0.0, 0.0],
            [1.5, 1.5, 2.5, 1.0, 0.0],
            [2.0, 1.5, 2.5, 1.0, 0.5],
            [2.5, 1.5, 2.5, 1.0, 1.0],
            [3.0, 1.5, 2.5, 0.0, 1.0],
        ];
        for row in data {
            let [x, xmin, xmax, pdf, cdf] = row;
            let d = DistributionUniform::new(xmin, xmax)?;
            assert_approx_eq!(d.pdf(x), pdf, 1e-14);
            assert_approx_eq!(d.cdf(x), cdf, 1e-14);
        }
        Ok(())
    }

    #[test]
    fn mean_and_variance_work() -> Result<(), StrError> {
        let d = DistributionUniform::new(1.0, 3.0)?;
        assert_approx_eq!(d.mean(), 2.0, 1e-14);
        assert_approx_eq!(d.variance(), 1.0 / 3.0, 1e-14);
        Ok(())
    }

    #[test]
    fn sample_works() -> Result<(), StrError> {
        let mut rng = StdRng::seed_from_u64(1234);
        let dist_x = DistributionUniform::new(0.0, 2.0)?;
        let dist_y = DistributionUniform::new(0.0, 1.0)?;
        let x = dist_x.sample(&mut rng);
        let y = dist_y.sample(&mut rng);
        assert_approx_eq!(x, 0.23691851694908816, 1e-15);
        assert_approx_eq!(y, 0.16964948689475423, 1e-15);
        Ok(())
    }
}