在 Python 中找到 3D 中给定点最近点的最快方法

发布于 2024-08-28 22:02:36 字数 501 浏览 6 评论 0原文

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

目前,我只是循环遍历 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

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

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 in B and A to find which one is closest in distance. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡淡の花香 2024-09-04 22:02:36

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

有一个用 SWIG 包装的 C++ 实现与 BioPython 捆绑在一起,易于使用。

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.

感受沵的脚步 2024-09-04 22:02:36

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

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

仙气飘飘 2024-09-04 22:02:36

您可以使用 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])

我希望有所帮助。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文