gpt4 book ai didi

python - NetworkX MultiDiGraph 路径不区分平行边

转载 作者:行者123 更新时间:2023-11-28 18:00:24 25 4
gpt4 key购买 nike

如果我有一个非常简单的有向多重图

G = nx.MultiDiGraph()

G.add_edge('A', 'B', key=1)
G.add_edge('B', 'C', key=2)
G.add_edge('B', 'C', key=3)

--

(A) -1- (B) -2- (C)
\3/

我希望 nx.all_shortest_paths(G, source='A', target='C') 返回两条路;

  • A-1-B-2-C
  • A-1-B-3-C

但是(因为它目前已经实现)all_shortest_paths 只返回节点,而不是节点和边,所以我们只能得到一条路径;

>>> list(nx.all_shortest_paths(G, source='A', target='C'))
[['A', 'B', 'C']]

是否有任何简单/通用的方法来返回实际路径,而不是简单的节点列表?

最佳答案

networkx 没有内置函数来处理它,因此您必须手动完成所有操作。

nx.all_simple_paths() 返回节点列表,因此对于 MultiDiGraph 会有很多重复。因此,首先我们通过将 nx.all_simple_paths() 输出转换为 set 来移除它们,然后对其进行迭代。对于每条路径,我们提取节点对(例如:[1,2,3,4] -> [[1,2],[2,3],[3,4]])和对于每一对,我们得到它们之间所有边的 AtlasView。这是该算法的代码:

import networkx as nx
from pprint import pprint

# Create the graph with unique edges to check the algorithm correctness
G = nx.MultiDiGraph()
G.add_edges_from([
[1,2],
[1,2],
[1,2],
[2,3],
[2,3],
[2,3],
[3,4],
[3,4],
[2,4]
])
G.add_edge(1,2,data='WAKA')
G.add_edge(2,3,data='WAKKA')
G.add_edge(2,4,data='WAKA-WAKA')

# Our source and destination nodes
source = 1
destination = 4

# All unique single paths, like in nx.DiGraph
unique_single_paths = set(
tuple(path) # Sets can't be used with lists because they are not hashable
for path in nx.all_simple_paths(G, source, destination)
)

combined_single_paths = []
for path in unique_single_paths:
# Get all node pairs in path:
# [1,2,3,4] -> [[1,2],[2,3],[3,4]]
pairs = [path[i: i + 2] for i in range(len(path)-1)]

# Construct the combined list for path
combined_single_paths.append([
(pair, G[pair[0]][pair[1]]) # Pair and all node between these nodes
for pair in pairs
])
pprint(combined_single_paths)
[[((1, 2), AtlasView({0: {}, 1: {}, 2: {}, 3: {'data': 'WAKA'}})),
((2, 3), AtlasView({0: {}, 1: {}, 2: {}, 3: {'data': 'WAKKA'}})),
((3, 4), AtlasView({0: {}, 1: {}}))],
[((1, 2), AtlasView({0: {}, 1: {}, 2: {}, 3: {'data': 'WAKA'}})),
((2, 4), AtlasView({0: {}, 1: {'data': 'WAKA-WAKA'}}))]]

关于python - NetworkX MultiDiGraph 路径不区分平行边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56042626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com