Skip to main content

lib_jsl_special_functions/
log_functions.rs

1//! Functions for computing in the log domain without overflow or cancellation (SciPy's
2//! `logsumexp`, `softmax`, `log_softmax`, `logit`, `expit`, `log_expit`, `log_ndtr`), and the
3//! Box-Cox power transforms (`boxcox`, `boxcox1p`, `inv_boxcox`).
4//!
5//! See the book entry [Log-domain functions and inverse incomplete integrals](https://jwkunz.github.io/lib_jsl/book/special_functions/log-domain.html).
6
7use crate::error_function::erfc;
8use std::f64::consts::{FRAC_1_SQRT_2, PI};
9
10// ANCHOR: logsumexp
11/// `ln Σ exp(aᵢ)` without overflow (SciPy's `logsumexp`): with `m = max aᵢ`, the sum is
12/// `m + ln Σ exp(aᵢ − m)`, whose terms are at most 1. Returns `−∞` for an empty slice or when
13/// every term is `−∞`, and `+∞` if any term is `+∞`.
14pub fn logsumexp(a: &[f64]) -> f64 {
15    let m = a.iter().copied().fold(f64::NEG_INFINITY, f64::max);
16    if !m.is_finite() {
17        return if a.iter().any(|v| v.is_nan()) { f64::NAN } else { m };
18    }
19    m + a.iter().map(|&v| (v - m).exp()).sum::<f64>().ln()
20}
21// ANCHOR_END: logsumexp
22
23/// `ln |Σ bᵢ exp(aᵢ)|` and the sign of the sum, for weights of either sign (SciPy's `logsumexp`
24/// with `b` and `return_sign=True`). The log is `−∞` with sign 0 when the sum is zero.
25pub fn logsumexp_weighted(a: &[f64], b: &[f64]) -> (f64, f64) {
26    assert_eq!(a.len(), b.len(), "values and weights must have the same length");
27    let m = a.iter().zip(b).filter(|(_, w)| **w != 0.0).map(|(v, _)| *v).fold(f64::NEG_INFINITY, f64::max);
28    if !m.is_finite() {
29        return (m, if m.is_infinite() && m > 0.0 { 1.0 } else { 0.0 });
30    }
31    let s: f64 = a.iter().zip(b).map(|(&v, &w)| w * (v - m).exp()).sum();
32    if s == 0.0 { (f64::NEG_INFINITY, 0.0) } else { (m + s.abs().ln(), s.signum()) }
33}
34
35/// `exp(aᵢ) / Σ exp(aⱼ)`, computed as `exp(aᵢ − logsumexp(a))`.
36pub fn softmax(a: &[f64]) -> Vec<f64> {
37    let l = logsumexp(a);
38    a.iter().map(|v| (v - l).exp()).collect()
39}
40
41/// `aᵢ − logsumexp(a)`, the logarithm of [`softmax`] without underflow.
42pub fn log_softmax(a: &[f64]) -> Vec<f64> {
43    let l = logsumexp(a);
44    a.iter().map(|v| v - l).collect()
45}
46
47/// The log-odds `ln(p / (1 − p))`, the inverse of [`expit`].
48pub fn logit(p: f64) -> f64 {
49    (p / (1.0 - p)).ln()
50}
51
52/// The logistic sigmoid `1 / (1 + e^{−x})`, evaluated so that neither branch overflows.
53pub fn expit(x: f64) -> f64 {
54    if x >= 0.0 {
55        1.0 / (1.0 + (-x).exp())
56    } else {
57        let e = x.exp();
58        e / (1.0 + e)
59    }
60}
61
62/// `ln expit(x) = −ln(1 + e^{−x})`, accurate for large `|x|`.
63pub fn log_expit(x: f64) -> f64 {
64    if x >= 0.0 { -(-x).exp().ln_1p() } else { x - x.exp().ln_1p() }
65}
66
67// ANCHOR: log_ndtr
68/// The logarithm of the standard normal CDF, `ln Φ(x)` (SciPy's `log_ndtr`), accurate in both
69/// tails: for `x > −1` as `ln(1 − Φ(−x))` with `ln_1p`; for `−20 < x ≤ −1` from `erfc`, which is
70/// accurate relative to its tiny value; below that from the asymptotic series
71/// `ln Φ(x) = −x²/2 − ln(−x) − ½ ln 2π + ln(1 − 1/x² + 3/x⁴ − 15/x⁶ + …)`.
72pub fn log_ndtr(x: f64) -> f64 {
73    if x.is_nan() {
74        return f64::NAN;
75    }
76    if x > -1.0 {
77        return (-0.5 * erfc(x * FRAC_1_SQRT_2)).ln_1p();
78    }
79    if x > -20.0 {
80        return (0.5 * erfc(-x * FRAC_1_SQRT_2)).ln();
81    }
82    let x2 = x * x;
83    let (mut term, mut sum) = (1.0, 1.0);
84    for k in 1..12 {
85        term *= -((2 * k - 1) as f64) / x2;
86        sum += term;
87    }
88    -0.5 * x2 - (-x).ln() - 0.5 * (2.0 * PI).ln() + sum.ln()
89}
90// ANCHOR_END: log_ndtr
91
92/// The Box-Cox transform `(x^λ − 1)/λ`, and `ln x` for `λ = 0` (SciPy's `special.boxcox`),
93/// written with `exp_m1` so that it is continuous and accurate near `λ = 0`.
94pub fn boxcox(x: f64, lambda: f64) -> f64 {
95    if x < 0.0 {
96        return f64::NAN;
97    }
98    if lambda.abs() < 1e-19 { x.ln() } else { (lambda * x.ln()).exp_m1() / lambda }
99}
100
101/// The Box-Cox transform of `1 + x`, accurate for small `x` (SciPy's `boxcox1p`).
102pub fn boxcox1p(x: f64, lambda: f64) -> f64 {
103    if x < -1.0 {
104        return f64::NAN;
105    }
106    let l = x.ln_1p();
107    if lambda.abs() < 1e-19 { l } else { (lambda * l).exp_m1() / lambda }
108}
109
110/// The inverse of [`boxcox`]: `(1 + λy)^{1/λ}`, and `e^y` for `λ = 0`.
111pub fn inv_boxcox(y: f64, lambda: f64) -> f64 {
112    if lambda.abs() < 1e-19 { y.exp() } else { ((lambda * y).ln_1p() / lambda).exp() }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118
119    #[test]
120    fn logsumexp_avoids_overflow() {
121        assert!((logsumexp(&[1000.0, 1000.0]) - (1000.0 + 2f64.ln())).abs() < 1e-12);
122        assert!((logsumexp(&[-1000.0, -1000.0 + 3f64.ln()]) - (-1000.0 + 4f64.ln())).abs() < 1e-12);
123        assert_eq!(logsumexp(&[]), f64::NEG_INFINITY);
124        let (l, s) = logsumexp_weighted(&[0.0, 1.0], &[1.0, -1.0]);
125        assert!((l - (1f64.exp() - 1.0).ln()).abs() < 1e-14 && s == -1.0);
126        let p = softmax(&[1.0, 2.0, 3.0]);
127        assert!((p.iter().sum::<f64>() - 1.0).abs() < 1e-15);
128    }
129
130    #[test]
131    fn logistic_functions() {
132        assert_eq!(expit(0.0), 0.5);
133        assert!((logit(expit(3.7)) - 3.7).abs() < 1e-13);
134        assert_eq!(expit(-1000.0), 0.0);
135        assert!((log_expit(-1000.0) + 1000.0).abs() < 1e-12);
136        assert!((log_expit(40.0) + (-40f64).exp()).abs() < 1e-30);
137    }
138
139    #[test]
140    fn log_ndtr_in_both_tails() {
141        // SciPy: special.log_ndtr.
142        let cases = [(3.0, -0.0013508099647481925), (0.0, -std::f64::consts::LN_2), (-5.0, -15.064998393988727), (-30.0, -454.32124395634327), (-100.0, -5005.524208694205)];
143        for (x, want) in cases {
144            assert!((log_ndtr(x) - want).abs() <= 1e-13 * want.abs(), "{x}: {} vs {want}", log_ndtr(x));
145        }
146    }
147
148    #[test]
149    fn boxcox_round_trips() {
150        for lambda in [-1.5, -1e-12, 0.0, 0.5, 2.0] {
151            let y = boxcox(3.2, lambda);
152            assert!((inv_boxcox(y, lambda) - 3.2).abs() < 1e-12);
153        }
154        assert!((boxcox1p(1e-10, 0.5) - 9.99999999975e-11).abs() < 1e-25);
155    }
156}