Skip to main content

lib_jsl_statistics/
distance.rs

1//! Distances between observations, following `scipy.spatial.distance`: the standard metrics, the
2//! condensed pairwise distances of one set (`pdist`), the distances between two sets (`cdist`),
3//! and conversion between condensed and square forms (`squareform`).
4//!
5//! See the book entry [More descriptive statistics and robust regression](https://jwkunz.github.io/lib_jsl/book/statistics/robust-regression.html#distances).
6
7use lib_jsl_core::ErrorsJSL;
8
9/// A distance between two vectors `u` and `v`.
10#[derive(Clone, Debug, PartialEq)]
11pub enum Metric {
12    /// `‖u − v‖₂`.
13    Euclidean,
14    /// `‖u − v‖₂²`.
15    SqEuclidean,
16    /// `Σ |uᵢ − vᵢ|` (Manhattan).
17    Cityblock,
18    /// `max |uᵢ − vᵢ|`.
19    Chebyshev,
20    /// `(Σ |uᵢ − vᵢ|^p)^{1/p}`, `p ≥ 1`.
21    Minkowski(f64),
22    /// `√(Σ (uᵢ − vᵢ)² / Vᵢ)`, with given component variances `V`.
23    SEuclidean(Vec<f64>),
24    /// `√((u − v)ᵀ VI (u − v))`, with the inverse covariance matrix `VI` (rows).
25    Mahalanobis(Vec<Vec<f64>>),
26    /// `1 − u·v / (‖u‖ ‖v‖)`.
27    Cosine,
28    /// `1 −` the Pearson correlation of `u` and `v`.
29    Correlation,
30    /// `Σ |uᵢ − vᵢ| / (|uᵢ| + |vᵢ|)`, terms with `0/0` omitted.
31    Canberra,
32    /// `Σ |uᵢ − vᵢ| / Σ |uᵢ + vᵢ|`.
33    BrayCurtis,
34    /// The fraction of components that differ.
35    Hamming,
36    /// Treating the vectors as booleans (non-zero or not), the fraction of components where
37    /// exactly one is non-zero among those where either is (SciPy converts to booleans too).
38    Jaccard,
39}
40
41// ANCHOR: distance
42/// The distance between `u` and `v` under `metric` (SciPy's functions in `spatial.distance`).
43pub fn distance(u: &[f64], v: &[f64], metric: &Metric) -> f64 {
44    let diffs = u.iter().zip(v).map(|(a, b)| a - b);
45    match metric {
46        Metric::Euclidean => diffs.map(|d| d * d).sum::<f64>().sqrt(),
47        Metric::SqEuclidean => diffs.map(|d| d * d).sum(),
48        Metric::Cityblock => diffs.map(f64::abs).sum(),
49        Metric::Chebyshev => diffs.map(f64::abs).fold(0.0, f64::max),
50        Metric::Minkowski(p) => diffs.map(|d| d.abs().powf(*p)).sum::<f64>().powf(1.0 / p),
51        Metric::SEuclidean(var) => diffs.zip(var).map(|(d, s)| d * d / s).sum::<f64>().sqrt(),
52        Metric::Mahalanobis(vi) => {
53            let d: Vec<f64> = diffs.collect();
54            vi.iter().zip(&d).map(|(row, di)| di * row.iter().zip(&d).map(|(a, b)| a * b).sum::<f64>()).sum::<f64>().sqrt()
55        }
56        Metric::Cosine => {
57            let (uv, uu, vv) = u.iter().zip(v).fold((0.0, 0.0, 0.0), |(p, q, r), (a, b)| (p + a * b, q + a * a, r + b * b));
58            (1.0 - uv / (uu * vv).sqrt()).max(0.0)
59        }
60        Metric::Correlation => {
61            let n = u.len() as f64;
62            let (mu, mv) = (u.iter().sum::<f64>() / n, v.iter().sum::<f64>() / n);
63            let (uv, uu, vv) = u.iter().zip(v).fold((0.0, 0.0, 0.0), |(p, q, r), (a, b)| {
64                let (x, y) = (a - mu, b - mv);
65                (p + x * y, q + x * x, r + y * y)
66            });
67            (1.0 - uv / (uu * vv).sqrt()).max(0.0)
68        }
69        Metric::Canberra => u.iter().zip(v).map(|(a, b)| {
70            let den = a.abs() + b.abs();
71            if den == 0.0 { 0.0 } else { (a - b).abs() / den }
72        }).sum(),
73        Metric::BrayCurtis => {
74            let (num, den) = u.iter().zip(v).fold((0.0, 0.0), |(p, q), (a, b)| (p + (a - b).abs(), q + (a + b).abs()));
75            num / den
76        }
77        Metric::Hamming => u.iter().zip(v).filter(|(a, b)| a != b).count() as f64 / u.len() as f64,
78        Metric::Jaccard => {
79            let (mut differ, mut nonzero) = (0usize, 0usize);
80            for (a, b) in u.iter().zip(v) {
81                let (p, q) = (*a != 0.0, *b != 0.0);
82                if p || q {
83                    nonzero += 1;
84                    if p != q {
85                        differ += 1;
86                    }
87                }
88            }
89            if nonzero == 0 { 0.0 } else { differ as f64 / nonzero as f64 }
90        }
91    }
92}
93// ANCHOR_END: distance
94
95fn check_rows(rows: &[Vec<f64>]) -> Result<usize, ErrorsJSL> {
96    let d = rows.first().map_or(0, |r| r.len());
97    if rows.iter().any(|r| r.len() != d) {
98        return Err(ErrorsJSL::InvalidInputRange("all observations must have the same length"));
99    }
100    Ok(d)
101}
102
103/// The condensed distance matrix of `m` observations (SciPy's `pdist`): the `m(m − 1)/2`
104/// distances `d(i, j)` for `i < j`, in row order.
105pub fn pdist(points: &[Vec<f64>], metric: &Metric) -> Result<Vec<f64>, ErrorsJSL> {
106    check_rows(points)?;
107    let m = points.len();
108    let mut out = Vec::with_capacity(m * m.saturating_sub(1) / 2);
109    for i in 0..m {
110        for j in i + 1..m {
111            out.push(distance(&points[i], &points[j], metric));
112        }
113    }
114    Ok(out)
115}
116
117/// The `ma × mb` matrix of distances between two sets of observations (SciPy's `cdist`).
118pub fn cdist(a: &[Vec<f64>], b: &[Vec<f64>], metric: &Metric) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
119    let (da, db) = (check_rows(a)?, check_rows(b)?);
120    if !a.is_empty() && !b.is_empty() && da != db {
121        return Err(ErrorsJSL::InvalidInputRange("the two sets must have the same dimension"));
122    }
123    Ok(a.iter().map(|u| b.iter().map(|v| distance(u, v, metric)).collect()).collect())
124}
125
126// ANCHOR: squareform
127/// Expands a condensed distance vector into the symmetric square matrix with a zero diagonal
128/// (SciPy's `squareform`). Its length must be `m(m − 1)/2` for some `m`.
129pub fn squareform(condensed: &[f64]) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
130    let len = condensed.len();
131    let m = ((1.0 + (1.0 + 8.0 * len as f64).sqrt()) / 2.0).round() as usize;
132    if m * (m - 1) / 2 != len {
133        return Err(ErrorsJSL::InvalidInputRange("the length is not m(m − 1)/2 for any m"));
134    }
135    // Entry (i, j), i < j, sits at position i·m − i(i + 1)/2 + (j − i − 1) of the condensed form.
136    let index = |i: usize, j: usize| i * m - i * (i + 1) / 2 + (j - i - 1);
137    Ok((0..m).map(|i| (0..m).map(|j| match i.cmp(&j) {
138        std::cmp::Ordering::Less => condensed[index(i, j)],
139        std::cmp::Ordering::Greater => condensed[index(j, i)],
140        std::cmp::Ordering::Equal => 0.0,
141    }).collect()).collect())
142}
143// ANCHOR_END: squareform
144
145/// The condensed form of a square distance matrix (SciPy's `squareform` in the other direction):
146/// its entries above the diagonal, in row order. The matrix must be square and symmetric with a
147/// zero diagonal.
148pub fn squareform_to_condensed(matrix: &[Vec<f64>]) -> Result<Vec<f64>, ErrorsJSL> {
149    let m = matrix.len();
150    if matrix.iter().any(|r| r.len() != m) {
151        return Err(ErrorsJSL::InvalidInputRange("the matrix must be square"));
152    }
153    let mut out = Vec::with_capacity(m * m.saturating_sub(1) / 2);
154    for (i, row) in matrix.iter().enumerate() {
155        if row[i] != 0.0 {
156            return Err(ErrorsJSL::InvalidInputRange("the diagonal must be zero"));
157        }
158        for (j, &value) in row.iter().enumerate().skip(i + 1) {
159            if value != matrix[j][i] {
160                return Err(ErrorsJSL::InvalidInputRange("the matrix must be symmetric"));
161            }
162            out.push(value);
163        }
164    }
165    Ok(out)
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    #[test]
173    fn metrics_on_a_simple_pair() {
174        let (u, v) = ([1.0, 0.0, 2.0], [0.0, 1.0, 2.0]);
175        assert!((distance(&u, &v, &Metric::Euclidean) - 2f64.sqrt()).abs() < 1e-15);
176        assert_eq!(distance(&u, &v, &Metric::Cityblock), 2.0);
177        assert_eq!(distance(&u, &v, &Metric::Chebyshev), 1.0);
178        assert!((distance(&u, &v, &Metric::Cosine) - 0.2).abs() < 1e-15);
179        assert!((distance(&u, &v, &Metric::Hamming) - 2.0 / 3.0).abs() < 1e-15);
180        assert!((distance(&u, &v, &Metric::Jaccard) - 2.0 / 3.0).abs() < 1e-15);
181        // Values that differ but are both non-zero count as equal booleans.
182        assert_eq!(distance(&[1.0, 2.0, 0.0], &[3.0, 2.0, 0.0], &Metric::Jaccard), 0.0);
183        assert_eq!(distance(&u, &v, &Metric::Canberra), 2.0);
184        assert!((distance(&u, &v, &Metric::Minkowski(3.0)) - 2f64.powf(1.0 / 3.0)).abs() < 1e-15);
185        let id = vec![vec![1.0, 0.0, 0.0], vec![0.0, 1.0, 0.0], vec![0.0, 0.0, 1.0]];
186        assert!((distance(&u, &v, &Metric::Mahalanobis(id)) - 2f64.sqrt()).abs() < 1e-15);
187    }
188
189    #[test]
190    fn condensed_and_square_forms() {
191        let pts = vec![vec![0.0, 0.0], vec![3.0, 4.0], vec![6.0, 8.0], vec![0.0, 1.0]];
192        let d = pdist(&pts, &Metric::Euclidean).unwrap();
193        assert_eq!(d.len(), 6);
194        assert_eq!(d[0], 5.0);
195        let sq = squareform(&d).unwrap();
196        assert_eq!(sq[2][0], 10.0);
197        assert_eq!(squareform_to_condensed(&sq).unwrap(), d);
198        let c = cdist(&pts, &pts, &Metric::Euclidean).unwrap();
199        assert_eq!(c, sq);
200        assert!(squareform(&[1.0, 2.0]).is_err());
201    }
202}