Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Networkx : find all edges for a given path in a multiDiGraph

In my multi directed graph, I would like to find all the (simple) paths possible between 2 nodes. I manage to get all the path, but cannot distinguish which edge (given that it's a multiDiGraph) the source node takes to reach the target node.

For example I have A->B->C where there are multiple edges in parallele between (A,B) and (B,C). If I have let say 5 parallele edges for A->B and 2 parallele edges for B->C, the all_simple_path(graph, source='A', target='C') will return in total 7 paths, all are of course A->B->C

When using get_edge_data(), it returns ALL the parallele edge between each node. But what I want is to be able to list all the combinations edges taken by the specified nodes in the path.

Thank you !

like image 584
filipyoo Avatar asked May 31 '26 00:05

filipyoo


1 Answers

Use "all_simple_edge_paths" . It will give index of the edges.

import networkx as nx

G = nx.MultiDiGraph()
G.add_edge(1, 2, **{'prop1': 'A', 'prop2': 'B'})
G.add_edge(1, 3, **{'prop1': 'A', 'prop2': 'C'})
G.add_edge(2, 3, **{'prop1': 'B', 'prop2': 'C'})
G.add_edge(2, 3, **{'prop1': 'B1', 'prop2': 'C1'})

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



paths = nx.all_simple_edge_paths(G, source, destination)

for path in paths:
   print(" Path :: ")
   for edge in path:
       src = edge[0]
       dst = edge[1]
       print(str(src)+ " - "+str(dst)+ " :: "+str(G.get_edge_data(edge[0], edge[1])[edge[2]]))
like image 56
defender Avatar answered Jun 01 '26 14:06

defender