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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Common operations on f64 points in D-dimensional space.

use crate::Result;
use crate::common::kd_tree::{KdTreeSearch, PartialKdTree};
use crate::common::surface_point::SurfacePoint;
use crate::common::{IndexMask, PCoords};
use parry3d_f64::na::{AbstractRotation, Isometry, Point, SVector};

/// This is a simple helper function to help write a compact version of points that uses small
/// fixed sized arrays. Useful in unit tests or hard coded point definitions.
///
/// # Arguments
///
/// * `items`: a slice of fixed sized arrays to convert to points
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
///
/// ```
/// use engeom::Point2;
/// use engeom::common::points::to_points;
/// use approx::assert_relative_eq;
///
/// let points = to_points(&[[1.0, 2.0], [3.0, 4.0]]);
/// assert_eq!(points.len(), 2);
/// assert_relative_eq!(points[0], Point2::new(1.0, 2.0));
/// assert_relative_eq!(points[1], Point2::new(3.0, 4.0));
/// ```
pub fn to_points<const D: usize>(items: &[[f64; D]]) -> Vec<Point<f64, D>> {
    items.iter().map(|arr| Point::from(*arr)).collect()
}

/// Takes any slice of entities that implement `PCoords` and produces a new vec of points by
/// cloning the coordinates of each.
///
/// # Arguments
///
/// * `collection`: a slice of entities that implement `PCoords` to clone the coordinates of
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
pub fn clone_points<const D: usize>(collection: &[impl PCoords<D>]) -> Vec<Point<f64, D>> {
    collection
        .iter()
        .map(|pc| Point::from(pc.coords()))
        .collect()
}

/// Returns the area of a triangle defined by three points.
///
/// This function supports only 2D and 3D points:
/// - In 2D, the area is computed from the absolute value of the signed cross-product.
/// - In 3D, the area is computed as half of the norm of the cross-product of two triangle edges.
///
/// # Panics
///
/// Panics if `D` is not `2` or `3`.
///
/// # Examples
///
/// ```
/// use engeom::common::points::triangle_area;
/// use engeom::Point2;
///
/// let a = Point2::new(0.0, 0.0);
/// let b = Point2::new(2.0, 0.0);
/// let c = Point2::new(0.0, 2.0);
///
/// let area = triangle_area(&a, &b, &c);
/// assert_eq!(area, 2.0);
/// ```
pub fn triangle_area<const D: usize>(
    pa: &impl PCoords<D>,
    pb: &impl PCoords<D>,
    pc: &impl PCoords<D>,
) -> f64 {
    let ab = pb.coords() - pa.coords();
    let ac = pc.coords() - pa.coords();

    if D == 2 {
        0.5 * (ab[0] * ac[1] - ab[1] * ac[0]).abs()
    } else if D == 3 {
        0.5 * ab.cross(&ac).norm()
    } else {
        panic!("Area calculation is only implemented for 2D and 3D points");
    }
}

/// Measure the angle between `pc`->`p1` and `pc`->`p2` in D-dimensional space.
///
/// # Arguments
///
/// * `pc`: The common point from which the angle is measured.
/// * `p1`: The first point to measure the angle to.
/// * `p2`: The second point to measure the angle to.
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::Point2;
/// use engeom::common::points::three_point_angle;
/// let pc = Point2::new(0.0, 0.0);
/// let p1 = Point2::new(1.0, 0.0);
/// let p2 = Point2::new(0.0, 1.0);
/// let angle = three_point_angle(&pc, &p1, &p2);
///
/// assert_relative_eq!(angle, std::f64::consts::FRAC_PI_2, epsilon = 1e-6);
/// ```
pub fn three_point_angle<const D: usize>(
    pc: &impl PCoords<D>,
    p1: &impl PCoords<D>,
    p2: &impl PCoords<D>,
) -> f64 {
    let v1 = p1.coords() - pc.coords();
    let v2 = p2.coords() - pc.coords();
    v1.angle(&v2)
}

/// Returns the distance between two points in D-dimensional space.
///
/// # Arguments
///
/// * `a`: the first point
/// * `b`: the second point
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use engeom::common::points::dist;
/// use engeom::Point2;
/// let a = Point2::new(1.0, 2.0);
/// let b = Point2::new(3.0, 2.0);
/// let d = dist(&a, &b);
/// assert_eq!(d, 2.0);
/// ```
pub fn dist<const D: usize>(a: &impl PCoords<D>, b: &impl PCoords<D>) -> f64 {
    (a.coords() - b.coords()).norm()
}

