优化的python空间哈希

时间:2019-01-28 17:21:13

标签: python python-3.x algorithm optimization containers

我的粒子系统被约束在三角形网格的表面上,并且大部分分布良好,具有特定的平均密度,并以四方形结构组织。

适用于我正在制作的重新网格化框架。

因此,为了允许粒子之间进行迭代,我制作了这个空间散列容器,但是对于我的任务来说速度相当慢,因为这里有成千上万的粒子和数百万的邻域检查。

是否有进一步优化此数据结构的方法?还是有这样的粒子系统更快的数据结构?

class SpatialHash:
    def __init__(self, cell_size=0.1):
        self.buckets = {}
        self.items = {}
        self.size = cell_size

    def get_key(self, location):
        return (
            round(location[0] / self.size),
            round(location[1] / self.size),
            round(location[2] / self.size)
        )

    # item.coord refers to a vector containing the 3D location of the item
    def insert(self, item, key=None):
        if not key:
            key = self.get_key(item.coord)
        if key in self.buckets:
            self.buckets[key].add(item)
        else:
            self.buckets[key] = {item, }
        self.items[item] = self.buckets[key]

    def remove(self, item):
        if item in self.items:
            self.items[item].remove(item)
            del self.items[item]

    def update(self, item):
        self.remove(item)
        self.insert(item)

    def test_sphere(self, coord, radius, exclude=()):
        radius_sqr = radius ** 2
        radius = radius / self.size
        location = coord / self.size
        min_x = math.floor(location[0] - radius)
        max_x = math.ceil(location[0] + radius)
        min_y = math.floor(location[1] - radius)
        max_y = math.ceil(location[1] + radius)
        min_z = math.floor(location[2] - radius)
        max_z = math.ceil(location[2] + radius)
        for x in range(min_x, max_x + 1):
            for y in range(min_y, max_y + 1):
                for z in range(min_z, max_z + 1):
                    key = (x, y, z)
                    if key in self.buckets:
                        for item in self.buckets[key]:
                            if (item.coord - coord).length_squared <= radius_sqr:
                                if item in exclude:
                                    continue
                                yield item

0 个答案:

没有答案