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
use std::cmp::Ordering;
use std::collections::BinaryHeap;
pub trait Point: Sized + PartialEq {
fn distance(&self, other: &Self) -> f64;
fn move_towards(&self, other: &Self, d: f64) -> Self;
}
fn midpoint<P: Point>(a: &P, b: &P) -> P {
let d = a.distance(b);
a.move_towards(b, d / 2.0)
}
impl<const D: usize> Point for [f64; D] {
fn distance(&self, other: &Self) -> f64 {
self.iter()
.zip(other)
.map(|(a, b)| (*a - *b).powi(2))
.sum::<f64>()
.sqrt()
}
fn move_towards(&self, other: &Self, d: f64) -> Self {
let mut result = self.clone();
let distance = self.distance(other);
if distance == 0.0 {
return result;
}
let scale = d / self.distance(other);
for i in 0..D {
result[i] += scale * (other[i] - self[i]);
}
result
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
struct OrdF64(f64);
impl OrdF64 {
fn new(x: f64) -> Self {
assert!(!x.is_nan());
OrdF64(x)
}
}
impl Eq for OrdF64 {}
impl Ord for OrdF64 {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
struct Sphere<C> {
center: C,
radius: f64,
}
fn bounding_sphere<P: Point>(points: &[P]) -> Sphere<P> {
assert!(points.len() >= 2);
let a = &points
.iter()
.max_by_key(|a| OrdF64::new(points[0].distance(a)))
.unwrap();
let b = &points
.iter()
.max_by_key(|b| OrdF64::new(a.distance(b)))
.unwrap();
let mut center: P = midpoint(a, b);
let mut radius = center.distance(b).max(std::f64::EPSILON);
loop {
match points.iter().filter(|p| center.distance(p) > radius).next() {
None => break Sphere { center, radius },
Some(p) => {
let c_to_p = center.distance(&p);
let d = c_to_p - radius;
center = center.move_towards(p, d);
radius = radius * 1.01;
}
}
}
}
fn partition<P: Point, V>(
mut points: Vec<P>,
mut values: Vec<V>,
) -> ((Vec<P>, Vec<V>), (Vec<P>, Vec<V>)) {
assert!(points.len() >= 2);
assert_eq!(points.len(), values.len());
let a_i = points
.iter()
.enumerate()
.max_by_key(|(_, a)| OrdF64::new(points[0].distance(a)))
.unwrap()
.0;
let b_i = points
.iter()
.enumerate()
.max_by_key(|(_, b)| OrdF64::new(points[a_i].distance(b)))
.unwrap()
.0;
let (a_i, b_i) = (a_i.max(b_i), a_i.min(b_i));
let (mut aps, mut avs) = (vec![points.swap_remove(a_i)], vec![values.swap_remove(a_i)]);
let (mut bps, mut bvs) = (vec![points.swap_remove(b_i)], vec![values.swap_remove(b_i)]);
for (p, v) in points.into_iter().zip(values) {
if aps[0].distance(&p) < bps[0].distance(&p) {
aps.push(p);
avs.push(v);
} else {
bps.push(p);
bvs.push(v);
}
}
((aps, avs), (bps, bvs))
}
#[derive(Debug, Clone)]
enum BallTreeInner<P, V> {
Empty,
Leaf(P, Vec<V>),
Branch(
Sphere<P>,
Box<BallTreeInner<P, V>>,
Box<BallTreeInner<P, V>>,
),
}
impl<P: Point, V> Default for BallTreeInner<P, V> {
fn default() -> Self {
BallTreeInner::Empty
}
}
impl<P: Point, V> BallTreeInner<P, V> {
fn new(mut points: Vec<P>, values: Vec<V>) -> Self {
assert_eq!(
points.len(),
values.len(),
"Given two vectors of differing lengths. points: {}, values: {}",
points.len(),
values.len()
);
if points.is_empty() {
BallTreeInner::Empty
} else if points.iter().all(|p| p == &points[0]) {
BallTreeInner::Leaf(points.pop().unwrap(), values)
} else {
let sphere = bounding_sphere(&points);
let ((aps, avs), (bps, bvs)) = partition(points, values);
let (a_tree, b_tree) = (BallTreeInner::new(aps, avs), BallTreeInner::new(bps, bvs));
BallTreeInner::Branch(sphere, Box::new(a_tree), Box::new(b_tree))
}
}
fn distance(&self, p: &P) -> f64 {
match self {
BallTreeInner::Empty => std::f64::INFINITY,
BallTreeInner::Leaf(p0, _) => p.distance(p0),
BallTreeInner::Branch(sphere, _, _) => p.distance(&sphere.center) - sphere.radius,
}
}
}
#[derive(Debug, Copy, Clone)]
struct Item<T>(f64, T);
impl<T> PartialEq for Item<T> {
fn eq(&self, other: &Self) -> bool {
self.0 == other.0
}
}
impl<T> Eq for Item<T> {}
impl<T> PartialOrd for Item<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.0
.partial_cmp(&other.0)
.map(|ordering| ordering.reverse())
}
}
impl<T> Ord for Item<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.partial_cmp(other).unwrap()
}
}
#[derive(Debug)]
pub struct Iter<'tree, 'query, P, V> {
point: &'query P,
balls: &'query mut BinaryHeap<Item<&'tree BallTreeInner<P, V>>>,
i: usize,
max_radius: f64,
}
impl<'tree, 'query, P: Point, V> Iterator for Iter<'tree, 'query, P, V> {
type Item = (&'tree P, f64, &'tree V);
fn next(&mut self) -> Option<Self::Item> {
while self.balls.len() > 0 {
if let Item(d, BallTreeInner::Leaf(p, vs)) = self.balls.peek().unwrap() {
if self.i < vs.len() && *d <= self.max_radius {
self.i += 1;
return Some((p, *d, &vs[self.i - 1]));
}
}
self.i = 0;
if let Item(_, BallTreeInner::Branch(_, a, b)) = self.balls.pop().unwrap() {
let d_a = a.distance(self.point);
let d_b = b.distance(self.point);
if d_a <= self.max_radius {
self.balls.push(Item(d_a, a));
}
if d_b <= self.max_radius {
self.balls.push(Item(d_b, b));
}
}
}
None
}
}
impl<'tree, 'query, P, V> Drop for Iter<'tree, 'query, P, V> {
fn drop(&mut self) {
self.balls.clear();
}
}
#[derive(Debug, Clone)]
pub struct BallTree<P, V>(BallTreeInner<P, V>);
impl<P: Point, V> Default for BallTree<P, V> {
fn default() -> Self {
BallTree(BallTreeInner::default())
}
}
impl<P: Point, V> BallTree<P, V> {
pub fn new(points: Vec<P>, values: Vec<V>) -> Self {
BallTree(BallTreeInner::new(points, values))
}
pub fn query(&self) -> Query<P, V> {
Query {
ball_tree: self,
balls: Default::default(),
}
}
}
#[derive(Debug, Clone)]
pub struct Query<'tree, P, V> {
ball_tree: &'tree BallTree<P, V>,
balls: BinaryHeap<Item<&'tree BallTreeInner<P, V>>>,
}
impl<'tree, P: Point, V> Query<'tree, P, V> {
pub fn nn<'query>(
&'query mut self,
point: &'query P,
) -> Iter<'tree, 'query, P, V> {
self.nn_within(point, f64::INFINITY)
}
pub fn nn_within<'query>(
&'query mut self,
point: &'query P,
max_radius: f64,
) -> Iter<'tree, 'query, P, V> {
let balls = &mut self.balls;
balls.push(Item(self.ball_tree.0.distance(point), &self.ball_tree.0));
Iter {
point,
balls,
i: 0,
max_radius,
}
}
pub fn allocated_size(&self) -> usize {
self.balls.capacity() * std::mem::size_of::<Item<&'tree BallTreeInner<P, V>>>()
}
pub fn deallocate_memory(&mut self) {
assert!(self.balls.is_empty());
self.balls.shrink_to_fit();
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaChaRng;
use std::collections::HashSet;
#[test]
fn test_3d_points() {
let mut rng: ChaChaRng = SeedableRng::seed_from_u64(0xcb42c94d23346e96);
macro_rules! random_small_f64 {
() => {
rng.gen_range(-100.0, 100.0)
};
}
macro_rules! random_3d_point {
() => {
[
random_small_f64!(),
random_small_f64!(),
random_small_f64!(),
]
};
}
for _ in 0..1000 {
let point_count = rng.gen_range(0, 100usize);
let mut points = vec![];
let mut values = vec![];
for _ in 0..point_count {
let point = random_3d_point!();
let value = rng.gen::<u64>();
points.push(point);
values.push(value);
}
let tree = BallTree::new(points.clone(), values.clone());
let mut query = tree.query();
for _ in 0..100 {
let point = random_3d_point!();
let max_radius = rng.gen_range(0.0, 110.0);
let expected_values = points
.iter()
.zip(&values)
.filter(|(p, _)| p.distance(&point) <= max_radius)
.map(|(_, v)| v)
.cloned()
.collect::<HashSet<_>>();
let mut found_values = HashSet::new();
let mut previous_d = 0.0;
for (p, d, v) in query.nn_within(&point, max_radius) {
assert_eq!(point.distance(p), d);
assert!(d >= previous_d);
assert!(d <= max_radius);
previous_d = d;
found_values.insert(*v);
}
assert_eq!(expected_values, found_values);
}
assert!(query.allocated_size() > 0);
assert!(query.allocated_size() <= 2 * 8 * point_count.next_power_of_two().max(4));
query.deallocate_memory();
assert_eq!(query.allocated_size(), 0);
}
}
#[test]
fn test_point_array_impls() {
assert_eq!([5.0].distance(&[7.0]), 2.0);
assert_eq!([5.0].move_towards(&[3.0], 1.0), [4.0]);
assert_eq!([5.0, 3.0].distance(&[7.0, 5.0]), 2.0 * 2f64.sqrt());
assert_eq!(
[5.0, 3.0].move_towards(&[3.0, 1.0], 2f64.sqrt()),
[4.0, 2.0]
);
assert_eq!([0.0, 0.0, 0.0, 0.0].distance(&[2.0, 2.0, 2.0, 2.0]), 4.0);
assert_eq!(
[0.0, 0.0, 0.0, 0.0].move_towards(&[2.0, 2.0, 2.0, 2.0], 8.0),
[4.0, 4.0, 4.0, 4.0]
);
}
}