engeom 0.4.2

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
use crate::Result;
use crate::common::{IndexMask, PCoords};
use kdtree::KdTree as KdTreeInner;
use kdtree::distance::squared_euclidean;
use uuid::Uuid;

/// A KD tree associated with a unique UUID, such that it can be checked to be matched against a
/// specific entity.  The idea is that the UUID of the associated object will change if the object
/// points are modified, and thus the matched tree can be validated before use.
pub struct MatchedTree<const D: usize> {
    tree_uuid: Uuid,
    tree: KdTree<D>,
}

impl<const D: usize> MatchedTree<D> {
    pub fn new(tree_uuid: Uuid, tree: KdTree<D>) -> Self {
        Self { tree_uuid, tree }
    }

    pub fn tree_uuid(&self) -> Uuid {
        self.tree_uuid
    }

    pub fn tree(&self) -> &KdTree<D> {
        &self.tree
    }
}

pub trait KdTreeSearch<const D: usize> {
    fn nearest_one(&self, point: &impl PCoords<D>) -> (usize, f64);
    fn nearest(&self, point: &impl PCoords<D>, count: usize) -> Vec<(usize, f64)>;
    fn within(&self, point: &impl PCoords<D>, radius: f64) -> Vec<(usize, f64)>;

    fn len(&self) -> usize;
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

/// An immutable k-dimensional tree for fast searches on points in D dimensions
pub struct KdTree<const D: usize> {
    tree: KdTreeInner<f64, usize, [f64; D]>,
}

impl<const D: usize> KdTree<D> {
    /// Create a new immutable kd-tree from a list of points.
    ///
    /// # Arguments
    ///
    /// * `points`: A slice of points.
    ///
    /// returns: KdTree<{ D }>
    pub fn try_new(points: &[impl PCoords<D>]) -> Result<Self> {
        let mut entries: Vec<[f64; D]> = Vec::with_capacity(points.len());
        for p in points {
            entries.push(p.coords().into());
        }
        let mut tree = KdTreeInner::new(D);
        for (i, e) in entries.iter().enumerate() {
            tree.add(*e, i)?;
        }
        Ok(Self { tree })
    }
}

impl<const D: usize> KdTreeSearch<D> for KdTree<D> {
    /// Find the nearest point in the kd-tree to a given test point, returning the index of the
    /// nearest point and the distance to it.
    ///
    /// # Arguments
    ///
    /// * `point`: A test point to find the nearest point to.
    ///
    /// returns: (usize, f64)
    ///
    /// # Examples
    ///
    /// ```
    ///
    ///
    /// ```
    fn nearest_one(&self, point: &impl PCoords<D>) -> (usize, f64) {
        if let Ok(item) = self
            .tree
            .nearest(point.coords().as_slice(), 1, &squared_euclidean)
        {
            let (d, u) = &item[0];
            (**u, d.sqrt())
        } else {
            (usize::MAX, f64::INFINITY)
        }
    }

    /// Find the nearest `count` points in the kd-tree to a given point.
    ///
    /// # Arguments
    ///
    /// * `point`:
    /// * `count`:
    ///
    /// returns: Vec<(usize, f64), Global>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    fn nearest(&self, point: &impl PCoords<D>, count: usize) -> Vec<(usize, f64)> {
        let result = self
            .tree
            .nearest(point.coords().as_slice(), count, &squared_euclidean);

        if let Ok(neighbors) = result {
            neighbors.iter().map(|(d, u)| (**u, d.sqrt())).collect()
        } else {
            Vec::new()
        }
    }

    /// Find all points within a given radius of a point.
    ///
    /// # Arguments
    ///
    /// * `point`:
    /// * `radius`:
    ///
    /// returns: Vec<(usize, f64), Global>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    fn within(&self, point: &impl PCoords<D>, radius: f64) -> Vec<(usize, f64)> {
        if let Ok(result) = self.tree.within(
            point.coords().as_slice(),
            radius * radius,
            &squared_euclidean,
        ) {
            result.iter().map(|(d, u)| (**u, d.sqrt())).collect()
        } else {
            Vec::new()
        }
    }

    /// Get the number of points in the kd-tree.
    fn len(&self) -> usize {
        self.tree.size()
    }
}

/// A wrapper around a KdTree and a list of indices into an original list of points. This allows
/// for searches to be performed on a subset of the original points with indices returned which
/// correspond to the original list.
pub struct PartialKdTree<const D: usize> {
    tree: KdTree<D>,
    index_map: Vec<usize>,
}

