• 【路径规划】(3) RRT 算法求解最短路,附python完整代码


    大家好,今天和各位分享一下机器人路径规划中的 RRT 算法,感兴趣的点个关注,文末有 python 代码,那我们开始吧。


    1. 算法介绍

    RRT 算法是由学者 S.M.LaValle 提出来的路径规划算法。该算法是将空间中的一个起始点当作根节点,在空间中利用增量方式进行随机采样,然后向外延伸扩展增加叶节点。重复该步骤直到获得一个从起点到目标点的树,最后回溯找到从根节点到目标点的无碰撞的路径。 

    快速搜索随机树(RRT)算法是一种增量式采样的搜索方法,将它应用于路径规划时不需要任何参数整定,也不需要事先对环境信息进行处理和存储,具有良好的适应性,适合解决复杂环境以及多种约束条件的路径规划问题。 

    算法优点:

    (1)RRT 算法不需要启发式函数,可以在存在复杂障碍物的环境里快速规划出一条安全路径,且更适合实际应用,目前常被用于无人机的运动规划中。

    (2)RRT 的快速迭代生长方式决定了其在高维非凸空间的搜索优势

    算法缺点:

    (1)稳定性不佳,且内存消耗较大。扩展树生长方向随机,重复规划结果却有很大差异。

    (2)随机性采样导致相对效率较低。由于快速扩展随机树有随机采样性,没有目标启发导向,因此在采样过程中有很多无效采样节点,致使效率相对变低。

    (3)路径曲折冗余点较多,光滑性不佳。在 RRT 生成的路径中有许多无用的点,这些冗余点使得路径长度增多。

    (4)无法在动态障碍物中有效检测路径,不适合于动态环境规划与避障


    2. 算法原理

    传统 RRT 算法计算流程可分为两个阶段:

    第一个阶段。在任务环境中,以算法初始点作为根节点,通过随机采样、逐步迭代地方式,向任务环境中进行扩展,形成一棵随机树,通过判定采样点是否包含目标点或在目标范围内,来判断是否完成随机树的构造,结束采样;

    第二阶段。在随机树中从目标点依次往回遍历,直到寻回根节点,即可得到一条从初始点到目标点的有效路径。RRT的具体扩展方式如下图所示。 

    首先,以初始点 Pinit 作为随机树的根节点,在任务环境中随机选取一个采样点 Prand,从节点树中找出离采样点 Prand 最近的一个子节点 Pnear,以点 Pnear 为端点,沿着 Pnear——Prand 方向扩展一定的步长 𝜌,将另一端点记为 Pnew,

    Pnear 与 Pnew 的连线并未与环境障碍发生交叉,则将点 Pnew 和线段 Pnear--Pnew 加入到随机树中,成为新的子节点和新的路径;

    线段 Pnear 与 Pnew 和障碍发生交叉碰撞则舍弃点 Pnew重新选取新的采样点 Prand。重复上述步骤,直至点 Pnew与目标点 Pgoal 不存在障碍,且步长不大于𝜌,则将 Pgoal 加入到随机树中,至此,随机树构造完成。

    而计算所得的可行路径便是从离 Pgoal 最近的一个子节点 Pnew 依次向上搜索父节点,直到初始点 Pinit,基于 RRT 算法的路径规划结束,其主要流程框图如下图所示。

    RRT仿真结果如下图所示,左图为快速扩展随机树随机采样过程右图为最终提取到的运动路径规划轨迹。设置起始点(10,10)和终止点位置(490,490)坐标。


    3. 代码实现

    如下图,绿色线条代表RRT生长的树枝,红色线条代表搜索到的最优路径

    完整代码如下,每段都有注释,有问题在评论区留言

    1. import math
    2. import random
    3. import matplotlib.pyplot as plt
    4. import numpy as np
    5. class RRT:
    6. class Node: # 创建节点
    7. def __init__(self, x, y):
    8. self.x = x # 节点坐标
    9. self.y = y
    10. self.path_x = [] # 路径,作为画图的数据
    11. self.path_y = []
    12. self.parent = None #父节点
    13. class AreaBounds:
    14. """区域大小
    15. """
    16. def __init__(self, area):
    17. self.xmin = float(area[0])
    18. self.xmax = float(area[1])
    19. self.ymin = float(area[2])
    20. self.ymax = float(area[3])
    21. def __init__(self,
    22. start,
    23. goal,
    24. obstacle_list,
    25. rand_area,
    26. expand_dis=1.0, # 树枝长度
    27. goal_sample_rate=5,
    28. max_iter=500,
    29. play_area=None,
    30. robot_radius=0.0,
    31. ):
    32. """
    33. Setting Parameter
    34. start:起点 [x,y]
    35. goal:目标点 [x,y]
    36. obstacleList:障碍物位置列表 [[x,y,size],...]
    37. rand_area: 采样区域 x,y ∈ [min,max]
    38. play_area: 约束随机树的范围 [xmin,xmax,ymin,ymax]
    39. robot_radius: 机器人半径
    40. expand_dis: 扩展的步长
    41. goal_sample_rate: 采样目标点的概率,百分制.default: 5,即表示5%的概率直接采样目标点
    42. """
    43. self.start = self.Node(start[0], start[1]) # 根节点(0,0)
    44. self.end = self.Node(goal[0], goal[1]) # 终点(6,10)
    45. self.min_rand = rand_area[0] # -2 树枝生长区域xmin
    46. self.max_rand = rand_area[1] # 15 xmax
    47. if play_area is not None:
    48. self.play_area = self.AreaBounds(play_area) # 树枝生长区域,左下(-2,0)==>右上(12,14)
    49. else:
    50. self.play_area = None # 数值无限生长
    51. self.expand_dis = expand_dis # 树枝一次的生长长度
    52. self.goal_sample_rate = goal_sample_rate # 多少概率直接选终点
    53. self.max_iter = max_iter # 最大迭代次数
    54. self.obstacle_list = obstacle_list # 障碍物的坐标和半径
    55. self.node_list = [] # 保存节点
    56. self.robot_radius = robot_radius # 随机点的搜索半径
    57. # 路径规划
    58. def planning(self, animation=True,camara=None):
    59. # 将起点作为根节点x_{init}​,加入到随机树的节点集合中。
    60. self.node_list = [self.start] # 先在节点列表中保存起点
    61. for i in range(self.max_iter):
    62. # 从可行区域内随机选取一个节点x_{rand}
    63. rnd_node = self.sample_free()
    64. # 已生成的树中利用欧氏距离判断距离x_{rand}​最近的点x_{near}。
    65. # 从已知节点中选择和目标节点最近的节点
    66. nearest_ind = self.get_nearest_node_index(self.node_list, rnd_node) # 最接近的节点的索引
    67. nearest_node = self.node_list[nearest_ind] # 获取该最近已知节点的坐标
    68. # 从 x_{near} 与 x_{rand} 的连线方向上扩展固定步长 u,得到新节点 x_{new}
    69. new_node = self.steer(nearest_node, rnd_node, self.expand_dis)
    70. # 如果在可行区域内,且x_{near}与x_{new}之间无障碍物
    71. # 判断新点是否在规定的树的生长区域内,新点和最近点之间是否存在障碍物
    72. if self.is_inside_play_area(new_node, self.play_area) and \
    73. self.obstacle_free(new_node, self.obstacle_list, self.robot_radius):
    74. # 都满足才保存该点作为树节点
    75. self.node_list.append(new_node)
    76. # 如果此时得到的节点x_new到目标点的距离小于扩展步长,则直接将目标点作为x_rand。
    77. if self.calc_dist_to_goal(self.node_list[-1].x,self.node_list[-1].y) <= self.expand_dis:
    78. # 以新点为起点,向终点画树枝
    79. final_node = self.steer(self.node_list[-1], self.end, self.expand_dis)
    80. # 如果最新点和终点之间没有障碍物True
    81. if self.obstacle_free(final_node, self.obstacle_list, self.robot_radius):
    82. # 返回最终路径
    83. return self.generate_final_course(len(self.node_list) - 1)
    84. if animation and i % 5 ==0:
    85. self.draw_graph(rnd_node, camara)
    86. return None # cannot find path
    87. # 距离最近的已知节点坐标,随机坐标,从已知节点向随机节点的延展的长度
    88. def steer(self, from_node, to_node, extend_length=float("inf")):
    89. # d已知点和随机点之间的距离,theta两个点之间的夹角
    90. d, theta = self.calc_distance_and_angle(from_node, to_node)
    91. # 如果$x_{near}$与$x_{rand}$间的距离小于步长,则直接将$x_{rand}$作为新节点$x_{new}$
    92. if extend_length >= d: # 如果树枝的生长长度超出了随机点,就用随机点位置作为新节点
    93. new_x = to_node.x
    94. new_y = to_node.y
    95. else: # 如果树生长长度没达到随机点长度,就截取长度为extend_length的节点作为新节点
    96. new_x = from_node.x + math.cos(theta)*extend_length # 最近点 x + cos * extend_len
    97. new_y = from_node.y + math.sin(theta)*extend_length # 最近点 y + sin * extend_len
    98. new_node = self.Node(new_x,new_y) # 初始化新节点
    99. new_node.path_x = [from_node.x] # 最近点
    100. new_node.path_y = [from_node.y] #
    101. new_node.path_x.append(new_x) # 新点
    102. new_node.path_y.append(new_y)
    103. new_node.parent = from_node # 根节点变成最近点,用来指明方向
    104. return new_node
    105. def generate_final_course(self, goal_ind): # 终点坐标的索引
    106. """生成路径
    107. Args:
    108. goal_ind (_type_): 目标点索引
    109. Returns:
    110. _type_: _description_
    111. """
    112. path = [[self.end.x, self.end.y]] # 保存终点节点
    113. node = self.node_list[goal_ind]
    114. while node.parent is not None: # 根节点
    115. path.append([node.x, node.y])
    116. node = node.parent
    117. path.append([node.x, node.y])
    118. return path
    119. def calc_dist_to_goal(self, x, y):
    120. """计算(x,y)离目标点的距离
    121. """
    122. dx = x - self.end.x # 新点的x-终点的x
    123. dy = y - self.end.y
    124. return math.hypot(dx, dy) # 计算新点和终点之间的距离
    125. def sample_free(self):
    126. # 以(100-goal_sample_rate)%的概率随机生长,(goal_sample_rate)%的概率朝向目标点生长
    127. if random.randint(0, 100) > self.goal_sample_rate: # 大于5%就不选终点方向作为下一个节点
    128. rnd = self.Node(
    129. random.uniform(self.min_rand, self.max_rand), # 在树枝生长区域中随便取一个点
    130. random.uniform(self.min_rand, self.max_rand))
    131. else: # goal point sampling
    132. rnd = self.Node(self.end.x, self.end.y)
    133. return rnd
    134. # 绘制搜索过程
    135. def draw_graph(self, rnd=None, camera=None):
    136. if camera==None:
    137. plt.clf()
    138. # for stopping simulation with the esc key.
    139. plt.gcf().canvas.mpl_connect(
    140. 'key_release_event',
    141. lambda event: [exit(0) if event.key == 'escape' else None])
    142. # 画随机点
    143. if rnd is not None:
    144. plt.plot(rnd.x, rnd.y, "^k")
    145. if self.robot_radius > 0.0:
    146. self.plot_circle(rnd.x, rnd.y, self.robot_radius, '-r')
    147. # 画已生成的树
    148. for node in self.node_list:
    149. if node.parent:
    150. plt.plot(node.path_x, node.path_y, "-g")
    151. # 画障碍物
    152. for (ox, oy, size) in self.obstacle_list:
    153. self.plot_circle(ox, oy, size)
    154. # 如果约定了可行区域,则画出可行区域
    155. if self.play_area is not None:
    156. plt.plot([self.play_area.xmin, self.play_area.xmax,
    157. self.play_area.xmax, self.play_area.xmin,
    158. self.play_area.xmin],
    159. [self.play_area.ymin, self.play_area.ymin,
    160. self.play_area.ymax, self.play_area.ymax,
    161. self.play_area.ymin],
    162. "-k")
    163. # 画出起点和目标点
    164. plt.plot(self.start.x, self.start.y, "xr")
    165. plt.plot(self.end.x, self.end.y, "xr")
    166. plt.axis("equal")
    167. plt.axis([-2, 15, -2, 15])
    168. plt.grid(True)
    169. plt.pause(0.01)
    170. if camera!=None:
    171. camera.snap()
    172. # 静态方法无需实例化,也可以实例化后调用,静态方法内部不能调用self.的变量
    173. @staticmethod
    174. def plot_circle(x, y, size, color="-b"): # pragma: no cover
    175. deg = list(range(0, 360, 5))
    176. deg.append(0)
    177. xl = [x + size * math.cos(np.deg2rad(d)) for d in deg]
    178. yl = [y + size * math.sin(np.deg2rad(d)) for d in deg]
    179. plt.plot(xl, yl, color)
    180. @staticmethod
    181. def get_nearest_node_index(node_list, rnd_node): # 已知节点list,随机的节点坐标
    182. # 计算所有已知节点和随机节点之间的距离
    183. dlist = [(node.x - rnd_node.x)**2 + (node.y - rnd_node.y)**2
    184. for node in node_list]
    185. # 获得距离最小的节点的索引
    186. minind = dlist.index(min(dlist))
    187. return minind
    188. @staticmethod
    189. def is_inside_play_area(node, play_area):
    190. if play_area is None:
    191. return True # no play_area was defined, every pos should be ok
    192. if node.x < play_area.xmin or node.x > play_area.xmax or \
    193. node.y < play_area.ymin or node.y > play_area.ymax:
    194. return False # outside - bad
    195. else:
    196. return True # inside - ok
    197. @staticmethod
    198. def obstacle_free(node, obstacleList, robot_radius): # 目标点,障碍物中点和半径,移动时的占地半径
    199. if node is None:
    200. return False
    201. for (ox, oy, size) in obstacleList:
    202. dx_list = [ox - x for x in node.path_x]
    203. dy_list = [oy - y for y in node.path_y]
    204. d_list = [dx * dx + dy * dy for (dx, dy) in zip(dx_list, dy_list)]
    205. if min(d_list) <= (size+robot_radius)**2:
    206. return False # collision
    207. return True # safe
    208. @staticmethod
    209. def calc_distance_and_angle(from_node, to_node):
    210. """计算两个节点间的距离和方位角
    211. Args:
    212. from_node (_type_): _description_
    213. to_node (_type_): _description_
    214. Returns:
    215. _type_: _description_
    216. """
    217. dx = to_node.x - from_node.x
    218. dy = to_node.y - from_node.y
    219. d = math.hypot(dx, dy) # 平方根
    220. theta = math.atan2(dy, dx) # 夹角的弧度值
    221. return d, theta
    222. def main(gx=6.0, gy=10.0):
    223. print("start " + __file__)
    224. fig = plt.figure(1)
    225. # camera = Camera(fig) # 保存动图时使用
    226. camera = None # 不保存动图时,camara为None
    227. show_animation = True
    228. # ====Search Path with RRT====
    229. obstacleList = [(5, 5, 1), (3, 6, 2), (3, 8, 2), (3, 10, 2), (7, 5, 2),
    230. (9, 5, 2), (8, 10, 1)] # [x, y, radius]
    231. # Set Initial parameters
    232. rrt = RRT(
    233. start=[0, 0], # 起点位置
    234. goal=[gx, gy], # 终点位置
    235. rand_area=[-2, 15], # 树枝可生长区域[xmin,xmax]
    236. obstacle_list=obstacleList, # 障碍物
    237. play_area=[-2, 12, 0, 14], # 树的生长区域,左下[-2,0]==>右上[12,14]
    238. robot_radius=0.2 # 搜索半径
    239. )
    240. path = rrt.planning(animation=show_animation,camara=camera)
    241. if path is None:
    242. print("Cannot find path")
    243. else:
    244. print("found path!!")
    245. # 绘制最终路径
    246. if show_animation:
    247. rrt.draw_graph(camera=camera)
    248. plt.grid(True)
    249. plt.pause(0.01)
    250. plt.plot([x for (x, y) in path], [y for (x, y) in path], '-r')
    251. if camera!=None:
    252. camera.snap()
    253. # animation = camera.animate()
    254. # animation.save('trajectory.gif')
    255. plt.show()
    256. if __name__ == '__main__':
    257. main()
  • 相关阅读:
    Pandas数据分析15——pandas数据透视表和交叉表
    Docker上部署mysql(超简单!!!)
    华大单片机KEIL添加ST-LINK解决方法
    go build解决missing go.sum.entry
    sizeof类大小 + 程序内存空间理解 + const变量的生命周期实现
    Hadoop3教程(三):HDFS文件系统常用命令一览
    详解SQL中Groupings Sets 语句的功能和底层实现逻辑
    基于PyTorch的交通标志目标检测系统
    利用 Kubernetes 降本增效?EasyMR 基于 Kubernetes 部署的探索实践
    行政处罚有哪些?
  • 原文地址:https://blog.csdn.net/dgvv4/article/details/128077188