将双向图边转换为 NetworkX 中的无向边

Convert BiDirectional Graph Edges to Undirected Edges in NetworkX

我正在使用 NetworkX 执行以下操作:我有一个我想要的有向图 g 转换为无向图 h 使得 h 具有与 g 和 [=26= 相同的节点]e 是 h 中的边当且仅当 eg 中是双向的。比如我要变换:

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")])

进入

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

我应该在 NetworkX 中写什么 f(g) = h?我认为这是图形的某种组合 视图和过滤器,但我是 NetworkX 的新手,所以我不确定到底是什么。

您可以通过遍历有向图的边并检查反向边是否存在条件 if edge[::-1] in g.edges(): 来实现。如果反向边缘存在,只需将其添加到您的图形中。请参阅下面的代码:

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

输出结果为: