python graph_tool:获取_all_最短路径

时间:2017-07-05 14:55:25

标签: python algorithm graph shortest-path graph-tool

我想计算图中所有对之间的所有最短路径。为实现这一目标,我正在为图中的每个节点对使用graph_tool的all_shortest_paths函数。根据文档,如果给出,该函数能够尊重边权重。乍一看这很好用。但是,我发现返回的最短路径列表不完整。它似乎只包括最短路径,它也使用来自整套最短路径的最少跳数。

这是一个小例子:

import graph_tool
import graph_tool.topology

#setup graph
g = graph_tool.Graph()
g.add_vertex(5)
edges = [(0,1),(1,2),(3,2),(0,4),(4,3)]
metrics = [3, 4, 2, 1, 3]
g.edge_properties["metric"] = g.new_edge_property("int")
for i in range(len(metrics)):
    e = g.add_edge(*(edges[i]))
    g.edge_properties["metric"][e] = metrics[i]

#compute all shortest paths from 0 to 2
paths = graph_tool.topology.all_shortest_paths(g, 0, 2, weights=g.edge_properties["metric"])

for path in paths:
    print(path)

print("-"*10)

#increase metric of edge 0-4
g.edge_properties["metric"][g.edge(0,4)] = 2

#recompute all shortest paths from 0 to 2
paths = graph_tool.topology.all_shortest_paths(g, 0, 2, weights=g.edge_properties["metric"])

for path in paths:
    print(path)

它生成一个包含5个顶点和边的图形,形成从顶点0到顶点2的2条路径,如下所示:

0 --- 1 --- 2
 \         /
  \       /
   4 --- 3

显然,就跳数而言,路径[0,1,2]比[0,4,3,2]短。如果没有给出度量标准,则会正确识别(此处未演示)。

在示例的开头,边缘以这样的方式加权,即具有更多跳跃的第二条路径更短“#”;度量的总和为6,而另一个路径的总值为7.因此,算法正确返回[0,4,3,2]。

然后,0到4之间的边的度量增加1.现在两个路径具有相同的总值,并且都应该返回。然而,该算法仅返回[0,1,2]。我只能假设跳数仍然以某种方式考虑在内,即使我指定了一个度量标准,这就是为什么第二条路径被忽略的原因。据我所见,在官方文档中没有提到这种行为。

我忽略了什么吗?有没有更好的功能来做到这一点,即使是一个不同的库?我已经考虑过igraph作为替代方案,但它似乎只能计算每个节点对的一条最短路径。

1 个答案:

答案 0 :(得分:1)

这种行为确实是图形工具中的一个错误,在使用权重时会发生!我刚刚提交了一个解决方案:https://git.skewed.de/count0/graph-tool/commit/dc06771604dfd8f38d40e68ce16b537bc1afc272

感谢您抓住这个,以及非常明确的例子!

相关问题