Skip to main content

lib_jsl_statistics/
correlation.rs

1//! Covariance and correlation: Pearson, Spearman and Kendall.
2//!
3//! See the book entry [Correlation and covariance](https://jwkunz.github.io/lib_jsl/book/statistics/correlation.html).
4
5use crate::descriptive::mean;
6use lib_jsl_core::ErrorsJSL;
7use lib_jsl_special_functions::{normal_cdf, student_t_cdf};
8
9fn paired(x: &[f64], y: &[f64], minimum: usize) -> Result<(), ErrorsJSL> {
10    if x.len() != y.len() {
11        return Err(ErrorsJSL::IncompatibleArraySizes((x.len(), y.len())));
12    }
13    if x.len() < minimum {
14        return Err(ErrorsJSL::InvalidInputRange("Too few paired observations."));
15    }
16    Ok(())
17}
18
19/// The covariance `Σ(x − x̄)(y − ȳ) / (n − ddof)`.
20pub fn covariance(x: &[f64], y: &[f64], ddof: usize) -> Result<f64, ErrorsJSL> {
21    paired(x, y, ddof + 1)?;
22    let (mx, my) = (mean(x)?, mean(y)?);
23    Ok(x.iter().zip(y).map(|(a, b)| (a - mx) * (b - my)).sum::<f64>() / (x.len() - ddof) as f64)
24}
25
26/// A correlation coefficient with its two-sided p-value for the null hypothesis of no
27/// association.
28#[derive(Debug, Clone, Copy, PartialEq)]
29pub struct Correlation {
30    pub coefficient: f64,
31    pub p_value: f64,
32}
33
34fn t_test_of_r(r: f64, n: usize) -> f64 {
35    if n <= 2 {
36        return f64::NAN;
37    }
38    if r.abs() >= 1.0 {
39        return 0.0;
40    }
41    let df = (n - 2) as f64;
42    let t = r * (df / (1.0 - r * r)).sqrt();
43    2.0 * student_t_cdf(-t.abs(), df)
44}
45
46/// Pearson's product-moment correlation, with the p-value from `t = r √((n−2)/(1−r²))` on
47/// `n − 2` degrees of freedom (exact for bivariate normal data).
48pub fn pearson(x: &[f64], y: &[f64]) -> Result<Correlation, ErrorsJSL> {
49    paired(x, y, 2)?;
50    let (mx, my) = (mean(x)?, mean(y)?);
51    let (mut sxy, mut sxx, mut syy) = (0.0, 0.0, 0.0);
52    for (a, b) in x.iter().zip(y) {
53        sxy += (a - mx) * (b - my);
54        sxx += (a - mx) * (a - mx);
55        syy += (b - my) * (b - my);
56    }
57    if sxx == 0.0 || syy == 0.0 {
58        return Err(ErrorsJSL::InvalidInputRange("Correlation is undefined for a constant sample."));
59    }
60    let r = (sxy / (sxx * syy).sqrt()).clamp(-1.0, 1.0);
61    Ok(Correlation { coefficient: r, p_value: t_test_of_r(r, x.len()) })
62}
63
64/// Ranks starting at 1, with tied values given the average of their ranks.
65pub fn rank(x: &[f64]) -> Vec<f64> {
66    let mut order: Vec<usize> = (0..x.len()).collect();
67    order.sort_by(|&a, &b| x[a].total_cmp(&x[b]));
68    let mut ranks = vec![0.0; x.len()];
69    let mut i = 0;
70    while i < order.len() {
71        let mut j = i;
72        while j + 1 < order.len() && x[order[j + 1]] == x[order[i]] {
73            j += 1;
74        }
75        let average = (i + j) as f64 / 2.0 + 1.0;
76        for k in i..=j {
77            ranks[order[k]] = average;
78        }
79        i = j + 1;
80    }
81    ranks
82}
83
84/// Spearman's rank correlation (Pearson's on average ranks), with the same t approximation for
85/// the p-value. Measures any monotone association.
86pub fn spearman(x: &[f64], y: &[f64]) -> Result<Correlation, ErrorsJSL> {
87    paired(x, y, 2)?;
88    let r = pearson(&rank(x), &rank(y))?.coefficient;
89    Ok(Correlation { coefficient: r, p_value: t_test_of_r(r, x.len()) })
90}
91
92// ANCHOR: kendall
93/// Kendall's τ_b, `(C − D) / √((n₀ − n₁)(n₀ − n₂))` over concordant and discordant pairs with
94/// tie corrections, and a two-sided p-value from the normal approximation to `S = C − D` with
95/// the tie-corrected variance. `O(n²)`.
96pub fn kendall(x: &[f64], y: &[f64]) -> Result<Correlation, ErrorsJSL> {
97    paired(x, y, 2)?;
98    let n = x.len();
99    let mut s: i64 = 0;
100    for i in 0..n {
101        for j in i + 1..n {
102            let product = (x[i] - x[j]).signum() * (y[i] - y[j]).signum();
103            if x[i] != x[j] && y[i] != y[j] {
104                s += product as i64;
105            }
106        }
107    }
108    // Tie groups of each variable.
109    let groups = |v: &[f64]| -> Vec<f64> {
110        let mut sorted = v.to_vec();
111        sorted.sort_by(f64::total_cmp);
112        let mut out = Vec::new();
113        let mut i = 0;
114        while i < sorted.len() {
115            let mut j = i;
116            while j + 1 < sorted.len() && sorted[j + 1] == sorted[i] {
117                j += 1;
118            }
119            if j > i {
120                out.push((j - i + 1) as f64);
121            }
122            i = j + 1;
123        }
124        out
125    };
126    let (tx, ty) = (groups(x), groups(y));
127    let nf = n as f64;
128    let n0 = nf * (nf - 1.0) / 2.0;
129    let n1: f64 = tx.iter().map(|t| t * (t - 1.0) / 2.0).sum();
130    let n2: f64 = ty.iter().map(|t| t * (t - 1.0) / 2.0).sum();
131    let denominator = ((n0 - n1) * (n0 - n2)).sqrt();
132    if denominator == 0.0 {
133        return Err(ErrorsJSL::InvalidInputRange("Correlation is undefined for a constant sample."));
134    }
135    let tau = s as f64 / denominator;
136    let sum = |g: &[f64], f: &dyn Fn(f64) -> f64| g.iter().map(|&t| f(t)).sum::<f64>();
137    let v0 = nf * (nf - 1.0) * (2.0 * nf + 5.0);
138    let vt = sum(&tx, &|t| t * (t - 1.0) * (2.0 * t + 5.0));
139    let vu = sum(&ty, &|t| t * (t - 1.0) * (2.0 * t + 5.0));
140    let v1 = sum(&tx, &|t| t * (t - 1.0)) * sum(&ty, &|t| t * (t - 1.0)) / (2.0 * nf * (nf - 1.0));
141    let v2 = if n > 2 { sum(&tx, &|t| t * (t - 1.0) * (t - 2.0)) * sum(&ty, &|t| t * (t - 1.0) * (t - 2.0)) / (9.0 * nf * (nf - 1.0) * (nf - 2.0)) } else { 0.0 };
142    let variance = (v0 - vt - vu) / 18.0 + v1 + v2;
143    let z = s as f64 / variance.sqrt();
144    Ok(Correlation { coefficient: tau, p_value: 2.0 * normal_cdf(-z.abs(), 0.0, 1.0) })
145}
146// ANCHOR_END: kendall
147
148/// The covariance matrix of the columns `variables[k]` (each a sample of one variable).
149pub fn covariance_matrix(variables: &[Vec<f64>], ddof: usize) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
150    let k = variables.len();
151    let mut out = vec![vec![0.0; k]; k];
152    for i in 0..k {
153        for j in i..k {
154            let c = covariance(&variables[i], &variables[j], ddof)?;
155            out[i][j] = c;
156            out[j][i] = c;
157        }
158    }
159    Ok(out)
160}
161
162/// The Pearson correlation matrix of the columns `variables[k]`.
163pub fn correlation_matrix(variables: &[Vec<f64>]) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
164    let c = covariance_matrix(variables, 1)?;
165    let k = c.len();
166    Ok((0..k).map(|i| (0..k).map(|j| if i == j { 1.0 } else { c[i][j] / (c[i][i] * c[j][j]).sqrt() }).collect()).collect())
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    #[test]
174    fn pearson_on_anscombes_first_set() {
175        let x = [10.0, 8.0, 13.0, 9.0, 11.0, 14.0, 6.0, 4.0, 12.0, 7.0, 5.0];
176        let y = [8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68];
177        let r = pearson(&x, &y).unwrap();
178        assert!((r.coefficient - 0.816_420_516).abs() < 1e-8);
179        assert!((r.p_value - 0.002_169_6).abs() < 2e-6, "{}", r.p_value);
180        assert!((covariance(&x, &y, 1).unwrap() - 5.501).abs() < 1e-3);
181        assert_eq!(pearson(&[1.0, 2.0, 3.0], &[2.0, 4.0, 6.0]).unwrap().coefficient, 1.0);
182        assert!(pearson(&[1.0, 1.0], &[1.0, 2.0]).is_err() && pearson(&[1.0], &[1.0, 2.0]).is_err());
183    }
184
185    #[test]
186    fn rank_correlations() {
187        assert_eq!(rank(&[3.0, 1.0, 4.0, 1.0, 5.0]), vec![3.0, 1.5, 4.0, 1.5, 5.0]);
188        // Monotone but nonlinear: Spearman sees perfect association, Pearson does not.
189        let x: Vec<f64> = (1..=10).map(|v| v as f64).collect();
190        let y: Vec<f64> = x.iter().map(|v| v.powi(5)).collect();
191        assert_eq!(spearman(&x, &y).unwrap().coefficient, 1.0);
192        assert!(pearson(&x, &y).unwrap().coefficient < 0.9);
193        // Kendall: C = 6, D = 4 of 10 pairs.
194        let k = kendall(&[1.0, 2.0, 3.0, 4.0, 5.0], &[3.0, 4.0, 1.0, 2.0, 5.0]).unwrap();
195        assert!((k.coefficient - 0.2).abs() < 1e-15);
196        // Ties: τ_b uses the corrected denominator.
197        let t = kendall(&[1.0, 1.0, 2.0, 3.0], &[1.0, 2.0, 2.0, 3.0]).unwrap();
198        assert!((t.coefficient - 4.0 / 5.0).abs() < 1e-12, "{}", t.coefficient);
199        let m = correlation_matrix(&[x.clone(), y.clone(), x.iter().map(|v| -v).collect()]).unwrap();
200        assert!((m[0][2] + 1.0).abs() < 1e-12 && m[1][1] == 1.0 && (m[0][1] - m[1][0]).abs() < 1e-15);
201    }
202}