当前位置:   article > 正文

自动驾驶算法(二):A*算法讲解与代码实现_a*算法代码实现

a*算法代码实现

目录

1 A* 算法提出的动机

2 A*算法代码详解

3 A*算法完整代码


1 A* 算法提出的动机

        减少收录的珊格树目,增加搜索速度。在Dijkstra算法中,我们考虑收录栅格时我们考虑的是到起点的距离,我们会考虑收录距离起点较近的珊格进行收录。在A*算法,我们增加启发式函数,加快其导向终点的速度。

        举个例子:

        图中两个红色光晕节点,下面的点距离起点较近(蓝色的),所以Dijkstra会选择下面的节点进行收录。我们在这基础上增加这两个节点到终点的距离。我们发现上面节点到终点的距离会更加小,我们就会收录上面的节点。从而在收录节点的时候就会更加快速的导向终点。

        看一下算法对比:

A*
Dijkstra

        算法和Dijkstra相比仅多了一个启发项,因此代码架构只需要更改一点即可:

        当然,启发项不是随便加的,我们需要保证算法还是找到的最优路径。我们需要保证h(n) <= *h(n),这里*h(n)是最优解。

        比如我们从1-->3这个节点要寻找一条路径:

        我们回顾一下open list和close list:上方的h表示预计到终点的距离。(假设的...)

  1. openlist: 2(1+6) 3(5+0)
  2. closelist: 1(0)

        那么我会选择收录三号点。我们认为最优路径是1-->3而不是1-->2-->3我们就不能保证最优性了。但是1-->3的扩展点更加少,一部分程度上来说增加了速度。(有好有坏)

2 A*算法代码详解

        相比较于Dijkstra算法就增加了一个启发函数:

  1. # 选择扩展点 f(n) = g(n) + h(n)
  2. c_id = min(
  3. open_set,
  4. key=lambda o: open_set[o].cost + self.calc_heuristic(goal_node,
  5. open_set[
  6. o]))

        我们看一下这个启发函数:

  1. def calc_heuristic(n1, n2):
  2. w = 1.0 # weight of heuristic
  3. d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
  4. return d

        先来看函数调用,goal_node是目标点。

        d = w * math.hypot(n1.x - n2.x, n1.y - n2.y):使用欧几里得距离公式计算了两个节点在二维平面上的距离,其中n1.xn1.y分别表示节点n1的x坐标和y坐标,n2.xn2.y分别表示节点n2的x坐标和y坐标。将得到的距离乘以权重w得到启发式值d。也就是计算出了该节点到终点的距离作为启发项。其余与Dijkstra算法一致,不再赘述。

