简体   繁体   English

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

[英]Convert BiDirectional Graph Edges to Undirected Edges in NetworkX

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 .我正在使用NetworkX执行以下操作:我有一个有向图g ,我想将其转换为一个无向图h ,使得h具有与g相同的节点,并且eh中的一条边,当且仅当eg中是双向的。 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")])

有向图

into进入

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

无向图

What f(g) = h should I write in NetworkX?我应该在 NetworkX 中写什么f(g) = h I think it's some combination of graph views and filters, but I'm new to NetworkX so I'm not sure exactly what.我认为它是图形视图和过滤器的某种组合,但我是 NetworkX 的新手,所以我不确定到底是什么。

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 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: output 给出:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM