1

我有一些代码可以在地图中进行基本的光线追踪,以确定光线是否击中墙壁。

[编辑]:y_coords和x_coords的大小一般为18x1000(对应点)。self.map 是 800x800

def ray_trace(self, x, y, x_coords, y_coords):
    ray_distances = []
    resolution = self.parameters['resolution']
    for i in range(x_coords.shape[0]):
        distance = 0

        # filter x and y coords to stay within map regions
        ray_range = np.bitwise_and(x_coords[i]<799,y_coords[i]<799)

        # determine ending index where the ray stops
        len_ray = ray_range[ray_range==True].shape[0]

        # zip up the x and y coords
        ray_coords = np.c_[x_coords[i,0:len_ray], y_coords[i,0:len_ray]]

        # look up all the coordinates in the map and find where the map is
        # less than or equal to zero (this is a wall)
        ray_values, = np.where(self.map[tuple(ray_coords.T)] <= 0)

        # some special exceptions
        if not ray_values.shape[0]:
            if not len(ray_coords):
                end_of_ray = np.array([x/resolution, y/resolution])
            else:
                end_of_ray = ray_coords[len(ray_values)]
        else:
            # get the end of the ray
            end_of_ray = ray_coords[ray_values.item(0)]

        # find the distance from the originating point
        distance = math.sqrt((end_of_ray.item(0) - x/resolution)**2 + 
                             (end_of_ray.item(1) - y/resolution)**2)

        ray_distances.append(distance)
    return ray_distances

我在 np.c_ 和 np.where 行中遇到问题 - 我用 kernprof.py 对它们和那些行进行了分析,它们需要很长时间(尤其是 np.c_,它占用了 50% 的时间) . 有人对如何优化这个有任何想法吗?

4

1 回答 1

2

你真的不需要这么多地使用索引。高级索引意味着您可以使用两个大小相等的坐标数组进行索引,而无需先将它们组合成坐标。

coord_mask = (x_coords < 799) & (y_coords < 799)
for i in xrange(len(coord_mask)):
    distance = 0
    row_mask = coord_mask[i]
    row_x = x_coords[i, row_mask]
    row_y = y_coords[i, row_mask]
    mapvals = self.map[row_x, row_y] # advanced indexing
    ray_values, = (mapvals <= 0).nonzero()
    ...
于 2012-10-02T15:56:13.610 回答