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
use crate::Randomizable;

#[derive(Debug)]
pub struct Gamma {
    pub alpha: f64,
    pub tau: f64,
}

impl Gamma {
    pub fn new(alpha: f64, tau: f64) -> Self {
        Self { alpha, tau }
    }

    pub fn from_variance(average: f64, variance: f64) -> Self {
        let average_sqr = average * average;
        let sqrt = (average_sqr - variance).sqrt();
        Gamma::new(sqrt / (average - sqrt), average - sqrt)
    }

    pub fn from_sd(average: f64, sd: f64) -> Self {
        Self::from_variance(average, sd * sd)
    }

    pub fn probability(&self, t: f64) -> f64 {
        (-self.alpha - t / self.tau).exp() / self.tau
            * bessel::zero_order(2.0 * (self.alpha * t / self.tau).sqrt(), 10)
    }

    pub fn average(&self) -> f64 {
        self.tau * (self.alpha + 1.0)
    }

    pub fn variance(&self) -> f64 {
        self.tau * self.tau * (1.0 + 2.0 * self.alpha)
    }
}

impl Randomizable for Gamma {
    fn sample<D: rand::prelude::Distribution<f64>, R: rand::Rng + ?Sized>(
        distr: &D,
        rng: &mut R,
    ) -> Self {
        Self::new(
            Randomizable::sample(distr, rng),
            Randomizable::sample(distr, rng),
        )
    }
}

pub mod bessel {
    pub fn zero_order(x: f64, prec: i32) -> f64 {
        1f64 + (1..=prec)
            .map(|m| x.powi(2 * m) / 2f64.powi(2 * m) / factorial(m as f64).powi(2))
            .sum::<f64>()
    }

    fn factorial(n: f64) -> f64 {
        if n <= 1.0 {
            1.0
        } else {
            factorial(n - 1f64) * n
        }
    }
}