Python Networkx:在multiDiGraph中查找给定路径的所有边

问题描述 投票:3回答:1

在我的多向有向图中,我想找到2个节点之间可能的所有(简单)路径。我设法获得所有路径,但无法区分源节点到达目标节点所需的边缘(假设它是multiDiGraph)。

例如,我有A-> B-> C,其中在(A,B)和(B,C)之间存在多个平行边缘。如果我让A-> B的5个平行边和B-> C的2个平行边,则all_simple_path(graph,'='A',target ='C')将返回7个路径,所有都是课程A-> B-> C.

使用get_edge_data()时,它返回每个节点之间的所有平行边。但我想要的是能够列出路径中指定节点所采用的所有组合边。

谢谢 !

python graph networkx edges
1个回答
0
投票

我认为OP不需要这个答案,但它对其他人有用。

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'}}))]]
© www.soinside.com 2019 - 2024. All rights reserved.