iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python中怎么利用Dijkstra算法规划机器人路径
  • 916
分享到

python中怎么利用Dijkstra算法规划机器人路径

2023-06-20 19:06:11 916人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

今天就跟大家聊聊有关python中怎么利用Dijkstra算法规划机器人路径,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。一、算法原理如图所示,Dijkstra算法要解决的是一个有向

今天就跟大家聊聊有关python中怎么利用Dijkstra算法规划机器人路径,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、算法原理

python中怎么利用Dijkstra算法规划机器人路径

如图所示,Dijkstra算法要解决的是一个有向权重图中最短路径的寻找问题,图中红色节点1代表起始节点,蓝色节点6代表目标结点。箭头上的数字代表两个结点中的的距离,也就是模型中所谓的代价(cost)。

贪心算法需要设立两个集合,open_set(开集)和closed_set(闭集),然后根据以下程序进行操作:

  • 把初始结点放入到open_set中;

  • 把open_set中代价最小的节点取出来放入到closed_set中,并且作为当前节点;

  • 把与当前节点相邻的节点放入到open_set中,如果代价更小更新代价

  • 重复2-3过程,直到找到终点。

注意open_set中的代价是可变的,而closed_set中的代价已经是最小的代价了,这也是为什么叫做open和close的原因。

至于为什么closed_set中的代价是最小的,是因为我们使用了贪心算法,既然已经把节点加入到了close中,那么初始点到close节点中的距离就比到open中的距离小了,无论如何也不可能找到比它更小的了。

二、程序代码

