请用python语言写一段双向RRT路径规划算法
时间: 2023-06-30 22:22:52 浏览: 220
双向RRT路径规划算法(含bmp图,算法可直接运行)
好的,下面是一个简单的双向 RRT(Rapidly-exploring Random Tree)路径规划算法的 Python 实现:
```python
import numpy as np
import matplotlib.pyplot as plt
# 定义节点类
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.parent = None
# 定义 RRT 类
class RRT:
def __init__(self, start, goal, obstacle_list, step_size=0.1, max_iter=500):
self.start = Node(*start)
self.goal = Node(*goal)
self.obstacle_list = obstacle_list
self.step_size = step_size
self.max_iter = max_iter
self.node_list = [self.start]
# 判断是否与障碍物相交
def is_collision(self, n1, n2):
for (ox, oy, size) in self.obstacle_list:
dx = n2.x - n1.x
dy = n2.y - n1.y
d = np.hypot(dx, dy)
if d == 0:
return True
if size >= d:
return True
theta = np.arctan2(dy, dx)
nx = n1.x + size * np.cos(theta)
ny = n1.y + size * np.sin(theta)
if (ox - nx)**2 + (oy - ny)**2 <= size**2:
return True
return False
# 根据目标点生成随机点
def get_random_node(self):
if np.random.rand() < 0.5:
return Node(np.random.uniform(-5, 5), np.random.uniform(-5, 5))
else:
return Node(self.goal.x, self.goal.y)
# 寻找最近的节点
def nearest_node(self, n):
dlist = [(node.x - n.x)**2 + (node.y - n.y)**2 for node in self.node_list]
return self.node_list[np.argmin(dlist)]
# 扩展树
def expand_tree(self, n):
new_node = Node(n.x, n.y)
theta = np.random.uniform(-np.pi, np.pi)
new_node.x += self.step_size * np.cos(theta)
new_node.y += self.step_size * np.sin(theta)
new_node.parent = n
if not self.is_collision(n, new_node):
self.node_list.append(new_node)
# 搜索路径
def search_path(self):
for i in range(self.max_iter):
rnd_node = self.get_random_node()
nearest_node = self.nearest_node(rnd_node)
self.expand_tree(nearest_node)
# 反向搜索
rnd_node = self.get_random_node()
nearest_node = self.nearest_node(rnd_node)
self.expand_tree(nearest_node)
# 检查是否到达目标点
dx = self.node_list[-1].x - self.goal.x
dy = self.node_list[-1].y - self.goal.y
d = np.hypot(dx, dy)
if d <= self.step_size:
return self.generate_path(len(self.node_list) - 1)
return None
# 生成路径
def generate_path(self, goal_index):
path = [[self.goal.x, self.goal.y]]
node = self.node_list[goal_index]
while node.parent is not None:
path.append([node.x, node.y])
node = node.parent
path.append([node.x, node.y])
return np.array(path)
# 测试
def main():
obstacle_list = [(1, 1, 1), (2, 3, 1), (4, 4, 1), (4, 2, 1)]
start = (-4, -4)
goal = (4, 4)
rrt = RRT(start, goal, obstacle_list)
path = rrt.search_path()
if path is None:
print("No path found")
else:
print("Found path with %d nodes" % len(path))
plt.plot(path[:,0], path[:,1], '-r')
for (ox, oy, size) in obstacle_list:
circle = plt.Circle((ox, oy), size, color='k')
plt.gca().add_patch(circle)
plt.axis('equal')
plt.show()
if __name__ == '__main__':
main()
```
这个实现是基于 Python 的 NumPy 和 Matplotlib 库的。其中,Node 类表示节点,RRT 类表示 RRT 路径规划算法,包括判断是否与障碍物相交、生成随机点、寻找最近的节点、扩展树、搜索路径和生成路径等方法。在主函数中,我们定义了起点、终点和障碍物列表,然后创建 RRT 实例并搜索路径,最后绘制路径和障碍物。
阅读全文