Skip to main content

lib_jsl_statistics/
location_scale.rs

1//! More location, scale and shape summaries, following `scipy.stats`: trimmed means (`trim_mean`),
2//! standard scores (`zscore`), the `mode`, circular statistics (`circmean`, `circvar`,
3//! `circstd`), and the maximum-likelihood Box-Cox transform (`boxcox`, `boxcox_llf`,
4//! `boxcox_normmax`).
5//!
6//! See the book entry [More descriptive statistics and robust regression](https://jwkunz.github.io/lib_jsl/book/statistics/robust-regression.html).
7
8use crate::descriptive::{mean, standard_deviation};
9use lib_jsl_core::ErrorsJSL;
10use std::f64::consts::TAU;
11
12fn sorted(x: &[f64]) -> Vec<f64> {
13    let mut s = x.to_vec();
14    s.sort_by(f64::total_cmp);
15    s
16}
17
18// ANCHOR: trim_mean
19/// The mean after removing the `⌊proportion · n⌋` smallest and largest values (SciPy's
20/// `trim_mean`). With `proportion = 0` it is the mean; as it approaches ½ it approaches the median.
21pub fn trim_mean(x: &[f64], proportion: f64) -> Result<f64, ErrorsJSL> {
22    if x.is_empty() {
23        return Err(ErrorsJSL::InvalidInputRange("need at least one value"));
24    }
25    if !(0.0..0.5).contains(&proportion) {
26        return Err(ErrorsJSL::InvalidInputRange("the proportion to cut must be in [0, 0.5)"));
27    }
28    let s = sorted(x);
29    let cut = (proportion * s.len() as f64).floor() as usize;
30    mean(&s[cut..s.len() - cut])
31}
32// ANCHOR_END: trim_mean
33
34/// The standard scores `(xᵢ − x̄)/s` with `s` computed with `ddof` degrees of freedom removed
35/// (SciPy's `zscore`, whose default is `ddof = 0`).
36pub fn zscore(x: &[f64], ddof: usize) -> Result<Vec<f64>, ErrorsJSL> {
37    let m = mean(x)?;
38    let s = standard_deviation(x, ddof)?;
39    Ok(x.iter().map(|v| (v - m) / s).collect())
40}
41
42/// The most frequent value and its count; ties go to the smallest value (SciPy's `mode`).
43pub fn mode(x: &[f64]) -> Result<(f64, usize), ErrorsJSL> {
44    if x.is_empty() {
45        return Err(ErrorsJSL::InvalidInputRange("need at least one value"));
46    }
47    let s = sorted(x);
48    let (mut best, mut best_count) = (s[0], 0);
49    let mut i = 0;
50    while i < s.len() {
51        let j = s[i..].iter().take_while(|&&v| v == s[i]).count();
52        if j > best_count {
53            best = s[i];
54            best_count = j;
55        }
56        i += j;
57    }
58    Ok((best, best_count))
59}
60
61// ANCHOR: circular
62/// The mean resultant vector of angles in `[low, high)` (one period): its length `R ∈ [0, 1]`
63/// and direction, as an angle in radians.
64fn resultant(angles: &[f64], low: f64, high: f64) -> Result<(f64, f64), ErrorsJSL> {
65    if angles.is_empty() {
66        return Err(ErrorsJSL::InvalidInputRange("need at least one angle"));
67    }
68    if !(high > low) {
69        return Err(ErrorsJSL::InvalidInputRange("need high > low"));
70    }
71    let k = TAU / (high - low);
72    let (s, c) = angles.iter().fold((0.0, 0.0), |(s, c), &a| {
73        let t = (a - low) * k;
74        (s + t.sin(), c + t.cos())
75    });
76    let n = angles.len() as f64;
77    Ok(((s / n).hypot(c / n), s.atan2(c)))
78}
79
80/// The circular mean of angles with period `high − low` (SciPy's `circmean`; use `0` and `2π`
81/// for radians): the direction of the mean resultant vector, mapped into `[low, high)`.
82pub fn circmean(angles: &[f64], low: f64, high: f64) -> Result<f64, ErrorsJSL> {
83    let (_, theta) = resultant(angles, low, high)?;
84    Ok(low + theta.rem_euclid(TAU) * (high - low) / TAU)
85}
86
87/// The circular variance `1 − R` (SciPy's `circvar`), between 0 (all angles equal) and 1.
88pub fn circvar(angles: &[f64], low: f64, high: f64) -> Result<f64, ErrorsJSL> {
89    Ok(1.0 - resultant(angles, low, high)?.0)
90}
91
92/// The circular standard deviation `√(−2 ln R)`, in the units of the angles (SciPy's `circstd`).
93/// It approaches the ordinary standard deviation for concentrated angles.
94pub fn circstd(angles: &[f64], low: f64, high: f64) -> Result<f64, ErrorsJSL> {
95    let (r, _) = resultant(angles, low, high)?;
96    Ok((-2.0 * r.ln()).sqrt() * (high - low) / TAU)
97}
98// ANCHOR_END: circular
99
100/// The Box-Cox profile log-likelihood of `λ` for positive data (SciPy's `boxcox_llf`):
101/// `(λ − 1) Σ ln xᵢ − (n/2) ln σ̂²(λ)`, where `σ̂²` is the variance (`ddof = 0`) of the
102/// transformed data.
103pub fn boxcox_llf(lambda: f64, x: &[f64]) -> f64 {
104    let n = x.len() as f64;
105    let logs: Vec<f64> = x.iter().map(|v| v.ln()).collect();
106    let y: Vec<f64> = logs.iter().map(|&l| if lambda == 0.0 { l } else { (lambda * l).exp_m1() / lambda }).collect();
107    let m = y.iter().sum::<f64>() / n;
108    let var = y.iter().map(|v| (v - m).powi(2)).sum::<f64>() / n;
109    (lambda - 1.0) * logs.iter().sum::<f64>() - 0.5 * n * var.ln()
110}
111
112// ANCHOR: boxcox_normmax
113/// The `λ` that maximises [`boxcox_llf`] (SciPy's `boxcox_normmax` with `method='mle'`): the
114/// power that makes the data most nearly normal. A golden-section search on `[−2, 2]`, widened
115/// while the maximum sits at an end of the interval.
116pub fn boxcox_normmax(x: &[f64]) -> Result<f64, ErrorsJSL> {
117    if x.len() < 2 || x.iter().any(|&v| !(v > 0.0)) {
118        return Err(ErrorsJSL::InvalidInputRange("Box-Cox needs at least two positive values"));
119    }
120    if x.iter().all(|&v| v == x[0]) {
121        return Err(ErrorsJSL::InvalidInputRange("Box-Cox needs data that are not all equal"));
122    }
123    let f = |l: f64| -boxcox_llf(l, x);
124    let (mut lo, mut hi) = (-2.0, 2.0);
125    loop {
126        let g = 0.5 * (5f64.sqrt() - 1.0);
127        let (mut a, mut b) = (lo, hi);
128        let (mut c, mut d) = (b - g * (b - a), a + g * (b - a));
129        let (mut fc, mut fd) = (f(c), f(d));
130        while (b - a).abs() > 1e-12 * (1.0 + c.abs()) {
131            if fc < fd {
132                b = d;
133                d = c;
134                fd = fc;
135                c = b - g * (b - a);
136                fc = f(c);
137            } else {
138                a = c;
139                c = d;
140                fc = fd;
141                d = a + g * (b - a);
142                fd = f(d);
143            }
144        }
145        let best = 0.5 * (a + b);
146        let width = hi - lo;
147        if best - lo < 1e-6 * width && lo > -50.0 {
148            lo -= width;
149        } else if hi - best < 1e-6 * width && hi < 50.0 {
150            hi += width;
151        } else {
152            return Ok(best);
153        }
154    }
155}
156// ANCHOR_END: boxcox_normmax
157
158/// The maximum-likelihood Box-Cox transform of positive data and its `λ` (SciPy's `stats.boxcox`).
159pub fn boxcox(x: &[f64]) -> Result<(Vec<f64>, f64), ErrorsJSL> {
160    let lambda = boxcox_normmax(x)?;
161    Ok((x.iter().map(|&v| lib_jsl_special_functions::boxcox(v, lambda)).collect(), lambda))
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    #[test]
169    fn trimmed_mean_and_mode() {
170        let x = [1.0, 2.0, 3.0, 4.0, 100.0];
171        assert_eq!(trim_mean(&x, 0.2).unwrap(), 3.0);
172        assert_eq!(trim_mean(&x, 0.0).unwrap(), 22.0);
173        assert_eq!(mode(&[3.0, 1.0, 3.0, 1.0, 2.0]).unwrap(), (1.0, 2));
174        let z = zscore(&[1.0, 2.0, 3.0], 0).unwrap();
175        assert!((z[2] - 1.224744871391589).abs() < 1e-15);
176    }
177
178    #[test]
179    fn circular_statistics_wrap_around() {
180        // 350° and 10° average to 0°, not 180°.
181        let a = [350f64.to_radians(), 10f64.to_radians()];
182        let m = circmean(&a, 0.0, TAU).unwrap();
183        assert!(m.min(TAU - m) < 1e-12);
184        let deg = circmean(&[350.0, 10.0, 20.0], 0.0, 360.0).unwrap();
185        assert!((deg - 6.70495327058324).abs() < 1e-12);
186        assert!(circvar(&[1.0, 1.0], 0.0, TAU).unwrap().abs() < 1e-15);
187    }
188
189    #[test]
190    fn boxcox_recovers_a_log_normal() {
191        // exp of evenly spread normal quantiles: λ should be near 0.
192        let x: Vec<f64> = (1..200).map(|i| (lib_jsl_special_functions::normal_quantile(i as f64 / 200.0, 0.0, 1.0)).exp()).collect();
193        let l = boxcox_normmax(&x).unwrap();
194        assert!(l.abs() < 1e-6, "{l}");
195        // Squares of uniform-ish positive data want λ near 1/2.
196        let y: Vec<f64> = (1..200).map(|i| (5.0 + lib_jsl_special_functions::normal_quantile(i as f64 / 200.0, 0.0, 1.0)).powi(2)).collect();
197        assert!((boxcox_normmax(&y).unwrap() - 0.5).abs() < 0.05);
198    }
199}