Networkx:提取包含给定节点的有向组件(有向图) [英] Networkx: extract the connected component containing a given node (directed graph)

查看:662
本文介绍了Networkx:提取包含给定节点的有向组件(有向图)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从大图中提取包含特定节点的所有连接节点的子图.

I am trying to extract from a big graph the sub-graph of all connected nodes containing a specific node.

Networkx库中是否有解决方案?

Is there a solution in the Networkx library?


我的图是DiGraph


My graph is a DiGraph


措辞简单:
我希望图形中包含特定节点N_i以及使用任何传入或传出边直接或间接(通过其他节点)连接的所有节点的部分.
示例:


Rephrased simply:
I want the part of my graph that contain my specific node N_i and and all the nodes that are connected directly or indirectly (passing by other nodes) using any incoming or outcoming edges.
Example:

>>> g = nx.DiGraph()
>>> g.add_path(['A','B','C',])
>>> g.add_path(['X','Y','Z',])
>>> g.edges()
[('A', 'B'), ('B', 'C'), ('Y', 'Z'), ('X', 'Y')]

我想要的结果是:

>>> g2 = getSubGraph(g, 'B')
>>> g2.nodes()
['A', 'B', 'C']
>>> g2.edges()
[('A', 'B'), ('B', 'C')]

推荐答案

您可以使用shortest_path()查找从给定节点可到达的所有节点.在您的情况下,您需要先将图形转换为无向表示,以便同时跟踪内边缘和外边缘.

You can use shortest_path() to find all of the nodes reachable from a given node. In your case you need to first convert the graph to an undirected representation so both in- and out-edges are followed.

In [1]: import networkx as nx

In [2]: >>> g = nx.DiGraph()

In [3]: >>> g.add_path(['A','B','C',])

In [4]: >>> g.add_path(['X','Y','Z',])

In [5]: u = g.to_undirected()

In [6]: nodes = nx.shortest_path(u,'B').keys()

In [7]: nodes
Out[7]: ['A', 'C', 'B']

In [8]: s = g.subgraph(nodes)

In [9]: s.edges()
Out[9]: [('A', 'B'), ('B', 'C')]

或一行

In [10]: s = g.subgraph(nx.shortest_path(g.to_undirected(),'B'))

In [11]: s.edges()
Out[11]: [('A', 'B'), ('B', 'C')]

这篇关于Networkx:提取包含给定节点的有向组件(有向图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