Dijkstra算法学习笔记

算法原理部分

Dijkstra算法从起点开始逐步扩展,每一步为一个节点找到最短路径

循环以下命令:

   1、最开始收录起点进入open list

   2、选择open list中距离最小节点收录进closed list中

   3、收录节点后遍历该节点的邻接节点,将邻接节点(若未访问则收录进open list中)更新其到起点距离

理解:每次都将open list中据起点最短距离的节点引入closed list中,直至遍历到终点,得到最短路径。

实例:

1、收录未访问的距离起点最小节点-即起点1收录进open list,括号内为距离起点距离。

2、收录节点1进入closed list(由于在open list中距离最小),然后邻接节点2和4(邻接是由于1箭头指向只有2和4)收录进open list中,更新其到起点距离。并且收录open list中最小距离的4节点进入closed list中。

3、遍历4节点邻接节点(3、6、7),更新距离(更新3、6、7通过4节点到起点的距离,以下同理)收录进open list,选择距离最小节点2收录进closed list。

4、收录2邻接未访问的5节点进入open list,更新5节点距离。选择距离最小3节点进入closed list。

5、3节点无未收录邻接节点,则open list中无需收录节点。遍历邻接节点6,更新距离变为8。收录open list中最短距离节点7。

6、7点无未访问邻接节点,则无节点收录进openlist中。遍历邻接节点6,更新距离,open list中最短距离为终点6,则循环结束,得到最短距离路线。

以下为代码思路:

其中红框内为算法主要思路,与上面描述可以对应。

栅格地图

以一定的大小将地图栅格化

化为有权图则定义了路径的前进方向

代码讲解

1、主体代码

def main():
    # 设置起点和终点
    sx = -5.0  # [m] # 设置起点
    sy = -5.0  # [m]
    gx = 50.0  # [m] # 设置终点
    gy = 50.0  # [m]
    grid_size = 2.0  # [m] 设置栅格大小
    robot_radius = 1.0  # [m] 设置机器人大小

    # 设置障碍物位置(黑色边缘)
    ox, oy = [], []
    for i in range(-10, 60):
        ox.append(i)
        oy.append(-10.0)
    for i in range(-10, 60):
        ox.append(60.0)
        oy.append(i)
    for i in range(-10, 61):
        ox.append(i)
        oy.append(60.0)
    for i in range(-10, 61):
        ox.append(-10.0)
        oy.append(i)
    for i in range(-10, 40):
        ox.append(20.0)
        oy.append(i)
    for i in range(0, 40):
        ox.append(40.0)
        oy.append(60.0 - i)

    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "og")
        plt.plot(gx, gy, "xb")
        plt.grid(True) # 打开绘图网格线
        plt.axis("equal") # 设置x轴、y轴刻度相同

    dijkstra = Dijkstra(ox, oy, grid_size, robot_radius)
    rx, ry = dijkstra.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-r")
        plt.pause(0.01)
        plt.show()

2、Dijkstra对象(将函数封装在一起)

1)__init__:初始化函数,将障碍物信息,栅格大小和机器人大小进行初始化

    def __init__(self, ox, oy, resolution, robot_radius):
        """
        Initialize map for planning

        ox: x position list of Obstacles [m]
        oy: y position list of Obstacles [m]
        resolution: grid resolution [m]
        rr: robot radius[m]
        """

        self.min_x = None
        self.min_y = None
        self.max_x = None
        self.max_y = None
        self.x_width = None
        self.y_width = None
        self.obstacle_map = None

        self.resolution = resolution
        self.robot_radius = robot_radius
        self.calc_obstacle_map(ox, oy) # 构建栅格地图
        self.motion = self.get_motion_model() # 机器人运动方式

    class Node:
        def __init__(self, x, y, cost, parent_index):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost  # g(n) 路径值
            self.parent_index = parent_index  # 栅格索引,最后用于寻找路径

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.parent_index)

