找到 NetworkX 中所有节点对之间的所有最短路径

问题描述 投票:0回答:4

我正在尝试获取无向未加权图中所有节点对之间的所有最短路径。我目前正在使用

nx.all_pairs_shortest_path()
,但我不明白为什么它只为每对节点返回一条最短路径。我的图中存在循环,因此某些节点之间应该存在多个最短路径。有什么建议吗?

python python-3.x networkx graph-theory shortest-path
4个回答
4
投票

迭代图中的所有节点:

results = []
for n1 in G.nodes():
    for n2 in G.nodes():
        shortest_path = nx.single_source_dijkstra(G, source=n1, target=n2, weight=f)
        results.append(shortest_path)
        

2
投票

我自己偶然发现了这个问题,并找到她寻求解决方案。不幸的是,networkx 没有计算每对节点的所有最短路径的函数。此外,伊戈尔·米切蒂的答案根本没有给出我想要的东西,但它可能是可调整的。

math_noob 的答案很好,因为它足够接近,足以让我找到解决方案,但问题是它太慢了。

def single_source_shortest_paths(graph,source):
    shortest_paths_dict = {}
    for node in graph:
        shortest_paths_dict[node] = list(nx.all_shortest_paths(graph,source,node))
    return shortest_paths_dict

def all_shortest_paths(graph):
    for source in graph:
        yield source, single_source_shortest_paths(source)

所以我回到了networkx文档并尝试最后一次查找是否有我可以使用的功能。但没有,所以我决定自己实现它。所以我首先尝试通过 had 来实现所有内容,这有点混乱,只是意识到它好一点,但没有那么多,所以我决定我会尝试研究一下源代码并发现了一个圣杯,那就是

nx.predecessor
函数。

此函数仅在图和源节点上调用,因此它不依赖于目标节点,并且它是完成大部分艰苦工作的节点。因此,我只是重新创建了函数

single_source_shortest_paths
,但每个源节点仅调用一次
nx.predecessor
,然后执行与
all_shortest_path
相同的操作,其中仅包含使用正确的参数调用另一个函数。

def single_source_shortest_paths_pred(graph,source):
    shortest_paths_dict = {}
    pred = nx.predecessor(graph,source)
    for node in graph:
        shortest_paths_dict[node] = list(nx.algorithms.shortest_paths.generic._build_paths_from_predecessors([source], node, pred))
    return shortest_paths_dict

就时间而言,

nx.predecessor
花费了大部分时间来执行,因此第二个函数大约快 n 倍,其中 n 是图中的节点数


2
投票

我可能迟到了,但我刚刚遇到了同样的问题,这是我的解决方案:

 def all_shortest_paths(G):
    a = list(nx.all_pairs_shortest_path(G))
    all_sp_list = []
    for n in range(len(G.nodes)):
      a1 = a[n][1]
      for k,v in a1.items():
        all_sp_list.append(len(v))
    return all_sp_list

我尝试的所有其他方法都变得非常非常慢,因为我的图表有一堆节点,所以这是我最快的解决方案。


0
投票
import pandas as pd  # dataframes
import networkx as nx  # networks a.k.a graphs
from pprint import pprint  # pretty print


def new_pandas_edgelist():
    return pd.DataFrame(
        {
            "source": ["A", "A", "B", "C"],
            "target": ["B", "C", "D", "D"],
            "distance": [10, 20, 30, 40],
        }
    )


def new_graph(df: pd.DataFrame) -> nx.classes.graph.Graph:
    graph = nx.from_pandas_edgelist(df, edge_attr=["distance"], create_using=nx.Graph)
    return graph


def every_shortest_path(G):
    return {(source, target): a_shortest_path(G, source, target) for source in G for target in G}


def a_shortest_path(G, source, target, weight="distance"):
    return nx.single_source_dijkstra(G, source, target, weight=weight)


if __name__ == "__main__":
    df_edges = new_pandas_edgelist()
    graph = new_graph(df_edges)
    print("")
    print("every shortest path...")
    pprint(every_shortest_path(graph))

# every shortest path...
# {('A', 'A'): (0, ['A']),
#  ('A', 'B'): (10, ['A', 'B']),     
#  ('A', 'C'): (20, ['A', 'C']),
#  ('A', 'D'): (40, ['A', 'B', 'D']),
#  ('B', 'A'): (10, ['B', 'A']),
#  ('B', 'B'): (0, ['B']),
#  ('B', 'C'): (30, ['B', 'A', 'C']),
#  ('B', 'D'): (30, ['B', 'D']),
#  ('C', 'A'): (20, ['C', 'A']),
#  ('C', 'B'): (30, ['C', 'A', 'B']),
#  ('C', 'C'): (0, ['C']),
#  ('C', 'D'): (40, ['C', 'D']),
#  ('D', 'A'): (40, ['D', 'B', 'A']),
#  ('D', 'B'): (30, ['D', 'B']),
#  ('D', 'C'): (40, ['D', 'C']),
#  ('D', 'D'): (0, ['D'])}
© www.soinside.com 2019 - 2024. All rights reserved.