Skip to main content

lib_jsl_statistics/
regression.rs

1//! Straight-line fits: least squares with its standard errors and test (SciPy's `linregress`), and
2//! the robust median-of-slopes estimators of Theil and Sen (`theilslopes`) and Siegel
3//! (`siegelslopes`).
4//!
5//! See the book entry [More descriptive statistics and robust regression](https://jwkunz.github.io/lib_jsl/book/statistics/robust-regression.html#robust-lines).
6
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_special_functions::{normal_quantile, student_t_cdf};
9
10/// The result of [`linregress`].
11#[derive(Clone, Copy, Debug, PartialEq)]
12#[non_exhaustive]
13pub struct LinregressResult {
14    pub slope: f64,
15    pub intercept: f64,
16    /// Pearson's correlation coefficient.
17    pub rvalue: f64,
18    /// Two-sided p-value for the hypothesis that the slope is zero (t-test, `n − 2` degrees of
19    /// freedom).
20    pub pvalue: f64,
21    /// Standard error of the slope.
22    pub stderr: f64,
23    pub intercept_stderr: f64,
24}
25
26fn check(x: &[f64], y: &[f64], min: usize) -> Result<(), ErrorsJSL> {
27    if x.len() != y.len() {
28        return Err(ErrorsJSL::InvalidInputRange("x and y must have the same length"));
29    }
30    if x.len() < min {
31        return Err(ErrorsJSL::InvalidInputRange("too few points"));
32    }
33    Ok(())
34}
35
36// ANCHOR: linregress
37/// The least-squares line `y ≈ slope · x + intercept` (SciPy's `linregress`), from the centred
38/// sums `Sxx`, `Sxy`, `Syy`: `slope = Sxy/Sxx`, `r = Sxy/√(Sxx Syy)`, and the slope's standard
39/// error `√((1 − r²) Syy / ((n − 2) Sxx))`.
40pub fn linregress(x: &[f64], y: &[f64]) -> Result<LinregressResult, ErrorsJSL> {
41    check(x, y, 2)?;
42    let n = x.len() as f64;
43    let (mx, my) = (x.iter().sum::<f64>() / n, y.iter().sum::<f64>() / n);
44    let (mut sxx, mut sxy, mut syy) = (0.0, 0.0, 0.0);
45    for (a, b) in x.iter().zip(y) {
46        let (dx, dy) = (a - mx, b - my);
47        sxx += dx * dx;
48        sxy += dx * dy;
49        syy += dy * dy;
50    }
51    if sxx == 0.0 {
52        return Err(ErrorsJSL::InvalidInputRange("all x values are identical"));
53    }
54    let slope = sxy / sxx;
55    let intercept = my - slope * mx;
56    let r = if syy == 0.0 { 0.0 } else { (sxy / (sxx * syy).sqrt()).clamp(-1.0, 1.0) };
57    if x.len() == 2 {
58        return Ok(LinregressResult { slope, intercept, rvalue: r, pvalue: 1.0, stderr: 0.0, intercept_stderr: 0.0 });
59    }
60    let df = n - 2.0;
61    let stderr = ((1.0 - r * r) * syy / sxx / df).sqrt();
62    let t = r * (df / ((1.0 - r) * (1.0 + r))).sqrt();
63    let pvalue = if t.is_infinite() { 0.0 } else { 2.0 * student_t_cdf(-t.abs(), df) };
64    let intercept_stderr = stderr * (sxx / n + mx * mx).sqrt();
65    Ok(LinregressResult { slope, intercept, rvalue: r, pvalue, stderr, intercept_stderr })
66}
67// ANCHOR_END: linregress
68
69/// The result of [`theilslopes`] and [`siegelslopes`] (the latter has no confidence interval).
70#[derive(Clone, Copy, Debug, PartialEq)]
71pub struct RobustLine {
72    pub slope: f64,
73    pub intercept: f64,
74    /// Lower and upper confidence limits on the slope (Theil-Sen only; `NaN` for Siegel).
75    pub low_slope: f64,
76    pub high_slope: f64,
77}
78
79fn median_of(v: &mut [f64]) -> f64 {
80    v.sort_by(f64::total_cmp);
81    let n = v.len();
82    if n % 2 == 1 { v[n / 2] } else { 0.5 * (v[n / 2 - 1] + v[n / 2]) }
83}
84
85/// Sizes of the groups of tied values.
86fn tie_groups(x: &[f64]) -> Vec<usize> {
87    let mut s = x.to_vec();
88    s.sort_by(f64::total_cmp);
89    let mut groups = Vec::new();
90    let mut i = 0;
91    while i < s.len() {
92        let j = s[i..].iter().take_while(|&&v| v == s[i]).count();
93        if j > 1 {
94            groups.push(j);
95        }
96        i += j;
97    }
98    groups
99}
100
101// ANCHOR: theilslopes
102/// The Theil-Sen line (SciPy's `theilslopes` with `method='separate'`): the slope is the median
103/// of the pairwise slopes `(yⱼ − yᵢ)/(xⱼ − xᵢ)` over pairs with `xⱼ > xᵢ`, the intercept
104/// `median(y) − slope · median(x)`. The confidence interval at level `alpha` (SciPy's default
105/// 0.95) is Sen's: order statistics of the sorted slopes at ranks `(N ± z σ)/2`, where `σ²` is the
106/// variance of Kendall's statistic corrected for ties. Breakdown point 29 %.
107pub fn theilslopes(y: &[f64], x: &[f64], alpha: f64) -> Result<RobustLine, ErrorsJSL> {
108    check(x, y, 2)?;
109    let n = x.len();
110    let mut slopes = Vec::with_capacity(n * (n - 1) / 2);
111    for i in 0..n {
112        for j in 0..n {
113            if x[j] > x[i] {
114                slopes.push((y[j] - y[i]) / (x[j] - x[i]));
115            }
116        }
117    }
118    if slopes.is_empty() {
119        return Err(ErrorsJSL::InvalidInputRange("all x values are identical"));
120    }
121    let slope = median_of(&mut slopes);
122    let intercept = median_of(&mut y.to_vec()) - slope * median_of(&mut x.to_vec());
123    let alpha = if alpha > 0.5 { 1.0 - alpha } else { alpha };
124    let z = normal_quantile(alpha / 2.0, 0.0, 1.0);
125    let term = |k: usize| (k * (k - 1) * (2 * k + 5)) as f64;
126    let sigsq = (term(n) - tie_groups(x).into_iter().map(term).sum::<f64>() - tie_groups(y).into_iter().map(term).sum::<f64>()) / 18.0;
127    let sigma = sigsq.sqrt();
128    let nt = slopes.len() as f64;
129    // NumPy rounds halves to even; so does `round_ties_even`.
130    let ru = (((nt - z * sigma) / 2.0).round_ties_even() as i64).min(slopes.len() as i64 - 1).max(0) as usize;
131    let rl = ((((nt + z * sigma) / 2.0).round_ties_even() as i64) - 1).max(0) as usize;
132    Ok(RobustLine { slope, intercept, low_slope: slopes[rl.min(slopes.len() - 1)], high_slope: slopes[ru] })
133}
134// ANCHOR_END: theilslopes
135
136/// Siegel's repeated-medians line (SciPy's `siegelslopes` with `method='hierarchical'`): for each
137/// point the median slope to every other point with a different `x`, the slope is the median of
138/// those, and the intercept the median of `yᵢ − slope · xᵢ`. Breakdown point 50 %.
139pub fn siegelslopes(y: &[f64], x: &[f64]) -> Result<RobustLine, ErrorsJSL> {
140    check(x, y, 2)?;
141    let n = x.len();
142    let mut medians = Vec::with_capacity(n);
143    for j in 0..n {
144        let mut s: Vec<f64> = (0..n).filter(|&i| x[i] != x[j]).map(|i| (y[j] - y[i]) / (x[j] - x[i])).collect();
145        if !s.is_empty() {
146            medians.push(median_of(&mut s));
147        }
148    }
149    if medians.is_empty() {
150        return Err(ErrorsJSL::InvalidInputRange("all x values are identical"));
151    }
152    let slope = median_of(&mut medians);
153    let mut r: Vec<f64> = x.iter().zip(y).map(|(a, b)| b - slope * a).collect();
154    Ok(RobustLine { slope, intercept: median_of(&mut r), low_slope: f64::NAN, high_slope: f64::NAN })
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn exact_line() {
163        let x = [0.0, 1.0, 2.0, 3.0, 4.0];
164        let y: Vec<f64> = x.iter().map(|v| 2.0 * v - 1.0).collect();
165        let r = linregress(&x, &y).unwrap();
166        assert!((r.slope - 2.0).abs() < 1e-15 && (r.intercept + 1.0).abs() < 1e-15 && (r.rvalue - 1.0).abs() < 1e-15);
167        let t = theilslopes(&y, &x, 0.95).unwrap();
168        assert_eq!((t.slope, t.intercept), (2.0, -1.0));
169        let s = siegelslopes(&y, &x).unwrap();
170        assert_eq!((s.slope, s.intercept), (2.0, -1.0));
171    }
172
173    #[test]
174    fn robust_lines_ignore_outliers() {
175        let x: Vec<f64> = (0..20).map(|i| i as f64).collect();
176        let mut y: Vec<f64> = x.iter().map(|v| 0.5 * v + 3.0).collect();
177        y[3] = 100.0;
178        y[17] = -50.0;
179        assert!((theilslopes(&y, &x, 0.95).unwrap().slope - 0.5).abs() < 1e-12);
180        assert!((siegelslopes(&y, &x).unwrap().slope - 0.5).abs() < 1e-12);
181        assert!((linregress(&x, &y).unwrap().slope - 0.5).abs() > 0.5);
182    }
183}