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
pub mod params;

pub use params::*;

use crate::{DependentJoint, Distribution, IndependentJoint, RandomVariable};
use crate::{DiscreteDistribution, DistributionError};
use rand::prelude::*;
use rand_distr::Geometric as RandGeometric;
use std::{ops::BitAnd, ops::Mul};

/// Geometric
#[derive(Clone, Debug)]
pub struct Geometric;

#[derive(thiserror::Error, Debug)]
pub enum GeometricError {
    #[error("'p' must be probability.")]
    PMustBeProbability,
}

impl Distribution for Geometric {
    type Value = u64;
    type Condition = GeometricParams;

    fn fk(&self, x: &Self::Value, theta: &Self::Condition) -> Result<f64, DistributionError> {
        let p = theta.p();

        Ok((1.0 - p).powi((x - 1) as i32) * p)
    }

    fn sample(
        &self,
        theta: &Self::Condition,
        rng: &mut dyn RngCore,
    ) -> Result<Self::Value, DistributionError> {
        let p = theta.p();

        let geometric = match RandGeometric::new(p) {
            Ok(v) => Ok(v),
            Err(e) => Err(DistributionError::Others(e.into())),
        }?;

        Ok(rng.sample(geometric))
    }
}

impl DiscreteDistribution for Geometric {}

impl<Rhs, TRhs> Mul<Rhs> for Geometric
where
    Rhs: Distribution<Value = TRhs, Condition = GeometricParams>,
    TRhs: RandomVariable,
{
    type Output = IndependentJoint<Self, Rhs, u64, TRhs, GeometricParams>;

    fn mul(self, rhs: Rhs) -> Self::Output {
        IndependentJoint::new(self, rhs)
    }
}

impl<Rhs, URhs> BitAnd<Rhs> for Geometric
where
    Rhs: Distribution<Value = GeometricParams, Condition = URhs>,
    URhs: RandomVariable,
{
    type Output = DependentJoint<Self, Rhs, u64, GeometricParams, URhs>;

    fn bitand(self, rhs: Rhs) -> Self::Output {
        DependentJoint::new(self, rhs)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}