engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
use super::points::{mean_point, mean_point_weighted};
use crate::common::PCoords;
use crate::geom3::{Iso3, SvdBasis3, UnitVec3};
use crate::{Iso2, SvdBasis2};
use parry2d_f64::na::{Matrix2, Rotation2, Translation2, UnitComplex};
use parry3d_f64::na::{DMatrix, Matrix3, Point, SVector, Translation3, Unit, UnitQuaternion};
use std::f64::consts::FRAC_PI_2;

/// This structure contains the results of using singular value decomposition to determine the
/// basis vectors of a set of points and their singular values (scales). This can be used to roughly
/// estimate if a set of points in D-dimensional space falls along a point, line, or plane.
#[derive(Debug)]
pub struct SvdBasis<const D: usize> {
    /// The resultant basis vectors, sorted by their corresponding singular values so that the
    /// first vector is the most significant. These are given as unit vectors.
    pub basis: [SVector<f64, D>; D],

    /// The raw singular values associated with each basis vector. The singular values are the
    /// square root of the eigenvalues of the covariance matrix of the point set.  By squaring them
    /// and dividing by the number of points used to compute the basis, the variance accounted for
    /// by each basis vector can be determined.
    pub sv: [f64; D],

    /// The center of the original point set used to compute the basis. The SVD was computed by
    /// calculating this center (mean point) and then subtracting it from each point in the set.
    /// The basis vectors represent vectors relative to this center as their origin.
    pub center: Point<f64, D>,

    /// The number of points used to compute the basis
    pub n: usize,
}

impl<const D: usize> SvdBasis<D> {
    pub fn largest(&self) -> Unit<SVector<f64, D>> {
        Unit::new_unchecked(self.basis[0])
    }

    pub fn smallest(&self) -> Unit<SVector<f64, D>> {
        Unit::new_unchecked(self.basis[D - 1])
    }

    /// Calculates and returns the variance accounted for by each basis vector. The variance is
    /// calculated by squaring the singular value of each basis vector and dividing by the number
    /// of points used in the original decomposed matrix.
    ///
    /// The variance is the expected value of the squared deviation from the mean. It will have
    /// units of the distance squared.  For a measure of dispersion with units of distance, use
    /// the standard deviation.
    pub fn basis_variances(&self) -> [f64; D] {
        let mut result = [0.0; D];
        for (r, s) in result.iter_mut().zip(self.sv.iter()) {
            *r = s.powi(2) / (self.n as f64);
        }
        result
    }

    /// Calculates and returns the standard deviation of the point dispersion along each basis
    /// vector. These values have the same units as the original points (i.e. if the points were in
    /// millimeters, the standard deviations will be in millimeters).
    ///
    /// These are useful for interpreting the geometric results of the basis vectors. The actual
    /// dispersion of the points along each basis vector will vary depending on how the points are
    /// distributed in space, but it is reasonable to assume that almost all the points will be
    /// within a few standard deviations of the mean.  Thus, standard deviations can be used to
    /// estimate roughly how important a basis vector is in actual world units.
    pub fn basis_stdevs(&self) -> [f64; D] {
        let mut result = self.basis_variances();
        for r in result.iter_mut() {
            *r = r.sqrt();
        }
        result
    }

