在python中加权图中查找所有负周期和正周期的代码?

时间:2016-03-10 16:44:17

标签: python networkx

我是python的新手,我正在开发复杂的网络。我想在图中找到所有负周期和正周期,并且还找到参与制作周期(正周期或负周期)的边的权重。任何人都可以帮我吗? 例如:

nodes:[1,2,3,4,5] 

edges:[(1,2,w=1),(1,4,w=4),(2,3,w=2),(3,1,w=2),(3,5,w=1),(4,5,w=2),                     
(5,4,w=7),(4,3,w=-6),(5,1,w=3)] 


cycles:[(1-2-3-1,sum=1),(1-4-3-1,sum=0)....etc]

1 个答案:

答案 0 :(得分:1)

使用节点,边和边属性创建DiGraph:

nodes = [1,2,3,4,5] 
edges = edges = [(1,2,{'w': 1}), (1,4,{'w': 4}), (2,3,{'w':2}), (3,1,{'w': 2}), (3,5,{'w': 1}), (4,5,{'w':2}), (5,4,{'w': 7}), (4,3,{'w': -6}), (5,1,{'w': 3})]
G = nx.DiGraph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)

查找周期并计算其权重:

>>> cycles = nx.simple_cycles(G)
>>> weights = nx.get_edge_attributes(dgraph, 'w')
>>> for cycle in cycles:
        cycle.append(cycle[0])
        sumw = sum([weights[(cycle[i-1], cycle[i])] for i in range(1, len(cycle))])
        print cycle, sumw
[1, 4, 5, 1] 9
[1, 4, 3, 5, 1] 2
[1, 4, 3, 1] 0
[1, 2, 3, 5, 1] 7
[1, 2, 3, 1] 5
[3, 5, 4, 3] 2
[4, 5, 4] 9