在networkx中遍历连通组件并提取包含特定节点的组件

4 投票
2 回答
3496 浏览
提问于 2025-04-19 17:34

我有一个非常大的无向网络,这个网络被加载到一个NetworkX的graph()中,里面有很多不相连的部分。我还有一组我感兴趣的节点,这些节点被放在一个集合里。我想要查看所有的部分,提取出那些至少包含一个我感兴趣的节点的部分。

# create empty graph
g = nx.Graph()

# add edges to the graph
g.add_edges_from([['a','b'],['a','c'],['b','c'],['d','e'],['e','f'],['d','f'],['g','h'],['g','i'],['h','i']])

# load nodes of interest into a set
interest_nodes = set(['a', 'b', 'f'])

# number of connected components
nx.number_connected_components(g)

# loop through each connected component and add all of the edges for that component to a list if a node in that component is found in the interest_nodes
interest_edges = []
for i in nx.connected_component_subgraph(g):
    for u in i.edges():
        if u in interest_nodes:
            interest_edges.append(u)

但是,我得到的结果是一个空列表。

理想情况下,我希望能得到一个列表,里面包含所有连接部分的边,这些部分至少有一个节点在interest_nodes集合中。下面是我期望得到的结果,但实际上我什么都没有得到。

interest_edges = [('a', 'c'),
                  ('a', 'b'),
                  ('c', 'b'),
                  ('e', 'd'),
                  ('e', 'f'),
                  ('d', 'f')]

2 个回答

1

connected_component_subgraph()这个函数没有按照我预期的那样工作。作为一个替代方案,你可以遍历所有的连接组件,把所有感兴趣的节点和连接的节点都加到一个新的感兴趣列表里。

然后再遍历你的边。

interest_nodes = set(['a', 'b', 'f'])

interest_nodes_plus_connected = []
for c in nx.connected_components(g):
    for n in interest_nodes:    
        if n in c:
            for node in c:
                interest_nodes_plus_connected.append(node)

interest_nodes_plus_connected = set(interest_nodes_plus_connected)

interest_edges = []
for e in g.edges():
    for n in interest_nodes_plus_connected:
        if n in str(e[0]) or n in str(e[1]):
            interest_edges.append(e)
for ie in interest_edges:
    print ie
7

你已经很接近了。最简单的方法是检查每个组件,看看节点集合是否有重叠,可以通过检查两个集合交集的长度来判断。

import networkx as nx

g = nx.Graph([['a','b'],['a','c'],['b','c'],['d','e'],['e','f'],['d','f'],['g','h'],['g','i'],['h','i']])

interest_nodes = set(['a', 'b', 'f'])

interest_edges = []
for component in nx.connected_component_subgraphs(g):
    if len(set(component) & interest_nodes) > 0:
        interest_edges.extend(component.edges())

print interest_edges
# output
# [('a', 'c'), ('a', 'b'), ('c', 'b'), ('e', 'd'), ('e', 'f'), ('d', 'f')]

撰写回答