/// Returns the midpoint between two points in D-dimensional space.
///
/// # Arguments
///
/// * `a`: the first point
/// * `b`: the second point
///
/// returns: OPoint<f64, Const<{ D }>>
///
/// # Examples
///
/// ```
/// use engeom::common::points::mid_point;
/// use engeom::Point2;
/// let a = Point2::new(1.0, 2.0);
/// let b = Point2::new(3.0, 4.0);
/// let mid = mid_point(&a, &b);
/// assert_eq!(mid, Point2::new(2.0, 3.0));
/// ```
pub fn mid_point<const D: usize>(a: &impl PCoords<D>, b: &impl PCoords<D>) -> Point<f64, D> {
    Point::from(b.coords() + (a.coords() - b.coords()) * 0.5)
}

/// Returns the mean point of a set of points in D-dimensional space.  The mean is found by summing
/// the coordinates of all points and dividing by the number of points.  There is no weighting of
/// the points in this calculation.
///
/// # Arguments
///
/// * `points`: a slice of points to compute the mean of
///
/// returns: OPoint<f64, Const<{ D }>>
///
/// # Examples
///
/// ```
/// use engeom::common::points::mean_point;
/// use engeom::Point2;
/// let points = vec![Point2::new(1.0, 2.0), Point2::new(3.0, 4.0), Point2::new(5.0, 6.0)];
/// let mean = mean_point(&points);
/// assert_eq!(mean, Point2::new(3.0, 4.0));
/// ```
pub fn mean_point<const D: usize>(points: &[impl PCoords<D>]) -> Point<f64, D> {
    let mut sum = SVector::<f64, D>::zeros();
    for p in points {
        sum += p.coords();
    }
    Point::from(sum / points.len() as f64)
}

/// Computes the weighted mean point of a set of points in D-dimensional space
///
/// # Arguments
///
/// * `points`: the points to compute the weighted mean of
/// * `weights`: a slice of weights for each point. The length of this slice must be the same as
///   the length of the `points` slice
///
/// returns: OPoint<f64, Const<{ D }>>
pub fn mean_point_weighted<const D: usize>(
    points: &[impl PCoords<D>],
    weights: &[f64],
) -> Point<f64, D> {
    let mut sum = SVector::<f64, D>::zeros();
    let mut total_weight = 0.0;
    for (p, w) in points.iter().zip(weights) {
        sum += p.coords() * *w;
        total_weight += *w;
    }
    Point::from(sum / total_weight)
}

/// Produces a new set of points by evenly spacing points between `start` and `end` in
/// D-dimensional space.  The number of points to generate is specified by `num_points`.  The
/// start and end points are included in the result.
///
/// # Arguments
///
/// * `start`: the starting point (will be included in the result)
/// * `end`: the ending point (will be included in the result)
/// * `num_points`: the total number of points to generate
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::common::points::evenly_spaced_points;
/// use engeom::Point2;
/// let start = Point2::new(0.0, 0.0);
/// let end = Point2::new(2.0, 0.0);
/// let points = evenly_spaced_points(&start, &end, 3);
///
/// assert_eq!(points.len(), 3);
/// assert_relative_eq!(points[0], Point2::new(0.0, 0.0));
/// assert_relative_eq!(points[1], Point2::new(1.0, 0.0));
/// assert_relative_eq!(points[2], Point2::new(2.0, 0.0));
/// ```
pub fn evenly_spaced_points<const D: usize>(
    start: &impl PCoords<D>,
    end: &impl PCoords<D>,
    num_points: usize,
) -> Vec<Point<f64, D>> {
    // TODO: needs test coverage
    let mut result = Vec::new();
    let step = (end.coords() - start.coords()) / (num_points - 1) as f64;
    for i in 0..num_points {
        result.push((start.coords() + step * i as f64).into());
    }
    result
}

