geo-index icon indicating copy to clipboard operation
geo-index copied to clipboard

Return distances from KDTree::within function

Open adamthedash opened this issue 11 months ago • 3 comments

Hi, thanks for creating this crate! For my use case (swarm simulation), I'm searching for nearby entities using KDTree::within. However as it only returns the indices, I'm re-calculating the distances of neighbours to use downstream. I see internally that KDTree::within is already calculating it for candidate points, so was wondering if they could also be returned alongside the indices?

adamthedash avatar Jan 13 '25 01:01 adamthedash

Hello 👋

That sounds like you probably ideally want to use nearest neighbors instead of within. This is tracked by https://github.com/kylebarron/geo-index/issues/97.

The RTree implementation already has the nearest neighbor implementation, but an improvement will be to expose it as a rust Iterator instead of collecting into a Vec, see https://github.com/kylebarron/geo-index/pull/98 for a WIP but not yet functional implementation.

In this case, the item yielded by the iterator includes both the id and the (squared) distance: https://github.com/kylebarron/geo-index/blob/9ca258bf397250c46b52e0abaef47e29a5c71913/src/rtree/trait.rs#L248-L249

I think this approach would work the best for you as well: to implement an iterator-based nearest-neighbor search and then you can stop iteration once you've hit a certain number or distance.

kylebarron avatar Jan 13 '25 21:01 kylebarron

Thanks Kyle, I had tried RTree but it had ended up a bit slower than KDTree for me. I'll try my hand at contributing an implementation for it when I get some time over the next couple weeks if you don't beat me to to it!

adamthedash avatar Jan 18 '25 16:01 adamthedash

A PR to add the iterator approach of nearest neighbors to the KDTree would be most welcome!

kylebarron avatar Jan 28 '25 19:01 kylebarron