kiddo 6.0.0-alpha.4

A high-performance, flexible, ergonomic k-d tree library. Ideal for geo- and astro- nearest-neighbour and k-nearest-neighbor queries
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
use num_traits::ConstZero;
use std::fmt::{Debug, Display};
use std::ops::{AddAssign, Sub};

use fixed::types::extra::{U0, U16, U8};
use fixed::{FixedI32, FixedU16};

use num_traits::Float;

/// Trait for coordinate/axis types used in the [`KdTree`](crate::kd_tree::KdTree) (the `A` type parameter)
///
/// This trait must be implemented on a type for it to be usable as the coordinates
/// for points stored in a `KdTree`.
///
/// * By default, it is defined for [`f32`], [`f64`], [`u8`], [`u16`], and [`u32`].
/// * Enabling the `f16` feature adds support for the [`f16`](https://docs.rs/half/latest/half/struct.f16.html) type from the [`half`](https://docs.rs/half/latest/half/) crate.
/// * Enabling the `fixed` feature adds support for the following types from the [`fixed`](https://docs.rs/fixed/latest/fixed/) crate:
///     - [`FixedI32<U16>`](https://docs.rs/fixed/latest/fixed/struct.FixedI32.html)
///     - [`FixedI32<U0>`](https://docs.rs/fixed/latest/fixed/struct.FixedI32.html)
///     - [`FixedU16<U8>`](https://docs.rs/fixed/latest/fixed/struct.FixedU16.html)
///     - [`FixedU16<U0>`](https://docs.rs/fixed/latest/fixed/struct.FixedU16.html)
///     - [`FixedU8<U0>`](https://docs.rs/fixed/latest/fixed/struct.FixedU8.html)
///
/// (If you have a requirement to support a `fixed` type that is not listed, please open an issue on GitHub.)
pub trait Axis:
    Copy
    + PartialEq
    + PartialOrd
    + Sub<Output = Self>
    + AddAssign<Self>
    + Debug
    + Display
    + crate::stem_strategy::CompareBlock3
    + crate::stem_strategy::CompareBlock4
{
    /// Whether subtraction can represent a negative result.
    ///
    /// Custom axes default to unsigned semantics so generic algorithms retain
    /// their conservative ordered-subtraction paths unless explicitly opted in.
    const IS_SIGNED: bool = false;

    const VALUE_WIDTH_BYTES: usize = size_of::<Self::Coord>();

    /// Coordinate scalar type stored in the tree and queries.
    type Coord: Copy;

    /// Zero coord.
    fn zero() -> Self::Coord;

    /// Maximum coord value.
    fn max_value() -> Self::Coord;

    /// Minimum coord value.
    fn min_value() -> Self::Coord;

    /// If coord is max value or not.
    fn is_max_value(coord: Self::Coord) -> bool;

    /// Compares two coordinate values.
    fn cmp(a: Self::Coord, b: Self::Coord) -> std::cmp::Ordering;

    /// Absolute/saturating difference along one axis, in coord units.
    fn saturating_dist(a: Self::Coord, b: Self::Coord) -> Self::Coord;

    /// Saturating addition of two coordinate values.
    fn saturating_add(a: Self::Coord, b: Self::Coord) -> Self::Coord;

    /// Returns the maximum of two coordinate values.
    fn max(a: Self::Coord, b: Self::Coord) -> Self::Coord;
}

/// Macro to implement AxisUnified for floating-point types.
macro_rules! impl_axis_float {
    ($t:ty, SIMD_BLOCK_SUPPORT => ( $( $block_size:literal => ($prune_fn:path, $compare_fn:path) ),* $(,)? )) => {
        impl_axis_float!($t);

        $(
            impl_simd_block_support!($t, $block_size, $prune_fn, $compare_fn);
        )*
    };

    ($t:ty) => {
        impl Axis for $t {
            const IS_SIGNED: bool = true;

            type Coord = $t;

            #[inline(always)]
            fn zero() -> Self::Coord {
                0.0
            }

            #[inline(always)]
            fn max_value() -> Self::Coord {
                <$t>::infinity()
            }

            #[inline(always)]
            fn min_value() -> Self::Coord {
                <$t>::neg_infinity()
            }

            #[inline(always)]
            fn is_max_value(coord: Self::Coord) -> bool {
                coord.is_infinite() && coord.is_sign_positive()
            }

            #[inline(always)]
            fn cmp(a: Self::Coord, b: Self::Coord) -> std::cmp::Ordering {
                // debug_assert!(
                //     a.is_finite() && b.is_finite(),
                //     "NaNs / Infinities should not be present in axis coordinates"
                // );
                if a < b {
                    std::cmp::Ordering::Less
                } else if a > b {
                    std::cmp::Ordering::Greater
                } else {
                    std::cmp::Ordering::Equal
                }
            }

            #[inline(always)]
            fn saturating_dist(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                (a - b).abs()
            }

            #[inline(always)]
            fn saturating_add(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                a + b
            }

            #[inline(always)]
            fn max(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                a.max(b)
            }
        }
    };
}

