Convert BiDirectional Graph Edges to Undirected Edges in NetworkX

Viewed 308

I am using NetworkX to do the following: I have a directed graph g that I want to transform into an undirected graph h such that h has the same nodes as g and e is an edge in h iff e is bidirectional in g. For example, I want to transform:

import networkx as nx
g = nx.DiGraph([("A", "B"), ("B", "A"), ("A", "C"), ("C", "A"), ("B", "C"), ("C", "B"), ("A", "D"), ("C", "D"), ("B", "E"), ("C", "E")])

directed graph

into

h = nx.Graph([("A", "B"), ("A", "C"), ("B", "C")])
h.add_nodes_from(["D", "E"])

undirected graph

What f(g) = h should I write in NetworkX? I think it's some combination of graph views and filters, but I'm new to NetworkX so I'm not sure exactly what.

1 Answers

You can achieve that by iterating over the edges of you directed graph and checking if the reverse edge exist with the condition if edge[::-1] in g.edges():. If the reverse edge exist, just add it your graph. See code below:

import networkx as nx
import matplotlib.pyplot as plt

#Creating directed graph
g = nx.DiGraph([("A", "B"), ("B", "A"), ("A", "C"), ("C", "A"), ("B", "C"), ("C", "B"), ("A", "D"), ("C", "D"), ("B", "E"), ("C", "E")])

#Creating undirected graph
h=nx.Graph()
h.add_nodes_from(g)

for edge in g.edges():  
  if edge[::-1] in g.edges(): #check if reverse edge exist in graph
    h.add_edge(edge[0],edge[1])

#plot both graphs
fig=plt.figure(figsize=(15,6))
plt.subplot(121)
plt.title('Directed graph')
pos1=nx.circular_layout(g)
nx.draw(g,pos=pos1,with_labels=True, node_color='tab:orange')

plt.subplot(122)
plt.title('Undirected graph')
pos2=nx.circular_layout(h)
nx.draw(h,pos=pos2,with_labels=True, node_color='tab:green')

And the output gives:

enter image description here

Related