遍历networkx中图表的级别顺序

时间:2016-08-22 11:51:02

标签: python networkx

我正在尝试将DiGraph转换为n-ary树并按级别顺序或BFS显示节点。我的树与此类似,但更大,为了简单起见使用此示例:

G = networkx.DiGraph()
G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')])
G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')])
G.add_edges_from([('n2', 'n21'), ('n2', 'n22')])
G.add_edges_from([('n13', 'n131'), ('n22', 'n221')])

树:借用了此question

中的数据
n---->n1--->n11
 |     |--->n12
 |     |--->n13
 |           |--->n131 
 |--->n2              
 |     |---->n21     
 |     |---->n22     
 |            |--->n221 
 |--->n3

我正在使用networkx.DiGraph来成功创建图表。这是我创建DiGraph的代码:

G = nx.DiGraph()
roots = set()
for l in raw.splitlines():
    if len(l):
        target, prereq = regex1.split(l)
        deps = tuple(regex2.split(prereq))
        print("Add node:") + target
        roots.add(target)
        G.add_node(target)
        for d in deps:
            if d:
                G.add_edge(target, d)

我正在使用以下格式从大约200行的文件中读取所有数据并尝试获取依赖关系树。我的图表大约有100个节点,有600个边。

AAA: BBB,CCC,DDD,
BBB:
DDD: EEE,FFF,GGG,KKK
GGG: AAA,BBB,III,LLL
....
...
..
.

在线查看networkx文档后,现在我可以使用下面的代码在依赖树上实现拓扑排序的级别顺序输出。

order =  nx.topological_sort(G)
print "topological sort"
print order 

输出:

['n2', 'n3', 'n1', 'n21', 'n22', 'n11', 'n13', 'n12', 'n221', 'n131']

订单看起来是正确的,但由于我需要批量处理作业(节省时间)而不是顺序处理,我希望输出按级别排序的输出批次或使用BFS。实现这一目标的最佳方法是什么? 例如:等级[0:n],例如:

0. ['n'] 
1. ['n2', 'n3', 'n1',] 
2. ['n21', 'n22', 'n11',] 
3. ['n13', 'n12', 'n221', 'n131'] 

1 个答案:

答案 0 :(得分:4)

您可以使用bfs_edges()函数以广度优先搜索顺序获取节点列表。

In [1]: import networkx

In [2]: G = networkx.DiGraph()

In [3]: G.add_edges_from([('n', 'n1'), ('n', 'n2'), ('n', 'n3')])

In [4]: G.add_edges_from([('n4', 'n41'), ('n1', 'n11'), ('n1', 'n12'), ('n1', 'n13')])

In [5]: G.add_edges_from([('n2', 'n21'), ('n2', 'n22')])

In [6]: G.add_edges_from([('n13', 'n131'), ('n22', 'n221')])

In [7]: list(networkx.bfs_edges(G,'n'))
Out[7]: 
[('n', 'n2'),
 ('n', 'n3'),
 ('n', 'n1'),
 ('n2', 'n21'),
 ('n2', 'n22'),
 ('n1', 'n11'),
 ('n1', 'n13'),
 ('n1', 'n12'),
 ('n22', 'n221'),
 ('n13', 'n131')]

In [8]: [t for (s,t) in networkx.bfs_edges(G,'n')]
Out[8]: ['n2', 'n3', 'n1', 'n21', 'n22', 'n11', 'n13', 'n12', 'n221', 'n131']

In [9]: networkx.single_source_shortest_path_length(G,'n')
Out[9]: 
{'n': 0,
 'n1': 1,
 'n11': 2,
 'n12': 2,
 'n13': 2,
 'n131': 3,
 'n2': 1,
 'n21': 2,
 'n22': 2,
 'n221': 3,
 'n3': 1}