impl_axis_float!(f32);
impl_axis_float!(f64);

#[cfg(feature = "fixed")]
/// Macro to implement AxisUnified for fixed-point types.
macro_rules! impl_axis_fixed {
    // Pattern with SIMD block support
    ($t:ty, $is_signed:literal, SIMD_BLOCK_SUPPORT => ( $( $block_size:literal => ($prune_fn:path, $compare_fn:path) ),* $(,)? )) => {
        impl_axis_fixed!($t, $is_signed); // First implement the basic AxisUnified trait

        // Then implement SIMD block support for each specified block size
        $(
            impl_simd_block_support!($t, $block_size, $prune_fn, $compare_fn);
        )*
    };

    // Base pattern without SIMD block support (uses default unimplemented!() from traits)
    ($t:ty, $is_signed:literal) => {
        #[cfg(feature = "fixed")]
        impl Axis for $t {
            const IS_SIGNED: bool = $is_signed;

            type Coord = $t;

            #[inline(always)]
            fn zero() -> Self::Coord {
                <$t>::from_num(0)
            }

            #[inline(always)]
            fn max_value() -> Self::Coord {
                <Self::Coord>::MAX
            }

            #[inline(always)]
            fn min_value() -> Self::Coord {
                unimplemented!("min_value not yet implemented for fixed point types")
            }

            #[inline(always)]
            fn is_max_value(coord: Self::Coord) -> bool {
                coord == <$t>::max_value()
            }

            #[inline(always)]
            fn cmp(a: Self::Coord, b: Self::Coord) -> std::cmp::Ordering {
                a.cmp(&b)
            }

            #[inline(always)]
            fn saturating_dist(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                if a >= b {
                    a - b
                } else {
                    b - a
                }
            }

            #[inline(always)]
            fn saturating_add(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                a.saturating_add(b)
            }

            #[inline(always)]
            fn max(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                a.max(b)
            }
        }
    };
}

#[cfg(feature = "fixed")]
impl_axis_fixed!(FixedI32<U16>, true);
#[cfg(feature = "fixed")]
impl_axis_fixed!(FixedI32<U0>, true);
#[cfg(feature = "fixed")]
impl_axis_fixed!(FixedU16<U8>, false);

#[cfg(feature = "f16")]
impl Axis for half::f16 {
    const IS_SIGNED: bool = true;

    type Coord = half::f16;

    #[inline(always)]
    fn zero() -> Self::Coord {
        half::f16::from_f32(0.0)
    }

    #[inline(always)]
    fn max_value() -> Self::Coord {
        half::f16::from_f32(f32::INFINITY)
    }

    #[inline(always)]
    fn min_value() -> Self::Coord {
        half::f16::from_f32(f32::NEG_INFINITY)
    }

    #[inline(always)]
    fn is_max_value(coord: Self::Coord) -> bool {
        coord.is_infinite() && coord.is_sign_positive()
    }

    #[allow(clippy::ifs_same_cond)]
    #[inline(always)]
    fn cmp(a: Self::Coord, b: Self::Coord) -> std::cmp::Ordering {
        if a < b {
            std::cmp::Ordering::Less
        } else if b > a {
            std::cmp::Ordering::Greater
        } else {
            std::cmp::Ordering::Equal
        }
    }

    #[inline(always)]
    fn saturating_dist(a: Self::Coord, b: Self::Coord) -> Self::Coord {
        (a - b).abs()
    }

    #[inline(always)]
    fn saturating_add(a: Self::Coord, b: Self::Coord) -> Self::Coord {
        a + b
    }

    #[inline(always)]
    fn max(a: Self::Coord, b: Self::Coord) -> Self::Coord {
        if a > b {
            a
        } else {
            b
        }
    }
}

