danodonovan
danodonovan

Reputation: 20373

NetworkX MultiDiGraph paths not distinguishing parallel edges

If I have a very simple directed multigraph

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/ 

I would expect nx.all_shortest_paths(G, source='A', target='C') to return two paths;

but (as it's currently implemented) all_shortest_paths just returns the nodes, not the nodes and edges so we only get one path;

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

Is there any simple / generic method for returning actual paths, rather than simple node lists?

Upvotes: 4

Views: 691

Answers (1)

vurmux
vurmux

Reputation: 10030

networkx has no built-in functions to handle it so you have to do everything manually.

nx.all_simple_paths() returns node lists so for MultiDiGraph there will be many repetitions. So firstly we remove them by converting the nx.all_simple_paths() output to set and then iterate for it. For every path we extract node pairs (for example: [1,2,3,4] -> [[1,2],[2,3],[3,4]]) and for each pair we get AtlasView of all edges between them. Here is the code for this algorithm:

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

Upvotes: 1

Related Questions