1use crate::{Distribution, OpenClosed01};
12use core::fmt;
13use num_traits::Float;
14use rand::Rng;
15
16#[derive(Clone, Copy, Debug, PartialEq)]
45#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
46pub struct Gumbel<F>
47where
48 F: Float,
49 OpenClosed01: Distribution<F>,
50{
51 location: F,
52 scale: F,
53}
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum Error {
58 LocationNotFinite,
60 ScaleNotPositive,
62}
63
64impl fmt::Display for Error {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 f.write_str(match self {
67 Error::ScaleNotPositive => "scale is not positive and finite in Gumbel distribution",
68 Error::LocationNotFinite => "location is not finite in Gumbel distribution",
69 })
70 }
71}
72
73#[cfg(feature = "std")]
74impl std::error::Error for Error {}
75
76impl<F> Gumbel<F>
77where
78 F: Float,
79 OpenClosed01: Distribution<F>,
80{
81 pub fn new(location: F, scale: F) -> Result<Gumbel<F>, Error> {
83 if scale <= F::zero() || scale.is_infinite() || scale.is_nan() {
84 return Err(Error::ScaleNotPositive);
85 }
86 if location.is_infinite() || location.is_nan() {
87 return Err(Error::LocationNotFinite);
88 }
89 Ok(Gumbel { location, scale })
90 }
91}
92
93impl<F> Distribution<F> for Gumbel<F>
94where
95 F: Float,
96 OpenClosed01: Distribution<F>,
97{
98 fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> F {
99 let x: F = rng.sample(OpenClosed01);
100 self.location - self.scale * (-x.ln()).ln()
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 #[should_panic]
110 fn test_zero_scale() {
111 Gumbel::new(0.0, 0.0).unwrap();
112 }
113
114 #[test]
115 #[should_panic]
116 fn test_infinite_scale() {
117 Gumbel::new(0.0, f64::INFINITY).unwrap();
118 }
119
120 #[test]
121 #[should_panic]
122 fn test_nan_scale() {
123 Gumbel::new(0.0, f64::NAN).unwrap();
124 }
125
126 #[test]
127 #[should_panic]
128 fn test_infinite_location() {
129 Gumbel::new(f64::INFINITY, 1.0).unwrap();
130 }
131
132 #[test]
133 #[should_panic]
134 fn test_nan_location() {
135 Gumbel::new(f64::NAN, 1.0).unwrap();
136 }
137
138 #[test]
139 fn test_sample_against_cdf() {
140 fn neg_log_log(x: f64) -> f64 {
141 -(-x.ln()).ln()
142 }
143 let location = 0.0;
144 let scale = 1.0;
145 let iterations = 100_000;
146 let increment = 1.0 / iterations as f64;
147 let probabilities = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9];
148 let mut quantiles = [0.0; 9];
149 for (i, p) in probabilities.iter().enumerate() {
150 quantiles[i] = neg_log_log(*p);
151 }
152 let mut proportions = [0.0; 9];
153 let d = Gumbel::new(location, scale).unwrap();
154 let mut rng = crate::test::rng(1);
155 for _ in 0..iterations {
156 let replicate = d.sample(&mut rng);
157 for (i, q) in quantiles.iter().enumerate() {
158 if replicate < *q {
159 proportions[i] += increment;
160 }
161 }
162 }
163 assert!(proportions
164 .iter()
165 .zip(&probabilities)
166 .all(|(p_hat, p)| (p_hat - p).abs() < 0.003))
167 }
168
169 #[test]
170 fn gumbel_distributions_can_be_compared() {
171 assert_eq!(Gumbel::new(1.0, 2.0), Gumbel::new(1.0, 2.0));
172 }
173}