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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use crate::distribution::{Discrete, Univariate};
use rand::distributions::Distribution;
use rand::distributions::OpenClosed01;
use rand::Rng;
use crate::statistics::*;
use std::{f64, u64};
use crate::{Result, StatsError};

/// Implements the
/// [Geometric](https://en.wikipedia.org/wiki/Geometric_distribution)
/// distribution
///
/// # Examples
///
/// ```
/// use statrs::distribution::{Geometric, Discrete};
/// use statrs::statistics::Mean;
///
/// let n = Geometric::new(0.3).unwrap();
/// assert_eq!(n.mean(), 1.0 / 0.3);
/// assert_eq!(n.pmf(1), 0.3);
/// assert_eq!(n.pmf(2), 0.21);
/// ```
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Geometric {
    p: f64,
}

impl Geometric {
    /// Constructs a new shifted geometric distribution with a probability
    /// of `p`
    ///
    /// # Errors
    ///
    /// Returns an error if `p` is not in `(0, 1]`
    ///
    /// # Examples
    ///
    /// ```
    /// use statrs::distribution::Geometric;
    ///
    /// let mut result = Geometric::new(0.5);
    /// assert!(result.is_ok());
    ///
    /// result = Geometric::new(0.0);
    /// assert!(result.is_err());
    /// ```
    pub fn new(p: f64) -> Result<Geometric> {
        if p <= 0.0 || p > 1.0 || p.is_nan() {
            Err(StatsError::BadParams)
        } else {
            Ok(Geometric { p: p })
        }
    }

    /// Returns the probability `p` of the geometric
    /// distribution
    ///
    /// # Examples
    ///
    /// ```
    /// use statrs::distribution::Geometric;
    ///
    /// let n = Geometric::new(0.5).unwrap();
    /// assert_eq!(n.p(), 0.5);
    /// ```
    pub fn p(&self) -> f64 {
        self.p
    }
}

impl Distribution<f64> for Geometric {
    fn sample<R: Rng + ?Sized>(&self, r: &mut R) -> f64 {
        if self.p == 1.0 {
            1.0
        } else {
            let x: f64 = r.sample(OpenClosed01);
            x.log(1.0 - self.p).ceil()
        }
    }
}

impl Univariate<u64, f64> for Geometric {
    /// Calculates the cumulative distribution function for the geometric
    /// distribution at `x`
    ///
    /// # Formula
    ///
    /// ```ignore
    /// 1 - (1 - p) ^ (x + 1)
    /// ```
    fn cdf(&self, x: f64) -> f64 {
        if x < 1.0 {
            0.0
        } else if x == f64::INFINITY {
            1.0
        } else {
            1.0 - (1.0 - self.p).powf(x.floor())
        }
    }
}

impl Min<u64> for Geometric {
    /// Returns the minimum value in the domain of the
    /// geometric distribution representable by a 64-bit
    /// integer
    ///
    /// # Formula
    ///
    /// ```ignore
    /// 1
    /// ```
    fn min(&self) -> u64 {
        1
    }
}

impl Max<u64> for Geometric {
    /// Returns the maximum value in the domain of the
    /// geometric distribution representable by a 64-bit
    /// integer
    ///
    /// # Formula
    ///
    /// ```ignore
    /// 2^63 - 1
    /// ```
    fn max(&self) -> u64 {
        u64::MAX
    }
}

impl Mean<f64> for Geometric {
    /// Returns the mean of the geometric distribution
    ///
    /// # Formula
    ///
    /// ```ignore
    /// 1 / p
    /// ```
    fn mean(&self) -> f64 {
        1.0 / self.p
    }
}

impl Variance<f64> for Geometric {
    /// Returns the standard deviation of the geometric distribution
    ///
    /// # Formula
    ///
    /// ```ignore
    /// (1 - p) / p^2
    /// ```
    fn variance(&self) -> f64 {
        (1.0 - self.p) / (self.p * self.p)
    }

