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
// Copyright 2022 The Ferric AI Project Developers
use rand_distr::Dirichlet as Dirichlet2;
use rand_distr::Distribution as Distribution2;
use crate::distributions::Distribution;
use rand::Rng;
/// Dirichlet distribution over the probability simplex $\Delta^{K-1}$.
///
/// A sample $\mathbf{x} = (x_1, \ldots, x_K)$ satisfies $x_i > 0$ and
/// $\sum_{i=1}^K x_i = 1$. The PDF is
///
/// $$p(\mathbf{x} \mid \boldsymbol\alpha) =
/// \frac{\Gamma(\alpha_0)}{\prod_{i=1}^K \Gamma(\alpha_i)}
/// \prod_{i=1}^K x_i^{\alpha_i - 1},
/// \quad \alpha_0 = \textstyle\sum_i \alpha_i$$
///
/// where $\alpha_i > 0$ are the concentration parameters. When all
/// $\alpha_i = 1$ the distribution is uniform over the simplex.
///
/// The Dirichlet is conjugate to the Multinomial and is commonly used as
/// a prior over categorical probabilities.
///
/// See [Dirichlet distribution](https://en.wikipedia.org/wiki/Dirichlet_distribution)
/// on Wikipedia for further details.
///
/// # Examples
///
/// ```
/// use ferric::distributions::{Dirichlet, Distribution};
/// use rand::thread_rng;
///
/// let dist = Dirichlet::new(vec![1.0, 1.0, 1.0]).unwrap();
/// let theta: Vec<f64> = dist.sample(&mut thread_rng());
/// println!("theta = {:?}", theta);
/// ```
pub struct Dirichlet {
alphas: Vec<f64>,
}
impl Dirichlet {
/// Construct a Dirichlet distribution with concentration vector `alphas`
/// ($\boldsymbol\alpha$).
///
/// # Errors
///
/// Returns `Err` if fewer than two concentrations are given or any
/// concentration is not strictly positive.
pub fn new(alphas: Vec<f64>) -> Result<Dirichlet, String> {
if alphas.len() < 2 {
return Err(
"Dirichlet: concentration vector must contain at least 2 elements".to_string(),
);
}
for &a in &alphas {
if a <= 0.0 {
return Err(format!(
"Dirichlet: all concentrations must be > 0, got {}",
a
));
}
}
Ok(Dirichlet { alphas })
}
}
impl<R: Rng + ?Sized> Distribution<R> for Dirichlet {
type Domain = Vec<f64>;
fn sample(&self, rng: &mut R) -> Vec<f64> {
Dirichlet2::new(&self.alphas).unwrap().sample(rng)
}
/// Returns
/// $\ln\Gamma(\alpha_0) - \sum_i \ln\Gamma(\alpha_i)
/// + \sum_i (\alpha_i - 1)\ln x_i$
/// where $\alpha_0 = \sum_i \alpha_i$.
///
/// Returns $-\infty$ if `x` has the wrong length, any component is
/// outside $(0, 1)$, or the components do not sum to $1 \pm 10^{-9}$.
fn log_prob(&self, x: &Vec<f64>) -> f64 {
if x.len() != self.alphas.len() {
return f64::NEG_INFINITY;
}
for &xi in x {
if xi <= 0.0 || xi >= 1.0 {
return f64::NEG_INFINITY;
}
}
if (x.iter().sum::<f64>() - 1.0).abs() > 1e-9 {
return f64::NEG_INFINITY;
}
let sum_alpha: f64 = self.alphas.iter().sum();
let log_z: f64 =
libm::lgamma(sum_alpha) - self.alphas.iter().map(|&a| libm::lgamma(a)).sum::<f64>();
let log_kernel: f64 = self
.alphas
.iter()
.zip(x.iter())
.map(|(&a, &xi)| (a - 1.0) * xi.ln())
.sum();
log_z + log_kernel
}
fn is_discrete(&self) -> bool {
false
}
}
impl std::fmt::Display for Dirichlet {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Dirichlet {{ alphas = {:?} }}", self.alphas)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::ThreadRng;
use rand::thread_rng;
#[test]
fn dirichlet_sample() {
let mut rng = thread_rng();
let alphas = vec![2.0f64, 3.0, 5.0];
let dist = Dirichlet::new(alphas.clone()).unwrap();
println!("dist = {}", dist);
let trials = 10000;
let mut sums = vec![0.0f64; 3];
for _ in 0..trials {
let x = dist.sample(&mut rng);
// each sample must lie in the simplex
assert!(x.iter().all(|&xi| xi > 0.0 && xi < 1.0));
assert!((x.iter().sum::<f64>() - 1.0).abs() < 1e-10);
for (s, xi) in sums.iter_mut().zip(x.iter()) {
*s += xi;
}
}
// Check empirical mean = alpha_i / sum(alpha)
let sum_alpha: f64 = alphas.iter().sum();
for (i, &alpha_i) in alphas.iter().enumerate() {
let empirical_mean = sums[i] / (trials as f64);
let expected_mean = alpha_i / sum_alpha;
assert!(
(empirical_mean - expected_mean).abs() < 0.02,
"component {} empirical mean {} != expected {}",
i,
empirical_mean,
expected_mean
);
}
}
#[test]
fn dirichlet_log_prob() {
// Dirichlet(1,1,1): log_prob at uniform point [1/3, 1/3, 1/3]
// log p = lgamma(3) - 3*lgamma(1) + 0 = ln(2) - 0 = ln(2)
let dist = Dirichlet::new(vec![1.0, 1.0, 1.0]).unwrap();
let x = vec![1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0];
let lp = <Dirichlet as Distribution<ThreadRng>>::log_prob(&dist, &x);
// lgamma(3)=ln(2); 3*lgamma(1)=0; kernel = 0*(-ln3)*3 = 0
assert!((lp - 2.0f64.ln()).abs() < 1e-9);
// wrong length
let lp_short = <Dirichlet as Distribution<ThreadRng>>::log_prob(&dist, &vec![0.5, 0.5]);
assert_eq!(lp_short, f64::NEG_INFINITY);
// component out of (0,1)
let lp_bad = <Dirichlet as Distribution<ThreadRng>>::log_prob(&dist, &vec![0.0, 0.5, 0.5]);
assert_eq!(lp_bad, f64::NEG_INFINITY);
// sum != 1
let lp_sum = <Dirichlet as Distribution<ThreadRng>>::log_prob(&dist, &vec![0.4, 0.4, 0.4]);
assert_eq!(lp_sum, f64::NEG_INFINITY);
assert!(!<Dirichlet as Distribution<ThreadRng>>::is_discrete(&dist));
}
#[test]
#[should_panic]
fn dirichlet_too_short() {
Dirichlet::new(vec![1.0]).unwrap();
}
#[test]
#[should_panic]
fn dirichlet_zero_concentration() {
Dirichlet::new(vec![1.0, 0.0, 1.0]).unwrap();
}
}