3 A*算法完整代码

  1. """
  2. A* grid planning
  3. author: Atsushi Sakai(@Atsushi_twi)
  4. Nikos Kanargias (nkana@tee.gr)
  5. See Wikipedia article (https://en.wikipedia.org/wiki/A*_search_algorithm)
  6. """
  7. import math
  8. import matplotlib.pyplot as plt
  9. show_animation = True
  10. class AStarPlanner:
  11. def __init__(self, ox, oy, resolution, rr):
  12. """
  13. Initialize grid map for a star planning
  14. ox: x position list of Obstacles [m]
  15. oy: y position list of Obstacles [m]
  16. resolution: grid resolution [m]
  17. rr: robot radius[m]
  18. """
  19. self.resolution = resolution
  20. self.rr = rr
  21. self.min_x, self.min_y = 0, 0
  22. self.max_x, self.max_y = 0, 0
  23. self.obstacle_map = None
  24. self.x_width, self.y_width = 0, 0
  25. self.motion = self.get_motion_model()
  26. self.calc_obstacle_map(ox, oy)
  27. class Node:
  28. def __init__(self, x, y, cost, parent_index):
  29. self.x = x # index of grid
  30. self.y = y # index of grid
  31. self.cost = cost
  32. self.parent_index = parent_index
  33. def __str__(self):
  34. return str(self.x) + "," + str(self.y) + "," + str(
  35. self.cost) + "," + str(self.parent_index)
  36. def planning(self, sx, sy, gx, gy):
  37. """
  38. A star path search
  39. input:
  40. s_x: start x position [m]
  41. s_y: start y position [m]
  42. gx: goal x position [m]
  43. gy: goal y position [m]
  44. output:
  45. rx: x position list of the final path
  46. ry: y position list of the final path
  47. """
  48. start_node = self.Node(self.calc_xy_index(sx, self.min_x),
  49. self.calc_xy_index(sy, self.min_y), 0.0, -1)
  50. goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
  51. self.calc_xy_index(gy, self.min_y), 0.0, -1)
  52. open_set, closed_set = dict(), dict()
  53. open_set[self.calc_grid_index(start_node)] = start_node
  54. while 1:
  55. if len(open_set) == 0:
  56. print("Open set is empty..")
  57. break
  58. # 选择扩展点 f(n) = g(n) + h(n)
  59. c_id = min(
  60. open_set,
  61. key=lambda o: open_set[o].cost + self.calc_heuristic(goal_node,
  62. open_set[
  63. o]))
  64. current = open_set[c_id]
  65. # show graph
  66. if show_animation: # pragma: no cover
  67. plt.plot(self.calc_grid_position(current.x, self.min_x),
  68. self.calc_grid_position(current.y, self.min_y), "xc")
  69. # for stopping simulation with the esc key.
  70. plt.gcf().canvas.mpl_connect('key_release_event',
  71. lambda event: [exit(
  72. 0) if event.key == 'escape' else None])
  73. if len(closed_set.keys()) % 10 == 0:
  74. plt.pause(0.001)
  75. if current.x == goal_node.x and current.y == goal_node.y:
  76. print("Find goal")
  77. goal_node.parent_index = current.parent_index
  78. goal_node.cost = current.cost
  79. break
  80. # Remove the item from the open set
  81. del open_set[c_id]
  82. # Add it to the closed set
  83. closed_set[c_id] = current
  84. # expand_grid search grid based on motion model
  85. for i, _ in enumerate(self.motion):
  86. node = self.Node(current.x + self.motion[i][0],
  87. current.y + self.motion[i][1],
  88. current.cost + self.motion[i][2], c_id)
  89. n_id = self.calc_grid_index(node)
  90. # If the node is not safe, do nothing
  91. if not self.verify_node(node):
  92. continue
  93. if n_id in closed_set:
  94. continue
  95. if n_id not in open_set:
  96. open_set[n_id] = node # discovered a new node
  97. else:
  98. if open_set[n_id].cost > node.cost:
  99. # This path is the best until now. record it
  100. open_set[n_id] = node
  101. rx, ry = self.calc_final_path(goal_node, closed_set)
  102. return rx, ry
  103. def calc_final_path(self, goal_node, closed_set):
  104. # generate final course
  105. rx, ry = [self.calc_grid_position(goal_node.x, self.min_x)], [
  106. self.calc_grid_position(goal_node.y, self.min_y)]
  107. parent_index = goal_node.parent_index
  108. while parent_index != -1:
  109. n = closed_set[parent_index]
  110. rx.append(self.calc_grid_position(n.x, self.min_x))
  111. ry.append(self.calc_grid_position(n.y, self.min_y))
  112. parent_index = n.parent_index
  113. return rx, ry
  114. @staticmethod
  115. def calc_heuristic(n1, n2):
  116. w = 1.0 # weight of heuristic
  117. d = w * math.hypot(n1.x - n2.x, n1.y - n2.y)
  118. return d
  119. def calc_grid_position(self, index, min_position):
  120. """
  121. calc grid position
  122. :param index:
  123. :param min_position:
  124. :return:
  125. """
  126. pos = index * self.resolution + min_position
  127. return pos
  128. def calc_xy_index(self, position, min_pos):
  129. return round((position - min_pos) / self.resolution)
  130. def calc_grid_index(self, node):
  131. return node.y * self.x_width + node.x
  132. def verify_node(self, node):
  133. px = self.calc_grid_position(node.x, self.min_x)
  134. py = self.calc_grid_position(node.y, self.min_y)
  135. if px < self.min_x:
  136. return False
  137. elif py < self.min_y:
  138. return False
  139. elif px >= self.max_x:
  140. return False
  141. elif py >= self.max_y:
  142. return False
  143. # collision check
  144. if self.obstacle_map[node.x][node.y]:
  145. return False
  146. return True
  147. def calc_obstacle_map(self, ox, oy):
  148. self.min_x = round(min(ox))
  149. self.min_y = round(min(oy))
  150. self.max_x = round(max(ox))
  151. self.max_y = round(max(oy))
  152. print("min_x:", self.min_x)
  153. print("min_y:", self.min_y)
  154. print("max_x:", self.max_x)
  155. print("max_y:", self.max_y)
  156. self.x_width = round((self.max_x - self.min_x) / self.resolution)
  157. self.y_width = round((self.max_y - self.min_y) / self.resolution)
  158. print("x_width:", self.x_width)
  159. print("y_width:", self.y_width)
  160. # obstacle map generation
  161. self.obstacle_map = [[False for _ in range(self.y_width)]
  162. for _ in range(self.x_width)]
  163. for ix in range(self.x_width):
  164. x = self.calc_grid_position(ix, self.min_x)
  165. for iy in range(self.y_width):
  166. y = self.calc_grid_position(iy, self.min_y)
  167. for iox, ioy in zip(ox, oy):
  168. d = math.hypot(iox - x, ioy - y)
  169. if d <= self.rr:
  170. self.obstacle_map[ix][iy] = True
  171. break
  172. @staticmethod
  173. def get_motion_model():
  174. # dx, dy, cost
  175. motion = [[1, 0, 1],
  176. [0, 1, 1],
  177. [-1, 0, 1],
  178. [0, -1, 1],
  179. [-1, -1, math.sqrt(2)],
  180. [-1, 1, math.sqrt(2)],
  181. [1, -1, math.sqrt(2)],
  182. [1, 1, math.sqrt(2)]]
  183. return motion
  184. def main():
  185. print(__file__ + " start!!")
  186. # start and goal position
  187. sx = -5.0 # [m]
  188. sy = -5.0 # [m]
  189. gx = 50.0 # [m]
  190. gy = 50.0 # [m]
  191. grid_size = 2.0 # [m]
  192. robot_radius = 1.0 # [m]
  193. # set obstacle positions
  194. ox, oy = [], []
  195. for i in range(-10, 60):
  196. ox.append(i)
  197. oy.append(-10.0)
  198. for i in range(-10, 60):
  199. ox.append(60.0)
  200. oy.append(i)
  201. for i in range(-10, 61):
  202. ox.append(i)
  203. oy.append(60.0)
  204. for i in range(-10, 61):
  205. ox.append(-10.0)
  206. oy.append(i)
  207. for i in range(-10, 40):
  208. ox.append(20.0)
  209. oy.append(i)
  210. for i in range(0, 40):
  211. ox.append(40.0)
  212. oy.append(60.0 - i)
  213. if show_animation: # pragma: no cover
  214. plt.plot(ox, oy, ".k")
  215. plt.plot(sx, sy, "og")
  216. plt.plot(gx, gy, "xb")
  217. plt.grid(True)
  218. plt.axis("equal")
  219. a_star = AStarPlanner(ox, oy, grid_size, robot_radius)
  220. rx, ry = a_star.planning(sx, sy, gx, gy)
  221. if show_animation: # pragma: no cover
  222. plt.plot(rx, ry, "-r")
  223. plt.pause(0.001)
  224. plt.show()
  225. if __name__ == '__main__':
  226. main()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/848846
推荐阅读
相关标签
  

闽ICP备14008679号