Skip to main content

lib_jsl_statistics/
multivariate.rs

1//! Multivariate distributions (SciPy's `multivariate_normal`, `multivariate_t`, `dirichlet`,
2//! `wishart`, `invwishart` and `multinomial`): densities, moments, entropies and sampling.
3//! Matrices are `Vec<Vec<f64>>` of rows.
4//!
5//! See the book entry [Multivariate distributions and further tests](https://jwkunz.github.io/lib_jsl/book/statistics/multivariate-tests.html).
6
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_random::uniform_generator::UniformGenerator;
9use lib_jsl_special_functions::gamma::{digamma, ln_gamma};
10use lib_jsl_special_functions::polygamma::multigammaln;
11use std::f64::consts::PI;
12
13type Matrix = Vec<Vec<f64>>;
14
15/// The lower Cholesky factor of a symmetric positive definite matrix.
16fn cholesky(a: &Matrix) -> Result<Matrix, ErrorsJSL> {
17    let n = a.len();
18    if a.iter().any(|r| r.len() != n) {
19        return Err(ErrorsJSL::InvalidInputRange("the matrix must be square"));
20    }
21    let mut l = vec![vec![0.0; n]; n];
22    for j in 0..n {
23        let d = a[j][j] - (0..j).map(|k| l[j][k] * l[j][k]).sum::<f64>();
24        if !(d > 0.0) || !d.is_finite() {
25            return Err(ErrorsJSL::InvalidInputRange("the matrix must be symmetric positive definite"));
26        }
27        l[j][j] = d.sqrt();
28        for i in j + 1..n {
29            if (a[i][j] - a[j][i]).abs() > 1e-10 * (a[i][j].abs() + a[j][i].abs()).max(1e-300) {
30                return Err(ErrorsJSL::InvalidInputRange("the matrix must be symmetric"));
31            }
32            l[i][j] = (a[i][j] - (0..j).map(|k| l[i][k] * l[j][k]).sum::<f64>()) / l[j][j];
33        }
34    }
35    Ok(l)
36}
37
38fn log_det_from_cholesky(l: &Matrix) -> f64 {
39    2.0 * l.iter().enumerate().map(|(i, r)| r[i].ln()).sum::<f64>()
40}
41
42/// `L⁻¹ b` by forward substitution.
43fn forward(l: &Matrix, b: &[f64]) -> Vec<f64> {
44    let mut y = b.to_vec();
45    for i in 0..y.len() {
46        y[i] = (y[i] - (0..i).map(|k| l[i][k] * y[k]).sum::<f64>()) / l[i][i];
47    }
48    y
49}
50
51/// `A⁻¹` for symmetric positive definite `A`, from its Cholesky factor.
52fn inverse_from_cholesky(l: &Matrix) -> Matrix {
53    let n = l.len();
54    let mut inv = vec![vec![0.0; n]; n];
55    for j in 0..n {
56        let mut e = vec![0.0; n];
57        e[j] = 1.0;
58        let y = forward(l, &e);
59        // Back substitution with Lᵀ.
60        let mut x = y;
61        for i in (0..n).rev() {
62            x[i] = (x[i] - (i + 1..n).map(|k| l[k][i] * x[k]).sum::<f64>()) / l[i][i];
63        }
64        for i in 0..n {
65            inv[i][j] = x[i];
66        }
67    }
68    inv
69}
70
71/// A standard normal deviate by the Box-Muller transform.
72pub(crate) fn standard_normal<U: UniformGenerator>(rng: &mut U) -> f64 {
73    let mut u = rng.next_f64();
74    while u <= 0.0 {
75        u = rng.next_f64();
76    }
77    let v = rng.next_f64();
78    (-2.0 * u.ln()).sqrt() * (2.0 * PI * v).cos()
79}
80
81/// A Gamma(shape, 1) deviate (Marsaglia and Tsang, 2000).
82pub(crate) fn standard_gamma<U: UniformGenerator>(shape: f64, rng: &mut U) -> f64 {
83    if shape < 1.0 {
84        let u = rng.next_f64().max(f64::MIN_POSITIVE);
85        return standard_gamma(shape + 1.0, rng) * u.powf(1.0 / shape);
86    }
87    let d = shape - 1.0 / 3.0;
88    let c = 1.0 / (9.0 * d).sqrt();
89    loop {
90        let x = standard_normal(rng);
91        let v = (1.0 + c * x).powi(3);
92        if v <= 0.0 {
93            continue;
94        }
95        let u = rng.next_f64();
96        if u.ln() < 0.5 * x * x + d - d * v + d * v.ln() {
97            return d * v;
98        }
99    }
100}
101
102// ANCHOR: mvn
103/// The multivariate normal distribution `N(μ, Σ)` (SciPy's `multivariate_normal`), for a
104/// positive definite `Σ`: `log f(x) = −½ (d log 2π + log|Σ| + (x − μ)ᵀ Σ⁻¹ (x − μ))`, with the
105/// quadratic form computed as `‖L⁻¹(x − μ)‖²` from the Cholesky factor `Σ = L Lᵀ`.
106#[derive(Clone, Debug)]
107pub struct MultivariateNormal {
108    pub mean: Vec<f64>,
109    pub cov: Matrix,
110    chol: Matrix,
111    log_det: f64,
112    /// For a singular covariance: the eigen-structure on its range.
113    psd: Option<Psd>,
114}
115
116/// A positive semidefinite covariance through its eigendecomposition (SciPy's `_PSD`): the
117/// `r` eigenvectors with eigenvalues above `eps` span the support.
118#[derive(Clone, Debug)]
119struct Psd {
120    /// `d × r`: the eigenvectors scaled by `√λ` (for sampling).
121    root: Matrix,
122    /// `d × r`: the eigenvectors scaled by `1/√λ` (for the Mahalanobis distance).
123    pinv_root: Matrix,
124    /// `d × (d − r)`: a basis of the null space.
125    null: Matrix,
126    rank: usize,
127    eps: f64,
128}
129
130/// The eigenvalues and eigenvectors (as columns) of a symmetric matrix by cyclic Jacobi
131/// rotations.
132fn symmetric_eigen(a: &Matrix) -> (Vec<f64>, Matrix) {
133    let n = a.len();
134    let mut m = a.clone();
135    let mut v: Matrix = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
136    for _ in 0..100 {
137        let off: f64 = (0..n).flat_map(|i| (0..n).filter(move |&j| j != i).map(move |j| (i, j))).map(|(i, j)| m[i][j] * m[i][j]).sum();
138        let scale: f64 = (0..n).map(|i| m[i][i] * m[i][i]).sum::<f64>().max(f64::MIN_POSITIVE);
139        if off <= 1e-30 * scale {
140            break;
141        }
142        for p in 0..n {
143            for q in p + 1..n {
144                if m[p][q] == 0.0 {
145                    continue;
146                }
147                let theta = (m[q][q] - m[p][p]) / (2.0 * m[p][q]);
148                let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
149                let t = if theta == 0.0 { 1.0 } else { t };
150                let c = 1.0 / (t * t + 1.0).sqrt();
151                let s = t * c;
152                for row in m.iter_mut() {
153                    let (x, y) = (row[p], row[q]);
154                    row[p] = c * x - s * y;
155                    row[q] = s * x + c * y;
156                }
157                let (lo, hi) = m.split_at_mut(q);
158                for (x, y) in lo[p].iter_mut().zip(hi[0].iter_mut()) {
159                    let (a, b) = (*x, *y);
160                    *x = c * a - s * b;
161                    *y = s * a + c * b;
162                }
163                for row in v.iter_mut() {
164                    let (x, y) = (row[p], row[q]);
165                    row[p] = c * x - s * y;
166                    row[q] = s * x + c * y;
167                }
168            }
169        }
170    }
171    ((0..n).map(|i| m[i][i]).collect(), v)
172}
173
174/// [`symmetric_eigen`] for the QMC sampler.
175pub(crate) fn symmetric_eigen_pub(a: &[Vec<f64>]) -> (Vec<f64>, Matrix) {
176    symmetric_eigen(&a.to_vec())
177}
178
179impl MultivariateNormal {
180    pub fn new(mean: Vec<f64>, cov: Matrix) -> Result<Self, ErrorsJSL> {
181        if cov.len() != mean.len() || mean.is_empty() {
182            return Err(ErrorsJSL::InvalidInputRange("the mean and covariance must have one dimension"));
183        }
184        let chol = cholesky(&cov)?;
185        let log_det = log_det_from_cholesky(&chol);
186        Ok(MultivariateNormal { mean, cov, chol, log_det, psd: None })
187    }
188
189    // ANCHOR: allow_singular
190    /// A normal distribution whose covariance may be singular (SciPy's
191    /// `multivariate_normal(mean, cov, allow_singular=True)`). The covariance's eigenvalues
192    /// above `ε = 10⁶ ε_mach max|λ|` define its rank `r` and range; the density is the `r`-
193    /// dimensional one on the affine support `μ + range(Σ)`, with the pseudo-determinant and
194    /// pseudo-inverse, and zero off it.
195    pub fn new_allow_singular(mean: Vec<f64>, cov: Matrix) -> Result<Self, ErrorsJSL> {
196        let d = mean.len();
197        if cov.len() != d || d == 0 || cov.iter().any(|r| r.len() != d) {
198            return Err(ErrorsJSL::InvalidInputRange("the mean and covariance must have one dimension"));
199        }
200        if let Ok(chol) = cholesky(&cov) {
201            let log_det = log_det_from_cholesky(&chol);
202            return Ok(MultivariateNormal { mean, cov, chol, log_det, psd: None });
203        }
204        let (lam, v) = symmetric_eigen(&cov);
205        let eps = 1e6 * f64::EPSILON * lam.iter().fold(0.0f64, |m, x| m.max(x.abs()));
206        if lam.iter().any(|&l| l < -eps) {
207            return Err(ErrorsJSL::InvalidInputRange("the covariance must be positive semidefinite"));
208        }
209        let keep: Vec<usize> = (0..d).filter(|&i| lam[i] > eps).collect();
210        let drop: Vec<usize> = (0..d).filter(|&i| lam[i] <= eps).collect();
211        let col = |cols: &[usize], f: &dyn Fn(f64) -> f64| -> Matrix { (0..d).map(|i| cols.iter().map(|&j| v[i][j] * f(lam[j])).collect()).collect() };
212        let psd = Psd {
213            root: col(&keep, &|l| l.sqrt()),
214            pinv_root: col(&keep, &|l| 1.0 / l.sqrt()),
215            null: col(&drop, &|_| 1.0),
216            rank: keep.len(),
217            eps,
218        };
219        let log_det = keep.iter().map(|&j| lam[j].ln()).sum();
220        Ok(MultivariateNormal { mean, cov, chol: Vec::new(), log_det, psd: Some(psd) })
221    }
222    // ANCHOR_END: allow_singular
223
224    pub fn dim(&self) -> usize {
225        self.mean.len()
226    }
227    /// The rank of the covariance (`d` unless singular).
228    pub fn rank(&self) -> usize {
229        self.psd.as_ref().map_or(self.dim(), |p| p.rank)
230    }
231    /// The squared Mahalanobis distance `(x − μ)ᵀ Σ⁺ (x − μ)` (with the pseudo-inverse when the
232    /// covariance is singular).
233    pub fn mahalanobis_sq(&self, x: &[f64]) -> f64 {
234        let d: Vec<f64> = x.iter().zip(&self.mean).map(|(a, b)| a - b).collect();
235        match &self.psd {
236            None => forward(&self.chol, &d).iter().map(|v| v * v).sum(),
237            Some(p) => (0..p.rank).map(|j| (0..d.len()).map(|i| d[i] * p.pinv_root[i][j]).sum::<f64>().powi(2)).sum(),
238        }
239    }
240    pub fn logpdf(&self, x: &[f64]) -> f64 {
241        if let Some(p) = &self.psd {
242            let d: Vec<f64> = x.iter().zip(&self.mean).map(|(a, b)| a - b).collect();
243            let residual: f64 = (0..self.dim() - p.rank).map(|j| (0..d.len()).map(|i| d[i] * p.null[i][j]).sum::<f64>().powi(2)).sum::<f64>().sqrt();
244            if residual >= p.eps {
245                return f64::NEG_INFINITY;
246            }
247        }
248        let r = self.rank() as f64;
249        -0.5 * (r * (2.0 * PI).ln() + self.log_det + self.mahalanobis_sq(x))
250    }
251    pub fn pdf(&self, x: &[f64]) -> f64 {
252        self.logpdf(x).exp()
253    }
254    /// `½ log((2πe)^r |Σ|₊)` (the pseudo-determinant when singular).
255    pub fn entropy(&self) -> f64 {
256        0.5 * (self.rank() as f64 * (2.0 * PI * std::f64::consts::E).ln() + self.log_det)
257    }
258    /// `μ + L z` for standard normal `z` (`L` a square root of `Σ`).
259    pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Vec<f64> {
260        match &self.psd {
261            None => {
262                let z: Vec<f64> = (0..self.dim()).map(|_| standard_normal(rng)).collect();
263                (0..self.dim()).map(|i| self.mean[i] + (0..=i).map(|k| self.chol[i][k] * z[k]).sum::<f64>()).collect()
264            }
265            Some(p) => {
266                let z: Vec<f64> = (0..p.rank).map(|_| standard_normal(rng)).collect();
267                (0..self.dim()).map(|i| self.mean[i] + (0..p.rank).map(|k| p.root[i][k] * z[k]).sum::<f64>()).collect()
268            }
269        }
270    }
271}
272// ANCHOR_END: mvn
273
274/// The multivariate Student t distribution with location `μ`, shape `Σ` and `ν` degrees of
275/// freedom (SciPy's `multivariate_t`): `X = μ + Z/√(W/ν)`, `Z ~ N(0, Σ)`, `W ~ χ²_ν`.
276#[derive(Clone, Debug)]
277pub struct MultivariateT {
278    pub loc: Vec<f64>,
279    pub shape: Matrix,
280    pub df: f64,
281    normal: MultivariateNormal,
282}
283
284impl MultivariateT {
285    pub fn new(loc: Vec<f64>, shape: Matrix, df: f64) -> Result<Self, ErrorsJSL> {
286        if !(df > 0.0) {
287            return Err(ErrorsJSL::InvalidInputRange("the degrees of freedom must be positive"));
288        }
289        let normal = MultivariateNormal::new(loc.clone(), shape.clone())?;
290        Ok(MultivariateT { loc, shape, df, normal })
291    }
292    /// `log Γ((ν+d)/2) − log Γ(ν/2) − (d/2) log(νπ) − ½ log|Σ| − ((ν+d)/2) log(1 + δ²/ν)`.
293    pub fn logpdf(&self, x: &[f64]) -> f64 {
294        let (d, nu) = (self.loc.len() as f64, self.df);
295        let m = self.normal.mahalanobis_sq(x);
296        ln_gamma((nu + d) / 2.0) - ln_gamma(nu / 2.0) - 0.5 * d * (nu * PI).ln() - 0.5 * self.normal.log_det - 0.5 * (nu + d) * (m / nu).ln_1p()
297    }
298    pub fn pdf(&self, x: &[f64]) -> f64 {
299        self.logpdf(x).exp()
300    }
301    /// The covariance `ν/(ν − 2) Σ` (infinite for `ν ≤ 2`).
302    pub fn cov(&self) -> Matrix {
303        let f = if self.df > 2.0 { self.df / (self.df - 2.0) } else { f64::INFINITY };
304        self.shape.iter().map(|r| r.iter().map(|v| v * f).collect()).collect()
305    }
306    pub fn entropy(&self) -> f64 {
307        let (d, nu) = (self.loc.len() as f64, self.df);
308        -ln_gamma((nu + d) / 2.0) + ln_gamma(nu / 2.0) + 0.5 * d * (nu * PI).ln() + 0.5 * self.normal.log_det + 0.5 * (nu + d) * (digamma((nu + d) / 2.0) - digamma(nu / 2.0))
309    }
310    pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Vec<f64> {
311        let z = MultivariateNormal { mean: vec![0.0; self.loc.len()], ..self.normal.clone() }.sample(rng);
312        let w = 2.0 * standard_gamma(self.df / 2.0, rng) / self.df;
313        z.iter().zip(&self.loc).map(|(zi, m)| m + zi / w.sqrt()).collect()
314    }
315}
316
317/// The Dirichlet distribution on the simplex (SciPy's `dirichlet(α)`):
318/// `f(x) = Π x_i^{α_i − 1} / B(α)`, `B(α) = Π Γ(α_i) / Γ(α₀)`, `α₀ = Σ α_i`.
319#[derive(Clone, Debug)]
320pub struct Dirichlet {
321    pub alpha: Vec<f64>,
322}
323
324impl Dirichlet {
325    pub fn new(alpha: Vec<f64>) -> Result<Self, ErrorsJSL> {
326        if alpha.len() < 2 || alpha.iter().any(|a| !(*a > 0.0) || !a.is_finite()) {
327            return Err(ErrorsJSL::InvalidInputRange("α needs at least two positive entries"));
328        }
329        Ok(Dirichlet { alpha })
330    }
331    fn alpha0(&self) -> f64 {
332        self.alpha.iter().sum()
333    }
334    fn ln_beta(&self) -> f64 {
335        self.alpha.iter().map(|&a| ln_gamma(a)).sum::<f64>() - ln_gamma(self.alpha0())
336    }
337    /// The log density at a point of the simplex (components positive, summing to 1 within 10⁻¹⁰).
338    pub fn logpdf(&self, x: &[f64]) -> Result<f64, ErrorsJSL> {
339        if x.len() != self.alpha.len() || x.iter().any(|v| !(*v > 0.0)) || (x.iter().sum::<f64>() - 1.0).abs() > 1e-10 {
340            return Err(ErrorsJSL::InvalidInputRange("x must lie in the open simplex"));
341        }
342        Ok(x.iter().zip(&self.alpha).map(|(xi, a)| (a - 1.0) * xi.ln()).sum::<f64>() - self.ln_beta())
343    }
344    pub fn pdf(&self, x: &[f64]) -> Result<f64, ErrorsJSL> {
345        Ok(self.logpdf(x)?.exp())
346    }
347    pub fn mean(&self) -> Vec<f64> {
348        let a0 = self.alpha0();
349        self.alpha.iter().map(|a| a / a0).collect()
350    }
351    /// The marginal variances `α_i (α₀ − α_i) / (α₀² (α₀ + 1))`.
352    pub fn var(&self) -> Vec<f64> {
353        let a0 = self.alpha0();
354        self.alpha.iter().map(|a| a * (a0 - a) / (a0 * a0 * (a0 + 1.0))).collect()
355    }
356    /// The covariance matrix, `−α_i α_j / (α₀² (α₀ + 1))` off the diagonal.
357    pub fn cov(&self) -> Matrix {
358        let a0 = self.alpha0();
359        let v = self.var();
360        (0..self.alpha.len()).map(|i| (0..self.alpha.len()).map(|j| if i == j { v[i] } else { -self.alpha[i] * self.alpha[j] / (a0 * a0 * (a0 + 1.0)) }).collect()).collect()
361    }
362    /// `log B(α) + (α₀ − K) ψ(α₀) − Σ (α_i − 1) ψ(α_i)`.
363    pub fn entropy(&self) -> f64 {
364        let a0 = self.alpha0();
365        let k = self.alpha.len() as f64;
366        self.ln_beta() + (a0 - k) * digamma(a0) - self.alpha.iter().map(|&a| (a - 1.0) * digamma(a)).sum::<f64>()
367    }
368    /// Normalised independent Gamma(α_i) deviates.
369    pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Vec<f64> {
370        let g: Vec<f64> = self.alpha.iter().map(|&a| standard_gamma(a, rng)).collect();
371        let s: f64 = g.iter().sum();
372        g.iter().map(|v| v / s).collect()
373    }
374}
375
376// ANCHOR: wishart
377/// The Wishart distribution of `X = Σ_k z_k z_kᵀ`, `z_k ~ N(0, S)`, with `ν > p − 1` degrees of
378/// freedom (SciPy's `wishart(df, scale)`): `log f(X) = ((ν − p − 1)/2) log|X| − tr(S⁻¹X)/2 −
379/// (νp/2) log 2 − (ν/2) log|S| − log Γ_p(ν/2)`. Sampling uses Bartlett's decomposition
380/// `X = L A Aᵀ Lᵀ`, `A` lower triangular with `A_ii = √χ²_{ν−i}` and standard normal entries
381/// below the diagonal.
382#[derive(Clone, Debug)]
383pub struct Wishart {
384    pub df: f64,
385    pub scale: Matrix,
386    chol: Matrix,
387    log_det: f64,
388}
389
390impl Wishart {
391    pub fn new(df: f64, scale: Matrix) -> Result<Self, ErrorsJSL> {
392        let p = scale.len() as f64;
393        if !(df > p - 1.0) {
394            return Err(ErrorsJSL::InvalidInputRange("the degrees of freedom must exceed p − 1"));
395        }
396        let chol = cholesky(&scale)?;
397        let log_det = log_det_from_cholesky(&chol);
398        Ok(Wishart { df, scale, chol, log_det })
399    }
400    pub fn logpdf(&self, x: &Matrix) -> Result<f64, ErrorsJSL> {
401        let p = self.scale.len();
402        let lx = cholesky(x)?;
403        let inv_s = inverse_from_cholesky(&self.chol);
404        let trace: f64 = (0..p).map(|i| (0..p).map(|j| inv_s[i][j] * x[j][i]).sum::<f64>()).sum();
405        let (nu, pf) = (self.df, p as f64);
406        Ok(0.5 * (nu - pf - 1.0) * log_det_from_cholesky(&lx) - 0.5 * trace - 0.5 * nu * pf * 2f64.ln() - 0.5 * nu * self.log_det - multigammaln(nu / 2.0, p as u32))
407    }
408    pub fn pdf(&self, x: &Matrix) -> Result<f64, ErrorsJSL> {
409        Ok(self.logpdf(x)?.exp())
410    }
411    /// `ν S`.
412    pub fn mean(&self) -> Matrix {
413        self.scale.iter().map(|r| r.iter().map(|v| v * self.df).collect()).collect()
414    }
415    /// The variances of the entries, `ν (S_ij² + S_ii S_jj)`.
416    pub fn var(&self) -> Matrix {
417        let s = &self.scale;
418        (0..s.len()).map(|i| (0..s.len()).map(|j| self.df * (s[i][j] * s[i][j] + s[i][i] * s[j][j])).collect()).collect()
419    }
420    /// `(ν − p − 1) S`, for `ν ≥ p + 1`.
421    pub fn mode(&self) -> Option<Matrix> {
422        let p = self.scale.len() as f64;
423        (self.df >= p + 1.0).then(|| self.scale.iter().map(|r| r.iter().map(|v| v * (self.df - p - 1.0)).collect()).collect())
424    }
425    /// `((p + 1)/2) log|S| + (p(p + 1)/2) log 2 + log Γ_p(ν/2) − ((ν − p − 1)/2) ψ_p(ν/2) + νp/2`.
426    pub fn entropy(&self) -> f64 {
427        let p = self.scale.len();
428        let (nu, pf) = (self.df, p as f64);
429        let psi_p: f64 = (0..p).map(|i| digamma((nu - i as f64) / 2.0)).sum();
430        0.5 * (pf + 1.0) * self.log_det + 0.5 * pf * (pf + 1.0) * 2f64.ln() + multigammaln(nu / 2.0, p as u32) - 0.5 * (nu - pf - 1.0) * psi_p + 0.5 * nu * pf
431    }
432    pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Matrix {
433        let p = self.scale.len();
434        let mut a = vec![vec![0.0; p]; p];
435        for (i, row) in a.iter_mut().enumerate() {
436            row[i] = (2.0 * standard_gamma((self.df - i as f64) / 2.0, rng)).sqrt();
437            for v in row.iter_mut().take(i) {
438                *v = standard_normal(rng);
439            }
440        }
441        // B = L A, X = B Bᵀ.
442        let b: Matrix = (0..p).map(|i| (0..p).map(|j| (0..p).map(|k| self.chol[i][k] * a[k][j]).sum()).collect()).collect();
443        (0..p).map(|i| (0..p).map(|j| (0..p).map(|k| b[i][k] * b[j][k]).sum()).collect()).collect()
444    }
445}
446// ANCHOR_END: wishart
447
448/// The inverse Wishart distribution of `X⁻¹` for `X ~ Wishart(ν, Ψ⁻¹)` (SciPy's
449/// `invwishart(df, scale = Ψ)`): `log f(X) = (ν/2) log|Ψ| − (νp/2) log 2 − log Γ_p(ν/2) −
450/// ((ν + p + 1)/2) log|X| − tr(Ψ X⁻¹)/2`.
451#[derive(Clone, Debug)]
452pub struct InvWishart {
453    pub df: f64,
454    pub scale: Matrix,
455    log_det: f64,
456}
457
458impl InvWishart {
459    pub fn new(df: f64, scale: Matrix) -> Result<Self, ErrorsJSL> {
460        let p = scale.len() as f64;
461        if !(df > p - 1.0) {
462            return Err(ErrorsJSL::InvalidInputRange("the degrees of freedom must exceed p − 1"));
463        }
464        let log_det = log_det_from_cholesky(&cholesky(&scale)?);
465        Ok(InvWishart { df, scale, log_det })
466    }
467    pub fn logpdf(&self, x: &Matrix) -> Result<f64, ErrorsJSL> {
468        let p = self.scale.len();
469        let lx = cholesky(x)?;
470        let inv_x = inverse_from_cholesky(&lx);
471        let trace: f64 = (0..p).map(|i| (0..p).map(|j| self.scale[i][j] * inv_x[j][i]).sum::<f64>()).sum();
472        let (nu, pf) = (self.df, p as f64);
473        Ok(0.5 * nu * self.log_det - 0.5 * nu * pf * 2f64.ln() - multigammaln(nu / 2.0, p as u32) - 0.5 * (nu + pf + 1.0) * log_det_from_cholesky(&lx) - 0.5 * trace)
474    }
475    pub fn pdf(&self, x: &Matrix) -> Result<f64, ErrorsJSL> {
476        Ok(self.logpdf(x)?.exp())
477    }
478    /// `Ψ / (ν − p − 1)`, for `ν > p + 1`.
479    pub fn mean(&self) -> Option<Matrix> {
480        let p = self.scale.len() as f64;
481        (self.df > p + 1.0).then(|| self.scale.iter().map(|r| r.iter().map(|v| v / (self.df - p - 1.0)).collect()).collect())
482    }
483    /// `Ψ / (ν + p + 1)`.
484    pub fn mode(&self) -> Matrix {
485        let p = self.scale.len() as f64;
486        self.scale.iter().map(|r| r.iter().map(|v| v / (self.df + p + 1.0)).collect()).collect()
487    }
488    pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Result<Matrix, ErrorsJSL> {
489        let inv_scale = inverse_from_cholesky(&cholesky(&self.scale)?);
490        let w = Wishart::new(self.df, inv_scale)?.sample(rng);
491        Ok(inverse_from_cholesky(&cholesky(&w)?))
492    }
493}
494
495/// The multinomial distribution of the counts of `n` independent draws from `p.len()` categories
496/// with probabilities `p` (SciPy's `multinomial(n, p)`).
497#[derive(Clone, Debug)]
498pub struct Multinomial {
499    pub n: u64,
500    pub p: Vec<f64>,
501}
502
503impl Multinomial {
504    pub fn new(n: u64, p: Vec<f64>) -> Result<Self, ErrorsJSL> {
505        if p.is_empty() || p.iter().any(|v| !(0.0..=1.0).contains(v)) || (p.iter().sum::<f64>() - 1.0).abs() > 1e-10 {
506            return Err(ErrorsJSL::InvalidInputRange("p must be probabilities summing to 1"));
507        }
508        Ok(Multinomial { n, p })
509    }
510    /// `log n! − Σ log x_i! + Σ x_i log p_i`; −∞ unless the counts sum to `n`.
511    pub fn logpmf(&self, x: &[u64]) -> f64 {
512        if x.len() != self.p.len() || x.iter().sum::<u64>() != self.n {
513            return f64::NEG_INFINITY;
514        }
515        let mut s = ln_gamma(self.n as f64 + 1.0);
516        for (&xi, &pi) in x.iter().zip(&self.p) {
517            s -= ln_gamma(xi as f64 + 1.0);
518            if xi > 0 {
519                if pi == 0.0 {
520                    return f64::NEG_INFINITY;
521                }
522                s += xi as f64 * pi.ln();
523            }
524        }
525        s
526    }
527    pub fn pmf(&self, x: &[u64]) -> f64 {
528        self.logpmf(x).exp()
529    }
530    pub fn mean(&self) -> Vec<f64> {
531        self.p.iter().map(|p| self.n as f64 * p).collect()
532    }
533    /// `n (diag(p) − p pᵀ)`.
534    pub fn cov(&self) -> Matrix {
535        let n = self.n as f64;
536        (0..self.p.len()).map(|i| (0..self.p.len()).map(|j| n * (if i == j { self.p[i] } else { 0.0 } - self.p[i] * self.p[j])).collect()).collect()
537    }
538    /// One draw, category by category: `x_i ~ Binomial(n − Σ_{j<i} x_j, p_i / (1 − Σ_{j<i} p_j))`.
539    pub fn sample<U: UniformGenerator>(&self, rng: &mut U) -> Vec<u64> {
540        let mut left = self.n;
541        let mut mass = 1.0;
542        let mut out = Vec::with_capacity(self.p.len());
543        for (i, &pi) in self.p.iter().enumerate() {
544            if i + 1 == self.p.len() {
545                out.push(left);
546                break;
547            }
548            let q = if mass > 0.0 { (pi / mass).clamp(0.0, 1.0) } else { 0.0 };
549            let mut k = 0;
550            for _ in 0..left {
551                if rng.next_f64() < q {
552                    k += 1;
553                }
554            }
555            out.push(k);
556            left -= k;
557            mass -= pi;
558        }
559        out
560    }
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566    use lib_jsl_random::uniform_generator::UniformRNG;
567
568    #[test]
569    fn densities_and_sampling() {
570        // A diagonal covariance: the log density is a sum of univariate ones.
571        let mvn = MultivariateNormal::new(vec![1.0, -2.0], vec![vec![4.0, 0.0], vec![0.0, 0.25]]).unwrap();
572        let x = [2.0, -1.5];
573        let uni = |z: f64, m: f64, s: f64| -0.5 * ((z - m) / s).powi(2) - (s * (2.0 * PI).sqrt()).ln();
574        assert!((mvn.logpdf(&x) - (uni(2.0, 1.0, 2.0) + uni(-1.5, -2.0, 0.5))).abs() < 1e-14);
575        assert!(MultivariateNormal::new(vec![0.0, 0.0], vec![vec![1.0, 2.0], vec![2.0, 1.0]]).is_err(), "not positive definite");
576        let mut rng = UniformRNG::from_seed(5);
577        let n = 4000;
578        let mut m = [0.0; 2];
579        for _ in 0..n {
580            let s = mvn.sample(&mut rng);
581            m[0] += s[0] / n as f64;
582            m[1] += s[1] / n as f64;
583        }
584        assert!((m[0] - 1.0).abs() < 0.1 && (m[1] + 2.0).abs() < 0.03, "{m:?}");
585        // As ν → ∞ the multivariate t tends to the normal.
586        let t = MultivariateT::new(vec![1.0, -2.0], vec![vec![4.0, 0.0], vec![0.0, 0.25]], 1e9).unwrap();
587        assert!((t.logpdf(&x) - mvn.logpdf(&x)).abs() < 1e-6);
588        let d = Dirichlet::new(vec![2.0, 3.0, 5.0]).unwrap();
589        let s = d.sample(&mut rng);
590        assert!((s.iter().sum::<f64>() - 1.0).abs() < 1e-14 && s.iter().all(|v| *v > 0.0));
591        // Dirichlet(1, 1) is uniform on the simplex: density 1.
592        assert!((Dirichlet::new(vec![1.0, 1.0]).unwrap().pdf(&[0.3, 0.7]).unwrap() - 1.0).abs() < 1e-14);
593        // Wishart samples average to ν S.
594        let w = Wishart::new(6.0, vec![vec![1.0, 0.3], vec![0.3, 2.0]]).unwrap();
595        let mut mean = [[0.0; 2]; 2];
596        for _ in 0..2000 {
597            let x = w.sample(&mut rng);
598            for i in 0..2 {
599                for j in 0..2 {
600                    mean[i][j] += x[i][j] / 2000.0;
601                }
602            }
603        }
604        let want = w.mean();
605        assert!((0..2).all(|i| (0..2).all(|j| (mean[i][j] - want[i][j]).abs() < 0.08 * want[i][i].max(want[j][j]))), "{mean:?}");
606        // The multinomial probabilities of all outcomes sum to 1.
607        let m3 = Multinomial::new(4, vec![0.2, 0.5, 0.3]).unwrap();
608        let total: f64 = (0..=4u64).flat_map(|a| (0..=4 - a).map(move |b| [a, b, 4 - a - b])).map(|x| m3.pmf(&x)).sum();
609        assert!((total - 1.0).abs() < 1e-14);
610        assert_eq!(m3.sample(&mut rng).iter().sum::<u64>(), 4);
611    }
612
613    #[test]
614    fn singular_covariance() {
615        // X = (Z, Z, W): rank 2.
616        let cov = vec![vec![1.0, 1.0, 0.0], vec![1.0, 1.0, 0.0], vec![0.0, 0.0, 4.0]];
617        let m = MultivariateNormal::new_allow_singular(vec![0.0; 3], cov).unwrap();
618        assert_eq!(m.rank(), 2);
619        // On the support the density is that of (√2 Z along (1,1)/√2, W): N(0,2) × N(0,4).
620        let x = [0.3, 0.3, -1.0];
621        let t = 0.3f64 * 2f64.sqrt();
622        let want = (-t * t / 4.0 - 1.0 / 8.0).exp() / (2.0 * PI * (2.0f64 * 4.0).sqrt());
623        assert!((m.pdf(&x) - want).abs() < 1e-14, "{} vs {want}", m.pdf(&x));
624        assert_eq!(m.pdf(&[0.3, 0.4, 0.0]), 0.0);
625        let mut rng = lib_jsl_random::uniform_generator::UniformRNG::from_seed(3);
626        let s = m.sample(&mut rng);
627        assert!((s[0] - s[1]).abs() < 1e-12);
628    }
629}