impl<const D: usize> PartialKdTree<D> {
    /// Create a new partial kd-tree from a list of points and a list of indices into the original.
    ///
    /// The `indices` array should be a list of indices into the `all_points` array. The tree will
    /// be built using only the points at those indices, *however*, the indices returned by the
    /// search methods will be the indices into the original `all_points` array.
    ///
    /// # Arguments
    ///
    /// * `all_points`: A slice of points.
    /// * `indices`: A slice of indices into the `all_points` array to use for the tree.
    ///
    /// returns: PartialKdTree<{ D }>
    ///
    /// # Examples
    ///
    /// ```
    ///
    /// ```
    pub fn try_new(all_points: &[impl PCoords<D>], mask: &IndexMask) -> Result<Self> {
        if mask.len() != all_points.len() {
            panic!("Mask length must match the length of all_points");
        }

        let mut points = Vec::new();
        let mut index_map = Vec::new();
        for i in mask.iter_true() {
            points.push(all_points[i].coords());
            index_map.push(i);
        }
        let tree = KdTree::try_new(&points)?;
        Ok(Self { tree, index_map })
    }
}

impl<const D: usize> KdTreeSearch<D> for PartialKdTree<D> {
    fn nearest_one(&self, point: &impl PCoords<D>) -> (usize, f64) {
        let (i, d) = self.tree.nearest_one(point);
        (self.index_map[i], d)
    }

    fn nearest(&self, point: &impl PCoords<D>, count: usize) -> Vec<(usize, f64)> {
        let result = self.tree.nearest(point, count);
        result
            .iter()
            .map(|(i, d)| (self.index_map[*i], *d))
            .collect::<Vec<_>>()
    }

    fn within(&self, point: &impl PCoords<D>, radius: f64) -> Vec<(usize, f64)> {
        let result = self.tree.within(point, radius);
        result
            .iter()
            .map(|(i, d)| (self.index_map[*i], *d))
            .collect::<Vec<_>>()
    }

