Skip to main content

lib_jsl_statistics/
normality.rs

1//! Tests of normality, following `scipy.stats`: Shapiro-Wilk ([`shapiro`], Royston's algorithm
2//! AS R94), Anderson-Darling ([`anderson_normal`]), Jarque-Bera ([`jarque_bera`]) and
3//! D'Agostino and Pearson's omnibus test ([`normaltest`], from [`skewtest`] and [`kurtosistest`]).
4//!
5//! See the book entry [More hypothesis tests](https://jwkunz.github.io/lib_jsl/book/statistics/more-tests.html).
6
7use crate::hypothesis_tests::{Alternative, TestResult};
8use lib_jsl_core::ErrorsJSL;
9use lib_jsl_special_functions::{chi_square_survival, normal_cdf, normal_quantile};
10
11fn sorted(x: &[f64]) -> Vec<f64> {
12    let mut s = x.to_vec();
13    s.sort_by(f64::total_cmp);
14    s
15}
16
17fn poly(c: &[f64], x: f64) -> f64 {
18    c.iter().rev().fold(0.0, |acc, &ci| acc * x + ci)
19}
20
21// ANCHOR: shapiro
22/// The Shapiro-Wilk test (SciPy's `shapiro`): `W` measures how well the ordered sample matches
23/// the expected normal order statistics, `W = (Σ aᵢ x₍ᵢ₎)² / Σ (xᵢ − x̄)²`, with Royston's
24/// approximations (AS R94) to the coefficients `aᵢ` and to the null distribution of `ln(1 − W)`.
25/// Valid for 3 ≤ n ≤ 5000.
26pub fn shapiro(x: &[f64]) -> Result<TestResult, ErrorsJSL> {
27    let n = x.len();
28    if !(3..=5000).contains(&n) || x.iter().any(|v| !v.is_finite()) {
29        return Err(ErrorsJSL::InvalidInputRange("Shapiro-Wilk needs 3 to 5000 finite values"));
30    }
31    let xs = sorted(x);
32    let nn2 = n / 2;
33    let an = n as f64;
34    // Coefficients for the lower half; a[i] pairs x₍ₙ₋ᵢ₎ with x₍ᵢ₎.
35    let mut a = vec![0.0; nn2];
36    if n == 3 {
37        a[0] = 0.5f64.sqrt();
38    } else {
39        let an25 = an + 0.25;
40        let m: Vec<f64> = (1..=nn2).map(|i| normal_quantile((i as f64 - 0.375) / an25, 0.0, 1.0)).collect();
41        let summ2 = 2.0 * m.iter().map(|v| v * v).sum::<f64>();
42        let ssumm2 = summ2.sqrt();
43        let rsn = 1.0 / an.sqrt();
44        let c1 = [0.0, 0.221157, -0.147981, -2.07119, 4.434685, -2.706056];
45        let c2 = [0.0, 0.042981, -0.293762, -1.752461, 5.682633, -3.582633];
46        let a1 = poly(&c1, rsn) - m[0] / ssumm2;
47        let (i1, fac) = if n > 5 {
48            let a2 = -m[1] / ssumm2 + poly(&c2, rsn);
49            a[1] = a2;
50            (2, ((summ2 - 2.0 * m[0] * m[0] - 2.0 * m[1] * m[1]) / (1.0 - 2.0 * a1 * a1 - 2.0 * a2 * a2)).sqrt())
51        } else {
52            (1, ((summ2 - 2.0 * m[0] * m[0]) / (1.0 - 2.0 * a1 * a1)).sqrt())
53        };
54        a[0] = a1;
55        for i in i1..nn2 {
56            a[i] = -m[i] / fac;
57        }
58    }
59    let mean = xs.iter().sum::<f64>() / an;
60    let ssq: f64 = xs.iter().map(|v| (v - mean) * (v - mean)).sum();
61    if ssq == 0.0 {
62        return Err(ErrorsJSL::InvalidInputRange("all values are equal"));
63    }
64    let num: f64 = (0..nn2).map(|i| a[i] * (xs[n - 1 - i] - xs[i])).sum();
65    let w = (num * num / ssq).min(1.0);
66    // The p-value.
67    let pw = if n == 3 {
68        let pi6 = 6.0 / std::f64::consts::PI;
69        let stqr = (0.75f64).sqrt().asin();
70        (pi6 * (w.sqrt().asin() - stqr)).max(0.0)
71    } else {
72        let w1 = (1.0 - w).ln();
73        let (y, m, s) = if n <= 11 {
74            let gamma = poly(&[-2.273, 0.459], an);
75            if w1 >= gamma {
76                return Ok(TestResult { statistic: w, p_value: 1e-99, degrees_of_freedom: f64::NAN });
77            }
78            (-(gamma - w1).ln(), poly(&[0.544, -0.39978, 0.025054, -6.714e-4], an), poly(&[1.3822, -0.77857, 0.062767, -0.0020322], an).exp())
79        } else {
80            let xx = an.ln();
81            (w1, poly(&[-1.5861, -0.31082, -0.083751, 0.0038915], xx), poly(&[-0.4803, -0.082676, 0.0030302], xx).exp())
82        };
83        1.0 - normal_cdf((y - m) / s, 0.0, 1.0)
84    };
85    Ok(TestResult { statistic: w, p_value: pw, degrees_of_freedom: f64::NAN })
86}
87// ANCHOR_END: shapiro
88
89/// The result of [`anderson_normal`].
90#[derive(Clone, Debug)]
91#[non_exhaustive]
92pub struct AndersonResult {
93    pub statistic: f64,
94    /// The critical values at the significance levels.
95    pub critical_values: [f64; 5],
96    /// 15%, 10%, 5%, 2.5%, 1%.
97    pub significance_levels: [f64; 5],
98}
99
100/// The Anderson-Darling test of normality with estimated mean and standard deviation (SciPy's
101/// `anderson(x, 'norm')`): `A² = −n − Σ (2i − 1)/n [ln Φ(zᵢ) + ln(1 − Φ(z₍ₙ₊₁₋ᵢ₎))]`, with the
102/// Stephens critical values adjusted for `n`. The null hypothesis is rejected at a level if the
103/// statistic exceeds its critical value.
104pub fn anderson_normal(x: &[f64]) -> Result<AndersonResult, ErrorsJSL> {
105    let n = x.len();
106    if n < 2 {
107        return Err(ErrorsJSL::InvalidInputRange("need at least two values"));
108    }
109    let xs = sorted(x);
110    let an = n as f64;
111    let mean = xs.iter().sum::<f64>() / an;
112    let sd = (xs.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (an - 1.0)).sqrt();
113    let z: Vec<f64> = xs.iter().map(|v| (v - mean) / sd).collect();
114    let logcdf = |v: f64| normal_cdf(v, 0.0, 1.0).ln();
115    let logsf = |v: f64| normal_cdf(-v, 0.0, 1.0).ln();
116    let s: f64 = (0..n).map(|i| (2 * i + 1) as f64 / an * (logcdf(z[i]) + logsf(z[n - 1 - i]))).sum();
117    let a2 = -an - s;
118    let div = 1.0 + 0.75 / an + 2.25 / (an * an);
119    let base = [0.561, 0.631, 0.752, 0.873, 1.035];
120    Ok(AndersonResult { statistic: a2, critical_values: base.map(|b| (b / div * 1000.0).round() / 1000.0), significance_levels: [15.0, 10.0, 5.0, 2.5, 1.0] })
121}
122
123fn moments(x: &[f64]) -> (f64, f64, f64) {
124    let n = x.len() as f64;
125    let m = x.iter().sum::<f64>() / n;
126    let m2 = x.iter().map(|v| (v - m).powi(2)).sum::<f64>() / n;
127    let m3 = x.iter().map(|v| (v - m).powi(3)).sum::<f64>() / n;
128    let m4 = x.iter().map(|v| (v - m).powi(4)).sum::<f64>() / n;
129    (m2, m3, m4)
130}
131
132/// The Jarque-Bera test: `JB = n/6 (S² + K²/4)` from the sample skewness `S` and excess kurtosis
133/// `K` (biased), asymptotically χ² with 2 degrees of freedom (SciPy's `jarque_bera`).
134pub fn jarque_bera(x: &[f64]) -> Result<TestResult, ErrorsJSL> {
135    if x.len() < 2 {
136        return Err(ErrorsJSL::InvalidInputRange("need at least two values"));
137    }
138    let n = x.len() as f64;
139    let (m2, m3, m4) = moments(x);
140    let (s, k) = (m3 / m2.powf(1.5), m4 / (m2 * m2) - 3.0);
141    let jb = n / 6.0 * (s * s + k * k / 4.0);
142    Ok(TestResult { statistic: jb, p_value: chi_square_survival(jb, 2.0), degrees_of_freedom: 2.0 })
143}
144
145fn normal_tail(z: f64, alternative: Alternative) -> f64 {
146    match alternative {
147        Alternative::TwoSided => 2.0 * normal_cdf(-z.abs(), 0.0, 1.0),
148        Alternative::Less => normal_cdf(z, 0.0, 1.0),
149        Alternative::Greater => normal_cdf(-z, 0.0, 1.0),
150    }
151}
152
153// ANCHOR: dagostino
154/// D'Agostino's test that the skewness is that of a normal distribution (SciPy's `skewtest`,
155/// n ≥ 8): the sample skewness is transformed to an approximately standard normal `Z`.
156pub fn skewtest(x: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
157    let n = x.len() as f64;
158    if n < 8.0 {
159        return Err(ErrorsJSL::InvalidInputRange("skewtest needs at least 8 values"));
160    }
161    let (m2, m3, _) = moments(x);
162    let b2 = m3 / m2.powf(1.5);
163    let mut y = b2 * ((n + 1.0) * (n + 3.0) / (6.0 * (n - 2.0))).sqrt();
164    let beta2 = 3.0 * (n * n + 27.0 * n - 70.0) * (n + 1.0) * (n + 3.0) / ((n - 2.0) * (n + 5.0) * (n + 7.0) * (n + 9.0));
165    let w2 = -1.0 + (2.0 * (beta2 - 1.0)).sqrt();
166    let delta = 1.0 / (0.5 * w2.ln()).sqrt();
167    let alpha = (2.0 / (w2 - 1.0)).sqrt();
168    if y == 0.0 {
169        y = 1.0;
170    }
171    let z = delta * (y / alpha + ((y / alpha).powi(2) + 1.0).sqrt()).ln();
172    Ok(TestResult { statistic: z, p_value: normal_tail(z, alternative), degrees_of_freedom: f64::NAN })
173}
174
175/// Anscombe and Glynn's test that the kurtosis is that of a normal distribution (SciPy's
176/// `kurtosistest`, n ≥ 5).
177pub fn kurtosistest(x: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
178    let n = x.len() as f64;
179    if n < 5.0 {
180        return Err(ErrorsJSL::InvalidInputRange("kurtosistest needs at least 5 values"));
181    }
182    let (m2, _, m4) = moments(x);
183    let b2 = m4 / (m2 * m2);
184    let e = 3.0 * (n - 1.0) / (n + 1.0);
185    let varb2 = 24.0 * n * (n - 2.0) * (n - 3.0) / ((n + 1.0).powi(2) * (n + 3.0) * (n + 5.0));
186    let xx = (b2 - e) / varb2.sqrt();
187    let sqrtbeta1 = 6.0 * (n * n - 5.0 * n + 2.0) / ((n + 7.0) * (n + 9.0)) * (6.0 * (n + 3.0) * (n + 5.0) / (n * (n - 2.0) * (n - 3.0))).sqrt();
188    let a = 6.0 + 8.0 / sqrtbeta1 * (2.0 / sqrtbeta1 + (1.0 + 4.0 / (sqrtbeta1 * sqrtbeta1)).sqrt());
189    let term1 = 1.0 - 2.0 / (9.0 * a);
190    let denom = 1.0 + xx * (2.0 / (a - 4.0)).sqrt();
191    let term2 = if denom == 0.0 { f64::NAN } else { denom.signum() * ((1.0 - 2.0 / a) / denom.abs()).cbrt() };
192    let z = (term1 - term2) / (2.0 / (9.0 * a)).sqrt();
193    Ok(TestResult { statistic: z, p_value: normal_tail(z, alternative), degrees_of_freedom: f64::NAN })
194}
195
196/// D'Agostino and Pearson's omnibus test (SciPy's `normaltest`): `K² = Z_skew² + Z_kurt²`,
197/// approximately χ² with 2 degrees of freedom.
198pub fn normaltest(x: &[f64]) -> Result<TestResult, ErrorsJSL> {
199    let (s, k) = (skewtest(x, Alternative::TwoSided)?.statistic, kurtosistest(x, Alternative::TwoSided)?.statistic);
200    let k2 = s * s + k * k;
201    Ok(TestResult { statistic: k2, p_value: chi_square_survival(k2, 2.0), degrees_of_freedom: 2.0 })
202}
203// ANCHOR_END: dagostino