组织3d点并通过距离位置找到它们

时间:2015-02-27 08:45:00

标签: python algorithm

我在3D环境中工作。我在这个空间中有一些由x,y,z位置表示的物体。

# My objects names (in my real context it's pheromone "point")
A = 1
B = 2
C = 3
D = 4

# My actual way to stock their positions
pheromones_positions = {
    (25, 25, 60): [A, D],
    (10, 90, 30): [B],
    (5, 85, 8): [C]
}

我的目标是找到某个点(信息素)靠近(距离)给定的位置。我只是这样做:

def calc_distance(a, b):
    return sqrt((a[0]-b[0])**2+(a[1]-b[1])**2+(a[2]-b[2])**2)

def found_in_dict(search, points, distance):
    for point in points:
        if calc_distance(search, point) <= distance:
            return points[point]

founds = found_in_dict((20, 20, 55), pheromones_positions, 10)
# found [1, 4] (A and D)

但是,有很多信息素,它很慢(逐个测试......)。如何组织这些3D位置以更快地找到“距离给定位置的位置”? 是否存在能以这种方式帮助我的算法或图书馆(numpy?)?

1 个答案:

答案 0 :(得分:0)

您应该一次计算所有(平方)距离。使用NumPy,您可以简单地从所有位置坐标的(nx3)数组中减去1x3大小的目标点,并将平方坐标差求和,以获得包含n个元素的列表:

squaredDistances = np.sum((np.array(pheromones_positions.keys()) - (20, 20, 55))**2, axis=1)
idx = np.where(squaredDistances < 10**2)[0]
print pheromones_positions.values()[idx]

输出:

[1, 4]

顺便说一下:由于你的return语句在所有点的for循环中,它将在找到第一个点后停止迭代。所以你可能会错过第二场或第三场比赛。