Calculate distance from one point to all others

前端 未结 3 537
予麋鹿
予麋鹿 2021-01-15 09:34

I am working with a list of ID, X, and Y data for fire hydrant locations. I am trying to find the three closest fire hydrants for each fire hydrant in the list.

a =

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-15 10:20

    You do not have to calculate all distances of all points to all others to get the three nearest neighbours for all points.

    A kd-tree search will be much more efficient due to its O(log n) complexity instead of a O(n**2) time complexity for the brute force method (calculating all distances).

    Example

    import numpy as np
    from scipy import spatial
    
    #Create some coordinates and indices
    #It is assumed that the coordinates are unique (only one entry per hydrant)
    Coords=np.random.rand(1000*2).reshape(1000,2)
    Coords*=100
    Indices=np.arange(1000) #Indices 
    
    def get_indices_of_nearest_neighbours(Coords,Indices):
      tree=spatial.cKDTree(Coords)
      #k=4 because the first entry is the nearest neighbour 
      # of a point with itself
      res=tree.query(Coords, k=4)[1][:,1:]
      return Indices[res]
    

提交回复
热议问题