/// Generate a new set of points by evenly spacing points between `start` and `end` in D-dimensional
/// space.  The number of points to generate is specified by `num_points`.  The start and end points
/// are **not** included in the result.
///
/// # Arguments
///
/// * `start`: the starting point (will not be included in the result)
/// * `end`: the ending point (will not be included in the result)
/// * `num_points`: the total number of points to generate
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::common::points::evenly_spaced_points_between;
/// use engeom::Point2;
/// let start = Point2::new(0.0, 0.0);
/// let end = Point2::new(2.0, 0.0);
/// let points = evenly_spaced_points_between(&start, &end, 3);
///
/// assert_eq!(points.len(), 3);
/// assert_relative_eq!(points[0], Point2::new(0.5, 0.0));
/// assert_relative_eq!(points[1], Point2::new(1.0, 0.0));
/// assert_relative_eq!(points[2], Point2::new(1.5, 0.0));
/// ```
pub fn evenly_spaced_points_between<const D: usize>(
    start: &impl PCoords<D>,
    end: &impl PCoords<D>,
    num_points: usize,
) -> Vec<Point<f64, D>> {
    let mut result = Vec::new();
    let step = (end.coords() - start.coords()) / (num_points + 1) as f64;
    for i in 1..num_points + 1 {
        result.push((start.coords() + step * i as f64).into());
    }

    result
}

/// Creates a new vec of points from a slice of points by filling in gaps between points where the
/// distance between them is greater than `max_dist`.  An evenly spaced set of points is inserted
/// between the two points to satisfy the `max_dist` threshold.
///
/// This is the opposite of a simplification algorithm, like Ramer-Douglas-Peucker, and can be used
/// to precondition a set of points before using an algorithm which relies on proximity.
///
/// # Arguments
///
/// * `original`: the original slice of points to fill gaps in.
/// * `max_dist`: the maximum distance between points in the new set of points.
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::common::points::fill_gaps;
/// use engeom::Point2;
/// let points = vec![Point2::new(0.0, 0.0), Point2::new(2.0, 0.0)];
/// let filled = fill_gaps(&points, 1.5);
///
/// assert_eq!(filled.len(), 3);
/// assert_relative_eq!(filled[0], Point2::new(0.0, 0.0));
/// assert_relative_eq!(filled[1], Point2::new(1.0, 0.0));
/// assert_relative_eq!(filled[2], Point2::new(2.0, 0.0));
/// ```
pub fn fill_gaps<const D: usize>(original: &[Point<f64, D>], max_dist: f64) -> Vec<Point<f64, D>> {
    // We fill gaps by iterating through the points, and if the distance between the current point
    // and its predecessor is greater than some threshold, we compute the number of points that
    // should be inserted (evenly spaced) between the two points to satisfy the `max_dist`
    // threshold.
    if original.len() < 2 {
        return original.to_vec();
    }

    let mut result = vec![original[0]];

    for p in original.iter().skip(1) {
        let d = dist(p, result.last().unwrap());
        if d > max_dist {
            let mut n = 1;
            while d / (n + 1) as f64 > max_dist {
                n += 1;
            }
            for x in evenly_spaced_points_between(result.last().unwrap(), p, n) {
                result.push(x);
            }
        }
        result.push(*p);
    }

    result
}

/// Returns the point in a set of points which has the largest value when projected onto a vector.
/// This is effectively the same as finding the point that is the furthest in the direction of the
/// vector.
///
/// There is nothing assumed about the list of points, so it is an O(n) operation where n is the
/// number of points in the set.
///
/// # Arguments
///
/// * `points`: the set of points to search
/// * `vector`: the vector to project the points onto
///
/// returns: Option<(usize, OPoint<f64, Const<{ D }>>)>
///
/// # Examples
///
/// ```
/// use engeom::common::points::max_point_in_direction;
/// use engeom::{Point2, Vector2};
/// use approx::assert_relative_eq;
///
/// let dir = Vector2::new(-10.0, -10.0);
///
/// let points = vec![
///    Point2::new(10.0, 0.0),
///    Point2::new(11.0, 1.0),
///    Point2::new(12.0, 2.0),
///    Point2::new(13.0, 3.0),
/// ];
///
/// let (_, max) = max_point_in_direction(&points, &dir).unwrap();
/// assert_relative_eq!(max, Point2::new(10.0, 0.0));
/// ```
pub fn max_point_in_direction<const D: usize>(
    points: &[impl PCoords<D>],
    vector: &SVector<f64, D>,
) -> Option<(usize, Point<f64, D>)> {
    let mut max_dist = f64::MIN;
    let mut max_i = None;

    for (i, p) in points.iter().enumerate() {
        let dist = p.coords().dot(vector);
        if dist > max_dist {
            max_dist = dist;
            max_i = Some(i);
        }
    }

    max_i.map(|max_i| (max_i, points[max_i].coords().into()))
}

