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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use crate::distribution::Continuous;
use crate::function::gamma;
use crate::prec;
use crate::statistics::*;
use nalgebra::{Dim, Dyn, OMatrix, OVector};
use std::f64;
/// Implements the
/// [Dirichlet](https://en.wikipedia.org/wiki/Dirichlet_distribution)
/// distribution
///
/// # Examples
///
/// ```
/// use statrs::distribution::{Dirichlet, Continuous};
/// use statrs::statistics::Distribution;
/// use nalgebra::DVector;
/// use statrs::statistics::MeanN;
///
/// let n = Dirichlet::new(vec![1.0, 2.0, 3.0]).unwrap();
/// assert_eq!(n.mean().unwrap(), DVector::from_vec(vec![1.0 / 6.0, 1.0 / 3.0, 0.5]));
/// assert_eq!(n.pdf(&DVector::from_vec(vec![0.33333, 0.33333, 0.33333])), 2.222155556222205);
/// ```
#[derive(Clone, PartialEq, Debug)]
pub struct Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
alpha: OVector<f64, D>,
}
/// Represents the errors that can occur when creating a [`Dirichlet`].
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
#[non_exhaustive]
pub enum DirichletError {
/// Alpha contains less than two elements.
AlphaTooShort,
/// Alpha contains an element that is NaN, infinite, zero or less than zero.
AlphaHasInvalidElements,
}
impl std::fmt::Display for DirichletError {
#[cfg_attr(coverage_nightly, coverage(off))]
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
DirichletError::AlphaTooShort => write!(f, "Alpha contains less than two elements"),
DirichletError::AlphaHasInvalidElements => write!(
f,
"Alpha contains an element that is NaN, infinite, zero or less than zero"
),
}
}
}
impl std::error::Error for DirichletError {}
impl Dirichlet<Dyn> {
/// Constructs a new dirichlet distribution with the given
/// concentration parameters (alpha)
///
/// # Errors
///
/// Returns an error if any element `x` in alpha exist
/// such that `x < = 0.0` or `x` is `NaN`, or if the length of alpha is
/// less than 2
///
/// # Examples
///
/// ```
/// use statrs::distribution::Dirichlet;
/// use nalgebra::DVector;
///
/// let alpha_ok = vec![1.0, 2.0, 3.0];
/// let mut result = Dirichlet::new(alpha_ok);
/// assert!(result.is_ok());
///
/// let alpha_err = vec![0.0];
/// result = Dirichlet::new(alpha_err);
/// assert!(result.is_err());
/// ```
pub fn new(alpha: Vec<f64>) -> Result<Self, DirichletError> {
Self::new_from_nalgebra(alpha.into())
}
/// Constructs a new dirichlet distribution with the given
/// concentration parameter (alpha) repeated `n` times
///
/// # Errors
///
/// Returns an error if `alpha < = 0.0` or `alpha` is `NaN`,
/// or if `n < 2`
///
/// # Examples
///
/// ```
/// use statrs::distribution::Dirichlet;
///
/// let mut result = Dirichlet::new_with_param(1.0, 3);
/// assert!(result.is_ok());
///
/// result = Dirichlet::new_with_param(0.0, 1);
/// assert!(result.is_err());
/// ```
pub fn new_with_param(alpha: f64, n: usize) -> Result<Self, DirichletError> {
Self::new(vec![alpha; n])
}
}
impl<D> Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
/// Constructs a new distribution with the given vector for `alpha`
/// Does not clone the vector it takes ownership of
///
/// # Error
///
/// Returns an error if vector has length less than 2 or if any element
/// of alpha is NOT finite positive
pub fn new_from_nalgebra(alpha: OVector<f64, D>) -> Result<Self, DirichletError> {
if alpha.len() < 2 {
return Err(DirichletError::AlphaTooShort);
}
if alpha.iter().any(|&a_i| !a_i.is_finite() || a_i <= 0.0) {
return Err(DirichletError::AlphaHasInvalidElements);
}
Ok(Self { alpha })
}
/// Returns the concentration parameters of
/// the dirichlet distribution as a slice
///
/// # Examples
///
/// ```
/// use statrs::distribution::Dirichlet;
/// use nalgebra::DVector;
///
/// let n = Dirichlet::new(vec![1.0, 2.0, 3.0]).unwrap();
/// assert_eq!(n.alpha(), &DVector::from_vec(vec![1.0, 2.0, 3.0]));
/// ```
pub fn alpha(&self) -> &nalgebra::OVector<f64, D> {
&self.alpha
}
fn alpha_sum(&self) -> f64 {
self.alpha.sum()
}
/// Returns the entropy of the dirichlet distribution
///
/// # Formula
///
/// ```text
/// ln(B(α)) - (K - α_0)ψ(α_0) - Σ((α_i - 1)ψ(α_i))
/// ```
///
/// where
///
/// ```text
/// B(α) = Π(Γ(α_i)) / Γ(Σ(α_i))
/// ```
///
/// `α_0` is the sum of all concentration parameters,
/// `K` is the number of concentration parameters, `ψ` is the digamma
/// function, `α_i`
/// is the `i`th concentration parameter, and `Σ` is the sum from `1` to `K`
pub fn entropy(&self) -> Option<f64> {
let sum = self.alpha_sum();
let num = self.alpha.iter().fold(0.0, |acc, &x| {
acc + gamma::ln_gamma(x) + (x - 1.0) * gamma::digamma(x)
});
let entr =
-gamma::ln_gamma(sum) + (sum - self.alpha.len() as f64) * gamma::digamma(sum) - num;
Some(entr)
}
}
impl<D> std::fmt::Display for Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Dir({}, {})", self.alpha.len(), &self.alpha)
}
}
#[cfg(feature = "rand")]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
impl<D> ::rand::distributions::Distribution<OVector<f64, D>> for Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
fn sample<R: ::rand::Rng + ?Sized>(&self, rng: &mut R) -> OVector<f64, D> {
let mut sum = 0.0;
OVector::from_iterator_generic(
self.alpha.shape_generic().0,
nalgebra::Const::<1>,
self.alpha.iter().map(|&a| {
let sample = super::gamma::sample_unchecked(rng, a, 1.0);
sum += sample;
sample
}),
)
}
}
impl<D> MeanN<OVector<f64, D>> for Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
/// Returns the means of the dirichlet distribution
///
/// # Formula
///
/// ```text
/// α_i / α_0
/// ```
///
/// for the `i`th element where `α_i` is the `i`th concentration parameter
/// and `α_0` is the sum of all concentration parameters
fn mean(&self) -> Option<OVector<f64, D>> {
let sum = self.alpha_sum();
Some(self.alpha.map(|x| x / sum))
}
}
impl<D> VarianceN<OMatrix<f64, D, D>> for Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator:
nalgebra::allocator::Allocator<D> + nalgebra::allocator::Allocator<D, D>,
{
/// Returns the variances of the dirichlet distribution
///
/// # Formula
///
/// ```text
/// (α_i * (α_0 - α_i)) / (α_0^2 * (α_0 + 1))
/// ```
///
/// for the `i`th element where `α_i` is the `i`th concentration parameter
/// and `α_0` is the sum of all concentration parameters
fn variance(&self) -> Option<OMatrix<f64, D, D>> {
let sum = self.alpha_sum();
let normalizing = sum * sum * (sum + 1.0);
let mut cov = OMatrix::from_diagonal(&self.alpha.map(|x| x * (sum - x) / normalizing));
let mut offdiag = |x: usize, y: usize| {
let elt = -self.alpha[x] * self.alpha[y] / normalizing;
cov[(x, y)] = elt;
cov[(y, x)] = elt;
};
for i in 0..self.alpha.len() {
for j in 0..i {
offdiag(i, j);
}
}
Some(cov)
}
}
impl<D> Continuous<&OVector<f64, D>, f64> for Dirichlet<D>
where
D: Dim,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>
+ nalgebra::allocator::Allocator<D, D>
+ nalgebra::allocator::Allocator<nalgebra::Const<1>, D>,
{
/// Calculates the probabiliy density function for the dirichlet
/// distribution
/// with given `x`'s corresponding to the concentration parameters for this
/// distribution
///
/// # Panics
///
/// If any element in `x` is not in `(0, 1)`, the elements in `x` do not
/// sum to
/// `1` with a tolerance of `1e-4`, or if `x` is not the same length as
/// the vector of
/// concentration parameters for this distribution
///
/// # Formula
///
/// ```text
/// (1 / B(α)) * Π(x_i^(α_i - 1))
/// ```
///
/// where
///
/// ```text
/// B(α) = Π(Γ(α_i)) / Γ(Σ(α_i))
/// ```
///
/// `α` is the vector of concentration parameters, `α_i` is the `i`th
/// concentration parameter, `x_i` is the `i`th argument corresponding to
/// the `i`th concentration parameter, `Γ` is the gamma function,
/// `Π` is the product from `1` to `K`, `Σ` is the sum from `1` to `K`,
/// and `K` is the number of concentration parameters
fn pdf(&self, x: &OVector<f64, D>) -> f64 {
self.ln_pdf(x).exp()
}
/// Calculates the log probabiliy density function for the dirichlet
/// distribution
/// with given `x`'s corresponding to the concentration parameters for this
/// distribution
///
/// # Panics
///
/// If any element in `x` is not in `(0, 1)`, the elements in `x` do not
/// sum to
/// `1` with a tolerance of `1e-4`, or if `x` is not the same length as
/// the vector of
/// concentration parameters for this distribution
///
/// # Formula
///
/// ```text
/// ln((1 / B(α)) * Π(x_i^(α_i - 1)))
/// ```
///
/// where
///
/// ```text
/// B(α) = Π(Γ(α_i)) / Γ(Σ(α_i))
/// ```
///
/// `α` is the vector of concentration parameters, `α_i` is the `i`th
/// concentration parameter, `x_i` is the `i`th argument corresponding to
/// the `i`th concentration parameter, `Γ` is the gamma function,
/// `Π` is the product from `1` to `K`, `Σ` is the sum from `1` to `K`,
/// and `K` is the number of concentration parameters
fn ln_pdf(&self, x: &OVector<f64, D>) -> f64 {
if self.alpha.len() != x.len() {
panic!("Arguments must have correct dimensions.");
}
let mut term = 0.0;
let mut sum_x = 0.0;
let mut sum_alpha = 0.0;
for (&x_i, &alpha_i) in x.iter().zip(self.alpha.iter()) {
assert!(0.0 < x_i && x_i < 1.0, "Arguments must be in (0, 1)");
term += (alpha_i - 1.0) * x_i.ln() - gamma::ln_gamma(alpha_i);
sum_x += x_i;
sum_alpha += alpha_i;
}
assert!(
prec::almost_eq(sum_x, 1.0, 1e-4),
"Arguments must sum up to 1"
);
term + gamma::ln_gamma(sum_alpha)
}
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use super::*;
use std::fmt::{Debug, Display};
use nalgebra::{dmatrix, dvector, vector, DimMin, OVector};
fn try_create<D>(alpha: OVector<f64, D>) -> Dirichlet<D>
where
D: DimMin<D, Output = D>,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
let mvn = Dirichlet::new_from_nalgebra(alpha);
assert!(mvn.is_ok());
mvn.unwrap()
}
fn bad_create_case<D>(alpha: OVector<f64, D>)
where
D: DimMin<D, Output = D>,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
let dd = Dirichlet::new_from_nalgebra(alpha);
assert!(dd.is_err());
}
fn test_almost<F, T, D>(alpha: OVector<f64, D>, expected: T, acc: f64, eval: F)
where
T: Debug + Display + approx::RelativeEq<Epsilon = f64>,
F: FnOnce(Dirichlet<D>) -> T,
D: DimMin<D, Output = D>,
nalgebra::DefaultAllocator: nalgebra::allocator::Allocator<D>,
{
let dd = try_create(alpha);
let x = eval(dd);
assert_relative_eq!(expected, x, epsilon = acc);
}
#[test]
fn test_create() {
try_create(vector![1.0, 2.0]);
try_create(vector![1.0, 2.0, 3.0, 4.0, 5.0]);
assert!(Dirichlet::new(vec![1.0, 2.0, 3.0, 4.0, 5.0]).is_ok());
// try_create(vector![0.001, f64::INFINITY, 3756.0]); // moved to bad case as this is degenerate
}
#[test]
fn test_bad_create() {
bad_create_case(vector![1.0, f64::NAN]);
bad_create_case(vector![1.0, 0.0]);
bad_create_case(vector![1.0, f64::INFINITY]);
bad_create_case(vector![-1.0, 2.0]);
bad_create_case(vector![1.0]);
bad_create_case(vector![1.0, 2.0, 0.0, 4.0, 5.0]);
bad_create_case(vector![1.0, f64::NAN, 3.0, 4.0, 5.0]);
bad_create_case(vector![0.0, 0.0, 0.0]);
bad_create_case(vector![0.001, f64::INFINITY, 3756.0]); // moved to bad case as this is degenerate
}
#[test]
fn test_mean() {
let mean = |dd: Dirichlet<_>| dd.mean().unwrap();
test_almost(vec![0.5; 5].into(), vec![1.0 / 5.0; 5].into(), 1e-15, mean);
test_almost(
dvector![0.1, 0.2, 0.3, 0.4],
dvector![0.1, 0.2, 0.3, 0.4],
1e-15,
mean,
);
test_almost(
dvector![1.0, 2.0, 3.0, 4.0],
dvector![0.1, 0.2, 0.3, 0.4],
1e-15,
mean,
);
}
#[test]
fn test_variance() {
let variance = |dd: Dirichlet<_>| dd.variance().unwrap();
test_almost(
dvector![1.0, 2.0],
dmatrix![0.055555555555555, -0.055555555555555;
-0.055555555555555, 0.055555555555555;
],
1e-15,
variance,
);
test_almost(
dvector![0.1, 0.2, 0.3, 0.4],
dmatrix![0.045, -0.010, -0.015, -0.020;
-0.010, 0.080, -0.030, -0.040;
-0.015, -0.030, 0.105, -0.060;
-0.020, -0.040, -0.060, 0.120;
],
1e-15,
variance,
);
}
// #[test]
// fn test_std_dev() {
// let alpha = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
// let sum = alpha.iter().fold(0.0, |acc, x| acc + x);
// let n = Dirichlet::new(&alpha).unwrap();
// let res = n.std_dev();
// for i in 1..11 {
// let f = i as f64;
// assert_almost_eq!(res[i-1], (f * (sum - f) / (sum * sum * (sum + 1.0))).sqrt(), 1e-15);
// }
// }
#[test]
fn test_entropy() {
let entropy = |x: Dirichlet<_>| x.entropy().unwrap();
test_almost(
vector![0.1, 0.3, 0.5, 0.8],
-17.46469081094079,
1e-30,
entropy,
);
test_almost(
vector![0.1, 0.2, 0.3, 0.4],
-21.53881433791513,
1e-30,
entropy,
);
}
#[test]
fn test_pdf() {
let pdf = |arg| move |x: Dirichlet<_>| x.pdf(&arg);
test_almost(
vector![0.1, 0.3, 0.5, 0.8],
18.77225681167061,
1e-12,
pdf([0.01, 0.03, 0.5, 0.46].into()),
);
test_almost(
vector![0.1, 0.3, 0.5, 0.8],
0.8314656481199253,
1e-14,
pdf([0.1, 0.2, 0.3, 0.4].into()),
);
}
#[test]
fn test_ln_pdf() {
let ln_pdf = |arg| move |x: Dirichlet<_>| x.ln_pdf(&arg);
test_almost(
vector![0.1, 0.3, 0.5, 0.8],
18.77225681167061_f64.ln(),
1e-12,
ln_pdf([0.01, 0.03, 0.5, 0.46].into()),
);
test_almost(
vector![0.1, 0.3, 0.5, 0.8],
0.8314656481199253_f64.ln(),
1e-14,
ln_pdf([0.1, 0.2, 0.3, 0.4].into()),
);
}
#[test]
#[should_panic]
fn test_pdf_bad_input_length() {
let n = try_create(dvector![0.1, 0.3, 0.5, 0.8]);
n.pdf(&dvector![0.5]);
}
#[test]
#[should_panic]
fn test_pdf_bad_input_range() {
let n = try_create(vector![0.1, 0.3, 0.5, 0.8]);
n.pdf(&vector![1.5, 0.0, 0.0, 0.0]);
}
#[test]
#[should_panic]
fn test_pdf_bad_input_sum() {
let n = try_create(vector![0.1, 0.3, 0.5, 0.8]);
n.pdf(&vector![0.5, 0.25, 0.8, 0.9]);
}
#[test]
#[should_panic]
fn test_ln_pdf_bad_input_length() {
let n = try_create(dvector![0.1, 0.3, 0.5, 0.8]);
n.ln_pdf(&dvector![0.5]);
}
#[test]
#[should_panic]
fn test_ln_pdf_bad_input_range() {
let n = try_create(vector![0.1, 0.3, 0.5, 0.8]);
n.ln_pdf(&vector![1.5, 0.0, 0.0, 0.0]);
}
#[test]
#[should_panic]
fn test_ln_pdf_bad_input_sum() {
let n = try_create(vector![0.1, 0.3, 0.5, 0.8]);
n.ln_pdf(&vector![0.5, 0.25, 0.8, 0.9]);
}
#[test]
fn test_error_is_sync_send() {
fn assert_sync_send<T: Sync + Send>() {}
assert_sync_send::<DirichletError>();
}
}