微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何优化关于计算两点之间最短路径的脚本 - python

如何解决如何优化关于计算两点之间最短路径的脚本 - python

我有一个 networkx 图 G,其中包含公共交通站点数据作为节点,边代表公共交通网络的每条路线。我有一个脚本,它在一定时间内返回一对点坐标([x_coord1,y_coord1][x_coord2,y_coord2])。

对于这对点,我希望能够获得 G 上最近的两个停靠站,然后计算它们之间的最短路径。

我这样做了,而且效果很好,但花费了太多时间。整个函数运行大约需要 600-850 毫秒(请参阅下面的代码),这太长了(因为我需要在循环中执行大约 1000 万条路径)。

Bellow 是我在知道的情况下编写的函数

  • A 是 G 的每个节点的所有 lon/lat 值的列表数组,格式为 array([[x1,y1],[x2,y2],[x3,y3],...])
  • 格式为 [x_coord1,y_coord1] 的 coord_source 是前一个脚本返回的对的第一个
  • 格式为 [x_coord2,y_coord2] 的 coord_targ 是前一个脚本返回的点对的第二个点
def short_path(A,coord_source,coord_targ,G):
    get1 = A[spatial.KDTree(A).query(coord_source)[1]]  ###--- Gets the closest stop station to pt1 and %time of this line gives a walltime of 150 ms approximately
    get2 = A[spatial.KDTree(A).query(coord_targ)[1]]  ###--- same for this one but for pt2
    
    for k in G.nodes().keys():
        lon = G.nodes()[k]['stop_lon']
        lat = G.nodes()[k]['stop_lat']            

        if (lon == get1[0]) & (lat == get1[1]):
            source = k
        if (lon == get2[0]) & (lat == get2[1]):
            target = k
    
    pcc = nx.shortest_path(G,source=source,target=target,weight='time')  ###--- %time of this line gives a walltime of 200 ms

有没有办法让我的脚本运行得更快?另外,如果有些部分不够清楚,请告诉我,我会尽力更好地解释它们。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。