k_nearest
Find k-nearest neighbors for a list of points with arbitrary dimensions
Code example
const MAX_NEIGHBORS: usize = 16;
const MAX_DISTANCE: f32 = 1.0;
fn example(points: &[Point]) {
let kd_tree = k_nearest::KDTree::<
3, f32, Point, Adapter, Metric, >::new(points);
for point in points.iter() {
let mut neighbors = [(0.0, 0); MAX_NEIGHBORS];
let count = kd_tree.k_nearest(point, &mut neighbors, MAX_DISTANCE);
let neighbors = &neighbors[0..count];
...
}
}
For a Point with values as members
struct Point {
x: f32,
y: f32,
z: f32,
}
struct Adapter;
impl k_nearest::Adapter<3, f32, Point> for Adapter {
fn get(point: &Point, dimension: usize) -> f32 {
match dimension {
0 => point.x,
1 => point.y,
2 => point.z,
_ => unreachable!(),
}
}
}
For a point with values as array
struct Point([f32; 3]);
struct Adapter;
impl k_nearest::Adapter<3, f32, Point> for Adapter {
fn get(point: &Point, dimension: usize) -> f32 {
point.0[dimension]
}
fn get_all(point: &Point) -> [f32; 3] {
point.0
}
}
Metric
type Metric = k_nearest::EuclideanDistanceSquared;
struct ManhattenDistance;
impl<const N: usize> Metric<N, f32> for ManhattenDistance {
fn distance(left: &[f32; N], right: &[f32; N]) -> f32 {
(0..N)
.map(|d| left[d] - right[d])
.map(|v| v.abs())
.fold(0.0, |sum, v| sum + v)
}
fn distance_plane(position: &[f32; N], plane: f32, dimension: usize) -> f32 {
let diff = position[dimension] - plane;
diff.abs()
}
}