Rotation fitting, Procrustes analysis and Hausdorff distance
| Problem | Find the rotation that best maps one set of vectors onto another; average rotations; compare shapes up to position, size and orientation; interpolate on a sphere; measure how far apart two point sets are; and search point clouds for close pairs, including in periodic boxes |
| Devised by | Grace Wahba (1965), the attitude problem; Wolfgang Kabsch (1976); F. Landis Markley et al. (2007), averaging quaternions; John Gower (1975), Procrustes analysis; Ken Shoemake (1985, 1992), slerp and uniform random rotations; Felix Hausdorff (1914); Abdel Aziz Taha and Allan Hanbury (2015), the early-break algorithm |
| Accuracy | To rounding; the same results as scipy.spatial |
| Cost | Alignment: plus a 3 × 3 SVD; mean: plus a 4 × 4 eigenproblem; Procrustes: ; Hausdorff: worst case, typically near ; pair search: |
| Read first | Rotations, Euler angles and quaternions, Spatial trees |
| API | align_vectors, rotation_mean, procrustes, orthogonal_procrustes, geometric_slerp; Rotation3 (from_rotvec, as_rotvec, from_mrp, as_mrp, random); directed_hausdorff; KdTree::query_pairs, PeriodicKdTree |
Overview
This entry fills the remaining gaps between the geometry chapter and scipy.spatial:
- Rotation fitting (
Rotation.align_vectors). Given vectors measured in two frames, such as star directions seen by a spacecraft and catalogued, or atom positions in two molecules, find the rotation between the frames. This is Wahba’s problem, solved by Kabsch’s algorithm. - Averaging rotations (
Rotation.mean), for example to fuse several attitude estimates. - Rotation representations: rotation vectors and modified Rodrigues parameters, and uniformly distributed random rotations.
- Procrustes analysis (
procrustes,orthogonal_procrustes), which compares two shapes after removing translation, scale and rotation. It is the basis of shape statistics in biology and of point-set registration. - Geometric slerp: points along a great circle of a sphere in any dimension.
- The Hausdorff distance, the largest distance from a point of one set to the nearest point of the other, a standard measure for comparing segmentations and curves.
- k-d tree extras: all pairs within a distance (
query_pairs), pair counts between two sets (count_neighbors, the basis of correlation functions in cosmology), and periodic boxes, where distances wrap round as in simulations with periodic boundary conditions.
Where it is used
Aligning one set of points with another is a basic step in many measurement problems.
- 3-D scanning and registration. The rotation that best maps one scan onto another is the core of the iterative closest point method used in surveying and robotics.
- Robotics and navigation. Estimating the orientation of a vehicle from sensor vectors (sun sensor, magnetometer, gravity) is Wahba’s problem, solved on satellites and drones.
- Biology and shape analysis. Procrustes analysis compares the shapes of bones, leaves or faces independent of position, scale and rotation.
- Quality control. The Hausdorff distance measures how far a manufactured part departs from its CAD model.
History
Grace Wahba (1965) posed the problem of finding a spacecraft’s attitude from vector observations, and Paul Davenport soon solved it with quaternions (the q-method). Wolfgang Kabsch (1976) gave the SVD solution for superimposing molecular structures, now standard in structural biology. F. Landis Markley, Yang Cheng, John Crassidis and Yaakov Oshman (2007) showed that the average of rotations is the leading eigenvector of a quadratic form in their quaternions.
John Gower (1975) introduced generalised Procrustes analysis for comparing configurations in statistics. Ken Shoemake (1985) introduced slerp to computer animation, and later (1992) gave the method for uniform random rotations used here. Felix Hausdorff (1914) defined the distance between sets in his Grundzüge der Mengenlehre. Abdel Aziz Taha and Allan Hanbury (2015) gave the early-break algorithm that SciPy uses.
The idea
Wahba’s problem and Kabsch’s algorithm
Minimising over rotations is the same as maximising with . If , the maximum over orthogonal matrices is at . That matrix may be a reflection. Flipping the sign of the last singular direction,
gives the best proper rotation. The minimum is , whose square root is the reported rssd.
With a single pair, or one pair weighted infinitely (the primary), the primary is aligned exactly by the smallest rotation. The one remaining degree of freedom, a rotation by about , is chosen to best align the others. Its optimum is an atan2 of two weighted sums.
The mean rotation
The chordal distance between rotations is for unit quaternions. Minimising the weighted sum of these distances therefore maximises with . The mean is the leading eigenvector of this symmetric 4 × 4 matrix. Because enters squared, the sign ambiguity does not matter.
Representations and random rotations
- Rotation vector: a rotation by about the unit axis is . Its quaternion is , and the ratio is evaluated by its series near .
- Modified Rodrigues parameters: , a three-parameter form that is non-singular for every .
- Random rotations: Shoemake’s construction maps three uniform numbers to a uniformly distributed unit quaternion, through a uniformly chosen point on written in two orthogonal planes.
Procrustes analysis
Both configurations are centred and scaled to unit Frobenius norm. The orthogonal matrix minimising is from the SVD . Unlike Kabsch, reflections are allowed here, as in SciPy. The best scale is . The disparity is what remains, : 0 for identical shapes and at most 1.
The Hausdorff distance
, and the Hausdorff distance is . Computed directly it costs distances. Taha and Hanbury’s observation is that the inner minimum for only matters if it exceeds the current maximum. The inner loop can therefore stop at the first closer than that maximum. For similar sets this happens almost at once, and the cost is close to linear.
Periodic boxes
On a torus , the distance between two points is the distance to the nearest periodic image. A query point within the box has its nearest image among its translates by in each coordinate. Querying an ordinary k-d tree with each translate and merging the results gives the periodic answer.
Implementation
/// The rotation `C` minimising `Σ wᵢ ‖aᵢ − C bᵢ‖²` (SciPy's `Rotation.align_vectors`; Wahba's
/// problem). With `B = Σ wᵢ aᵢ bᵢᵀ = U S Vᵀ`, the answer is `C = U diag(1, 1, det(UVᵀ)) Vᵀ` (Kabsch's
/// algorithm); the determinant correction keeps it a rotation rather than a reflection. With a
/// single pair, or one infinite weight, that pair (the primary) is aligned exactly by the
/// smallest rotation, and the remaining freedom — a rotation about the primary — best aligns
/// the others.
pub fn align_vectors(a: &[[f64; 3]], b: &[[f64; 3]], weights: Option<&[f64]>) -> Result<Alignment, ErrorsJSL> {
let n = a.len();
if n == 0 || b.len() != n {
return Err(ErrorsJSL::IncompatibleArraySizes((a.len(), b.len())));
}
let w: Vec<f64> = match weights {
Some(w) if w.len() != n => return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), n))),
Some(w) if w.iter().any(|v| v.is_nan() || *v < 0.0) => return Err(ErrorsJSL::InvalidInputRange("align_vectors: weights must be non-negative")),
Some(w) => w.to_vec(),
None => vec![1.0; n],
};
let n_inf = w.iter().filter(|v| v.is_infinite()).count();
if n_inf > 1 {
return Err(ErrorsJSL::InvalidInputRange("align_vectors: only one infinite weight is allowed"));
}
if n == 1 || n_inf == 1 {
let p = if n == 1 { 0 } else { w.iter().position(|v| v.is_infinite()).expect("one infinite weight") };
return align_with_primary(a, b, &w, p);
}
let mut bm = vec![vec![0.0; 3]; 3];
for i in 0..n {
for r in 0..3 {
for c in 0..3 {
bm[r][c] += w[i] * a[i][r] * b[i][c];
}
}
}
let (mut u, mut s, v) = svd_square(&bm);
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();
if determinant(&uv) < 0.0 {
s[2] = -s[2];
for row in u.iter_mut() {
row[2] = -row[2];
}
}
let c: Matrix3 = std::array::from_fn(|r| std::array::from_fn(|col| (0..3).map(|k| u[r][k] * v[col][k]).sum()));
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>();
Ok(Alignment { rotation: Rotation3::from_matrix(&c), rssd: ssd.max(0.0).sqrt() })
}
/// The orthogonal matrix `R` minimising `‖A R − B‖_F` and the scale `Σ σᵢ` (SciPy's
/// `orthogonal_procrustes`): with `AᵀB = U S Vᵀ`, `R = U Vᵀ`. `A` and `B` are `m × d` (rows are
/// points); reflections are allowed.
pub fn orthogonal_procrustes(a: &[Vec<f64>], b: &[Vec<f64>]) -> Result<(Vec<Vec<f64>>, f64), ErrorsJSL> {
let (m, d) = shape(a)?;
if shape(b)? != (m, d) {
return Err(ErrorsJSL::IncompatibleArraySizes((b.len(), m)));
}
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();
let (u, s, v) = svd_square(&atb);
let r = (0..d).map(|i| (0..d).map(|j| (0..d).map(|k| u[i][k] * v[j][k]).sum()).collect()).collect();
Ok((r, s.iter().sum()))
}
/// The result of [`procrustes`].
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ProcrustesResult {
/// The first data set, centred and scaled to unit Frobenius norm.
pub mtx1: Vec<Vec<f64>>,
/// The second, centred, scaled, and rotated (or reflected) and rescaled onto the first.
pub mtx2: Vec<Vec<f64>>,
/// `Σ (mtx1 − mtx2)²`, between 0 (identical shapes) and 1.
pub disparity: f64,
}
/// Procrustes analysis of two configurations of `m` points in `d` dimensions (SciPy's
/// `scipy.spatial.procrustes`): both are centred and scaled to unit norm, then the second is
/// rotated (reflections allowed) and scaled to best match the first; the disparity is the
/// remaining sum of squared differences, a measure of difference in shape.
pub fn procrustes(data1: &[Vec<f64>], data2: &[Vec<f64>]) -> Result<ProcrustesResult, ErrorsJSL> {
let (m, d) = shape(data1)?;
if shape(data2)? != (m, d) {
return Err(ErrorsJSL::IncompatibleArraySizes((data2.len(), m)));
}
let standardise = |x: &[Vec<f64>]| -> Result<Vec<Vec<f64>>, ErrorsJSL> {
let mean: Vec<f64> = (0..d).map(|j| x.iter().map(|r| r[j]).sum::<f64>() / m as f64).collect();
let c: Vec<Vec<f64>> = x.iter().map(|r| r.iter().zip(&mean).map(|(v, mu)| v - mu).collect()).collect();
let norm = c.iter().flatten().map(|v| v * v).sum::<f64>().sqrt();
if norm == 0.0 {
return Err(ErrorsJSL::InvalidInputRange("procrustes: the input must contain more than one distinct point"));
}
Ok(c.into_iter().map(|r| r.into_iter().map(|v| v / norm).collect()).collect())
};
let mtx1 = standardise(data1)?;
let mtx2 = standardise(data2)?;
let (r, s) = orthogonal_procrustes(&mtx1, &mtx2)?;
// mtx2 ← mtx2 Rᵀ s.
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();
let disparity = mtx1.iter().zip(&mtx2).flat_map(|(p, q)| p.iter().zip(q).map(|(a, b)| (a - b).powi(2))).sum();
Ok(ProcrustesResult { mtx1, mtx2, disparity })
}
/// The directed Hausdorff distance `h(u, v) = max_{a ∈ u} min_{b ∈ v} ‖a − b‖` between point sets
/// in any dimension (SciPy's `directed_hausdorff`), by Taha and Hanbury's early-break algorithm:
/// the inner search over `v` stops as soon as some point is closer than the largest minimum found
/// so far, since that `a` can no longer raise the maximum. SciPy shuffles the points first (with
/// a fixed seed) to make early breaks likely; the library keeps the given order, which gives the
/// same distance and, without ties, the same pair.
pub fn directed_hausdorff(u: &[Vec<f64>], v: &[Vec<f64>]) -> Result<DirectedHausdorff, ErrorsJSL> {
let d = u.first().map_or(0, |p| p.len());
if u.is_empty() || v.is_empty() || d == 0 || u.iter().chain(v).any(|p| p.len() != d) {
return Err(ErrorsJSL::InvalidInputRange("directed_hausdorff: need non-empty point sets of one dimension"));
}
let (mut cmax, mut iu, mut iv) = (0.0f64, 0usize, 0usize);
for (i, a) in u.iter().enumerate() {
let (mut cmin, mut jmin, mut broke) = (f64::INFINITY, 0usize, false);
for (j, b) in v.iter().enumerate() {
let dist: f64 = a.iter().zip(b).map(|(x, y)| (x - y) * (x - y)).sum();
if dist < cmax {
broke = true;
break;
}
if dist < cmin {
cmin = dist;
jmin = j;
}
}
if !broke && cmin != f64::INFINITY && cmin > cmax {
cmax = cmin;
iu = i;
iv = jmin;
}
}
Ok(DirectedHausdorff { distance: cmax.sqrt(), index_u: iu, index_v: iv })
}
- The SVDs are of 3 × 3, 4 × 4 or matrices, computed by one-sided Jacobi rotations inside the geometry crate, so it does not depend on the linear-algebra crate.
Rotation3::randomtakes a source of uniform numbers, so any generator can be used; the rotations are not SciPy’s for the same seed.- SciPy shuffles the points in
directed_hausdorffto make early breaks likely. The library keeps their order, which gives the same distance and, without ties, the same pair. align_vectorsdoes not return SciPy’s sensitivity matrix.
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_geograph_refs.py. Rotations are compared by the angle of the rotation between them:
Table 24.9. Rotation fitting, representations, Procrustes analysis, slerp, Hausdorff distance and k-d tree extras against `scipy.spatial`.
| Function | Difference from SciPy | Notes |
|---|---|---|
align_vectors, 12 noisy pairs | 0 | rssd 0 |
align_vectors, weighted | 0 | rssd 7e-14 |
align_vectors, one infinite weight | 0 | rssd 2e-16 |
align_vectors, a single pair | 0 | rssd 1e-17 |
rotation_mean, 10 rotations, plain and weighted | 0 | |
from_rotvec, as_rotvec, as_mrp, from_mrp (angles 3·10⁻⁶ to π − 10⁻⁹) | 0 | components 2e-16 |
procrustes, 15 points in 3-D | 3e-16 | disparity 0.001887 (7e-19) |
geometric_slerp, 4-D, 7 points | 2e-16 | |
directed_hausdorff, 200 and 150 points | 0 | same pair of points |
query_pairs (268 pairs), count_neighbors ([80, 615, 4157]) | identical | |
| Periodic box: 4 nearest of 20 queries; pairs | 0 | same neighbours; 295 pairs (same) |
Every result agrees with SciPy’s to rounding. The Hausdorff distance picks the same pair of points, the pair searches find the same pairs and counts, and the periodic queries find the same neighbours.
Figure 24.15. Procrustes superposition of an outline and a copy that was rotated by 120°, scaled by 1.7, moved and perturbed. After centring and scaling (grey), the rotation found from the SVD brings the copy onto the original. The disparity, 0.0019, measures only the perturbation.
Strengths
- The SVD solution is optimal and needs no starting guess, unlike iterative registration.
- The mean rotation is unaffected by the sign ambiguity of quaternions, and is exact for the chordal metric.
- The Hausdorff computation is near-linear for similar sets.
Weaknesses
- The chordal mean is not the geodesic (Karcher) mean, though it is close for clustered rotations.
- Periodic queries cost ordinary queries.
- No
HalfspaceIntersection,SphericalVoronoi, or Delaunay triangulations and hulls beyond three dimensions.
Exercises
- Why does maximise over orthogonal ? (Hint: write .)
- Show that for unit quaternions.
- A shape and its mirror image: what is their Procrustes disparity (reflections allowed), and what does
align_vectorsreturn for them? - Give an example of sets with but .
Hints and answers
- is orthogonal, so its diagonal entries are at most 1, and , with equality at .
- Use and .
- The disparity is 0.
align_vectorsreturns the best proper rotation, with a positiverssd. - , : every point of is in , but is at distance 1 from .
Further reading
- G. Wahba, “A least squares estimate of satellite attitude”, SIAM Review 7 (1965) 409.
- W. Kabsch, “A solution for the best rotation to relate two sets of vectors”, Acta Crystallographica A 32 (1976) 922–923.
- F. L. Markley, Y. Cheng, J. L. Crassidis and Y. Oshman, “Averaging quaternions”, Journal of Guidance, Control, and Dynamics 30 (2007) 1193–1197.
- J. C. Gower, “Generalized Procrustes analysis”, Psychometrika 40 (1975) 33–51.
- K. Shoemake, “Uniform random rotations”, in Graphics Gems III, Academic Press (1992) 124–132.
- A. A. Taha and A. Hanbury, “An efficient algorithm for calculating the exact Hausdorff distance”, IEEE Transactions on Pattern Analysis and Machine Intelligence 37 (2015) 2153–2163.