Skip to main content

lib_jsl_geometry/algorithms/
alignment.rs

1//! Fitting rotations to data, following `scipy.spatial`: the rotation that best aligns two sets
2//! of vectors (`Rotation.align_vectors`, the Kabsch or Wahba problem), the mean of rotations
3//! (`Rotation.mean`), orthogonal Procrustes analysis (`procrustes`, `orthogonal_procrustes`),
4//! and interpolation along great circles (`geometric_slerp`).
5//!
6//! See the book entry [Rotation fitting, Procrustes analysis and Hausdorff distance](https://jwkunz.github.io/lib_jsl/book/geometry/alignment.html).
7
8use super::quaternions::Quaternion;
9use super::rotations::{Matrix3, Rotation3};
10use super::small_svd::{determinant, svd_square};
11use lib_jsl_core::ErrorsJSL;
12
13fn dot3(a: [f64; 3], b: [f64; 3]) -> f64 {
14    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
15}
16
17fn cross3(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
18    [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
19}
20
21fn norm3(a: [f64; 3]) -> f64 {
22    dot3(a, a).sqrt()
23}
24
25/// The result of [`align_vectors`].
26#[derive(Clone, Copy, Debug)]
27#[non_exhaustive]
28pub struct Alignment {
29    /// The rotation `C` with `a ≈ C b`.
30    pub rotation: Rotation3,
31    /// The root of the weighted sum of squared distances `√Σ wᵢ ‖aᵢ − C bᵢ‖²` (without the
32    /// primary pair when its weight is infinite).
33    pub rssd: f64,
34}
35
36// ANCHOR: align_vectors
37/// The rotation `C` minimising `Σ wᵢ ‖aᵢ − C bᵢ‖²` (SciPy's `Rotation.align_vectors`; Wahba's
38/// problem). With `B = Σ wᵢ aᵢ bᵢᵀ = U S Vᵀ`, the answer is `C = U diag(1, 1, det(UVᵀ)) Vᵀ` (Kabsch's
39/// algorithm); the determinant correction keeps it a rotation rather than a reflection. With a
40/// single pair, or one infinite weight, that pair (the primary) is aligned exactly by the
41/// smallest rotation, and the remaining freedom — a rotation about the primary — best aligns
42/// the others.
43pub fn align_vectors(a: &[[f64; 3]], b: &[[f64; 3]], weights: Option<&[f64]>) -> Result<Alignment, ErrorsJSL> {
44    let n = a.len();
45    if n == 0 || b.len() != n {
46        return Err(ErrorsJSL::IncompatibleArraySizes((a.len(), b.len())));
47    }
48    let w: Vec<f64> = match weights {
49        Some(w) if w.len() != n => return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), n))),
50        Some(w) if w.iter().any(|v| v.is_nan() || *v < 0.0) => return Err(ErrorsJSL::InvalidInputRange("align_vectors: weights must be non-negative")),
51        Some(w) => w.to_vec(),
52        None => vec![1.0; n],
53    };
54    let n_inf = w.iter().filter(|v| v.is_infinite()).count();
55    if n_inf > 1 {
56        return Err(ErrorsJSL::InvalidInputRange("align_vectors: only one infinite weight is allowed"));
57    }
58    if n == 1 || n_inf == 1 {
59        let p = if n == 1 { 0 } else { w.iter().position(|v| v.is_infinite()).expect("one infinite weight") };
60        return align_with_primary(a, b, &w, p);
61    }
62    let mut bm = vec![vec![0.0; 3]; 3];
63    for i in 0..n {
64        for r in 0..3 {
65            for c in 0..3 {
66                bm[r][c] += w[i] * a[i][r] * b[i][c];
67            }
68        }
69    }
70    let (mut u, mut s, v) = svd_square(&bm);
71    let uv: Vec<Vec<f64>> = (0..3).map(|r| (0..3).map(|c| (0..3).map(|k| u[r][k] * v[c][k]).sum()).collect()).collect();
72    if determinant(&uv) < 0.0 {
73        s[2] = -s[2];
74        for row in u.iter_mut() {
75            row[2] = -row[2];
76        }
77    }
78    let c: Matrix3 = std::array::from_fn(|r| std::array::from_fn(|col| (0..3).map(|k| u[r][k] * v[col][k]).sum()));
79    let ssd: f64 = (0..n).map(|i| w[i] * (dot3(a[i], a[i]) + dot3(b[i], b[i]))).sum::<f64>() - 2.0 * s.iter().sum::<f64>();
80    Ok(Alignment { rotation: Rotation3::from_matrix(&c), rssd: ssd.max(0.0).sqrt() })
81}
82// ANCHOR_END: align_vectors
83
84/// Align `a[p] ← b[p]` exactly with the smallest rotation, then rotate about `â[p]` by the angle
85/// that best aligns the other pairs.
86fn align_with_primary(a: &[[f64; 3]], b: &[[f64; 3]], w: &[f64], p: usize) -> Result<Alignment, ErrorsJSL> {
87    let (na, nb) = (norm3(a[p]), norm3(b[p]));
88    if na == 0.0 || nb == 0.0 {
89        return Err(ErrorsJSL::InvalidInputRange("align_vectors: cannot align zero-length primary vectors"));
90    }
91    let ap = a[p].map(|v| v / na);
92    let bp = b[p].map(|v| v / nb);
93    let cross = cross3(bp, ap);
94    let primary = if norm3(cross) == 0.0 && dot3(ap, bp) < 0.0 {
95        // Exactly opposite: half a turn about an axis perpendicular to â, as SciPy picks it.
96        let i = (0..3).min_by(|&x, &y| ap[x].abs().total_cmp(&ap[y].abs())).expect("three components");
97        let axis = match i {
98            0 => [0.0, -ap[2], ap[1]],
99            1 => [ap[2], 0.0, -ap[0]],
100            _ => [-ap[1], ap[0], 0.0],
101        };
102        Rotation3::from_axis_angle(axis, std::f64::consts::PI)
103    } else {
104        Rotation3::from_two_vectors(bp, ap)
105    };
106    let (mut sn, mut cs) = (0.0, 0.0);
107    for i in (0..a.len()).filter(|&i| i != p) {
108        let c = primary.rotate(b[i]);
109        sn += w[i] * dot3(cross3(c, a[i]), ap);
110        cs += w[i] * (dot3(c, a[i]) - dot3(c, ap) * dot3(a[i], ap));
111    }
112    let phi = sn.atan2(cs);
113    let rotation = Rotation3::from_axis_angle(ap, phi) * primary;
114    // The primary counts only when its weight is finite (the single-pair case).
115    let ssd: f64 = (0..a.len())
116        .filter(|&i| i != p || w[p].is_finite())
117        .map(|i| {
118            let c = rotation.rotate(b[i]);
119            w[i] * (0..3).map(|k| (a[i][k] - c[k]).powi(2)).sum::<f64>()
120        })
121        .sum();
122    Ok(Alignment { rotation, rssd: ssd.sqrt() })
123}
124
125// ANCHOR: mean
126/// The mean of rotations (SciPy's `Rotation.mean`): the unit quaternion maximising
127/// `Σ wᵢ (q · qᵢ)²`, the eigenvector of the largest eigenvalue of `Σ wᵢ qᵢ qᵢᵀ` (Markley et al.).
128/// It minimises the weighted sum of squared chordal distances `‖R − Rᵢ‖²`, and is unaffected by
129/// the sign ambiguity `q ~ −q`.
130pub fn rotation_mean(rotations: &[Rotation3], weights: Option<&[f64]>) -> Result<Rotation3, ErrorsJSL> {
131    if rotations.is_empty() {
132        return Err(ErrorsJSL::InvalidInputRange("rotation_mean: the mean of no rotations is undefined"));
133    }
134    if let Some(w) = weights {
135        if w.len() != rotations.len() {
136            return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), rotations.len())));
137        }
138        if w.iter().any(|v| !v.is_finite() || *v < 0.0) {
139            return Err(ErrorsJSL::InvalidInputRange("rotation_mean: weights must be non-negative"));
140        }
141    }
142    let mut k = vec![vec![0.0; 4]; 4];
143    for (i, r) in rotations.iter().enumerate() {
144        let q = r.quaternion();
145        let v = [q.x, q.y, q.z, q.w];
146        let wi = weights.map_or(1.0, |w| w[i]);
147        for p in 0..4 {
148            for c in 0..4 {
149                k[p][c] += wi * v[p] * v[c];
150            }
151        }
152    }
153    // K is symmetric positive semi-definite: its leading singular vector is the eigenvector.
154    let (u, _, _) = svd_square(&k);
155    Ok(Rotation3::from_quaternion(Quaternion::new(u[3][0], u[0][0], u[1][0], u[2][0])))
156}
157// ANCHOR_END: mean
158
159// ANCHOR: procrustes
160/// The orthogonal matrix `R` minimising `‖A R − B‖_F` and the scale `Σ σᵢ` (SciPy's
161/// `orthogonal_procrustes`): with `AᵀB = U S Vᵀ`, `R = U Vᵀ`. `A` and `B` are `m × d` (rows are
162/// points); reflections are allowed.
163pub fn orthogonal_procrustes(a: &[Vec<f64>], b: &[Vec<f64>]) -> Result<(Vec<Vec<f64>>, f64), ErrorsJSL> {
164    let (m, d) = shape(a)?;
165    if shape(b)? != (m, d) {
166        return Err(ErrorsJSL::IncompatibleArraySizes((b.len(), m)));
167    }
168    let atb: Vec<Vec<f64>> = (0..d).map(|r| (0..d).map(|c| (0..m).map(|i| a[i][r] * b[i][c]).sum()).collect()).collect();
169    let (u, s, v) = svd_square(&atb);
170    let r = (0..d).map(|i| (0..d).map(|j| (0..d).map(|k| u[i][k] * v[j][k]).sum()).collect()).collect();
171    Ok((r, s.iter().sum()))
172}
173
174/// The result of [`procrustes`].
175#[derive(Clone, Debug)]
176#[non_exhaustive]
177pub struct ProcrustesResult {
178    /// The first data set, centred and scaled to unit Frobenius norm.
179    pub mtx1: Vec<Vec<f64>>,
180    /// The second, centred, scaled, and rotated (or reflected) and rescaled onto the first.
181    pub mtx2: Vec<Vec<f64>>,
182    /// `Σ (mtx1 − mtx2)²`, between 0 (identical shapes) and 1.
183    pub disparity: f64,
184}
185
186/// Procrustes analysis of two configurations of `m` points in `d` dimensions (SciPy's
187/// `scipy.spatial.procrustes`): both are centred and scaled to unit norm, then the second is
188/// rotated (reflections allowed) and scaled to best match the first; the disparity is the
189/// remaining sum of squared differences, a measure of difference in shape.
190pub fn procrustes(data1: &[Vec<f64>], data2: &[Vec<f64>]) -> Result<ProcrustesResult, ErrorsJSL> {
191    let (m, d) = shape(data1)?;
192    if shape(data2)? != (m, d) {
193        return Err(ErrorsJSL::IncompatibleArraySizes((data2.len(), m)));
194    }
195    let standardise = |x: &[Vec<f64>]| -> Result<Vec<Vec<f64>>, ErrorsJSL> {
196        let mean: Vec<f64> = (0..d).map(|j| x.iter().map(|r| r[j]).sum::<f64>() / m as f64).collect();
197        let c: Vec<Vec<f64>> = x.iter().map(|r| r.iter().zip(&mean).map(|(v, mu)| v - mu).collect()).collect();
198        let norm = c.iter().flatten().map(|v| v * v).sum::<f64>().sqrt();
199        if norm == 0.0 {
200            return Err(ErrorsJSL::InvalidInputRange("procrustes: the input must contain more than one distinct point"));
201        }
202        Ok(c.into_iter().map(|r| r.into_iter().map(|v| v / norm).collect()).collect())
203    };
204    let mtx1 = standardise(data1)?;
205    let mtx2 = standardise(data2)?;
206    let (r, s) = orthogonal_procrustes(&mtx1, &mtx2)?;
207    // mtx2 ← mtx2 Rᵀ s.
208    let mtx2: Vec<Vec<f64>> = mtx2.iter().map(|row| (0..d).map(|j| s * (0..d).map(|k| row[k] * r[j][k]).sum::<f64>()).collect()).collect();
209    let disparity = mtx1.iter().zip(&mtx2).flat_map(|(p, q)| p.iter().zip(q).map(|(a, b)| (a - b).powi(2))).sum();
210    Ok(ProcrustesResult { mtx1, mtx2, disparity })
211}
212// ANCHOR_END: procrustes
213
214fn shape(x: &[Vec<f64>]) -> Result<(usize, usize), ErrorsJSL> {
215    let m = x.len();
216    let d = x.first().map_or(0, |r| r.len());
217    if m == 0 || d == 0 || x.iter().any(|r| r.len() != d) {
218        return Err(ErrorsJSL::InvalidInputRange("expected a non-empty matrix with rows of equal length"));
219    }
220    Ok((m, d))
221}
222
223// ANCHOR: slerp
224/// Points along the great circle from `start` to `end` on the unit sphere in any dimension, at
225/// the fractions `t` of the way (SciPy's `geometric_slerp`):
226/// `(sin((1 − t)ω) start + sin(tω) end) / sin ω`, `ω` the angle between them. Both must be unit
227/// vectors; antipodal points have no unique great circle and are an error, and equal points give
228/// that point.
229pub fn geometric_slerp(start: &[f64], end: &[f64], t: &[f64]) -> Result<Vec<Vec<f64>>, ErrorsJSL> {
230    let tol = 1e-7;
231    if start.len() != end.len() || start.len() < 2 {
232        return Err(ErrorsJSL::IncompatibleArraySizes((start.len(), end.len())));
233    }
234    let unit = |v: &[f64]| (v.iter().map(|x| x * x).sum::<f64>().sqrt() - 1.0).abs() < tol;
235    if !unit(start) || !unit(end) {
236        return Err(ErrorsJSL::InvalidInputRange("geometric_slerp: start and end must be unit vectors"));
237    }
238    if t.iter().any(|v| !(0.0..=1.0).contains(v)) {
239        return Err(ErrorsJSL::InvalidInputRange("geometric_slerp: interpolation parameters must lie in [0, 1]"));
240    }
241    let d: f64 = start.iter().zip(end).map(|(a, b)| a * b).sum::<f64>().clamp(-1.0, 1.0);
242    if start.iter().zip(end).all(|(a, b)| (a - b).abs() <= tol) {
243        return Ok(t.iter().map(|_| start.to_vec()).collect());
244    }
245    if start.iter().zip(end).all(|(a, b)| (a + b).abs() <= tol) {
246        return Err(ErrorsJSL::InvalidInputRange("geometric_slerp: antipodal points have no unique great circle"));
247    }
248    let omega = d.acos();
249    let so = omega.sin();
250    Ok(t.iter()
251        .map(|&tt| {
252            let (p, q) = (((1.0 - tt) * omega).sin() / so, (tt * omega).sin() / so);
253            start.iter().zip(end).map(|(a, b)| p * a + q * b).collect()
254        })
255        .collect())
256}
257// ANCHOR_END: slerp
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    #[test]
264    fn recovers_a_rotation_and_handles_the_special_cases() {
265        let truth = Rotation3::from_axis_angle([0.3, -1.0, 0.5], 2.2);
266        let b = [[1.0, 0.0, 0.0], [0.0, 2.0, 0.5], [0.3, -0.4, 1.0], [1.0, 1.0, 1.0]];
267        let a: Vec<[f64; 3]> = b.iter().map(|&v| truth.rotate(v)).collect();
268        let r = align_vectors(&a, &b, None).unwrap();
269        assert!(r.rotation.angle_to(&truth) < 1e-12 && r.rssd < 1e-7);
270        // Mirrored data cannot be matched by a rotation: the determinant correction.
271        let mirror: Vec<[f64; 3]> = a.iter().map(|v| [-v[0], v[1], v[2]]).collect();
272        let r = align_vectors(&mirror, &b, None).unwrap();
273        assert!(crate::algorithms::rotations::is_rotation_matrix(&r.rotation.matrix(), 1e-12) && r.rssd > 0.5);
274        // A primary vector with infinite weight is matched exactly.
275        let noisy: Vec<[f64; 3]> = a.iter().enumerate().map(|(i, v)| [v[0] + 0.01 * i as f64, v[1], v[2]]).collect();
276        let r = align_vectors(&noisy, &b, Some(&[f64::INFINITY, 1.0, 1.0, 1.0])).unwrap();
277        let c = r.rotation.rotate(b[0]);
278        assert!((0..3).all(|k| (c[k] - noisy[0][k]).abs() < 1e-12));
279        // The mean of rotations about one axis is the rotation by the mean angle.
280        let rs: Vec<Rotation3> = [0.1, 0.4, 0.7].iter().map(|&t| Rotation3::from_axis_angle([0.0, 0.0, 1.0], t)).collect();
281        let m = rotation_mean(&rs, None).unwrap();
282        assert!(m.angle_to(&Rotation3::from_axis_angle([0.0, 0.0, 1.0], 0.4)) < 1e-12);
283    }
284
285    #[test]
286    fn procrustes_ignores_similarity_transforms() {
287        let a = vec![vec![1.0, 3.0], vec![1.0, 2.0], vec![1.0, 1.0], vec![2.0, 1.0]];
288        let b = vec![vec![4.0, -2.0], vec![4.0, -4.0], vec![4.0, -6.0], vec![2.0, -6.0]];
289        let r = procrustes(&a, &b).unwrap();
290        assert!(r.disparity < 1e-24, "{}", r.disparity);
291        let p = geometric_slerp(&[1.0, 0.0], &[0.0, 1.0], &[0.0, 0.5, 1.0]).unwrap();
292        let h = 0.5f64.sqrt();
293        assert!((p[1][0] - h).abs() < 1e-15 && (p[1][1] - h).abs() < 1e-15 && (p[2][1] - 1.0).abs() < 1e-15);
294        assert!(geometric_slerp(&[1.0, 0.0], &[-1.0, 0.0], &[0.5]).is_err());
295    }
296}