Skip to main content

lib_jsl_machine_learning/supervised/classification/
phylogenetic_trees.rs

1//! Phylogenetic tree construction from a distance matrix: UPGMA and neighbor joining.
2//!
3//! See the book entry [Hierarchical clustering and phylogenetic trees](https://jwkunz.github.io/lib_jsl/book/unsupervised/hierarchical.html#neighbour-joining).
4
5use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
6
7/// A weighted tree over `leaves` labelled leaves (ids `0..leaves`) and internal nodes (ids
8/// `leaves..`). UPGMA trees are rooted; neighbour-joining trees are unrooted and are drawn rooted
9/// at the final join for printing.
10#[derive(Debug, Clone, PartialEq)]
11pub struct PhylogeneticTree {
12    pub labels: Vec<String>,
13    /// Undirected edges `(a, b, length)`.
14    pub edges: Vec<(usize, usize, f64)>,
15    /// The root node, for rooted (UPGMA) trees.
16    pub root: Option<usize>,
17    nodes: usize,
18}
19
20fn validate(distances: VR2D, labels: &[&str]) -> Result<usize, ErrorsJSL> {
21    let n = distances.nrows();
22    if n < 2 || distances.ncols() != n || labels.len() != n {
23        return Err(ErrorsJSL::IncompatibleArraySizes((n, labels.len())));
24    }
25    for i in 0..n {
26        if distances[[i, i]].abs() > 1e-12 {
27            return Err(ErrorsJSL::InvalidInputRange("The distance matrix must have a zero diagonal."));
28        }
29        for j in 0..n {
30            if !distances[[i, j]].is_finite() || distances[[i, j]] < 0.0 || (distances[[i, j]] - distances[[j, i]]).abs() > 1e-9 * (1.0 + distances[[i, j]].abs()) {
31                return Err(ErrorsJSL::InvalidInputRange("Distances must be finite, non-negative and symmetric."));
32            }
33        }
34    }
35    Ok(n)
36}
37
38impl PhylogeneticTree {
39    pub fn leaves(&self) -> usize {
40        self.labels.len()
41    }
42
43    pub fn nodes(&self) -> usize {
44        self.nodes
45    }
46
47    fn adjacency(&self) -> Vec<Vec<(usize, f64)>> {
48        let mut adj = vec![Vec::new(); self.nodes];
49        for &(a, b, w) in &self.edges {
50            adj[a].push((b, w));
51            adj[b].push((a, w));
52        }
53        adj
54    }
55
56    /// The path-length (patristic) distance between every pair of leaves along the tree.
57    pub fn patristic_distances(&self) -> R2D {
58        let n = self.leaves();
59        let adj = self.adjacency();
60        let mut out = R2D::zeros((n, n));
61        for s in 0..n {
62            let mut dist = vec![f64::NAN; self.nodes];
63            dist[s] = 0.0;
64            let mut stack = vec![s];
65            while let Some(u) = stack.pop() {
66                for &(v, w) in &adj[u] {
67                    if dist[v].is_nan() {
68                        dist[v] = dist[u] + w;
69                        stack.push(v);
70                    }
71                }
72            }
73            for t in 0..n {
74                out[[s, t]] = dist[t];
75            }
76        }
77        out
78    }
79
80    /// The tree in Newick format, e.g. `((A:1.00000,B:1.00000):0.50000,C:1.50000);`.
81    pub fn to_newick(&self) -> String {
82        let adj = self.adjacency();
83        let root = self.root.unwrap_or(self.nodes - 1);
84        fn go(u: usize, parent: Option<usize>, adj: &[Vec<(usize, f64)>], t: &PhylogeneticTree, length: Option<f64>) -> String {
85            let kids: Vec<(usize, f64)> = adj[u].iter().copied().filter(|&(v, _)| Some(v) != parent).collect();
86            let name = if u < t.leaves() { t.labels[u].clone() } else { String::new() };
87            let body = if kids.is_empty() { name } else { format!("({})", kids.iter().map(|&(v, w)| go(v, Some(u), adj, t, Some(w))).collect::<Vec<_>>().join(",")) };
88            match length {
89                Some(w) => format!("{body}:{w:.5}"),
90                None => body,
91            }
92        }
93        format!("{};", go(root, None, &adj, self, None))
94    }
95
96    /// For rooted trees: the distance from the root to every leaf (equal for an ultrametric tree).
97    pub fn root_to_leaf_distances(&self) -> Option<Vec<f64>> {
98        let root = self.root?;
99        let adj = self.adjacency();
100        let mut dist = vec![f64::NAN; self.nodes];
101        dist[root] = 0.0;
102        let mut stack = vec![root];
103        while let Some(u) = stack.pop() {
104            for &(v, w) in &adj[u] {
105                if dist[v].is_nan() {
106                    dist[v] = dist[u] + w;
107                    stack.push(v);
108                }
109            }
110        }
111        Some(dist[..self.leaves()].to_vec())
112    }
113}
114
115/// UPGMA (unweighted pair group method with arithmetic mean): repeatedly merges the two closest
116/// clusters, placing the new node at half their distance, and averages distances weighted by
117/// cluster size. Assumes a constant evolutionary rate (a molecular clock) and returns a rooted,
118/// ultrametric tree; it is exact when the input is ultrametric.
119#[allow(clippy::needless_range_loop)]
120pub fn upgma(distances: VR2D, labels: &[&str]) -> Result<PhylogeneticTree, ErrorsJSL> {
121    let n = validate(distances, labels)?;
122    let mut d: Vec<Vec<f64>> = distances.rows().into_iter().map(|r| r.to_vec()).collect();
123    let mut active: Vec<usize> = (0..n).collect(); // node ids of the current clusters
124    let mut size = vec![1.0; n];
125    let mut height = vec![0.0; n];
126    let mut edges = Vec::new();
127    let mut next = n;
128    while active.len() > 1 {
129        let (mut bi, mut bj, mut best) = (0, 1, f64::INFINITY);
130        for a in 0..active.len() {
131            for b in a + 1..active.len() {
132                if d[a][b] < best {
133                    (bi, bj, best) = (a, b, d[a][b]);
134                }
135            }
136        }
137        let (ni, nj) = (active[bi], active[bj]);
138        let h = best / 2.0;
139        edges.push((next, ni, h - height[ni]));
140        edges.push((next, nj, h - height[nj]));
141        let (si, sj) = (size[ni], size[nj]);
142        let merged: Vec<f64> = (0..active.len()).map(|k| (d[bi][k] * si + d[bj][k] * sj) / (si + sj)).collect();
143        // Replace row/column bi by the merged cluster, drop bj.
144        for k in 0..active.len() {
145            d[bi][k] = merged[k];
146            d[k][bi] = merged[k];
147        }
148        d[bi][bi] = 0.0;
149        d.remove(bj);
150        d.iter_mut().for_each(|r| {
151            r.remove(bj);
152        });
153        active.remove(bj);
154        size.push(si + sj);
155        height.push(h);
156        active[bi] = next;
157        next += 1;
158    }
159    Ok(PhylogeneticTree { labels: labels.iter().map(|s| s.to_string()).collect(), edges, root: Some(next - 1), nodes: next })
160}
161
162/// Neighbour joining (Saitou and Nei): repeatedly joins the pair that minimises the total tree
163/// length, using the net divergence of each taxon to correct for unequal rates. Returns an
164/// unrooted tree and recovers the true tree exactly from additive distances.
165#[allow(clippy::needless_range_loop)]
166pub fn neighbor_joining(distances: VR2D, labels: &[&str]) -> Result<PhylogeneticTree, ErrorsJSL> {
167    let n = validate(distances, labels)?;
168    let mut d: Vec<Vec<f64>> = distances.rows().into_iter().map(|r| r.to_vec()).collect();
169    let mut active: Vec<usize> = (0..n).collect();
170    let mut edges = Vec::new();
171    let mut next = n;
172    // ANCHOR: neighbor_joining
173    while active.len() > 2 {
174        let m = active.len();
175        let r: Vec<f64> = (0..m).map(|i| (0..m).map(|j| d[i][j]).sum()).collect();
176        let (mut bi, mut bj, mut best) = (0, 1, f64::INFINITY);
177        for i in 0..m {
178            for j in i + 1..m {
179                let q = (m as f64 - 2.0) * d[i][j] - r[i] - r[j];
180                if q < best {
181                    (bi, bj, best) = (i, j, q);
182                }
183            }
184        }
185        let li = 0.5 * d[bi][bj] + (r[bi] - r[bj]) / (2.0 * (m as f64 - 2.0));
186        let lj = d[bi][bj] - li;
187        edges.push((next, active[bi], li));
188        edges.push((next, active[bj], lj));
189        let merged: Vec<f64> = (0..m).map(|k| 0.5 * (d[bi][k] + d[bj][k] - d[bi][bj])).collect();
190        for k in 0..m {
191            d[bi][k] = merged[k];
192            d[k][bi] = merged[k];
193        }
194        d[bi][bi] = 0.0;
195        d.remove(bj);
196        d.iter_mut().for_each(|row| {
197            row.remove(bj);
198        });
199        active.remove(bj);
200        active[bi] = next;
201        next += 1;
202    }
203    edges.push((active[0], active[1], d[0][1]));
204    // ANCHOR_END: neighbor_joining
205    Ok(PhylogeneticTree { labels: labels.iter().map(|s| s.to_string()).collect(), edges, root: None, nodes: next })
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211    use ndarray::arr2;
212
213    fn close(a: &R2D, b: &R2D, tol: f64) -> bool {
214        a.dim() == b.dim() && a.iter().zip(b.iter()).all(|(x, y)| (x - y).abs() < tol)
215    }
216
217    #[test]
218    fn upgma_recovers_an_ultrametric_tree() {
219        // ((A,B),C) with A-B = 2, others 6: heights 1 and 3.
220        let d = arr2(&[[0.0, 2.0, 6.0], [2.0, 0.0, 6.0], [6.0, 6.0, 0.0]]);
221        let t = upgma(d.view(), &["A", "B", "C"]).unwrap();
222        assert!(close(&t.patristic_distances(), &d, 1e-12));
223        assert_eq!(t.to_newick(), "((A:1.00000,B:1.00000):2.00000,C:3.00000);");
224        let heights = t.root_to_leaf_distances().unwrap();
225        assert!(heights.iter().all(|h| (h - 3.0).abs() < 1e-12));
226    }
227
228    #[test]
229    fn neighbor_joining_recovers_additive_distances_exactly() {
230        // Known additive tree: leaves a..e on a caterpillar with unequal branch lengths.
231        let d = arr2(&[
232            [0.0, 5.0, 9.0, 9.0, 8.0],
233            [5.0, 0.0, 10.0, 10.0, 9.0],
234            [9.0, 10.0, 0.0, 8.0, 7.0],
235            [9.0, 10.0, 8.0, 0.0, 3.0],
236            [8.0, 9.0, 7.0, 3.0, 0.0],
237        ]); // the textbook (Saitou-Nei / Wikipedia) example
238        let t = neighbor_joining(d.view(), &["a", "b", "c", "d", "e"]).unwrap();
239        assert!(close(&t.patristic_distances(), &d, 1e-9));
240        assert_eq!(t.edges.len(), 2 * 5 - 3); // unrooted binary tree on 5 leaves
241        assert!(t.edges.iter().all(|e| e.2 > -1e-9));
242        assert!(t.root.is_none());
243        // Cherries (a,b) and (d,e) must be sister groups.
244        let newick = t.to_newick();
245        assert!(newick.contains('a') && newick.ends_with(';'));
246    }
247
248    #[test]
249    fn nj_beats_upgma_when_rates_differ() {
250        // Additive but strongly non-clock-like: A has a very long branch.
251        let d = arr2(&[[0.0, 11.0, 12.0, 13.0], [11.0, 0.0, 3.0, 4.0], [12.0, 3.0, 0.0, 3.0], [13.0, 4.0, 3.0, 0.0]]);
252        let labels = ["A", "B", "C", "D"];
253        let nj = neighbor_joining(d.view(), &labels).unwrap();
254        let up = upgma(d.view(), &labels).unwrap();
255        let err = |t: &PhylogeneticTree| t.patristic_distances().iter().zip(d.iter()).map(|(a, b)| (a - b).abs()).sum::<f64>();
256        assert!(err(&nj) < 1e-9 && err(&up) > 1.0);
257    }
258
259    #[test]
260    fn two_taxa_and_validation() {
261        let d = arr2(&[[0.0, 4.0], [4.0, 0.0]]);
262        let nj = neighbor_joining(d.view(), &["x", "y"]).unwrap();
263        assert_eq!(nj.edges, vec![(0, 1, 4.0)]);
264        let up = upgma(d.view(), &["x", "y"]).unwrap();
265        assert_eq!(up.to_newick(), "(x:2.00000,y:2.00000);");
266        assert!(upgma(arr2(&[[0.0]]).view(), &["x"]).is_err());
267        assert!(upgma(d.view(), &["x"]).is_err());
268        assert!(neighbor_joining(arr2(&[[0.0, 1.0], [2.0, 0.0]]).view(), &["x", "y"]).is_err());
269        assert!(neighbor_joining(arr2(&[[1.0, 1.0], [1.0, 0.0]]).view(), &["x", "y"]).is_err());
270        assert!(neighbor_joining(arr2(&[[0.0, -1.0], [-1.0, 0.0]]).view(), &["x", "y"]).is_err());
271    }
272}