【问题标题】:Fastest way to find the closest point to a given point in 3D, in Python在 Python 中找到与 3D 中给定点最近的点的最快方法
【发布时间】:2012-03-02 00:02:03
【问题描述】:

假设我在 A 中有 10,000 个点,在 B 中有 10,000 个点,并且想为每个 B 点找出 A 中最近的点。

目前,我只是遍历 B 和 A 中的每个点,以找出距离最近的点。即。

B = [(.5, 1, 1), (1, .1, 1), (1, 1, .2)]
A = [(1, 1, .3), (1, 0, 1), (.4, 1, 1)]
C = {}
for bp in B:
   closestDist = -1
   for ap in A:
      dist = sum(((bp[0]-ap[0])**2, (bp[1]-ap[1])**2, (bp[2]-ap[2])**2))
      if(closestDist > dist or closestDist == -1):
         C[bp] = ap
         closestDist = dist
print C

但是,我确信有更快的方法来做到这一点...有什么想法吗?

【问题讨论】:

    标签: python distance points closest


    【解决方案1】:

    在这种情况下,我通常使用kd-tree

    有一个易于使用的C++ implementation wrapped with SWIG and bundled with BioPython

    【讨论】:

    • 仅供参考,我目前使用 scipy 的 kd-tree
    【解决方案2】:

    您可以使用一些空间查找结构。一个简单的选项是octree;更高级的包括BSP tree

    【讨论】:

      【解决方案3】:

      你可以使用 numpy 广播。例如,

      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()
      

      将打印 2,1,0 分别是 a 中最接近 B 的 1,2,3 行的行。

      否则,您可以使用广播:

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

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2011-05-20
        • 2018-08-28
        • 1970-01-01
        • 1970-01-01
        • 2021-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-25
        相关资源
        最近更新 更多