Search code examples
rustkdtree

How can I input the data from an Array2<f64> into a kdtree?


I have a point cloud in an ndarray Array2 that is 3x500. I would like to make a kd tree from those points using the KdTree crate. https://docs.rs/kdtree/0.6.0/kdtree/

  1. The following example is in the KdTree documentation :
let dimensions = 2;
let mut kdtree = KdTree::new(dimensions);

But when I try that, I get :

cannot infer type for type parameter `A`
consider giving `tree` the explicit type `kdtree::kdtree::KdTree<A, T, U>`, where the type parameter `A` is specified

And I don't know what A, T, and U are supposed to be.

  1. To add the points I tried to use :
pub fn add(&mut self, point: U, data: T) -> Result<(), ErrorKind> 

But I don't know what data is supposed to be.


Solution

  • This is because you are only trying to run this :

    let dimensions = 2;
    let mut kdtree = KdTree::new(dimensions); // kdtree type is KdTree<?, ?, ?>
    

    instead of :

    let a: ([f64; 2], usize) = ([0f64, 0f64], 0);
    let b: ([f64; 2], usize) = ([1f64, 1f64], 1);
    let c: ([f64; 2], usize) = ([2f64, 2f64], 2);
    let d: ([f64; 2], usize) = ([3f64, 3f64], 3);
    
    let dimensions = 2;
    let mut kdtree = KdTree::new(dimensions); // kdTree type is KdTree<f64, usize, &[f64; 2]>
    
    kdtree.add(&a.0, a.1).unwrap();
    kdtree.add(&b.0, b.1).unwrap();
    kdtree.add(&c.0, c.1).unwrap();
    kdtree.add(&d.0, d.1).unwrap();
    

    You can change the top code to :

    let dimensions = 2;
    // we provide the type ourselves
    let mut kdtree: KdTree<f64, usize, &[f64; 2]> = KdTree::new(dimensions);
    

    Now this happens how Rust infers the type of variables during compile time.

    The compiler can usually infer what type we want to use based on the value and how we use it

    In the second piece of code Rust was able to figure out the type we want kdtree to have by looking at our add method, but this did not happend in first case because no extra info was provided.

    The third piece of code works beacuse we explicitly type out the type of kdtree.

    But I don't know what data is supposed to be

    Here data : T is a generic and can be anything.