self.calc_obstacle_map(ox, oy):构建栅格地图函数

    def calc_obstacle_map(self, ox, oy):
        ''' 第1步:构建栅格地图 '''
        # 获取地图边界值:最小值最大值
        self.min_x = round(min(ox))
        self.min_y = round(min(oy))
        self.max_x = round(max(ox))
        self.max_y = round(max(oy))
        print("min_x:", self.min_x)
        print("min_y:", self.min_y)
        print("max_x:", self.max_x)
        print("max_y:", self.max_y)

        # 计算x.y方向具体栅格个数
        self.x_width = round((self.max_x - self.min_x) / self.resolution)
        self.y_width = round((self.max_y - self.min_y) / self.resolution)
        print("x_width:", self.x_width)
        print("y_width:", self.y_width)

        # 初始化地图:地图可通行区域为False,据障碍物小于机器人半径的为True,见以下遍历障碍物
        self.obstacle_map = [[False for _ in range(self.y_width)]
                             for _ in range(self.x_width)]
        # 设置障碍物
        # 其中前两层为遍历栅格,其中ix,iy为栅格下标
        for ix in range(self.x_width):
            x = self.calc_position(ix, self.min_x) # 计算具体位置
            for iy in range(self.y_width):
                y = self.calc_position(iy, self.min_y)
        
            # def calc_position(self, index, minp):
                pos = index * self.resolution + minp # 下标×栅格大小+最小位置=位置
                return pos

                # 遍历障碍物
                for iox, ioy in zip(ox, oy):
                    d = math.hypot(iox - x, ioy - y) # 计算点到障碍物的距离
                    if d <= self.robot_radius: # 若点到障碍物距离小于机器人半径,则识别为障碍物
                        self.obstacle_map[ix][iy] = True
                        break

self.motion = self.get_motion_model():定义机器人运动方式

    def get_motion_model():
        # dx, dy, cost
        # 转换为有权图,即机器人能运动的[x,y,运动距离]
        motion = [[1, 0, 1], # 往右走
                  [0, 1, 1], # 往左走
                  [-1, 0, 1],
                  [0, -1, 1],
                  [-1, -1, math.sqrt(2)], #对角走
                  [-1, 1, math.sqrt(2)],
                  [1, -1, math.sqrt(2)],
                  [1, 1, math.sqrt(2)]]

        return motion

2)Node:存储栅格节点

    class Node:
        def __init__(self, x, y, cost, parent_index):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost  # g(n) 路径值
            self.parent_index = parent_index  # 栅格索引,最后用于寻找路径

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.parent_index)

3)planning(self, sx, sy, gx, gy):以节点的方式搜索路径

得到起始点和终点的节点,创建open_set和closed_set。将起点放入open_set中。

    def planning(self, sx, sy, gx, gy):
   
        # 得到起始点和终点的节点
        start_node = self.Node(self.calc_xy_index(sx, self.min_x),
                               self.calc_xy_index(sy, self.min_y), 0.0, -1)  
        goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
                              self.calc_xy_index(gy, self.min_y), 0.0, -1)
        # calc_xy_index:round((position - minp) / self.resolution)
        
        open_set, closed_set = dict(), dict()     # key - value: hash表
        open_set[self.calc_index(start_node)] = start_node # 存入起点
        # calc_index(self, node): node.y * self.x_width + node.x 行×宽度+所在列

循环下列命令

        while 1:
            c_id = min(open_set, key=lambda o: open_set[o].cost)  # 取cost最小的节点
            current = open_set[c_id]

            # 画图
            if show_animation:  # pragma: no cover
                plt.plot(self.calc_position(current.x, self.min_x),
                         self.calc_position(current.y, self.min_y), "xc")
                # for stopping simulation with the esc key.
                plt.gcf().canvas.mpl_connect(
                    'key_release_event',
                    lambda event: [exit(0) if event.key == 'escape' else None])
                if len(closed_set.keys()) % 10 == 0:
                    plt.pause(0.001)

            # 判断是否是终点
            if current.x == goal_node.x and current.y == goal_node.y:
                print("Find goal")
                goal_node.parent_index = current.parent_index
                goal_node.cost = current.cost
                break

            # 在open_set中删除cost最小节点
            del open_set[c_id]

            # 将最小节点加入closed_set中
            closed_set[c_id] = current

            # 基于运动模型扩展搜索网络
            for move_x, move_y, move_cost in self.motion:
                node = self.Node(current.x + move_x,
                                 current.y + move_y,
                                 current.cost + move_cost, c_id)
                n_id = self.calc_index(node) # 计算新节点的key

                if n_id in closed_set: # 是否收录该点若收录则进入下一循环
                    continue

                if not self.verify_node(node): # 判断是否超过范围
                    continue

                if n_id not in open_set: # 栅格可行则更新到起点的距离
                    open_set[n_id] = node  # Discover a new node
                else:
                    if open_set[n_id].cost >= node.cost:
                        # This path is the best until now. record it!
                        open_set[n_id] = node

以下为上述代码中的 verify_node(node):判断节点是否超过范围

    def verify_node(self, node):
        px = self.calc_position(node.x, self.min_x)
        py = self.calc_position(node.y, self.min_y)
        
        # 判断是否超出边界
        if px < self.min_x:
            return False
        if py < self.min_y:
            return False
        if px >= self.max_x:
            return False
        if py >= self.max_y:
            return False

        if self.obstacle_map[node.x][node.y]: # 判断是否为障碍物
            return False

        return True

