简体   繁体   English

Python NetworkX从节点作为根在有向图中找到子图

[英]Python NetworkX find a subgraph in a Directed Graph from a node as root

I am writing a code to extract information from a directed graph. 我正在编写代码以从有向图提取信息。 This graph has cycles as well. 该图也具有周期。 For example, 例如,

A->B->C->D
A->E->F->A
B->F->G

From this graph, I want to create a sub graph or the list of the nodes, where the input would be any node, and output would be the graph where the input node is the root, or the list of the nodes that has all the child nodes ( till the end of the graph ) from the input nodes 从这个图上,我想创建一个子图或节点列表,其中输入是任何节点,输出将是图,其中输入节点是根,或者具有所有节点的节点列表。输入节点的子节点(直到图的末尾)

For example, in the above example, 1. If the input node is C, the output would be D 2. If the input node is B, the output node would be C,D,F,G,A ( Since there is a cycle, which makes A to B bidirectional ) 3. If the input is G, the output is blank or null. 例如,在上面的示例中,1.如果输入节点为C,则输出为D。2.如果输入节点为B,则输出节点为C,D,F,G,A(由于存在一个循环,使A到B是双向的)。3.如果输入为G,则输出为空白或为空。

Is there any functionality in python networkx, that I can use to solve this problem ? python networkx中有什么功能可以用来解决此问题吗?

Alternatively, is there any other tool that can help me solve this problem ? 或者,是否有其他工具可以帮助我解决此问题?

What you want is the function dfs_preorder_nodes() . 您想要的是dfs_preorder_nodes()函数。 Here is a little demo based on your data: 这是一个基于您的数据的演示:

import networkx as nx

g = nx.DiGraph()

g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')

g.add_edge('A', 'E')
g.add_edge('E', 'F')
g.add_edge('F', 'A')

g.add_edge('B', 'F')
g.add_edge('F', 'G')

print('A:', list(nx.dfs_preorder_nodes(g, 'A')))
print('B:', list(nx.dfs_preorder_nodes(g, 'B')))
print('G:', list(nx.dfs_preorder_nodes(g, 'G')))

Output: 输出:

A: ['A', 'B', 'C', 'D', 'F', 'G', 'E']
B: ['B', 'C', 'D', 'F', 'A', 'E', 'G']
G: ['G']

The output includes the starting node. 输出包括起始节点。 Therefore, if you don't want it, just remove the first element from the list. 因此,如果您不想要它,只需从列表中删除第一个元素即可。

Note that dfs_preorder_nodes() returns a generator object. 注意, dfs_preorder_nodes()返回一个生成器对象。 That is why I called list() to get usable output. 这就是为什么我调用list()以获得可用的输出的原因。

nx.ego_graph() does exactly what you describe. nx.ego_graph()完全符合您的描述。 Using the example given by @Hai Vu: 使用@Hai Vu给出的示例:

g = nx.DiGraph()

g.add_edge('A', 'B')
g.add_edge('B', 'C')
g.add_edge('C', 'D')
g.add_edge('A', 'E')
g.add_edge('E', 'F')
g.add_edge('F', 'A')
g.add_edge('B', 'F')
g.add_edge('F', 'G')

a = nx.ego_graph(g, 'A', radius=100)
a.node
#out: NodeView(('A', 'B', 'C', 'D', 'E', 'F', 'G'))

list(nx.ego_graph(g, 'G', radius=100).node)
#out: ['G']

radius should be an arbitrarily large number if you would like to get all nodes in the tree until the leafs. 如果您想让树中的所有节点直到叶子都出现, radius应该是任意大的数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM