NetworkX isomorphism - how to find edge mapping

149 Views Asked by At

I have the following two isomorphic graphs with different edge labels:

G1 = nx.Graph()
G1.add_edges_from([(1,2), (2,3), (3,4), (4,2)])
attrs1 = {(1, 2): {'label': 'Albert'}, (2, 3): {'label': 'Bob'}, (3, 4): {'label': 'Cole'}, (4, 2): {'label': 'Dan'}}
nx.set_edge_attributes(G1, attrs1)

G2 = nx.Graph()
G2.add_edges_from([(13,14), (12,13), (11,12), (14,12)])
attrs2 = {(11, 12): {'label': 'Alice'}, (12, 13): {'label': 'Barbara'}, (13, 14): {'label': 'Cathrine'}, (14, 12): {'label': 'Delia'}}
nx.set_edge_attributes(G2, attrs2)

I use nx.isomorphism to find the correct mapping between the nodes:

GM = isomorphism.GraphMatcher(G1, G2)
GM.is_isomorphic()
print(GM.mapping)
>>> {1: 11, 2: 12, 3: 13, 4: 14}

There is no built-in way to directly get the mapping between the edges. What is the most efficient way to get a dictionary between the edge labels?

{'Albert': 'Alice', 'Bob': 'Barbara', 'Cole': 'Cathrine', 'Dan': 'Delia'}

Many thanks for all suggestions!

2

There are 2 best solutions below

0
coaxialquantum On BEST ANSWER

Here is an answer inspired by @J_H's comment.

Let's relabel the nodes of G1 to match the names of G2:

node_map = GM.mapping
G1b = nx.relabel_nodes(G1, node_map)

Create EdgeView objects for the two graphs. Through these, the edge lables can be accessed.

e1 = G1b.edges()
e2 = G2.edges()

Now eg with a list comprehension we obtain the desired output:

[(e2[j]['label'], e1[j]['label']) for j in list(e1)]

<<< [('Alice', 'Albert'),
<<< ('Barbara', 'Bob'),
<<< ('Delia', 'Dan'),
<<< ('Cathrine', 'Cole')]
2
ravenspoint On
LOOP E over edges in G1
   GET v1,v2 the nodes connected by E
   GET v1g2,v2g2 the isomorphic vertices in G2 if v1,v2
   GET Eg2 the edge between v1g2,v2g2 in G2
   LABEL Eg2 with E's label