"""Grid based Dijkstra planningauthor: Atsushi Sakai(@Atsushi_twi)"""import matplotlib.pyplot as pltimport mathshow_animation = Trueclass Dijkstra:    def __init__(self, ox, oy, resolution, robot_radius):        """        Initialize map for a star 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            self.parent_index = parent_index  # index of previous Node        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)        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()        open_set[self.calc_index(start_node)] = start_node        while 1:            c_id = min(open_set, key=lambda o: open_set[o].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            # Remove the item from the open set            del open_set[c_id]            # Add it to the closed set            closed_set[c_id] = current            # expand search grid based on motion model            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)                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    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.min_y) * self.x_width + (node.x - self.min_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):        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)        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)]        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        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 motiondef main():    print(__file__ + " start!!")    # start and goal position    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]    # set obstacle positions    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")    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()

三、运行结果

python中怎么利用Dijkstra算法规划机器人路径

四、 A*算法:Djikstra算法的改进

Dijkstra算法实际上是贪心搜索算法,算法复杂度为O( n 2 n^2 n2),为了减少无效搜索的次数,我们可以增加一个启发式函数(heuristic),比如搜索点到终点目标的距离,在选择open_set元素的时候,我们将cost变成cost+heuristic,就可以给出搜索的方向性,这样就可以减少南辕北辙的情况。我们可以run一下PythonRobotics中的Astar代码,得到以下结果:

python中怎么利用Dijkstra算法规划机器人路径

看完上述内容,你们对python中怎么利用Dijkstra算法规划机器人路径有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注编程网Python频道,感谢大家的支持。

--结束END--

本文标题: python中怎么利用Dijkstra算法规划机器人路径

本文链接: https://www.lsjlt.com/news/299627.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python中怎么利用Dijkstra算法规划机器人路径
    今天就跟大家聊聊有关python中怎么利用Dijkstra算法规划机器人路径,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。一、算法原理如图所示,Dijkstra算法要解决的是一个有向...
    99+
    2023-06-20
  • 一文教你用python编写Dijkstra算法进行机器人路径规划
    目录前言一、算法原理二、程序代码三、运行结果四、 A*算法:Djikstra算法的改进总结前言 为了机器人在寻路的过程中避障并且找到最短距离,我们需要使用一些算法进行路径规划(Pat...
    99+
    2024-04-02
  • python中怎么利用Dijkstra算法求最短路径
    python中怎么利用Dijkstra算法求最短路径,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。  从某源点到其余各顶点的最短路径  Dijkstra算法可用...
    99+
    2023-06-02
  • 【路径规划】局部路径规划算法——人工势场法(含python实现 | c++实现)
    文章目录 参考资料1. 算法简介2. 算法精讲2.1 引力势场2.2 斥力势场2.3 合力势场 3. 引力斥力推导计算4. 算法缺陷与改进4.1 目标不可达的问题4.2 陷入局部最优的问题...
    99+
    2023-09-01
    算法 自动驾驶 路径规划 人工势场 python
  • PHP中如何进行机器人自主导航和路径规划?
    随着机器人技术的快速发展,机器人自主导航和路径规划成为了机器人研究中的重要方向。在PHP中,机器人自主导航和路径规划涉及到多个技术点,包括机器人定位、环境感知、路线规划、控制指令等等。本文将从这些方面详细介绍PHP中如何进行机器人自主导航和...
    99+
    2023-05-22
    PHP 机器人自主导航 路径规划
  • python动态规划算法怎么用
    小编给大家分享一下python动态规划算法怎么用,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!python有哪些常用库python常用的库:1.requesuts;2.scrapy;3.pillow;4.twisted;5...
    99+
    2023-06-14
  • 怎么在python中利用pathlib构建路径
    怎么在python中利用pathlib构建路径?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。python主要应用领域有哪些1、云计算,典型应用OpenStack...
    99+
    2023-06-14
  • PostgreSQL中使用动态规划算法构造连接路径的实现函数是哪个
    这篇文章主要介绍“PostgreSQL中使用动态规划算法构造连接路径的实现函数是哪个”,在日常操作中,相信很多人在PostgreSQL中使用动态规划算法构造连接路径的实现函数是哪个问题上存在疑惑,小编查阅了...
    99+
    2024-04-02
  • Python中怎么利用os.listdir方法判断相关路径是否为文件
    这期内容当中小编将会给大家带来有关Python中怎么利用os.listdir方法判断相关路径是否为文件,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。Python判断是否为文件在Python os.list...
    99+
    2023-06-17
  • 怎么在python中使用os.path方法解析路径
    这篇文章给大家介绍怎么在python中使用os.path方法解析路径,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。python有哪些常用库python常用的库:1.requesuts;2.scrapy;3.pillow...
    99+
    2023-06-14
  • Python中怎么利用KNN算法处理缺失数据
    这篇文章将为大家详细讲解有关Python中怎么利用KNN算法处理缺失数据,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。KNN代表" K最近邻居",这是一种简单算法,可根据...
    99+
    2023-06-16
  • Python中怎么利用DBSCAN实现一个密度聚类算法
    Python中怎么利用DBSCAN实现一个密度聚类算法,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。基于密度这点有什么好处呢我们知道kmeans聚类算法只能处理球形的簇,也就是...
    99+
    2023-06-16
  • python opencv3机器学习之EM算法怎么使用
    今天小编给大家分享一下python opencv3机器学习之EM算法怎么使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解...
    99+
    2023-07-02
  • 怎么使用python+Word2Vec实现中文聊天机器人
    本篇内容主要讲解“怎么使用python+Word2Vec实现中文聊天机器人”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么使用python+Word2Vec实现中文聊天机器人”吧! ...
    99+
    2023-07-05
  • 怎么在Python中利用排序算法实现插入排序
    怎么在Python中利用排序算法实现插入排序,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。一、插入排序插入排序与我们平时打扑克牌非常相似,将新摸到的牌插入到已有的牌中合适的位置...
    99+
    2023-06-15
  • 如何在Python中利用机器学习算法进行数据挖掘和预测
    如何在Python中利用机器学习算法进行数据挖掘和预测引言随着大数据时代的到来,数据挖掘和预测成为了数据科学研究的重要组成部分。而Python作为一种简洁优雅的编程语言,拥有强大的数据处理和机器学习库,成为了数据挖掘和预测的首选工具。本文将...
    99+
    2023-10-22
    机器学习 预测 Python 数据挖掘
  • 怎么在java中利用GUI实现一个加法计算器
    怎么在java中利用GUI实现一个加法计算器?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。java基本数据类型有哪些Java的基本数据类型分为:1、整数类型,用来表示整数的数据...
    99+
    2023-06-14
  • 怎么在python中利用后缀表达式实现一个计算器功能
    本文章向大家介绍怎么在python中利用后缀表达式实现一个计算器功能的基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。前缀表达式运算符在数字的前面1 + (2 + 3) * 4 - 5 (中缀)- + 1 * + ...
    99+
    2023-06-06
  • 怎么在python中利用机器学习实现预测股票交易信号
    本篇文章给大家分享的是有关怎么在python中利用机器学习实现预测股票交易信号,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。数据获取与指标构建先引入需要用到的libraries...
    99+
    2023-06-15
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作