Skip to main content

brep_ransac/
math.rs

1use serde::{Deserialize, Serialize};
2use std::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
3
4use crate::numerical::{linear_algebra, scalar};
5
6#[derive(Clone, Copy, Debug, Default, PartialEq, Deserialize, Serialize)]
7/// A three-dimensional vector with double-precision components.
8pub struct Vec3 {
9    /// The x component.
10    pub x: f64,
11    /// The y component.
12    pub y: f64,
13    /// The z component.
14    pub z: f64,
15}
16
17impl Vec3 {
18    /// The zero vector.
19    pub const ZERO: Self = Self::new(0.0, 0.0, 0.0);
20    /// The positive x-axis unit vector.
21    pub const X: Self = Self::new(1.0, 0.0, 0.0);
22    /// The positive y-axis unit vector.
23    pub const Y: Self = Self::new(0.0, 1.0, 0.0);
24    /// The positive z-axis unit vector.
25    pub const Z: Self = Self::new(0.0, 0.0, 1.0);
26
27    /// Creates a vector from Cartesian components.
28    pub const fn new(x: f64, y: f64, z: f64) -> Self {
29        Self { x, y, z }
30    }
31    /// Returns the dot product with `rhs`.
32    pub fn dot(self, rhs: Self) -> f64 {
33        self.x * rhs.x + self.y * rhs.y + self.z * rhs.z
34    }
35    /// Returns the right-handed cross product with `rhs`.
36    pub fn cross(self, rhs: Self) -> Self {
37        Self::new(
38            self.y * rhs.z - self.z * rhs.y,
39            self.z * rhs.x - self.x * rhs.z,
40            self.x * rhs.y - self.y * rhs.x,
41        )
42    }
43    /// Returns the squared Euclidean length.
44    pub fn length_squared(self) -> f64 {
45        self.dot(self)
46    }
47    /// Returns the Euclidean length.
48    pub fn length(self) -> f64 {
49        self.length_squared().sqrt()
50    }
51    /// Returns a unit vector in the same direction, or `None` if the vector
52    /// is zero, too small to normalize reliably, or non-finite.
53    pub fn normalized(self) -> Option<Self> {
54        let length = self.length();
55        (length.is_finite() && length > scalar::MIN_NORMALIZABLE_NORM).then(|| self / length)
56    }
57    /// Returns the Euclidean distance to `rhs`.
58    pub fn distance(self, rhs: Self) -> f64 {
59        (self - rhs).length()
60    }
61    /// Returns whether all components are finite.
62    pub fn is_finite(self) -> bool {
63        self.x.is_finite() && self.y.is_finite() && self.z.is_finite()
64    }
65    /// Returns the component at index 0, 1, or 2.
66    ///
67    /// # Panics
68    ///
69    /// Panics when `index` is greater than 2.
70    pub fn component(self, index: usize) -> f64 {
71        [self.x, self.y, self.z][index]
72    }
73    /// Chooses a deterministic sign by making the largest-magnitude component
74    /// non-negative.
75    pub fn canonicalized(self) -> Self {
76        let values = [self.x, self.y, self.z];
77        let index = (0..3)
78            .max_by(|&a, &b| values[a].abs().total_cmp(&values[b].abs()))
79            .unwrap();
80        if values[index] < 0.0 {
81            -self
82        } else {
83            self
84        }
85    }
86    /// Builds two unit vectors perpendicular to this vector and each other.
87    ///
88    /// Returns `None` when this vector cannot be normalized.
89    pub fn orthonormal_basis(self) -> Option<(Self, Self)> {
90        let n = self.normalized()?;
91        let seed = if n.x.abs() <= n.y.abs() && n.x.abs() <= n.z.abs() {
92            Self::X
93        } else if n.y.abs() <= n.z.abs() {
94            Self::Y
95        } else {
96            Self::Z
97        };
98        let u = n.cross(seed).normalized()?;
99        Some((u, n.cross(u)))
100    }
101}
102
103impl Add for Vec3 {
104    type Output = Self;
105    fn add(self, r: Self) -> Self {
106        Self::new(self.x + r.x, self.y + r.y, self.z + r.z)
107    }
108}
109impl Sub for Vec3 {
110    type Output = Self;
111    fn sub(self, r: Self) -> Self {
112        Self::new(self.x - r.x, self.y - r.y, self.z - r.z)
113    }
114}
115impl Mul<f64> for Vec3 {
116    type Output = Self;
117    fn mul(self, s: f64) -> Self {
118        Self::new(self.x * s, self.y * s, self.z * s)
119    }
120}
121impl Div<f64> for Vec3 {
122    type Output = Self;
123    fn div(self, s: f64) -> Self {
124        self * (1.0 / s)
125    }
126}
127impl Neg for Vec3 {
128    type Output = Self;
129    fn neg(self) -> Self {
130        self * -1.0
131    }
132}
133impl AddAssign for Vec3 {
134    fn add_assign(&mut self, r: Self) {
135        *self = *self + r;
136    }
137}
138impl SubAssign for Vec3 {
139    fn sub_assign(&mut self, r: Self) {
140        *self = *self - r;
141    }
142}
143
144pub(crate) fn outer_accumulate(matrix: &mut [[f64; 3]; 3], value: Vec3, weight: f64) {
145    let v = [value.x, value.y, value.z];
146    for i in 0..3 {
147        for j in 0..3 {
148            matrix[i][j] += weight * v[i] * v[j];
149        }
150    }
151}
152
153/// How [`jacobi_eigen_symmetric3`] turns a pivot pair with equal diagonals
154/// (`tau` = ±0, where `(1 + tau²)` gives `t = ±1`).
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156pub enum JacobiZeroTurn {
157    /// `t = tau.signum()`: `-0.0` (equal diagonals, negative off-diagonal)
158    /// turns by `-1`. The RANSAC fits' convention.
159    Signed,
160    /// `t = +1` at either zero. The kernel carrier fits' and the
161    /// reconstruction copies' convention (`theta >= 0` / `theta == 0`).
162    Positive,
163}
164
165/// Dependency-free Jacobi eigensolver for real symmetric 3x3 matrices.
166///
167/// Classic Jacobi (largest off-diagonal first, at most 64 rotations, stop at
168/// `1e-15 * max|a|`). Returns the eigenvalues in ascending order and, for
169/// each, its eigenvector as `[x, y, z]`: the accumulated rotation's column,
170/// unit to rounding but NOT renormalised. The one eigensolver behind the
171/// RANSAC fits (`eigen_symmetric3` renormalises it), the kernel's mesh
172/// segmentation carrier fits and the reconstruction plane/axis reads.
173///
174/// `zero_turn` names the one place the former copies differed: a rotation
175/// whose pivot pair has equal diagonals (`tau` = ±0). Every other `tau`
176/// gives the same turn bit for bit under either convention.
177pub fn jacobi_eigen_symmetric3(
178    mut a: [[f64; 3]; 3],
179    zero_turn: JacobiZeroTurn,
180) -> ([f64; 3], [[f64; 3]; 3]) {
181    let mut v = [[0.0; 3]; 3];
182    for (i, row) in v.iter_mut().enumerate() {
183        row[i] = 1.0;
184    }
185    let scale = a
186        .iter()
187        .flatten()
188        .fold(0.0_f64, |m, x| m.max(x.abs()))
189        .max(linear_algebra::MATRIX_SCALE_FLOOR);
190    for _ in 0..64 {
191        let mut pair = (0, 1);
192        for candidate in [(0, 2), (1, 2)] {
193            if a[candidate.0][candidate.1].abs() > a[pair.0][pair.1].abs() {
194                pair = candidate;
195            }
196        }
197        let (p, q) = pair;
198        if a[p][q].abs() <= linear_algebra::JACOBI_RELATIVE_CONVERGENCE * scale {
199            break;
200        }
201        let tau = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
202        let t = if tau == 0.0 && zero_turn == JacobiZeroTurn::Positive {
203            1.0
204        } else {
205            tau.signum() / (tau.abs() + (1.0 + tau * tau).sqrt())
206        };
207        let c = 1.0 / (1.0 + t * t).sqrt();
208        let s = t * c;
209        let apq = a[p][q];
210        a[p][p] -= t * apq;
211        a[q][q] += t * apq;
212        a[p][q] = 0.0;
213        a[q][p] = 0.0;
214        for k in 0..3 {
215            if k != p && k != q {
216                let (akp, akq) = (a[k][p], a[k][q]);
217                a[k][p] = c * akp - s * akq;
218                a[p][k] = a[k][p];
219                a[k][q] = s * akp + c * akq;
220                a[q][k] = a[k][q];
221            }
222            let (vkp, vkq) = (v[k][p], v[k][q]);
223            v[k][p] = c * vkp - s * vkq;
224            v[k][q] = s * vkp + c * vkq;
225        }
226    }
227    let mut order = [0, 1, 2];
228    order.sort_by(|&i, &j| a[i][i].total_cmp(&a[j][j]));
229    let values = order.map(|i| a[i][i]);
230    let vectors = order.map(|i| [v[0][i], v[1][i], v[2][i]]);
231    (values, vectors)
232}
233
234/// [`jacobi_eigen_symmetric3`] with each eigenvector renormalised.
235pub(crate) fn eigen_symmetric3(a: [[f64; 3]; 3]) -> ([f64; 3], [Vec3; 3]) {
236    let (values, vectors) = jacobi_eigen_symmetric3(a, JacobiZeroTurn::Signed);
237    let vectors = vectors.map(|[x, y, z]| Vec3::new(x, y, z).normalized().unwrap_or(Vec3::ZERO));
238    (values, vectors)
239}
240
241/// Iteration and acceptance policy of [`refine_cone`].
242#[derive(Clone, Copy, Debug, PartialEq)]
243pub struct ConeRefinePolicy {
244    /// Gauss-Newton steps taken at most.
245    pub steps: usize,
246    /// Stop once a step's norm falls below this (`0.0`: always take `steps`).
247    pub stop_below: f64,
248    /// A point at most this far from the axis takes no part in a step.
249    pub min_radius: f64,
250    /// Clamp the half angle into `(1e-6, pi/2 - 1e-6)` after every step;
251    /// `false` leaves it to the caller's own range test.
252    pub clamp_angle: bool,
253}
254
255/// Gauss-Newton refinement of a cone over a point slice: apex, unit axis
256/// into the nappe, and half angle, with the six parameters apex (3), two
257/// axis tilts along an orthonormal frame of the axis, and the angle. The
258/// residual of a point is `rho cos(a) - h sin(a)` (h along the axis, rho
259/// from it). Each step solves the normal equations with `solve_linear`.
260/// `None` when the axis cannot be normalised, a step is singular, or the
261/// result is not finite.
262pub fn refine_cone(
263    points: &[[f64; 3]],
264    apex: [f64; 3],
265    axis: [f64; 3],
266    half_angle: f64,
267    policy: ConeRefinePolicy,
268) -> Option<([f64; 3], [f64; 3], f64)> {
269    let mut apex = Vec3::new(apex[0], apex[1], apex[2]);
270    let mut axis = Vec3::new(axis[0], axis[1], axis[2]).normalized()?;
271    let mut half_angle = half_angle;
272    for _ in 0..policy.steps {
273        let (e1, e2) = axis.orthonormal_basis()?;
274        let (sin_a, cos_a) = half_angle.sin_cos();
275        let mut ata = vec![vec![0.0_f64; 6]; 6];
276        let mut atb = vec![0.0_f64; 6];
277        for p in points {
278            let d = Vec3::new(p[0], p[1], p[2]) - apex;
279            let h = d.dot(axis);
280            let radial = d - axis * h;
281            let rho = radial.length();
282            if rho <= policy.min_radius {
283                continue;
284            }
285            let w = radial / rho;
286            let residual = rho * cos_a - h * sin_a;
287            let j_apex = axis * sin_a - w * cos_a;
288            let c_tilt = -((h / rho) * cos_a + sin_a);
289            let row = [
290                j_apex.x,
291                j_apex.y,
292                j_apex.z,
293                c_tilt * d.dot(e1),
294                c_tilt * d.dot(e2),
295                -rho * sin_a - h * cos_a,
296            ];
297            for i in 0..6 {
298                for j in 0..6 {
299                    ata[i][j] += row[i] * row[j];
300                }
301                atb[i] -= row[i] * residual;
302            }
303        }
304        let step = solve_linear(ata, atb)?;
305        apex = apex + Vec3::new(step[0], step[1], step[2]);
306        axis = (axis + e1 * step[3] + e2 * step[4]).normalized()?;
307        half_angle += step[5];
308        if policy.clamp_angle {
309            half_angle = half_angle.clamp(1e-6, std::f64::consts::FRAC_PI_2 - 1e-6);
310        }
311        let step_size = step.iter().map(|s| s * s).sum::<f64>().sqrt();
312        if step_size < policy.stop_below {
313            break;
314        }
315    }
316    (apex.is_finite() && axis.is_finite() && half_angle.is_finite())
317        .then_some(([apex.x, apex.y, apex.z], [axis.x, axis.y, axis.z], half_angle))
318}
319
320pub(crate) fn solve_linear(mut a: Vec<Vec<f64>>, mut b: Vec<f64>) -> Option<Vec<f64>> {
321    let n = b.len();
322    if a.len() != n || a.iter().any(|r| r.len() != n) {
323        return None;
324    }
325    let scale = a
326        .iter()
327        .flatten()
328        .fold(0.0_f64, |m, x| m.max(x.abs()))
329        .max(1.0);
330    for col in 0..n {
331        let pivot = (col..n).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs()))?;
332        if a[pivot][col].abs() <= linear_algebra::LINEAR_PIVOT_RELATIVE_MIN * scale {
333            return None;
334        }
335        a.swap(col, pivot);
336        b.swap(col, pivot);
337        let d = a[col][col];
338        for j in col..n {
339            a[col][j] /= d;
340        }
341        b[col] /= d;
342        for i in 0..n {
343            if i != col {
344                let f = a[i][col];
345                for j in col..n {
346                    a[i][j] -= f * a[col][j];
347                }
348                b[i] -= f * b[col];
349            }
350        }
351    }
352    b.iter().all(|x| x.is_finite()).then_some(b)
353}
354
355/// Rows may be `Vec<f64>` or fixed arrays (`[f64; 3]` saves the hot torus and
356/// circle initializers one allocation per sample); the arithmetic is the same.
357pub(crate) fn least_squares<R: AsRef<[f64]>>(
358    rows: &[R],
359    rhs: &[f64],
360    regularization: f64,
361) -> Option<Vec<f64>> {
362    let n = rows.first()?.as_ref().len();
363    if rows.len() != rhs.len() || rows.iter().any(|r| r.as_ref().len() != n) {
364        return None;
365    }
366    let mut ata = vec![vec![0.0; n]; n];
367    let mut atb = vec![0.0; n];
368    for (row, &value) in rows.iter().zip(rhs) {
369        let row = row.as_ref();
370        for i in 0..n {
371            atb[i] += row[i] * value;
372            for j in 0..n {
373                ata[i][j] += row[i] * row[j];
374            }
375        }
376    }
377    for (i, row) in ata.iter_mut().enumerate() {
378        row[i] += regularization;
379    }
380    solve_linear(ata, atb)
381}
382
383/// Solve a tall least-squares system with column-pivoted, reorthogonalized QR.
384///
385/// Unlike [`least_squares`], this does not form the normal equations. It is
386/// intended for small parameter counts whose observation matrix can be badly
387/// conditioned but still has observable full rank, such as tangent planes on
388/// a narrowly trimmed cone.
389pub(crate) fn least_squares_qr<R: AsRef<[f64]>>(
390    rows: &[R],
391    rhs: &[f64],
392    relative_rank_min: f64,
393) -> Option<Vec<f64>> {
394    let parameter_count = rows.first()?.as_ref().len();
395    if parameter_count == 0
396        || rows.len() < parameter_count
397        || rows.len() != rhs.len()
398        || !relative_rank_min.is_finite()
399        || relative_rank_min < 0.0
400        || rows.iter().any(|row| {
401            let row = row.as_ref();
402            row.len() != parameter_count || row.iter().any(|value| !value.is_finite())
403        })
404        || rhs.iter().any(|value| !value.is_finite())
405    {
406        return None;
407    }
408
409    let mut columns: Vec<Vec<f64>> = (0..parameter_count)
410        .map(|column| rows.iter().map(|row| row.as_ref()[column]).collect())
411        .collect();
412    let mut residual_rhs = rhs.to_vec();
413    let mut permutation: Vec<usize> = (0..parameter_count).collect();
414    let mut upper = vec![vec![0.0; parameter_count]; parameter_count];
415    let mut projected_rhs = vec![0.0; parameter_count];
416    let squared_norm = |values: &[f64]| values.iter().map(|value| value * value).sum::<f64>();
417    let reference_norm = columns
418        .iter()
419        .map(|column| squared_norm(column).sqrt())
420        .fold(0.0_f64, f64::max);
421    if !reference_norm.is_finite() || reference_norm <= 0.0 {
422        return None;
423    }
424
425    for rank in 0..parameter_count {
426        let pivot = (rank..parameter_count).max_by(|&left, &right| {
427            squared_norm(&columns[left]).total_cmp(&squared_norm(&columns[right]))
428        })?;
429        if pivot != rank {
430            columns.swap(rank, pivot);
431            permutation.swap(rank, pivot);
432            for row in upper.iter_mut().take(rank) {
433                row.swap(rank, pivot);
434            }
435        }
436        let norm = squared_norm(&columns[rank]).sqrt();
437        if !norm.is_finite() || norm <= relative_rank_min * reference_norm {
438            return None;
439        }
440        upper[rank][rank] = norm;
441        let direction: Vec<_> = columns[rank].iter().map(|value| value / norm).collect();
442        projected_rhs[rank] = direction
443            .iter()
444            .zip(&residual_rhs)
445            .map(|(left, right)| left * right)
446            .sum();
447        for (value, direction_value) in residual_rhs.iter_mut().zip(&direction) {
448            *value -= direction_value * projected_rhs[rank];
449        }
450        for (column, values) in columns.iter_mut().enumerate().skip(rank + 1) {
451            // A second modified Gram-Schmidt pass retains substantially more
452            // of the small singular direction on narrow normal fans.
453            let mut projection = direction
454                .iter()
455                .zip(&*values)
456                .map(|(left, right)| left * right)
457                .sum::<f64>();
458            for (value, direction_value) in values.iter_mut().zip(&direction) {
459                *value -= direction_value * projection;
460            }
461            let correction = direction
462                .iter()
463                .zip(&*values)
464                .map(|(left, right)| left * right)
465                .sum::<f64>();
466            for (value, direction_value) in values.iter_mut().zip(&direction) {
467                *value -= direction_value * correction;
468            }
469            projection += correction;
470            upper[rank][column] = projection;
471        }
472    }
473
474    let mut pivoted_solution = vec![0.0; parameter_count];
475    for row in (0..parameter_count).rev() {
476        let remainder = (row + 1..parameter_count)
477            .map(|column| upper[row][column] * pivoted_solution[column])
478            .sum::<f64>();
479        pivoted_solution[row] = (projected_rhs[row] - remainder) / upper[row][row];
480    }
481    if pivoted_solution.iter().any(|value| !value.is_finite()) {
482        return None;
483    }
484    let mut solution = vec![0.0; parameter_count];
485    for (pivoted, original) in permutation.into_iter().enumerate() {
486        solution[original] = pivoted_solution[pivoted];
487    }
488    Some(solution)
489}
490