简体   繁体   English

在Python中以3D查找最接近给定点的最快方法

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

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. 因此,可以说我在A中有10,000点,在B中有10,000点,并且想找出每个B点中A中最接近的点。

Currently, I simply loop through every point in B and A to find which one is closest in distance. 目前,我只是遍历B和A中的每个点,以找出距离最近的那个点。 ie. 即。

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

However, I am sure there is a faster way to do this... any ideas? 但是,我敢肯定有一种更快的方法来执行此操作...有什么想法吗?

I typically use a kd-tree in such situations. 我通常在这种情况下使用kd树

There is a C++ implementation wrapped with SWIG and bundled with BioPython that's easy to use. 有一个用SWIG包装并与BioPython捆绑在一起C ++实现 ,易于使用。

You could use some spatial lookup structure. 您可以使用一些空间查找结构。 A simple option is an octree ; 一个简单的选择是八叉树 fancier ones include the BSP tree . 更好的是BSP树

You could use numpy broadcasting. 您可以使用numpy广播。 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. 将打印2,1,0,分别是A中最接近B的1,2,3行的行。

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. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM