列表增长时的高效最近邻搜索?

时间:2016-01-21 00:22:13

标签: python nearest-neighbor

我一直在重写一个古老的迷宫类型的东西,我为了好玩,虽然它不是一个迷宫,它有点抽象和缩小,所以我不能只做if location in locations搜索。

我已经完成了一个基本的最近邻搜索,并尝试对其进行一些优化,但它仍然非常慢,因为每增加10倍节点,需要1000倍以上的计算(10,000个节点需要1670亿,仅用于碰撞)检查),所以我认为没有更多的事情可以做到这一点。

这是稍微编辑的代码,它们通常是一个类,我遍历每个节点并获取大小/位置属性(将其更改为node[0]node[1])。想象一下node_list有数千个值。

dimensions = 3
dimensions_range = range(dimensions)
def collision_check(node_list, location, size, bounds=None):

    #Check new node is within bounds (if set)
    if bounds:
        for i in dimensions_range:
            if not bounds[0][i] + size <= location[i] <= bounds[1][i] - size:
                return True

    #Find if any nodes are overlapping
    for node in node_list:
        size_total = size + node[0]
        distance = [abs(a - b) for a, b in zip(location, node[1])]

        #Take these two lines out and the time taken doubles
        if max(distance) > size_total:
            continue

        #Square to do one half of pythagoras
        distance_total = sum(pow(i, 2) for i in distance)
        if distance_total < pow(size_total, 2):
            return True

    return False

node_list = [
[0.5, (0, 0, 0)],
[0.5, (0, 0, 1)]
]

new_size, new_loc = [0.5, (0, 0, 2)]
print collision_check(node_list, new_loc, new_size)
#No collision

new_size, new_loc = [0.6, (0, 0, 2)]
print collision_check(node_list, new_loc, new_size)
#Collision

我在考虑一个段类型的想法,但由于节点有维度,一个点可能会跨越4个段,这意味着我必须对每个节点进行if any(i in existing_segments for i in current_segments)检查,这听起来很多喜欢它可能最终会变慢。我听说过KD树,并没有真正了解它们,但我猜他们不会很好地处理被添加的点数。

无论如何,这并不是什么重要的事情,我只是好奇是否有更好的方法来做到这一点并非荒谬的进步。

0 个答案:

没有答案
相关问题