如何将二部图转换为无二部图

时间:2019-08-28 13:52:24

标签: python-3.x graph networkx bipartite

很长一段时间以来,我一直在努力做到这一点,所以我最好问你。

首先,我正在研究 python 3 networkx

我有一个二部图作为图像A ,其中根据节点的'group'属性有两种类型的节点(group ='R'和group ='X')。同样,有些关系是可逆的,如R4,有些则不是(所以我想在这种情况下我们必须展开节点)。

我需要的是仅保留R组的节点并消除X个节点,但是保持它们之间的关系。也就是说,将绿色节点转换为边缘,并仅保留蓝色节点的图形

哦!!!有人可以帮我吗?

非常欢迎任何帮助。

衷心感谢您!

  

此处的图形图像:

     

https://media.springernature.com/full/springer-static/image/art%3A10.1038%2Fs41540-018-0067-y/MediaObjects/41540_2018_67_Fig1_HTML.png

1 个答案:

答案 0 :(得分:0)

遍历图的节点,如果该节点为绿色,则在其所有邻居之间添加一条边(该边只会是蓝色)。最后,删除所有绿色节点。

to_remove = []
for node in G.nodes(data = True):
    if node[1]["type"] == "Green": ## check if the node is green
        to_remove.append(node[0])
        ## go over all neighbours of the node and add an edge between them
        neighbours =  list(G.neighbors(node[0]))
        for i in range(0, len(neighbours)-1):
            for j in range(i+1, len(neighbours)):
                G.add_edge(neighbours[i],neighbours[j])

## remove the green nodes
G.remove_nodes_from(to_remove)