Python:如何优化所有可能的最短路径的计数?

时间:2016-04-27 13:20:59

标签: python graph graph-algorithm networkx shortest-path

3x3网络中,我希望能够确定任意两个节点之间的所有最短路径。然后,对于网络中的每个节点,我想计算通过一个特定节点的最短路径数。

这需要使用nx.all_shortest_paths(G,source,target)函数,该函数返回generator。这与使用nx.all_pairs_shortest_path(G)不同,如建议here。不同之处在于,在前一种情况下,函数计算 all 任意两个节点之间的最短路径,而在后一种情况下,它计算同一对之间的仅一条最短路径节点。

鉴于我需要考虑所有最短路径,我已经提出了以下脚本。这就是我生成我正在使用的网络的方式:

import networkx as nx
N=3
G=nx.grid_2d_graph(N,N)
pos = dict( (n, n) for n in G.nodes() )
labels = dict( ((i, j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds.sort()
vals.sort()
pos2=dict(zip(vals,inds))
nx.draw_networkx(G, pos=pos2, with_labels=False, node_size = 15)

这就是我打印任意两个节点之间所有最短路径的方式:

for n in G.nodes():
    for j in G.nodes():
        if (n!=j): #Self-loops are excluded
            gener=nx.all_shortest_paths(G,source=n,target=j)
            print('From node '+str(n)+' to '+str(j))
            for p in gener:
                print(p) 
            print('------')

结果是从节点x到节点y的路径,该路径仅包括沿途的节点。我得到的摘录是:

From node 0 to 2 #Only one path exists
[0, 1, 2] #Node 1 is passed through while going from node 0 to node 2
------
From node 0 to 4 #Two paths exist
[0, 1, 4] #Node 1 is passed through while going from node 0 to node 4
[0, 3, 4] #Node 3 is passed through while going from node 0 to node 4
------
...continues until all pairs of nodes are covered...

我的问题:如何修改最后一个代码块,以确保我知道总共有多少条最短路径通过每个节点?根据摘录结果我已经知道了提供,节点1通过2次,而节点3通过1次(排除开始和结束节点)。需要执行此计算以计算通过每个节点的最终路径数。

2 个答案:

答案 0 :(得分:2)

我建议将每个节点的dict映射为0

counts = {}
for n in G.nodes(): counts[n] = 0

然后对于你找到的每个路径 - 你已经找到并打印它们 - 遍历路径上的顶点,增加你的dict中的适当值:

# ...
for p in gener:
    print(p)
    for v in p: counts[v] += 1

答案 1 :(得分:1)

您要计算的是非标准化betweenness centrality

来自Wikipedia

  

中介中心性是节点在网络中的中心性的指标。它等于从所有顶点到通过该节点的所有其他顶点的最短路径数。

更一般地说,我建议您查看所有standard measures of centrality already in Networkx