计算最后路径:calc_final_path(goal_node, closed_set)

 rx, ry = self.calc_final_path(goal_node, closed_set) # 计算最后路径

        return rx, ry
    def calc_final_path(self, goal_node, closed_set):
        # generate final course
        rx, ry = [self.calc_position(goal_node.x, self.min_x)], [
            self.calc_position(goal_node.y, self.min_y)]
        
        # 通过终点的父节点一直循环,直到返回到起点得到路径
        parent_index = goal_node.parent_index # 返回终点的父节点索引
        while parent_index != -1: # 父节点为-1时为起点
            n = closed_set[parent_index]
            rx.append(self.calc_position(n.x, self.min_x))
            ry.append(self.calc_position(n.y, self.min_y))
            parent_index = n.parent_index

        return rx, ry

以下附上总的算法代码

"""

Grid based Dijkstra planning

author: Atsushi Sakai(@Atsushi_twi)

"""

import matplotlib.pyplot as plt
import math

show_animation = True


class Dijkstra:

    def __init__(self, ox, oy, resolution, robot_radius):
        """
        Initialize map for planning

        ox: x position list of Obstacles [m]
        oy: y position list of Obstacles [m]
        resolution: grid resolution [m]
        rr: robot radius[m]
        """

        self.min_x = None
        self.min_y = None
        self.max_x = None
        self.max_y = None
        self.x_width = None
        self.y_width = None
        self.obstacle_map = None

        self.resolution = resolution
        self.robot_radius = robot_radius
        self.calc_obstacle_map(ox, oy) # 构建栅格地图
        self.motion = self.get_motion_model() # 机器人运动方式

    class Node:
        def __init__(self, x, y, cost, parent_index):
            self.x = x  # index of grid
            self.y = y  # index of grid
            self.cost = cost  # g(n) 路径值
            self.parent_index = parent_index  # 栅格索引,最后用于寻找路径

        def __str__(self):
            return str(self.x) + "," + str(self.y) + "," + str(
                self.cost) + "," + str(self.parent_index)

    def planning(self, sx, sy, gx, gy):
        """
        dijkstra path search

        input:
            s_x: start x position [m]
            s_y: start y position [m]
            gx: goal x position [m]
            gx: goal x position [m]

        output:
            rx: x position list of the final path
            ry: y position list of the final path
        """

        # 得到起始点和终点的节点
        start_node = self.Node(self.calc_xy_index(sx, self.min_x),
                               self.calc_xy_index(sy, self.min_y), 0.0, -1)   # round((position - minp) / self.resolution)
        goal_node = self.Node(self.calc_xy_index(gx, self.min_x),
                              self.calc_xy_index(gy, self.min_y), 0.0, -1)

        open_set, closed_set = dict(), dict()     # key - value: hash表
        open_set[self.calc_index(start_node)] = start_node

        while 1:
            c_id = min(open_set, key=lambda o: open_set[o].cost)  # 取cost最小的节点
            current = open_set[c_id]

            # show graph
            if show_animation:  # pragma: no cover
                plt.plot(self.calc_position(current.x, self.min_x),
                         self.calc_position(current.y, self.min_y), "xc")
                # for stopping simulation with the esc key.
                plt.gcf().canvas.mpl_connect(
                    'key_release_event',
                    lambda event: [exit(0) if event.key == 'escape' else None])
                if len(closed_set.keys()) % 10 == 0:
                    plt.pause(0.001)

            # 判断是否是终点
            if current.x == goal_node.x and current.y == goal_node.y:
                print("Find goal")
                goal_node.parent_index = current.parent_index
                goal_node.cost = current.cost
                break

            # 在open_set中删除cost最小节点
            del open_set[c_id]

            # 将最小节点加入closed_set中
            closed_set[c_id] = current

            # 基于运动模型扩展搜索网络
            for move_x, move_y, move_cost in self.motion:
                node = self.Node(current.x + move_x,
                                 current.y + move_y,
                                 current.cost + move_cost, c_id)
                n_id = self.calc_index(node) # 计算新节点的key

                if n_id in closed_set: # 是否收录该点若收录则进入下一循环
                    continue

                if not self.verify_node(node): # 判断是否超过范围
                    continue

                if n_id not in open_set: # 栅格可行则更新到起点的距离
                    open_set[n_id] = node  # Discover a new node
                else:
                    if open_set[n_id].cost >= node.cost:
                        # This path is the best until now. record it!
                        open_set[n_id] = node

        rx, ry = self.calc_final_path(goal_node, closed_set) # 计算最后路径

        return rx, ry

    # 求路径,其中rx,ry存储路径
    def calc_final_path(self, goal_node, closed_set):
        # generate final course
        rx, ry = [self.calc_position(goal_node.x, self.min_x)], [
            self.calc_position(goal_node.y, self.min_y)]
        parent_index = goal_node.parent_index
        while parent_index != -1:
            n = closed_set[parent_index]
            rx.append(self.calc_position(n.x, self.min_x))
            ry.append(self.calc_position(n.y, self.min_y))
            parent_index = n.parent_index

        return rx, ry

    def calc_position(self, index, minp):
        pos = index * self.resolution + minp # 下标×栅格大小+最小位置=位置
        return pos

    def calc_xy_index(self, position, minp):
        return round((position - minp) / self.resolution)

    def calc_index(self, node):
        return node.y * self.x_width + node.x

    # 判断是否超出范围
    def verify_node(self, node):
        px = self.calc_position(node.x, self.min_x)
        py = self.calc_position(node.y, self.min_y)

        if px < self.min_x:
            return False
        if py < self.min_y:
            return False
        if px >= self.max_x:
            return False
        if py >= self.max_y:
            return False

        if self.obstacle_map[node.x][node.y]: # 是否为障碍物
            return False

        return True

    def calc_obstacle_map(self, ox, oy):
        ''' 第1步:构建栅格地图 '''
        # 获取地图边界值:最小值最大值
        self.min_x = round(min(ox))
        self.min_y = round(min(oy))
        self.max_x = round(max(ox))
        self.max_y = round(max(oy))
        print("min_x:", self.min_x)
        print("min_y:", self.min_y)
        print("max_x:", self.max_x)
        print("max_y:", self.max_y)

        # 计算x.y方向具体栅格个数
        self.x_width = round((self.max_x - self.min_x) / self.resolution)
        self.y_width = round((self.max_y - self.min_y) / self.resolution)
        print("x_width:", self.x_width)
        print("y_width:", self.y_width)

        # obstacle map generation
        # 初始化地图
        self.obstacle_map = [[False for _ in range(self.y_width)]
                             for _ in range(self.x_width)]
        # 设置障碍物
        # 其中前两层为遍历栅格,其中ix,iy为栅格下标
        for ix in range(self.x_width):
            x = self.calc_position(ix, self.min_x) # 计算具体位置
            for iy in range(self.y_width):
                y = self.calc_position(iy, self.min_y)

                # 遍历障碍物
                for iox, ioy in zip(ox, oy):
                    d = math.hypot(iox - x, ioy - y) # 计算点到障碍物的距离
                    if d <= self.robot_radius: # 若点到障碍物距离小于机器人半径,则识别为障碍物
                        self.obstacle_map[ix][iy] = True
                        break

    @staticmethod
    def get_motion_model():
        # dx, dy, cost
        # 转换为有权图,即机器人能运动的[x,y,运动距离]
        motion = [[1, 0, 1], # 往右走
                  [0, 1, 1], # 往左走
                  [-1, 0, 1],
                  [0, -1, 1],
                  [-1, -1, math.sqrt(2)],
                  [-1, 1, math.sqrt(2)],
                  [1, -1, math.sqrt(2)],
                  [1, 1, math.sqrt(2)]]

        return motion

