Python rtree nearest - what exactly it does?

5k views Asked by At

I have the following setup - it's rtree build on points:

from collections import defaultdict
from math import sqrt
import rtree.index

points = [(5, 4), (3, 1), (6, 3), (2, 8), (7, 8), (8, 1), (2, 3), (0, 4), (3, 7), (6, 4)]

idx = rtree.index.Rtree()

for i, p in enumerate(points):
    idx.insert(i, p+p, p)

Now I'm trying to find all points within the certain distance from certain point:

max_distance=5
p = (6,4)
list(idx.nearest(p, 5, objects='raw'))

I receive

[(6, 4), (6, 3), (5, 4), (8, 1), (2, 3), (7, 8)]

The question is - why (3, 1) is not included in the list? The distance is ~4.24 so it should be included, right?

1

There are 1 answers

0
Nathan Molinari On

The nearest method "Returns the k-nearest objects to the given coordinates.", that is, it will return the nearest objects independent on its distance.

The distance of objects isn't a parameter of nearest function, as described on Rtree documentation. The second parameter is the number of results that you want. In your case it returns six values because the points (6, 3), (5, 4) has the same distance (1) to the point (6, 4).

To obtain the objects in a certain distance you should use the intersection method.