Fastest way to find the closest point to a given point in 3D, in Python

后端 未结 3 1435
长情又很酷
长情又很酷 2021-02-14 13:19

So lets say I have 10,000 points in A and 10,000 points in B and want to find out the closest point in A for every B point.

Currently, I simply loop through every point

相关标签:
3条回答
  • 2021-02-14 13:58

    I typically use a kd-tree in such situations.

    There is a C++ implementation wrapped with SWIG and bundled with BioPython that's easy to use.

    0 讨论(0)
  • 2021-02-14 14:18

    You could use some spatial lookup structure. A simple option is an octree; fancier ones include the BSP tree.

    0 讨论(0)
  • 2021-02-14 14:21

    You could use numpy broadcasting. For example,

    from numpy import *
    import numpy as np
    
    a=array(A)
    b=array(B)
    #using looping
    for i in b:
        print sum((a-i)**2,1).argmin()
    

    will print 2,1,0 which are the rows in a that are closest to the 1,2,3 rows of B, respectively.

    Otherwise, you can use broadcasting:

    z = sum((a[:,:, np.newaxis] - b)**2,1)
    z.argmin(1) # gives array([2, 1, 0])
    

    I hope that helps.

    0 讨论(0)
提交回复
热议问题