    /// Compute the basis vectors of a set of points using singular value decomposition.  This uses
    /// `nalgebra`'s SVD implementation. The basis vectors are sorted by their corresponding
    /// singular values so that the first vector is the most significant. The basis vectors are
    /// returned as unit vectors.
    ///
    /// The result struct can be used to compute the variance and/or standard deviation of the
    /// point set along each basis vector.  This can be used to quickly estimate if a set of points
    /// falls into a shape with a lower dimensionality than the space they are in, such as lying
    /// along a line or plane.
    ///
    /// This is a relatively fast operation on a set of points. Computation on a set of 500 points
    /// was measured to take about 25us on a Xeon E-2286M (passmark 15,120) and 70us on a Core
    /// i7-10510U (passmark 6,700).  The time appears to be linearly proportional to the number of
    /// points.
    ///
    /// # Arguments
    ///
    /// * `points`:
    /// * `weights`:
    ///
    /// returns: SvdBasis<{ D }>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn from_points(points: &[impl PCoords<D>], weights: Option<&[f64]>) -> Option<Self> {
        if points.is_empty() {
            return None;
        }
        if let Some(w) = weights {
            let center = mean_point_weighted(points, w);
            // Weighted least-squares fit: each row is the centered point scaled by the square root
            // of its weight, so that `MᵀM = Σ wᵢ (pᵢ − c)(pᵢ − c)ᵀ` is the weighted scatter matrix
            // whose dominant eigenvector is the weighted best-fit direction.
            let vectors = points
                .iter()
                .zip(w)
                .map(|(p, w)| (p.coords() - center.coords) * w.max(0.0).sqrt())
                .collect::<Vec<_>>();
            svd_from_vectors(&vectors, Some(center))
        } else {
            let center = mean_point(points);
            let vectors = points
                .iter()
                .map(|p| p.coords() - center.coords)
                .collect::<Vec<_>>();
            svd_from_vectors(&vectors, Some(center))
        }
    }

    /// Retrieve the rank of the decomposition by counting the number of singular values that are
    /// greater than the provided tolerance.  A rank of 0 indicates that all singular values are
    /// less than the tolerance, and thus the point set is essentially a single point. A rank of 1
    /// indicates that the point set is essentially a line. A rank of 2 indicates that the point
    /// set exists roughly in a plane.  The maximum rank is D, which indicates that the point set
    /// cannot be reduced to a lower dimension.
    ///
    /// The singular values do not directly have a clear physical meaning. They are square roots of
    /// the variance multiplied by the number of points used to compute the basis.  Thus they can
    /// be interpreted in relation to each other, and when they are very small.
    ///
    /// This method should be used either when you know roughly what a cutoff tolerance for the
    /// problem you're working on should be, or when you know the cutoff value should be very
    /// small.  Otherwise, consider examining the standard deviations of the basis vectors
    /// instead, as they will be easier to interpret (`basis_stdevs()`).
    ///
    /// # Arguments
    ///
    /// * `tol`: the largest value that a singular value can have and still be considered zero.
    ///
    /// returns: usize
    pub fn rank(&self, tol: f64) -> usize {
        let mut rank = 0;
        for s in self.sv.iter() {
            if *s > tol {
                rank += 1;
            }
        }
        rank
    }

    /// Given a point in the global coordinate system, return the coordinates of the point in the
    /// basis coordinate system.  This is done by subtracting the center of the basis from the
    /// point and then projecting the result onto each basis vector in sequence
    ///
    /// # Arguments
    ///
    /// * `point`:
    ///
    /// returns: OPoint<f64, Const<{ D }>>
    pub fn point_to_basis(&self, point: &Point<f64, D>) -> Point<f64, D> {
        let mut result = Point::<f64, D>::origin();
        for i in 0..D {
            let as_vec = point - self.center;
            result[i] = self.basis[i].dot(&as_vec);
        }
        result
    }

    pub fn vec_to_basis(&self, vector: &SVector<f64, D>) -> SVector<f64, D> {
        let mut result = SVector::<f64, D>::zeros();
        for i in 0..D {
            result[i] = self.basis[i].dot(vector);
        }
        result
    }

    /// Given a point in the basis coordinate system, return the coordinates of the point in the
    /// global coordinate system.  This is done by summing the product of the basis vectors and the
    /// corresponding coordinate of the point, and then adding the center of the basis.
    ///
    /// # Arguments
    ///
    /// * `point`:
    ///
    /// returns: OPoint<f64, Const<{ D }>>
    pub fn point_from_basis(&self, point: &Point<f64, D>) -> Point<f64, D> {
        let mut result = Point::<f64, D>::origin();
        for i in 0..D {
            result += self.basis[i] * point[i];
        }
        result + self.center.coords
    }
}

