当前位置: 首页 > article >正文

机器人路径规划

基于python计算从起始节点到目标节点的最短路径,使用Dijkstra算法和A*算法进行比较。最后,它会绘制出这两种算法找到的最短路径。

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np


def generate_node_positions(num_nodes):
    """生成随机节点位置"""
    return np.random.rand(num_nodes, 2)


def create_undirected_graph(node_positions):
    """创建无向图"""
    G = nx.Graph()
    for i in range(len(node_positions)):
        G.add_node(i, pos=(node_positions[i][0], node_positions[i][1]))
    for i in range(len(node_positions)):
        for j in range(i + 1, len(node_positions)):
            distance = np.linalg.norm(node_positions[i] - node_positions[j])
            if distance < 0.2:
                G.add_edge(i, j, weight=distance)
    return G


def calculate_shortest_path(G, start_node, end_node, algorithm='dijkstra'):
    """计算最短路径"""
    if algorithm == 'dijkstra':
        path = nx.dijkstra_path(G, source=start_node, target=end_node)
    elif algorithm == 'astar':
        heuristic = lambda n1, n2: np.linalg.norm(np.array(G.nodes[n1]['pos']) - np.array(G.nodes[n2]['pos']))
        path = nx.astar_path(G, source=start_node, target=end_node, heuristic=heuristic)
    else:
        raise ValueError("Unsupported algorithm")
    return path


def draw_routes(G, dijkstra_path, astar_path):
    """绘制路线,增加图形美化,并排显示Dijkstra和A*路径"""
    pos = nx.get_node_attributes(G, 'pos')
    fig, axs = plt.subplots(1, 2, figsize=(20, 8))  # 创建包含两个子图的窗口

    paths = [dijkstra_path, astar_path]
    titles = ["Dijkstra Path", "A* Path"]

    for ax, path, title in zip(axs, paths, titles):
        # 绘制节点,设置节点大小
        node_sizes = [50 if node in path else 300 for node in G.nodes()]
        nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color='lightblue', alpha=0.7, ax=ax)

        # 绘制边,设置透明度
        nx.draw_networkx_edges(G, pos, edgelist=G.edges(), edge_color='gray', alpha=0.5, ax=ax)

        # 突出显示路径边,设置颜色和宽度
        path_edges = list(zip(path, path[1:]))
        nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color='r', width=3, alpha=0.9, ax=ax)

        # 绘制标签,设置字体大小和颜色
        nx.draw_networkx_labels(G, pos, font_size=12, font_color='black', ax=ax)

        ax.set_title(title, fontsize=16)
        ax.axis('off')  # 关闭坐标轴

    plt.tight_layout()  # 自动调整子图参数,使之填充整个图像区域
    plt.show()


if __name__ == "__main__":
    num_nodes = 100
    node_positions = generate_node_positions(num_nodes)
    G = create_undirected_graph(node_positions)

    start_node = 1
    end_node = 99

    dijkstra_path = calculate_shortest_path(G, start_node, end_node, 'dijkstra')
    astar_path = calculate_shortest_path(G, start_node, end_node, 'astar')

    draw_routes(G, dijkstra_path, astar_path)


http://www.kler.cn/a/551309.html

相关文章:

  • 低成本、高效率且成熟的电商实时数据采集方案:梦想成真?
  • 基于Dapr与Kubernetes的弹性事件驱动架构:构建跨云可观测的松散耦合系统
  • DeepSeek 助力 Vue 开发:打造丝滑的日期选择器(Date Picker),未使用第三方插件
  • Unity学习part2
  • 论文阅读2——S波段宽波束圆极化天线设计
  • 如何利用 Java 在线生成 PDF 文件
  • 《Keras 3 :具有类似 U-Net 架构的图像分割》
  • 【一文读懂】什么是MVVM?
  • AWS助力AI智能扫地机器人马来西亚项目技术解析与成本优化实践
  • Vue3的Composition API
  • 前端与后端的对接事宜、注意事项
  • windows11升级到24H2后Oracle VM VirtualBox无法启动虚拟机
  • RabbitMQ 3.12.2:单节点与集群部署实战指南
  • 实战设计模式之组合模式
  • 基于python深度学习遥感影像地物分类与目标识别、分割实践技术应用
  • HBase Shell
  • 【BUG】Ubuntu|有nvcc,没有nvidia-smi指令,找不到nvidia-driver安装包
  • 机器学习之熵的计算方法及香农信息熵的含义
  • 使用右侧值现象来处理一个word导入登记表的需求
  • 像素绽放PixelBloom(AiPPT.com) 联合创始人蒲世林:创新者的窘境就是新物种的机会