    /// Returns the standard deviation of the geometric distribution
    ///
    /// # Remarks
    ///
    /// Returns `NAN` if `p` is `1`
    ///
    /// # Formula
    ///
    /// ```ignore
    /// sqrt(1 - p) / p
    /// ```
    fn std_dev(&self) -> f64 {
        (1.0 - self.p).sqrt() / self.p
    }
}

impl Entropy<f64> for Geometric {
    /// Returns the entropy of the geometric distribution
    ///
    /// # Formula
    ///
    /// ```ignore
    /// (-(1 - p) * log_2(1 - p) - p * log_2(p)) / p
    /// ```
    fn entropy(&self) -> f64 {
        (-self.p * self.p.log(2.0) - (1.0 - self.p) * (1.0 - self.p).log(2.0)) / self.p
    }
}

impl Skewness<f64> for Geometric {
    /// Returns the skewness of the geometric distribution
    ///
    /// # Formula
    ///
    /// ```ignore
    /// (2 - p) / sqrt(1 - p)
    /// ```
    fn skewness(&self) -> f64 {
        (2.0 - self.p) / (1.0 - self.p).sqrt()
    }
}

impl Mode<u64> for Geometric {
    /// Returns the mode of the geometric distribution
    ///
    /// # Formula
    ///
    /// ```ignore
    /// 1
    /// ```
    fn mode(&self) -> u64 {
        1
    }
}

impl Median<f64> for Geometric {
    /// Returns the median of the geometric distribution
    ///
    /// # Remarks
    ///
    /// Returns `1` if `p` is `1`
    ///
    /// # Formula
    ///
    /// ```ignore
    /// ceil(-1 / log_2(1 - p))
    /// ```
    fn median(&self) -> f64 {
        if self.p == 1.0 {
            1.0
        } else {
            (-f64::consts::LN_2 / (1.0 - self.p).ln()).ceil()
        }
    }
}

impl Discrete<u64, f64> for Geometric {
    /// Calculates the probability mass function for the geometric
    /// distribution at `x`
    ///
    /// # Formula
    ///
    /// ```ignore
    /// (1 - p)^(x - 1) * p
    /// ```
    fn pmf(&self, x: u64) -> f64 {
        if x == 0 {
            0.0
        } else {
            (1.0 - self.p).powi(x as i32 - 1) * self.p
        }
    }

    /// Calculates the log probability mass function for the geometric
    /// distribution at `x`
    ///
    /// # Formula
    ///
    /// ```ignore
    /// ln((1 - p)^(x - 1) * p)
    /// ```
    fn ln_pmf(&self, x: u64) -> f64 {
        if x == 0 {
            f64::NEG_INFINITY
        } else if self.p == 1.0 && x == 1 {
            0.0
        } else if self.p == 1.0 {
            f64::NEG_INFINITY
        } else {
            ((x - 1) as f64 * (1.0 - self.p).ln()) + self.p.ln()
        }
    }
}

#[cfg_attr(rustfmt, rustfmt_skip)]
#[cfg(test)]
mod test {
    use std::fmt::Debug;
    use std::{u64, f64};
    use crate::statistics::*;
    use crate::distribution::{Univariate, Discrete, Geometric};
    use crate::distribution::internal::*;

    fn try_create(p: f64) -> Geometric {
        let n = Geometric::new(p);
        assert!(n.is_ok());
        n.unwrap()
    }

    fn create_case(p: f64) {
        let n = try_create(p);
        assert_eq!(p, n.p());
    }

    fn bad_create_case(p: f64) {
        let n = Geometric::new(p);
        assert!(n.is_err());
    }

    fn get_value<T, F>(p: f64, eval: F) -> T
        where T: PartialEq + Debug,
              F: Fn(Geometric) -> T
    {
        let n = try_create(p);
        eval(n)
    }

    fn test_case<T, F>(p: f64, expected: T, eval: F)
        where T: PartialEq + Debug,
              F: Fn(Geometric) -> T
    {
        let x = get_value(p, eval);
        assert_eq!(expected, x);
    }

    fn test_almost<F>(p: f64, expected: f64, acc: f64, eval: F)
        where F: Fn(Geometric) -> f64
    {
        let x = get_value(p, eval);
        assert_almost_eq!(expected, x, acc);
    }

