顶点收缩 - 蟒蛇

时间:2018-03-30 20:10:22

标签: python-3.x networkx vertex

我有一个带有一些连通组件的子图,如下所示:

enter image description here

我正在使用

bicomponents = list(nx.biconnected_components(T))

识别子图中的所有连通组件。我需要删除整个连接组件并将该组件收缩到顶点并获得一个新叶。例如,我需要移除组件{28,30,31}并引入新的顶点51(我有n= 50个顶点,因此新的顶点将为51)并与{{{ 1}}得到一片新叶。

有人可以帮我这么做吗?

1 个答案:

答案 0 :(得分:2)

要收缩双连通组件,我们将首先重新标记每个组件中的节点,使它们具有相同的标签,然后删除自循环。

构造标签映射

label_mapping = {}
for idx, node_component in enumerate(filter(lambda s: len(s) > 2, nx.biconnected_components(g)), start=len(g) + 1):
    for node in node_component:
        if node not in label_mapping:
            label_mapping[node] = idx

这里我做了两个假设:我们丢弃了琐碎的双连通组件(因此filter,如果不希望的话可以很容易地删除),如果一个节点属于两个双连通组件(切割顶点),我们不会将这两个组件合并为一个节点,但为两个组件保留两个节点。如果这不是所需的行为,我们需要合并具有公共节点的组件,其解决方案位于this question

收缩组件

h = nx.relabel_nodes(g, label_mapping)
h.remove_edges_from(h.selfloop_edges())
相关问题