python - 如何优化关于计算两点之间最短路径的脚本 - python
问题描述
我有一个 networkx 图G
,其中包含作为节点的公共交通站点数据,边表示公共交通网络的每条路线。我有一个脚本,它返回一对点坐标([x_coord1, y_coord1]
和[x_coord2, y_coord2]
)一定的时间。
我希望能够G
为这对点打开两个最近的停靠站,然后计算它们之间的最短路径。
我这样做了,它工作得非常好,但它花费了太多时间。整个函数运行大约需要600-850 毫秒(参见下面的代码),这太长了(因为我需要在循环中执行大约1000 万条路径)。
Bellow 是我写的函数,我知道:
G
A 是格式中每个节点的所有 lon/lat 值的列表数组array([[x1, y1], [x2, y2], [x3, y3], ...])
- 格式中的 coord_source
[x_coord1, y_coord1]
是前一个脚本返回的对的第一个点 - 格式中的 coord_targ
[x_coord2, y_coord2]
是前一个脚本返回的对的第二个点
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
有没有办法让我的脚本运行得更快?另外,如果某些部分不够清楚,请告诉我,我会尽力更好地解释它们。
解决方案
推荐阅读
- javascript - 是否可以为机车滚动中的粘性图像添加最高价值?
- angular - Angular - 如何验证反应形式数组中的数字范围
- typescript - 有条件地启用身份验证策略的好方法是什么?
- c++ - 允许随机访问更新权重的 c++ 优先级队列?
- node.js - 读取 Kubernetes configMap , nodeJS/express API 应用程序
- parallel-processing - Oozie 如何安排分叉中的后续操作?
- python - 如何在代码工作簿中合并 Palantir Foundry 中的两个数据集?
- r - 修改元素周围元素的矩阵?
- php - 获取字符串 aXbcXYaXaY 中所有可能的组合
- java - 使用 Jackson 将 java.time.Duration 序列化为仅以毫秒为单位的 json