NetworkX DiGraph按节点创建子图(DiGraph) [英] NetworkX DiGraph create subgraph (DiGraph) by node

查看:3927
本文介绍了NetworkX DiGraph按节点创建子图(DiGraph)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按节点获取一个子图(红色区域): 子图由从输入节点可到达的所有节点组成.

I would like to get a subgraph (red area) by node: The subgraph is composed of all the nodes reachable from the input node.

类似于G.subgraph(3)从红色区域返回一个新的DiGraph.

like G.subgraph(3) returns a new DiGraph from the red area.

例如,我创建一个DiGraph:

For example I create a DiGraph as this:

import networkx as nx
G = nx.DiGraph()

G.add_path([1,2,3,4])
G.add_path([3,'a','b'])

A = nx.to_agraph(G)
A.layout()
A.draw('graph.png')

我查看了 https://networkx. github.io/documentation/latest/reference/generation/networkx.Graph.subgraph.html 并将其转换为单向.我测试了out_egdes,strong/weak_connected_component,但从未成功. 我还查看了如何查找 Networkx:提取有向图中的子图吗?包含给定节点(有向图)的连接组件.

I looked into https://networkx.github.io/documentation/latest/reference/generated/networkx.Graph.subgraph.html and converting it to unidirectional. I tested out_egdes, strong/weak_connected_component, but its never worked. I also looked How to find subgraphs in a directed graph without converting to undirected graph? and Networkx: extract the connected component containing a given node (directed graph).

我知道Subgraph在DiGraph中不起作用.

I know that Subgraph does not work in DiGraph.

有人可以告诉我该怎么做吗?如果生成的图也是DiGraph,那就很好了

Can someone please show me how to do this ? Would be nice if the resulting Graph is also a DiGraph

推荐答案

根据我的理解,创建子图的标准取决于可从输入节点到达的节点.那么下面的递归函数应该足以完成工作.

According to my understanding that the criteria of creation of the subgraph depends on the nodes reachable from the input node. Then the following recursive function should be sufficient to get the job done.

def create_subgraph(G,sub_G,start_node):
    for n in G.successors_iter(start_node):
        sub_G.add_path([start_node,n])
        create_subgraph(G,sub_G,n)

我复制了代码以创建图形,初始化了一个空的有向图,并按如下所示调用了函数:

I copied your code to create the graph, initialized an empty Directed graph and called the function as follows:

G = nx.DiGraph()
G.add_path([1,2,3,4])
G.add_path([3,'a','b'])
sub_G = nx.DiGraph()
create_subgraph(G, sub_G,3)

所得的Digraph如图所示.

The resulted Digraph is shown in the figure.

这篇关于NetworkX DiGraph按节点创建子图(DiGraph)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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