/// Compute the error of a linear interpolation between two points `p0` and `p1` with respect to a
/// test point `p_test`.  The error is the distance between the test point and the projection of the
/// test point onto the line defined by `p0` and `p1`.  This can be thought of as the error that
/// would exist if the test point did not exist.
///
/// # Arguments
///
/// * `p0`: the first point of the linear interpolation
/// * `p1`: the second point of the linear interpolation
/// * `p_test`: a test point to project onto the line defined by `p0` and `p1`
///
/// returns: f64
///
/// # Examples
///
/// ```
/// use approx::assert_relative_eq;
/// use engeom::Point2;
/// use engeom::common::points::linear_interpolation_error;
///
/// let p0 = Point2::new(0.0, 0.0);
/// let p1 = Point2::new(2.0, 0.0);
/// let p_test = Point2::new(1.0, 1.0);
///
/// let error = linear_interpolation_error(&p0, &p1, &p_test);
/// assert_relative_eq!(error, 1.0);
/// ```
pub fn linear_interpolation_error<const D: usize>(
    p0: &impl PCoords<D>,
    p1: &impl PCoords<D>,
    p_test: &Point<f64, D>,
) -> f64 {
    let sp = SurfacePoint::new_normalize(p0.coords().into(), p1.coords() - p0.coords());
    let proj = sp.projection(p_test);

    dist(p_test, &proj)
}

/// Perform the Ramer-Douglas-Peucker algorithm on a set of points in D-dimensional space.  The
/// algorithm simplifies a curve by reducing the number of points while preserving the shape of the
/// curve.  The `tol` parameter is the maximum distance from the simplified curve to the original
/// curve.
///
/// # Arguments
///
/// * `points`: The ordered set of points to simplify
/// * `tol`: The maximum distance from the simplified curve to the original curve
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
///
/// ```
///
/// ```
pub fn ramer_douglas_peucker<const D: usize>(
    points: &[Point<f64, D>],
    tol: f64,
) -> Vec<Point<f64, D>> {
    let mut rdp = Rdp::new(points, tol);
    rdp.simplify(0, points.len() - 1);
    rdp.generate_points()
}

/// A struct for handling the state of the Ramer-Douglas-Peucker algorithm.
struct Rdp<'a, const D: usize> {
    points: &'a [Point<f64, D>],
    keep: Vec<bool>,
    tol: f64,
}

impl<'a, const D: usize> Rdp<'a, D> {
    fn new(points: &'a [Point<f64, D>], tol: f64) -> Self {
        let keep = points.iter().map(|_| false).collect();
        Rdp { points, keep, tol }
    }

    fn simplify(&mut self, i0: usize, i1: usize) {
        self.keep[i0] = true;
        self.keep[i1] = true;
        if i1 - i0 < 2 {
            return;
        }

        let sp = SurfacePoint::new_normalize(self.points[i0], self.points[i1] - self.points[i0]);
        let mut max_dist = 0.0;
        let mut max_i = 0;

        for i in i0 + 1..i1 {
            let dist = (sp.projection(&self.points[i]) - self.points[i]).norm();
            if dist > max_dist {
                max_dist = dist;
                max_i = i;
            }
        }

        if max_dist > self.tol {
            self.simplify(i0, max_i);
            self.simplify(max_i, i1);
        }
    }

    fn generate_points(&self) -> Vec<Point<f64, D>> {
        let mut result = Vec::new();
        for i in 0..self.points.len() {
            if self.keep[i] {
                result.push(self.points[i]);
            }
        }
        result
    }
}

