问题遇到的现象和发生背景
这里有一个三层的for循环,运行速度想要优化一下
问题相关代码,请勿粘贴截图
for i in range(len(points_xy)):
weight_t=1
x_pos = int((points_xy[i][0] - x_min2) / abs(x_res2))
y_pos = int((y_max2 - points_xy[i][1]) / abs(x_res2))
# 先搜索以点为中心正方形区域,再在里面搜索圆形
y_len_min = (y_pos - radius_pixel_width - 1) if (y_pos - radius_pixel_width - 1) > 0 else 0
y_len_max = (y_pos + radius_pixel_width + 1) if (y_pos + radius_pixel_width + 1) < row else row
x_len_min = (x_pos - radius_pixel_width - 1) if (x_pos - radius_pixel_width - 1) > 0 else 0
x_len_max = (x_pos + radius_pixel_width + 1) if (x_pos + radius_pixel_width + 1) < col else col
for y in range(y_len_min, y_len_max):
for x in range(x_len_min, x_len_max):
distance = float(((x - x_pos) ** 2 + (y - y_pos) ** 2) ** 0.5)
dis=distance*30
if (distance < radius_pixel_width and distance > 0):
value = raster_data[y_pos][x_pos]
D_value=((radius_pixel_width - distance + 1)/(radius_pixel_width**2))*weight_t
if (result_data[y][x] != -999.0):
result_data[y][x] += D_value
else:
result_data[y][x] = D_value
elif(distance==0 and result_data[y][x] != -999.0):
result_data[y][x]+=(1*weight_t)
elif(distance==0 and result_data[y][x] == -999.0):
result_data[y][x] = 1*weight_t
运行结果及报错内容
我的解答思路和尝试过的方法
一开始加上jit,但是结果告诉我这里的point_xy是list好像不能用,我又把jit放在for循环内部,结果还是程序一直运行。问问怎么优化
for i in range(len(points_xy)):
x_pos = int((points_xy[i][0] - x_min) / abs(x_res))
y_pos = int((y_max - points_xy[i][1]) / abs(x_res))
# 先搜索以点为中心正方形区域,再在里面搜索圆形
y_len_min = (y_pos - radius_pixel_width - 1) if (y_pos - radius_pixel_width - 1) > 0 else 0
y_len_max = (y_pos + radius_pixel_width + 1) if (y_pos + radius_pixel_width + 1) < rows else rows
x_len_min = (x_pos - radius_pixel_width - 1) if (x_pos - radius_pixel_width - 1) > 0 else 0
x_len_max = (x_pos + radius_pixel_width + 1) if (x_pos + radius_pixel_width + 1) < cols else cols
@jit
def keral_map(y_len_min, y_len_max, x_len_min, x_len_max, x_pos, y_pos, radius_pixel_width, result_data):
weight_t = 1
for y in range(y_len_min, y_len_max):
for x in range(x_len_min, x_len_max):
distance = float(((x - x_pos) ** 2 + (y - y_pos) ** 2) ** 0.5)
# 判断在半径内
if (distance < radius_pixel_width and distance > 0):
D_value = ((radius_pixel_width - distance + 1) / (radius_pixel_width ** 2)) * weight_t
if (result_data[y][x] != -999.0):
result_data[y][x] += D_value
else:
result_data[y][x] = D_value
elif (distance == 0 and result_data[y][x] != -999.0):
result_data[y][x] += (1 * weight_t)
elif (distance == 0 and result_data[y][x] == -999.0):
result_data[y][x] = 1 * weight_t
return result_data
keral_map(y_len_min, y_len_max, x_len_min, x_len_max, x_pos, y_pos, radius_pixel_width, result_data)
我想要达到的结果
目前的速度大概都在25秒左右(6万个点),想能不能快一点