如何优化计算两点间最短路径的脚本

2024-10-01 09:30:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我做到了这一点,效果非常好,但这需要花费太多的时间。整个函数运行(见下面的代码)大约需要600-850毫秒,这太长了(因为我需要在循环中运行大约1000万条路径)

下面是我编写的函数,我知道:

  • 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

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


Tags: of脚本sourcetime格式thisstoplon