/// Generic 2 or 3 dimensional transformation of a slice of `Point` entities by an `Isometry`,
/// resulting in an owned `Vec` of new point entities being created and returned.
///
/// TODO: is parry's `transformed(...)` method acceptable to use here instead?
///
/// # Arguments
///
/// * `points`: a slice of `Point` entities to transform
/// * `transform`: the `Isometry` to apply to each point
///
/// returns: Vec<OPoint<f64, Const<{ D }>>, Global>
///
/// # Examples
///
/// ```
/// use engeom::{Point2, Iso2};
/// use engeom::common::points::transform_points;
/// use engeom::geom2::IsoExtensions2;
///
/// let points = vec![Point2::new(1.0, 2.0), Point2::new(3.0, 4.0)];
/// let transform = Iso2::from_translation(1.0, 2.0);
/// let transformed_points = transform_points(&points, &transform);
/// assert_eq!(transformed_points[0], Point2::new(2.0, 4.0));
/// assert_eq!(transformed_points[1], Point2::new(4.0, 6.0));
/// ```
pub fn transform_points<R, const D: usize>(
    points: &[Point<f64, D>],
    transform: &Isometry<f64, R, D>,
) -> Vec<Point<f64, D>>
where
    R: AbstractRotation<f64, D>,
{
    // TODO: needs test coverage
    points.iter().map(|p| transform * p).collect()
}

/// Clusters a set of points by distance tolerance, where all points reachable by a series of hops
/// less than or equal to the specified tolerance are grouped together into a single cluster.
///
/// This implementation does not make use of any spatial data structures, so it is O(n^2) in the
/// number of points.  Use it for relatively small numbers of points.
///
/// # Arguments
///
/// * `points`: the set of points from which to create clusters
/// * `tol`: the maximum distance between points in a cluster
///
/// returns: Vec<Vec<usize, Global>, Global>
pub fn cluster_points_by_tol<const D: usize>(
    points: &[Point<f64, D>],
    tol: f64,
) -> Result<Vec<Vec<usize>>> {
    let mut clusters = Vec::new();
    let mut working = IndexMask::new(points.len(), true);

    while !working.is_empty() {
        let mut group_mask = IndexMask::new(points.len(), false);
        group_mask.set(working.pop_true().unwrap(), true);
        loop {
            let tree = PartialKdTree::try_new(points, &group_mask)?;
            let mut to_add = Vec::new();

            // TODO: this can definitely be made more efficient by pre-selecting candidates
            for i in working.iter_true() {
                let (_, d) = tree.nearest_one(&points[i]);
                if d <= tol {
                    to_add.push(i);
                }
            }

            if to_add.is_empty() {
                break;
            } else {
                for i in to_add.iter().rev() {
                    group_mask.set(*i, true);
                    working.set(*i, false);
                }
            }
        }
        clusters.push(group_mask.to_indices());
    }

    Ok(clusters)
}