// TODO: Remove the current `MAX`-value exclusion for integer/fixed coordinates by
// flipping the tree invariant from `left < pivot, right >= pivot` to
// `left <= pivot, right > pivot`, then updating traversal, immutable pivot
// selection, mutable split-boundary handling, and block-compare semantics to
// match.
/// Macro to implement AxisUnified for unsigned integer types.
macro_rules! impl_axis_uint {
    // Pattern with SIMD block support
    ($t:ty, SIMD_BLOCK_SUPPORT => ( $( $block_size:literal => ($prune_fn:path, $compare_fn:path) ),* $(,)? )) => {
        impl_axis_uint!($t); // First implement the basic AxisUnified trait

        // Then implement SIMD block support for each specified block size
        $(
            impl_simd_block_support!($t, $block_size, $prune_fn, $compare_fn);
        )*
    };

    // Base pattern without SIMD block support (uses default unimplemented!() from traits)
    ($t:ty) => {
        impl Axis for $t {
            type Coord = $t;

            #[inline(always)]
            fn zero() -> Self::Coord {
                <Self::Coord>::ZERO
            }

            #[inline(always)]
            fn max_value() -> Self::Coord {
                <Self::Coord>::MAX
            }

            #[inline(always)]
            fn min_value() -> Self::Coord {
                <$t>::zero()
            }

            #[inline(always)]
            fn is_max_value(coord: Self::Coord) -> bool {
                coord == <$t>::MAX
            }

            #[inline(always)]
            fn cmp(a: Self::Coord, b: Self::Coord) -> std::cmp::Ordering {
                a.cmp(&b)
            }

            #[inline(always)]
            fn saturating_dist(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                if a >= b {
                    a - b
                } else {
                    b - a
                }
            }

            #[inline(always)]
            fn saturating_add(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                a.saturating_add(b)
            }

            #[inline(always)]
            fn max(a: Self::Coord, b: Self::Coord) -> Self::Coord {
                a.max(b)
            }
        }
    };
}

impl_axis_uint!(u8);
impl_axis_uint!(u16);
impl_axis_uint!(u32);

#[cfg(test)]
mod tests {
    use super::Axis;

    #[test]
    fn float_axis_helpers_behave_as_expected() {
        assert!(<f32 as Axis>::IS_SIGNED);
        assert_eq!(<f32 as Axis>::zero(), 0.0);
        assert!(<f32 as Axis>::is_max_value(<f32 as Axis>::max_value()));
        assert_eq!(<f32 as Axis>::cmp(1.0, 2.0), std::cmp::Ordering::Less);
        assert_eq!(<f32 as Axis>::cmp(2.0, 1.0), std::cmp::Ordering::Greater);
        assert_eq!(<f32 as Axis>::cmp(2.0, 2.0), std::cmp::Ordering::Equal);
        assert_eq!(<f32 as Axis>::saturating_dist(5.0, 2.5), 2.5);
        assert_eq!(<f32 as Axis>::saturating_add(1.5, 2.0), 3.5);
        assert_eq!(<f32 as Axis>::max(3.0, 4.0), 4.0);

        assert_eq!(<f64 as Axis>::zero(), 0.0);
        assert!(!<f64 as Axis>::is_max_value(<f64 as Axis>::min_value()));
        assert_eq!(<f64 as Axis>::saturating_dist(2.0, 5.5), 3.5);
    }

    #[test]
    fn unsigned_axis_helpers_behave_as_expected() {
        assert!(!<u8 as Axis>::IS_SIGNED);
        assert_eq!(<u8 as Axis>::zero(), 0);
        assert_eq!(<u8 as Axis>::min_value(), 0);
        assert_eq!(<u8 as Axis>::max_value(), u8::MAX);
        assert!(<u8 as Axis>::is_max_value(u8::MAX));
        assert_eq!(<u8 as Axis>::cmp(1, 2), std::cmp::Ordering::Less);
        assert_eq!(<u8 as Axis>::saturating_dist(2, 5), 3);
        assert_eq!(<u8 as Axis>::saturating_add(250, 10), u8::MAX);
        assert_eq!(<u8 as Axis>::max(3, 4), 4);

        assert_eq!(<u16 as Axis>::saturating_dist(9, 4), 5);
        assert_eq!(<u32 as Axis>::saturating_add(u32::MAX, 1), u32::MAX);
    }

    #[cfg(feature = "fixed")]
    #[test]
    fn fixed_axis_helpers_behave_as_expected() {
        assert!(<fixed::FixedI32<fixed::types::extra::U16> as Axis>::IS_SIGNED);
        assert!(!<fixed::FixedU16<fixed::types::extra::U8> as Axis>::IS_SIGNED);
        let a = fixed::FixedI32::<fixed::types::extra::U16>::from_num(1.5);
        let b = fixed::FixedI32::<fixed::types::extra::U16>::from_num(0.25);
        assert_eq!(
            <fixed::FixedI32<fixed::types::extra::U16> as Axis>::saturating_dist(a, b),
            fixed::FixedI32::<fixed::types::extra::U16>::from_num(1.25)
        );
        assert_eq!(
            <fixed::FixedU16<fixed::types::extra::U8> as Axis>::max(
                fixed::FixedU16::<fixed::types::extra::U8>::from_num(2),
                fixed::FixedU16::<fixed::types::extra::U8>::from_num(3)
            ),
            fixed::FixedU16::<fixed::types::extra::U8>::from_num(3)
        );
    }
}