fn svd_from_vectors<const D: usize>(
    vecs: &[SVector<f64, D>],
    center: Option<Point<f64, D>>,
) -> Option<SvdBasis<D>> {
    let n = vecs.len();
    let mut matrix = DMatrix::zeros(n, D);
    for (i, p) in vecs.iter().enumerate() {
        for j in 0..D {
            matrix[(i, j)] = p[j];
        }
    }

    let result = matrix.svd(false, true);
    let v_t = result.v_t?;

    if v_t.nrows() != D || v_t.ncols() != D {
        return None;
    }

    let mut basis = [SVector::<f64, D>::zeros(); D];
    let mut scales = [0.0; D];
    for i in 0..D {
        for j in 0..D {
            basis[i][j] = v_t[(i, j)];
        }
        scales[i] = result.singular_values[i];
    }

    Some(SvdBasis {
        basis,
        sv: scales,
        center: center.unwrap_or(Point::<f64, D>::origin()),
        n,
    })
}

pub fn iso3_from_basis(basis: &[SVector<f64, 3>; 3], origin: &Point<f64, 3>) -> Iso3 {
    let b0 = basis[0].normalize();
    let b1 = basis[1].normalize();
    let b2 = b0.cross(&b1).normalize();
    let rot_m = Matrix3::from_columns(&[b0, b1, b2]);
    let r = UnitQuaternion::from_matrix(&rot_m);
    let t = Translation3::from(origin.coords);
    Iso3::from_parts(t, r).inverse()
}

/// Create an isometry from an `x0` vector, a `y` vector, and an `origin` point. The `x0` vector
/// is a unit vector which defines the x-axis of the transformed coordinate system, exactly as
/// it is specified.  The `y` vector is used to derive `y0` by finding the component of `y` which
/// is orthogonal to `x0`.  The `z0` vector will be derived from `x0` and `y0` via the right hand
/// rule.  The `origin` point is the location of the origin of the transformed coordinate system.
///
/// # Arguments
///
/// * `x0`:
/// * `y`:
/// * `origin`:
///
/// returns: Isometry<f64, Unit<Quaternion<f64>>, 3>
///
/// # Examples
///
/// ```
///
/// ```
pub fn iso3_from_xyo(x0: &UnitVec3, y: &UnitVec3, origin: &Point<f64, 3>) -> Iso3 {
    // Project y onto x and then normalize to ensure it is a unit vector and orthogonal
    let y0 = Unit::new_normalize(y.into_inner() - x0.into_inner() * x0.dot(y));

    let z0 = x0.cross(&y0).normalize();

    let rot_m = Matrix3::from_columns(&[x0.into_inner(), y0.into_inner(), z0]);
    let r = UnitQuaternion::from_matrix(&rot_m);
    let t = Translation3::from(origin.coords);
    Iso3::from_parts(t, r).inverse()
}

pub fn iso2_from_basis(basis: &[SVector<f64, 2>; 2], origin: &Point<f64, 2>) -> Iso2 {
    let b0 = basis[0].normalize();
    let b1 = Rotation2::new(FRAC_PI_2) * b0;
    let rot_m = Matrix2::from_columns(&[b0, b1]);
    let r = UnitComplex::from_matrix(&rot_m);
    let t = Translation2::from(origin.coords);
    Iso2::from_parts(t, r).inverse()
}

impl From<&SvdBasis3> for Iso3 {
    fn from(value: &SvdBasis3) -> Self {
        iso3_from_basis(&value.basis, &value.center)
    }
}

impl From<&SvdBasis2> for Iso2 {
    fn from(value: &SvdBasis2) -> Self {
        iso2_from_basis(&value.basis, &value.center)
    }
}

impl From<SvdBasis3> for Iso3 {
    fn from(val: SvdBasis3) -> Self {
        iso3_from_basis(&val.basis, &val.center)
    }
}

