如何解决获取包含一定数量节点的networkx子图
我有一个networkx DiGraph,我想提取包含一定数量节点的子图。 例如,有向图是0-1-2-3-4-5。我想获取包含3个节点的所有子图。结果应为:0-1-2、1-2-3、2-3-4、3-4-5。 我该怎么办?
解决方法
我不确定我是否正确理解:您的示例暗示您只想要已连接子图?在有向图中,存在多种连接(弱连接和强连接)。因此,您必须确定要寻找的人。
这可能有效:
import networkx as nx
from itertools import combinations
# The graph in your example (as I understand it)
G = nx.DiGraph((i,i+1) for i in range(5))
num_of_nodes = 3 # Number of nodes in the subgraphs (here 3,as in your example)
subgraphs = [] # List for collecting the required subgraphs
for nodes in combinations(G.nodes,num_of_nodes):
G_sub = G.subgraph(nodes) # Create subgraph induced by nodes
# Check for weak connectivity
if nx.is_weakly_connected(G_sub):
subgraphs.append(G_sub)
combinations(G.nodes,num_of_nodes)
迭代num_of_nodes
中许多节点的G
的所有唯一组合。
所选子图正是您提到的子图:
print([H.nodes for H in subgraphs])
print([H.edges for H in subgraphs])
显示
[NodeView((0,1,2)),NodeView((1,2,3)),NodeView((2,3,4)),NodeView((3,4,5))]
[OutEdgeView([(0,1),(1,2)]),OutEdgeView([(1,2),(2,3)]),OutEdgeView([(2,3),(3,4)]),OutEdgeView([(3,4),(4,5)])]
如果您的图形是
G = nx.DiGraph([(i,i+1) for i in range(5)] + [(i+1,i) for i in range(5)])
您正在寻找牢固的连接性,那么您必须使用
...
# Check for strong connectivity
if nx.is_strongly_connected(G_sub):
...
(通常的警告:G.subgraph()
只给您一个视图。)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。