def main():
    # 设置起点和终点
    sx = -5.0  # [m] # 设置起点
    sy = -5.0  # [m]
    gx = 50.0  # [m] # 设置终点
    gy = 50.0  # [m]
    grid_size = 2.0  # [m] 设置栅格大小
    robot_radius = 1.0  # [m] 设置机器人大小

    # 设置障碍物位置(黑色边缘)
    ox, oy = [], []
    for i in range(-10, 60):
        ox.append(i)
        oy.append(-10.0)
    for i in range(-10, 60):
        ox.append(60.0)
        oy.append(i)
    for i in range(-10, 61):
        ox.append(i)
        oy.append(60.0)
    for i in range(-10, 61):
        ox.append(-10.0)
        oy.append(i)
    for i in range(-10, 40):
        ox.append(20.0)
        oy.append(i)
    for i in range(0, 40):
        ox.append(40.0)
        oy.append(60.0 - i)

    if show_animation:  # pragma: no cover
        plt.plot(ox, oy, ".k")
        plt.plot(sx, sy, "og")
        plt.plot(gx, gy, "xb")
        plt.grid(True) # 打开绘图网格线
        plt.axis("equal") # 设置x轴、y轴刻度相同

    dijkstra = Dijkstra(ox, oy, grid_size, robot_radius)
    rx, ry = dijkstra.planning(sx, sy, gx, gy)

    if show_animation:  # pragma: no cover
        plt.plot(rx, ry, "-r")
        plt.pause(0.01)
        plt.show()

if __name__ == '__main__':
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值