impl From<SvdBasis2> for Iso2 {
    fn from(val: SvdBasis2) -> Self {
        iso2_from_basis(&val.basis, &val.center)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geom2::{Point2, Vector2};
    use crate::geom3::{Point3, Vector3};
    use approx::assert_relative_eq;
    use std::f64::consts::{FRAC_PI_4, PI, SQRT_2};

    #[test]
    fn from_points_perfect() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];

        let result = SvdBasis3::from_points(&points, None).unwrap();
        assert_relative_eq!(result.center, Point3::origin());
        assert_relative_eq!(result.basis[0], Vector3::x_axis());
        assert_relative_eq!(result.basis[1], Vector3::y_axis());
        assert_relative_eq!(result.basis[2], Vector3::z_axis());
        assert_eq!(result.n, 4);
    }

    fn rot_z() -> [Vector3; 3] {
        let iso = Iso3::from_parts(
            Translation3::identity(),
            UnitQuaternion::from_euler_angles(0.0, 0.0, PI / 4.0),
        );

        [
            iso * Vector3::new(1.0, 0.0, 0.0),
            iso * Vector3::new(0.0, 1.0, 0.0),
            iso * Vector3::new(0.0, 0.0, 1.0),
        ]
    }

    #[test]
    fn test_forward_no_shift() {
        let basis = rot_z();

        let origin = Point3::origin();
        let iso = iso3_from_basis(&basis, &origin);

        let test_point = Point3::new(1.0, 1.0, 0.0);
        let result = iso * test_point;

        assert_relative_eq!(result, Point3::new(SQRT_2, 0.0, 0.0), epsilon = 1e-12);
    }

    #[test]
    fn test_forward_with_shift_0() {
        let basis = rot_z();
        let origin = Point3::new(1.0, 1.0, 0.0);
        let iso = iso3_from_basis(&basis, &origin);

        let test_point = Point3::new(2.0, 2.0, 0.0);
        let result = iso * test_point;

        assert_relative_eq!(result, Point3::new(SQRT_2, 0.0, 0.0), epsilon = 1e-12);
    }

    #[test]
    fn test_forward_with_shift_1() {
        let basis = rot_z();
        let origin = Point3::new(-1.0, -1.0, 0.0);
        let iso = iso3_from_basis(&basis, &origin);

        let test_point = Point3::new(1.0, 1.0, 0.0);
        let result = iso * test_point;

        assert_relative_eq!(result, Point3::new(SQRT_2 * 2.0, 0.0, 0.0), epsilon = 1e-12);
    }

    #[test]
    fn largest_returns_first_basis_vector() {
        // X spread ±2, Y spread ±1 → X is largest
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let largest = basis.largest();
        // Component-wise abs to ignore sign conventions
        assert_relative_eq!(
            largest.into_inner().abs(),
            Vector3::x_axis().into_inner().abs(),
            epsilon = 1e-10
        );
    }

    #[test]
    fn smallest_returns_last_basis_vector() {
        // Z has zero spread → smallest
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let smallest = basis.smallest();
        assert_relative_eq!(
            smallest.into_inner().abs(),
            Vector3::z_axis().into_inner().abs(),
            epsilon = 1e-10
        );
    }

    #[test]
    fn basis_variances_match_formula() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let variances = basis.basis_variances();
        for (i, &var) in variances.iter().enumerate() {
            assert_relative_eq!(var, basis.sv[i].powi(2) / basis.n as f64, epsilon = 1e-10);
        }
    }

    #[test]
    fn basis_stdevs_are_sqrt_of_variances() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let variances = basis.basis_variances();
        let stdevs = basis.basis_stdevs();
        for (&var, &std) in variances.iter().zip(stdevs.iter()) {
            assert_relative_eq!(std, var.sqrt(), epsilon = 1e-10);
        }
    }

    #[test]
    fn rank_collinear_points_is_1() {
        let points: Vec<Point3> = (0..5).map(|i| Point3::new(i as f64, 0.0, 0.0)).collect();
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        assert_eq!(basis.rank(1e-10), 1);
    }

    #[test]
    fn rank_planar_points_is_2() {
        let points = vec![
            Point3::new(1.0, 0.0, 0.0),
            Point3::new(-1.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        assert_eq!(basis.rank(1e-10), 2);
    }

    #[test]
    fn rank_3d_points_is_3() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
            Point3::new(0.0, 0.0, 0.5),
            Point3::new(0.0, 0.0, -0.5),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        assert_eq!(basis.rank(1e-10), 3);
    }

    #[test]
    fn rank_with_high_tolerance_reduces_rank() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
            Point3::new(0.0, 0.0, 0.5),
            Point3::new(0.0, 0.0, -0.5),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        // A tolerance above the smallest SV should drop the rank
        let tol = basis.sv[2] + 0.1;
        assert_eq!(basis.rank(tol), 2);
    }

    #[test]
    fn point_to_basis_and_back_round_trips() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let p = Point3::new(1.5, 0.5, 0.0);
        let in_basis = basis.point_to_basis(&p);
        let back = basis.point_from_basis(&in_basis);
        assert_relative_eq!(back, p, epsilon = 1e-10);
    }

    #[test]
    fn point_to_basis_axis_aligned_preserves_coords() {
        // Axis-aligned basis centered at origin → basis coords equal global coords
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let p = Point3::new(1.0, 0.5, 0.0);
        let in_basis = basis.point_to_basis(&p);
        assert_relative_eq!(in_basis.x, 1.0, epsilon = 1e-10);
        assert_relative_eq!(in_basis.y, 0.5, epsilon = 1e-10);
        assert_relative_eq!(in_basis.z, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn vec_to_basis_axis_aligned() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let v = Vector3::new(1.0, 0.0, 0.0);
        let vb = basis.vec_to_basis(&v);
        assert_relative_eq!(vb[0], 1.0, epsilon = 1e-10);
        assert_relative_eq!(vb[1], 0.0, epsilon = 1e-10);
        assert_relative_eq!(vb[2], 0.0, epsilon = 1e-10);
    }

    #[test]
    fn from_points_2d_axis_aligned() {
        let points = vec![
            Point2::new(-2.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 1.0),
            Point2::new(0.0, -1.0),
        ];
        let basis = SvdBasis2::from_points(&points, None).unwrap();
        assert_relative_eq!(basis.center, Point2::origin());
        assert_relative_eq!(
            basis.basis[0].abs(),
            Vector2::x_axis().into_inner().abs(),
            epsilon = 1e-10
        );
        assert_eq!(basis.n, 4);
    }

    #[test]
    fn from_points_2d_point_round_trip() {
        let points = vec![
            Point2::new(-2.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 1.0),
            Point2::new(0.0, -1.0),
        ];
        let basis = SvdBasis2::from_points(&points, None).unwrap();
        let p = Point2::new(1.0, 0.5);
        let back = basis.point_from_basis(&basis.point_to_basis(&p));
        assert_relative_eq!(back, p, epsilon = 1e-10);
    }

    #[test]
    fn from_points_with_equal_weights_returns_some() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let weights = vec![1.0f64; 4];
        let result = SvdBasis3::from_points(&points, Some(&weights));
        assert!(result.is_some());
        assert_eq!(result.unwrap().n, 4);
    }

    #[test]
    fn iso3_from_xyo_identity_axes() {
        let x0 = UnitVec3::new_normalize(Vector3::new(1.0, 0.0, 0.0));
        let y = UnitVec3::new_normalize(Vector3::new(0.0, 1.0, 0.0));
        let iso = iso3_from_xyo(&x0, &y, &Point3::origin());
        // With identity orientation, points should be unchanged
        let p = Point3::new(1.0, 2.0, 3.0);
        let result = iso * p;
        assert_relative_eq!(result, p, epsilon = 1e-10);
    }

    #[test]
    fn iso3_from_xyo_orthogonalizes_y() {
        // y has an X component that must be removed
        let x0 = UnitVec3::new_normalize(Vector3::new(1.0, 0.0, 0.0));
        let y = UnitVec3::new_normalize(Vector3::new(1.0, 1.0, 0.0));
        let iso = iso3_from_xyo(&x0, &y, &Point3::origin());
        // A point purely in the Y direction should have no X component in local frame
        let p = Point3::new(0.0, 1.0, 0.0);
        let result = iso * p;
        assert_relative_eq!(result.x, 0.0, epsilon = 1e-10);
        assert_relative_eq!(result.y, 1.0, epsilon = 1e-10);
        assert_relative_eq!(result.z, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn iso3_from_xyo_with_origin_offset() {
        let x0 = UnitVec3::new_normalize(Vector3::new(1.0, 0.0, 0.0));
        let y = UnitVec3::new_normalize(Vector3::new(0.0, 1.0, 0.0));
        let origin = Point3::new(1.0, 1.0, 0.0);
        let iso = iso3_from_xyo(&x0, &y, &origin);
        // A point at the origin location should map to the local origin
        let result = iso * origin;
        assert_relative_eq!(result, Point3::origin(), epsilon = 1e-10);
    }

    #[test]
    fn iso2_from_basis_identity() {
        let basis = [Vector2::new(1.0, 0.0), Vector2::new(0.0, 1.0)];
        let iso = iso2_from_basis(&basis, &Point2::origin());
        let p = Point2::new(1.0, 2.0);
        assert_relative_eq!(iso * p, p, epsilon = 1e-10);
    }

    #[test]
    fn iso2_from_basis_rotated_45_degrees() {
        let c = FRAC_PI_4.cos();
        let s = FRAC_PI_4.sin();
        let basis = [Vector2::new(c, s), Vector2::new(-s, c)];
        let iso = iso2_from_basis(&basis, &Point2::origin());
        // A point along the basis direction should land on local +X
        let p = Point2::new(c, s);
        let result = iso * p;
        assert_relative_eq!(result.x, 1.0, epsilon = 1e-10);
        assert_relative_eq!(result.y, 0.0, epsilon = 1e-10);
    }

    #[test]
    fn iso2_from_basis_with_origin_offset() {
        let basis = [Vector2::new(1.0, 0.0), Vector2::new(0.0, 1.0)];
        let origin = Point2::new(3.0, 4.0);
        let iso = iso2_from_basis(&basis, &origin);
        let result = iso * origin;
        assert_relative_eq!(result, Point2::origin(), epsilon = 1e-10);
    }

    #[test]
    fn from_ref_svd_basis3_for_iso3_maps_center_to_origin() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let iso = Iso3::from(&basis);
        assert_relative_eq!(iso * basis.center, Point3::origin(), epsilon = 1e-10);
    }

    #[test]
    fn from_owned_svd_basis3_for_iso3_maps_center_to_origin() {
        let points = vec![
            Point3::new(-2.0, 0.0, 0.0),
            Point3::new(2.0, 0.0, 0.0),
            Point3::new(0.0, 1.0, 0.0),
            Point3::new(0.0, -1.0, 0.0),
        ];
        let basis = SvdBasis3::from_points(&points, None).unwrap();
        let center = basis.center;
        let iso = Iso3::from(basis);
        assert_relative_eq!(iso * center, Point3::origin(), epsilon = 1e-10);
    }

    #[test]
    fn from_ref_svd_basis2_for_iso2_maps_center_to_origin() {
        let points = vec![
            Point2::new(-2.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 1.0),
            Point2::new(0.0, -1.0),
        ];
        let basis = SvdBasis2::from_points(&points, None).unwrap();
        let iso = Iso2::from(&basis);
        assert_relative_eq!(iso * basis.center, Point2::origin(), epsilon = 1e-10);
    }

    #[test]
    fn from_owned_svd_basis2_for_iso2_maps_center_to_origin() {
        let points = vec![
            Point2::new(-2.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 1.0),
            Point2::new(0.0, -1.0),
        ];
        let basis = SvdBasis2::from_points(&points, None).unwrap();
        let center = basis.center;
        let iso = Iso2::from(basis);
        assert_relative_eq!(iso * center, Point2::origin(), epsilon = 1e-10);
    }
}