    fn test_is_nan<F>(p: f64, eval: F)
        where F: Fn(Geometric) -> f64
    {
        let x = get_value(p, eval);
        assert!(x.is_nan());
    }

    #[test]
    fn test_create() {
        create_case(0.3);
        create_case(1.0);
    }

    #[test]
    fn test_bad_create() {
        bad_create_case(f64::NAN);
        bad_create_case(0.0);
        bad_create_case(-1.0);
        bad_create_case(2.0);
    }

    #[test]
    fn test_mean() {
        test_case(0.3, 1.0 / 0.3, |x| x.mean());
        test_case(1.0, 1.0, |x| x.mean());
    }

    #[test]
    fn test_variance() {
        test_case(0.3, 0.7 / (0.3 * 0.3), |x| x.variance());
        test_case(1.0, 0.0, |x| x.variance());
    }

    #[test]
    fn test_std_dev() {
        test_case(0.3, 0.7f64.sqrt() / 0.3, |x| x.std_dev());
        test_case(1.0, 0.0, |x| x.std_dev());
    }

    #[test]
    fn test_entropy() {
        test_almost(0.3, 2.937636330768973333333, 1e-14, |x| x.entropy());
        test_is_nan(1.0, |x| x.entropy());
    }

    #[test]
    fn test_skewness() {
        test_almost(0.3, 2.031888635868469187947, 1e-15, |x| x.skewness());
        test_case(1.0, f64::INFINITY, |x| x.skewness());
    }

    #[test]
    fn test_median() {
        test_case(0.0001, 6932.0, |x| x.median());
        test_case(0.1, 7.0, |x| x.median());
        test_case(0.3, 2.0, |x| x.median());
        test_case(0.9, 1.0, |x| x.median());
        test_case(1.0, 1.0, |x| x.median());
    }

    #[test]
    fn test_mode() {
        test_case(0.3, 1, |x| x.mode());
        test_case(1.0, 1, |x| x.mode());
    }

    #[test]
    fn test_min_max() {
        test_case(0.3, 1, |x| x.min());
        test_case(0.3, u64::MAX, |x| x.max());
    }

    #[test]
    fn test_pmf() {
        test_case(0.3, 0.3, |x| x.pmf(1));
        test_case(0.3, 0.21, |x| x.pmf(2));
        test_case(1.0, 1.0, |x| x.pmf(1));
        test_case(1.0, 0.0, |x| x.pmf(2));
        test_almost(0.5, 0.5, 1e-10, |x| x.pmf(1));
        test_almost(0.5, 0.25, 1e-10, |x| x.pmf(2));
    }

    #[test]
    fn test_pmf_lower_bound() {
        test_case(0.3, 0.0, |x| x.pmf(0));
    }

    #[test]
    fn test_ln_pmf() {
        test_almost(0.3, -1.203972804325935992623, 1e-15, |x| x.ln_pmf(1));
        test_almost(0.3, -1.560647748264668371535, 1e-15, |x| x.ln_pmf(2));
        test_case(1.0, 0.0, |x| x.ln_pmf(1));
        test_case(1.0, f64::NEG_INFINITY, |x| x.ln_pmf(2));
    }

    #[test]
    fn test_ln_pmf_lower_bound() {
        test_case(0.3, f64::NEG_INFINITY, |x| x.ln_pmf(0));
    }

    #[test]
    fn test_cdf() {
        test_case(1.0, 1.0, |x| x.cdf(1.0));
        test_case(1.0, 1.0, |x| x.cdf(2.0));
        test_almost(0.5, 0.5, 1e-10, |x| x.cdf(1.0));
        test_almost(0.5, 0.75, 1e-10, |x| x.cdf(2.0));
    }

    #[test]
    fn test_cdf_lower_bound() {
        test_case(0.3, 0.0, |x| x.cdf(0.0));
    }

    #[test]
    fn test_discrete() {
        test::check_discrete_distribution(&try_create(0.3), 100);
        test::check_discrete_distribution(&try_create(0.6), 100);
        test::check_discrete_distribution(&try_create(1.0), 1);
    }
}