在牢固连接的组件上查找边数

时间:2019-09-27 10:08:27

标签: python graph networkx edges connected-components

我有一个名为Gmedium的网络图,并且通过此代码找到了最大的强连接组件:

maxstmed = max(nx.strongly_connected_components(Gmedium), key=len)

我的问题是,如何找到此连接网络的边缘数量?如果您尝试查找节点数,则如下所示:

newGm = nx.Graph()
newGm.add_nodes_from(list(maxstmed))
newGm.number_of_nodes()

但是您不能将其应用于边缘,因为当我使用add_edges_from和number_of_edges时它返回0。我试图通过此方法手动进行计数:

count = 0
for u in list(newGm.nodes):
    for v in list(newGm.nodes):
        if u == v:
            continue
        if nx.has_path(Gmedium,u,v) == True:
            count += 1
print(count)

但是,对于大型网络(节点数超过10.000)而言,这是永远的。有人知道有效地处理它的算法或功能吗?我正在使用Python Ver。在Spyder环境中为3。谢谢。

1 个答案:

答案 0 :(得分:1)

您可以使用subgraph函数从原始图形中提取具有给定节点的子图形。您将节点的集合作为属性发送,它返回给您原始图的子图,其中包含这些节点和它们之间的边:

G = nx.fast_gnp_random_graph(30, 0.04, directed=True, seed=1)
nx.draw(G)

enter image description here

C = max(nx.strongly_connected_components(G), key=len)
print(C)
  

{0, 3, 4, 6, 8, 10, 11, 15, 21, 22, 24, 25}

S = G.subgraph(C)
nx.draw(S)

enter image description here

print(list(nx.edges(S)))
  

[(0, 3), (3, 4), (3, 21), (4, 6), (6, 11), (6, 15), (8, 0), (10, 6), (11, 8), (11, 15), (15, 24), (15, 25), (21, 8), (21, 22), (21, 15), (22, 24), (22, 25), (22, 15), (24, 10), (25, 0)]

相关问题