Skip to main content

ggplot_rs/stat/
hclust.rs

1//! `hclust`: agglomerative hierarchical clustering of a distance matrix — the
2//! leaf order a heatmap's rows and columns follow so that similar items sit
3//! side by side (R's `heatmap()`, `corrplot(order = "hclust")`,
4//! `ggcorrplot(hc.order = TRUE)`), and the merges a dendrogram draws
5//! ([`dendrogram_links`](super::tree::dendrogram_links) takes them as they
6//! are).
7//!
8//! The merges follow R's `hclust` convention: merge `k` (1-based) joins two
9//! children, `-(i + 1)` for item `i` and `m` for merge `m`. Ties merge the
10//! pair found first (lowest indices), so the result is deterministic.
11//!
12//! The leaf order goes one step beyond R's: when two clusters merge, each may
13//! be reversed so that the two leaves that meet are the closest of the four
14//! possible pairs — a cheap leaf-ordering pass that keeps neighbours
15//! across a merge similar too (the heatmap's blocks join smoothly).
16
17/// How the distance between two clusters is measured.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum Linkage {
21    /// The mean distance over all pairs (UPGMA, R's `"average"`).
22    #[default]
23    Average,
24    /// The largest pairwise distance (R's `"complete"`).
25    Complete,
26    /// The smallest pairwise distance (R's `"single"`).
27    Single,
28}
29
30/// The result of [`hclust`].
31#[derive(Clone, Debug, PartialEq)]
32pub struct Hclust {
33    /// One pair of children per merge (see the module docs for the
34    /// numbering), `n - 1` of them.
35    pub merge: Vec<(i64, i64)>,
36    /// The distance each merge happened at, non-decreasing for average,
37    /// complete and single linkage.
38    pub heights: Vec<f64>,
39    /// The items in leaf order (a permutation of `0..n`).
40    pub order: Vec<usize>,
41}
42
43/// Cluster `n` items from their `n × n` distance matrix (symmetric; only the
44/// upper triangle is read). A missing or non-finite distance counts as the
45/// largest finite one; a ragged row's missing entries too. No items: an
46/// empty result; one item: no merges and the order `[0]`.
47pub fn hclust(dist: &[Vec<f64>], linkage: Linkage) -> Hclust {
48    let n = dist.len();
49    let raw = |i: usize, j: usize| {
50        let (a, b) = if i < j { (i, j) } else { (j, i) };
51        dist[a].get(b).copied().filter(|d| d.is_finite())
52    };
53    let worst = (0..n)
54        .flat_map(|i| (i + 1..n).map(move |j| (i, j)))
55        .filter_map(|(i, j)| raw(i, j))
56        .fold(0.0_f64, f64::max);
57    let d = |i: usize, j: usize| raw(i, j).unwrap_or(worst);
58
59    // Active clusters: their id in the merge numbering, size and leaves (in
60    // leaf order), and the current cluster-to-cluster distances.
61    let mut ids: Vec<i64> = (0..n).map(|i| -(i as i64 + 1)).collect();
62    let mut size: Vec<usize> = vec![1; n];
63    let mut leaves: Vec<Vec<usize>> = (0..n).map(|i| vec![i]).collect();
64    let mut alive: Vec<bool> = vec![true; n];
65    let mut cd: Vec<Vec<f64>> = (0..n)
66        .map(|i| (0..n).map(|j| if i == j { 0.0 } else { d(i, j) }).collect())
67        .collect();
68    let mut merge = Vec::with_capacity(n.saturating_sub(1));
69    let mut heights = Vec::with_capacity(n.saturating_sub(1));
70    for k in 1..n {
71        // the closest pair of live clusters, the first found on a tie
72        let mut best: Option<(usize, usize, f64)> = None;
73        for i in 0..n {
74            if !alive[i] {
75                continue;
76            }
77            for j in i + 1..n {
78                if alive[j] && best.is_none_or(|(_, _, b)| cd[i][j] < b) {
79                    best = Some((i, j, cd[i][j]));
80                }
81            }
82        }
83        let Some((a, b, h)) = best else { break };
84        // R lists a singleton before a merge, two singletons by item and two
85        // merges by age
86        let pair = if (ids[a] < 0) == (ids[b] < 0) {
87            if ids[a] < 0 {
88                (ids[a].max(ids[b]), ids[a].min(ids[b]))
89            } else {
90                (ids[a].min(ids[b]), ids[a].max(ids[b]))
91            }
92        } else {
93            (ids[a].min(ids[b]), ids[a].max(ids[b]))
94        };
95        merge.push(pair);
96        heights.push(h);
97        // the leaf order: orient both halves so the leaves that meet are
98        // the closest of the four candidates
99        let (la, lb) = (
100            std::mem::take(&mut leaves[a]),
101            std::mem::take(&mut leaves[b]),
102        );
103        let ends = |l: &[usize]| (l[0], l[l.len() - 1]);
104        let ((a0, a1), (b0, b1)) = (ends(&la), ends(&lb));
105        let options = [
106            (false, false, d(a1, b0)),
107            (false, true, d(a1, b1)),
108            (true, false, d(a0, b0)),
109            (true, true, d(a0, b1)),
110        ];
111        let (ra, rb, _) =
112            options
113                .iter()
114                .copied()
115                .fold(options[0], |acc, o| if o.2 < acc.2 { o } else { acc });
116        let mut joined: Vec<usize> = if ra {
117            la.into_iter().rev().collect()
118        } else {
119            la
120        };
121        if rb {
122            joined.extend(lb.into_iter().rev());
123        } else {
124            joined.extend(lb);
125        }
126        // the new cluster lives on in slot a
127        for x in 0..n {
128            if !alive[x] || x == a || x == b {
129                continue;
130            }
131            let (da, db) = (cd[a][x], cd[b][x]);
132            let v = match linkage {
133                Linkage::Average => {
134                    (da * size[a] as f64 + db * size[b] as f64) / (size[a] + size[b]) as f64
135                }
136                Linkage::Complete => da.max(db),
137                Linkage::Single => da.min(db),
138            };
139            cd[a][x] = v;
140            cd[x][a] = v;
141        }
142        alive[b] = false;
143        size[a] += size[b];
144        ids[a] = k as i64;
145        leaves[a] = joined;
146    }
147    let order = (0..n)
148        .find(|&i| alive[i])
149        .map(|i| leaves[i].clone())
150        .unwrap_or_default();
151    Hclust {
152        merge,
153        heights,
154        order,
155    }
156}
157
158/// The leaf order of `n` items from their `n × n` *similarity* matrix (a
159/// correlation's absolute value, a normalized mutual information): distance
160/// = largest similarity − similarity, average linkage.
161pub fn similarity_order(sim: &[Vec<f64>]) -> Vec<usize> {
162    let n = sim.len();
163    let top = sim
164        .iter()
165        .enumerate()
166        .flat_map(|(i, r)| {
167            r.iter()
168                .enumerate()
169                .filter(move |(j, _)| *j != i)
170                .map(|(_, v)| *v)
171        })
172        .filter(|v| v.is_finite())
173        .fold(f64::NEG_INFINITY, f64::max);
174    let dist: Vec<Vec<f64>> = (0..n)
175        .map(|i| {
176            (0..n)
177                .map(|j| {
178                    let s = sim[i].get(j).copied().unwrap_or(f64::NAN);
179                    if s.is_finite() {
180                        top - s
181                    } else {
182                        f64::NAN
183                    }
184                })
185                .collect()
186        })
187        .collect();
188    hclust(&dist, Linkage::Average).order
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    fn m(rows: &[&[f64]]) -> Vec<Vec<f64>> {
196        rows.iter().map(|r| r.to_vec()).collect()
197    }
198
199    #[test]
200    fn empty_and_single() {
201        assert_eq!(hclust(&[], Linkage::Average).order, Vec::<usize>::new());
202        let one = hclust(&m(&[&[0.0]]), Linkage::Average);
203        assert_eq!(one.order, vec![0]);
204        assert!(one.merge.is_empty());
205    }
206
207    // R: hclust(as.dist(d), "average") on the same matrix
208    #[test]
209    fn merges_and_heights_as_r() {
210        let d = m(&[
211            &[0.0, 2.0, 6.0, 10.0, 9.0],
212            &[2.0, 0.0, 5.0, 9.0, 8.0],
213            &[6.0, 5.0, 0.0, 4.0, 5.0],
214            &[10.0, 9.0, 4.0, 0.0, 3.0],
215            &[9.0, 8.0, 5.0, 3.0, 0.0],
216        ]);
217        let h = hclust(&d, Linkage::Average);
218        assert_eq!(h.merge, vec![(-1, -2), (-4, -5), (-3, 2), (1, 3)]);
219        assert_eq!(h.heights[..3], [2.0, 3.0, 4.5]);
220        // (6 + 10 + 9 + 5 + 9 + 8) / 6
221        assert!((h.heights[3] - 47.0 / 6.0).abs() < 1e-12);
222        // the two blocks side by side, 1 next to 2 and 2 next to 3
223        assert_eq!(h.order, vec![0, 1, 2, 3, 4]);
224    }
225
226    #[test]
227    fn complete_and_single() {
228        let d = m(&[&[0.0, 1.0, 4.0], &[1.0, 0.0, 2.0], &[4.0, 2.0, 0.0]]);
229        assert_eq!(hclust(&d, Linkage::Complete).heights, vec![1.0, 4.0]);
230        assert_eq!(hclust(&d, Linkage::Single).heights, vec![1.0, 2.0]);
231    }
232
233    // shuffled blocks come back together
234    #[test]
235    fn similarity_order_groups_blocks() {
236        // items 0, 2, 4 are one block, 1 and 3 another
237        let s = |i: usize, j: usize| {
238            if i == j {
239                1.0
240            } else if i % 2 == j % 2 {
241                0.8
242            } else {
243                0.1
244            }
245        };
246        let sim: Vec<Vec<f64>> = (0..5).map(|i| (0..5).map(|j| s(i, j)).collect()).collect();
247        let o = similarity_order(&sim);
248        let pos = |x: usize| o.iter().position(|&v| v == x).unwrap();
249        let mut evens = [pos(0), pos(2), pos(4)];
250        evens.sort();
251        assert_eq!(
252            evens[2] - evens[0],
253            2,
254            "the even block is contiguous: {o:?}"
255        );
256    }
257
258    #[test]
259    fn missing_distances_count_as_the_largest() {
260        let d = m(&[
261            &[0.0, f64::NAN, 1.0],
262            &[f64::NAN, 0.0, 3.0],
263            &[1.0, 3.0, 0.0],
264        ]);
265        let h = hclust(&d, Linkage::Single);
266        assert_eq!(h.merge[0], (-1, -3));
267        assert_eq!(h.heights, vec![1.0, 3.0]);
268    }
269}