/// Merges a set of points into a reduced set of points by merging clusters of points that are
/// within a specified distance tolerance. Each cluster is replaced by the mean of the points in the
/// cluster.
///
/// # Arguments
///
/// * `points`: the set of points to merge
/// * `tol`: points within this distance of each other are merged into a single point
///
/// returns: Result<Vec<OPoint<f64, Const<{ D }>>, Global>, Box<dyn Error, Global>>
pub fn merge_points_by_tol<const D: usize>(
    points: &[Point<f64, D>],
    tol: f64,
) -> Result<Vec<Point<f64, D>>> {
    let clusters = cluster_points_by_tol(points, tol)?;
    Ok(clusters
        .iter()
        .map(|c| mean_point(&c.iter().map(|i| points[*i]).collect::<Vec<_>>()))
        .collect())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geom2::{Curve2, Point2};
    use crate::{Point3, Vector2};
    use approx::assert_relative_eq;

    #[test]
    fn distance_calc() {
        let p0 = Point2::new(0.0, 0.0);
        let p1 = Point2::new(3.0, 4.0);
        let d = dist(&p0, &p1);
        assert_eq!(d, 5.0); // 3-4-5 triangle
    }

    #[test]
    fn test_simple_reduce() {
        let mut c = curve_from(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0)]);
        c = insert(&mut c, 0.25);
        c = insert(&mut c, 0.75);
        let points = c.clone_points();
        assert_eq!(points.len(), 5);
        let reduced = ramer_douglas_peucker(&points, 0.001);
        assert_eq!(reduced.len(), 3);
        assert_relative_eq!(reduced[0], Point2::new(0.0, 0.0));
        assert_relative_eq!(reduced[1], Point2::new(1.0, 0.0));
        assert_relative_eq!(reduced[2], Point2::new(1.0, 1.0));
    }

    fn curve_from(points: &[(f64, f64)]) -> Curve2 {
        let points = points
            .iter()
            .map(|(x, y)| Point2::new(*x, *y))
            .collect::<Vec<_>>();
        Curve2::from_points(&points, 0.001, false).unwrap()
    }

    fn insert(c: &mut Curve2, l: f64) -> Curve2 {
        let points = c.clone_points();
        let lengths = c.lengths();
        let mut working = points
            .iter()
            .zip(lengths.iter())
            .map(|(p, l)| (*l, *p))
            .collect::<Vec<_>>();
        working.push((l, c.at_length(l).unwrap().point()));
        working.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
        let points = working.iter().map(|(_, p)| *p).collect::<Vec<_>>();
        Curve2::from_points(&points, 0.001, false).unwrap()
    }

    #[test]
    fn single_point_between() {
        let p0 = Point2::new(0.0, 0.0);
        let p1 = Point2::new(2.0, 0.0);
        let points = evenly_spaced_points_between(&p0, &p1, 1);

        assert_eq!(points.len(), 1);
        assert_relative_eq!(points[0], Point2::new(1.0, 0.0));
    }

    #[test]
    fn test_fill_gaps() {
        let points = vec![Point2::new(0.0, 0.0), Point2::new(2.0, 0.0)];
        let filled = fill_gaps(&points, 1.5);

        assert_eq!(filled.len(), 3);
        assert_relative_eq!(filled[0], Point2::new(0.0, 0.0));
        assert_relative_eq!(filled[1], Point2::new(1.0, 0.0));
        assert_relative_eq!(filled[2], Point2::new(2.0, 0.0));
    }

    #[test]
    fn max_point_in_dir() {
        let dir = Vector2::new(-10.0, -10.0);

        let points = vec![
            Point2::new(10.0, 0.0),
            Point2::new(11.0, 1.0),
            Point2::new(12.0, 2.0),
            Point2::new(13.0, 3.0),
            Point2::new(14.0, 4.0),
        ];

        let (_, max) = max_point_in_direction(&points, &dir).unwrap();
        assert_relative_eq!(max, Point2::new(10.0, 0.0));
    }

    #[test]
    fn clustering_by_tolerance_0() -> Result<()> {
        let points = vec![
            Point2::new(0.0, 0.0),
            Point2::new(1.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 5.0),
            Point2::new(1.0, 5.0),
            Point2::new(0.0, 20.0),
        ];

        let mut c = cluster_points_by_tol(&points, 5.1)?;
        c.sort_by(|a, b| a.len().partial_cmp(&b.len()).unwrap());
        assert_eq!(c.len(), 2);
        assert_eq!(c[0].len(), 1);
        assert_eq!(c[1].len(), 5);

        let mut c0 = c[0].to_vec();
        c0.sort();
        let mut c1 = c[1].to_vec();
        c1.sort();

        assert_eq!(c0, vec![5]);
        assert_eq!(c1, vec![0, 1, 2, 3, 4]);

        Ok(())
    }

    #[test]
    fn clustering_by_tolerance_1() -> Result<()> {
        let points = vec![
            Point2::new(0.0, 0.0),
            Point2::new(1.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 5.0),
            Point2::new(1.0, 5.0),
            Point2::new(0.0, 20.0),
        ];

        let mut c = cluster_points_by_tol(&points, 1.1)?;
        assert_eq!(c.len(), 3);
        c.sort_by(|a, b| a.len().partial_cmp(&b.len()).unwrap());

        let mut c0 = c[0].to_vec();
        c0.sort();
        let mut c1 = c[1].to_vec();
        c1.sort();
        let mut c2 = c[2].to_vec();
        c2.sort();

        assert_eq!(c0, vec![5]);
        assert_eq!(c1, vec![3, 4]);
        assert_eq!(c2, vec![0, 1, 2]);

        Ok(())
    }

    #[test]
    fn merge_points_by_tolerance() -> Result<()> {
        let points = vec![
            Point2::new(0.0, 0.0),
            Point2::new(1.0, 0.0),
            Point2::new(2.0, 0.0),
            Point2::new(0.0, 5.0),
            Point2::new(1.0, 5.0),
            Point2::new(0.0, 20.0),
        ];

        let mut merged = merge_points_by_tol(&points, 1.1)?;
        assert_eq!(merged.len(), 3);

        merged.sort_by(|a, b| a.y.partial_cmp(&b.y).unwrap());

        assert_relative_eq!(merged[0], Point2::new(1.0, 0.0));
        assert_relative_eq!(merged[1], Point2::new(0.5, 5.0));
        assert_relative_eq!(merged[2], Point2::new(0.0, 20.0));

        Ok(())
    }

    #[test]
    fn three_point_angle_right_angle_2d() {
        let pc = Point2::new(0.0, 0.0);
        let p1 = Point2::new(1.0, 0.0);
        let p2 = Point2::new(0.0, 1.0);

        let angle = three_point_angle(&pc, &p1, &p2);

        assert_relative_eq!(angle, std::f64::consts::FRAC_PI_2, epsilon = 1e-12);
    }

    #[test]
    fn triangle_area_2d() {
        let a = Point2::new(0.0, 0.0);
        let b = Point2::new(2.0, 0.0);
        let c = Point2::new(0.0, 3.0);

        let area = triangle_area(&a, &b, &c);

        assert_relative_eq!(area, 3.0, epsilon = 1e-12);
    }

    #[test]
    fn triangle_area_3d() {
        let a = Point3::new(0.0, 0.0, 0.0);
        let b = Point3::new(2.0, 0.0, 0.0);
        let c = Point3::new(0.0, 3.0, 0.0);
        let area = triangle_area(&a, &b, &c);
        assert_relative_eq!(area, 3.0, epsilon = 1e-12);
    }

    #[test]
    fn linear_interpolation_error_zero_on_line() {
        let p0 = Point2::new(0.0, 0.0);
        let p1 = Point2::new(2.0, 0.0);
        let p_test = Point2::new(1.0, 0.0);

        let error = linear_interpolation_error(&p0, &p1, &p_test);

        assert_relative_eq!(error, 0.0, epsilon = 1e-12);
    }

    #[test]
    fn linear_interpolation_error_one_on_line() {
        let p0 = Point2::new(0.0, 0.0);
        let p1 = Point2::new(2.0, 0.0);
        let p_test = Point2::new(1.0, 1.0);

        let error = linear_interpolation_error(&p0, &p1, &p_test);

        assert_relative_eq!(error, 1.0, epsilon = 1e-12);
    }

    #[test]
    fn mean_point_weighted_equal_weights_matches_unweighted() {
        let points = vec![
            Point3::new(0.0, 0.0, 0.0),
            Point3::new(2.0, 4.0, 6.0),
            Point3::new(-1.0, 3.0, 5.0),
            Point3::new(4.0, -2.0, 1.0),
        ];
        let weights = vec![2.5; points.len()];
        let weighted = mean_point_weighted(&points, &weights);
        let unweighted = mean_point(&points);
        assert_relative_eq!(weighted, unweighted, epsilon = 1e-12);
    }

    #[test]
    fn mean_point_weighted_known_value() {
        // Weighted mean of two points: with weights 1 and 3, the result sits 3/4 of the way from
        // the first point toward the second.
        let points = vec![Point2::new(0.0, 0.0), Point2::new(4.0, 8.0)];
        let weights = vec![1.0, 3.0];
        let mean = mean_point_weighted(&points, &weights);
        assert_relative_eq!(mean, Point2::new(3.0, 6.0), epsilon = 1e-12);
    }

    #[test]
    fn mean_point_weighted_zero_weights_are_ignored() {
        // Points with zero weight contribute nothing to either the numerator or the total weight,
        // so the result depends only on the non-zero-weighted points.
        let points = vec![
            Point2::new(1.0, 1.0),
            Point2::new(100.0, 100.0),
            Point2::new(3.0, 3.0),
        ];
        let weights = vec![1.0, 0.0, 1.0];
        let mean = mean_point_weighted(&points, &weights);
        assert_relative_eq!(mean, Point2::new(2.0, 2.0), epsilon = 1e-12);
    }

    #[test]
    fn mean_point_weighted_scale_invariant() {
        // Scaling every weight by a constant leaves the weighted mean unchanged.
        let points = vec![
            Point3::new(1.0, 2.0, 3.0),
            Point3::new(-4.0, 0.5, 7.0),
            Point3::new(2.0, -1.0, 0.0),
        ];
        let weights = vec![0.5, 2.0, 1.5];
        let scaled: Vec<f64> = weights.iter().map(|w| w * 10.0).collect();
        let a = mean_point_weighted(&points, &weights);
        let b = mean_point_weighted(&points, &scaled);
        assert_relative_eq!(a, b, epsilon = 1e-12);
    }
}