NetworkX MultiDiGraph路径无法区分平行边

时间:2019-05-08 14:02:52

标签: python networkx

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

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']]

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

1 个答案:

答案 0 :(得分:1)

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'}}))]]