    /// Get the number of points in the kd-tree.
    fn len(&self) -> usize {
        self.tree.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::indices::index_vec;
    use crate::common::points::dist;
    use crate::tests::stanford_bun_2;
    use crate::{Point2, Point3};
    use approx::assert_relative_eq;
    use rand::prelude::SliceRandom;

    #[test]
    fn kd_tree_build() {
        let points = vec![
            Point2::new(0.0, 0.0),
            Point2::new(1.0, 1.0),
            Point2::new(2.0, 2.0),
        ];
        let tree = KdTree::try_new(&points).expect("KD tree creation failed");
        assert_eq!(tree.len(), 3);
    }

    #[test]
    fn kd_tree_nearest() {
        let points = vec![
            Point2::new(0.0, 0.0),
            Point2::new(1.0, 1.0),
            Point2::new(2.0, 2.0),
        ];
        let tree = KdTree::try_new(&points).expect("KD tree creation failed");
        let (i, d) = tree.nearest_one(&Point2::new(1.25, 1.25));
        assert_eq!(i, 1);
        assert_relative_eq!(d, (0.25 * 0.25 * 2.0_f64).sqrt(), epsilon = 1e-6);
    }

    #[test]
    fn kd_tree_check_distances_within() {
        let points = vec![
            Point2::new(0.0, 0.0),
            Point2::new(1.0, 0.0),
            Point2::new(2.0, 0.0),
        ];
        let tree = KdTree::try_new(&points).expect("KD tree creation failed");
        let within = tree.within(&Point2::new(3.5, 0.0), 2.0);
        assert_eq!(within.len(), 1);
        assert_eq!(within[0].0, 2);
        assert_relative_eq!(within[0].1, 1.5, epsilon = 1e-6);
    }

    #[test]
    fn partial_kd_tree_maps() {
        let points = (0..20)
            .flat_map(|i| (0..20).map(move |j| Point2::new(i as f64, j as f64)))
            .collect::<Vec<_>>();

        let fixed_tree = KdTree::try_new(&points).expect("KD tree creation failed");

        for _ in 0..1000 {
            let mut test_select = index_vec(None, points.len());
            test_select.shuffle(&mut rand::rng());

            // Use only half of the points for the partial tree
            let mut mask = IndexMask::new(points.len(), false);
            for &i in test_select.iter().take(points.len() / 2) {
                mask.set(i, true);
            }
            let indices = mask.to_indices();

            let partial_tree =
                PartialKdTree::try_new(&points, &mask).expect("KD tree creation failed");

            for &i in indices.iter() {
                let p = &points[i];
                let (j, _d) = fixed_tree.nearest_one(p);
                let (k, e) = partial_tree.nearest_one(p);
                assert_eq!(i, j);
                assert_eq!(i, k);
                assert_relative_eq!(0.0, e, epsilon = 1e-6);
                assert_relative_eq!(0.0, e, epsilon = 1e-6);
            }
        }
    }

    #[test]
    fn partial_kd_tree_nearest() -> Result<()> {
        let mesh = stanford_bun_2();
        let even = (0..mesh.points().len()).step_by(2).collect::<Vec<_>>();
        let mask = IndexMask::try_from_indices(&even, mesh.points().len())?;
        let reduced_points = mask.clone_indices_of(mesh.points())?;
        let reduced_tree = KdTree::try_new(&reduced_points)?;

        let partial_tree = PartialKdTree::try_new(mesh.points(), &mask)?;
        let n = 3;

        for p in mesh.points().iter() {
            let mut result = partial_tree
                .nearest(p, n)
                .iter()
                .map(|x| x.0)
                .collect::<Vec<_>>();
            let mut reduced_result = reduced_tree
                .nearest(p, n)
                .iter()
                .map(|x| x.0)
                .collect::<Vec<_>>();
            result.sort();
            reduced_result.sort();

            assert_eq!(result.len(), reduced_result.len());
            for (a, b) in result.iter().zip(reduced_result.iter()) {
                assert_relative_eq!(mesh.points()[*a], reduced_points[*b], epsilon = 1e-6);
            }
        }

        Ok(())
    }

    #[test]
    fn kd_tree_nearest_one_matches_brute_force_on_stanford_bun_vertices() {
        let mesh = stanford_bun_2();
        let vertices = mesh.points().to_vec();
        let tree = KdTree::try_new(&vertices).expect("KD tree creation failed");

        for (expected_index, query) in vertices.iter().enumerate() {
            let (actual_index, actual_distance) = tree.nearest_one(query);
            assert_eq!(actual_index, expected_index);
            assert_relative_eq!(actual_distance, 0.0, epsilon = 1e-6);

            let expected = brute_force_nearest_n(&vertices, query, 1);
            assert_eq!(expected.len(), 1);
            assert_eq!(expected[0].0, expected_index);
            assert_relative_eq!(expected[0].1, 0.0, epsilon = 1e-6);
        }
    }

    #[test]
    fn kd_tree_nearest_matches_brute_force_on_stanford_bun_vertices() {
        let mesh = stanford_bun_2();
        let vertices = mesh.points().to_vec();
        let tree = KdTree::try_new(&vertices).expect("KD tree creation failed");

        for query in &vertices {
            let expected = brute_force_nearest_n(&vertices, query, 3);
            let actual = tree.nearest(query, 3);

            assert_eq!(actual.len(), expected.len());
            for ((actual_index, actual_distance), (expected_index, expected_distance)) in
                actual.iter().zip(expected.iter())
            {
                assert_eq!(actual_index, expected_index);
                assert_relative_eq!(actual_distance, expected_distance, epsilon = 1e-6);
            }
        }
    }

    #[test]
    fn kd_tree_within_matches_brute_force_on_stanford_bun_vertices() {
        let mesh = stanford_bun_2();
        let vertices = mesh.points().to_vec();
        let tree = KdTree::try_new(&vertices).expect("KD tree creation failed");

        let search_dist = mesh.aabb().extents().x * 0.1;

        for query in vertices.iter() {
            let expected = vertices
                .iter()
                .filter(|p| dist(query, *p) < search_dist)
                .count();
            let tested = tree.within(query, search_dist).len();
            assert_eq!(tested, expected);
        }
    }

    /// Returns the `count` nearest points to `query` as `(index, distance)` pairs,
    /// sorted from nearest to farthest.
    ///
    /// If `count` is larger than the number of points, all points are returned.
    ///
    /// This is brute force: it checks every point in the collection.
    pub fn brute_force_nearest_n(
        points: &[Point3],
        query: &Point3,
        count: usize,
    ) -> Vec<(usize, f64)> {
        let mut neighbors: Vec<(usize, f64)> = points
            .iter()
            .enumerate()
            .map(|(i, p)| {
                let dx = p.x - query.x;
                let dy = p.y - query.y;
                let dz = p.z - query.z;
                let dist = (dx * dx + dy * dy + dz * dz).sqrt();
                (i, dist)
            })
            .collect();

        neighbors.sort_by(|a, b| a.1.total_cmp(&b.1));
        neighbors.truncate(count);
        neighbors
    }
}