Faster way to calculate the number of shortest paths a vertex belongs to using Networkx

久未见 提交于 2019-12-05 20:26:57

The betweenness code you pointed to in NetworkX does almost what you want and can be adjusted easily.

In the betweenness function if you call the following (instead of _accumulate_basic) during the "accumulate" stage it should calculate the stress centrality (untested)

def _accumulate_stress(betweenness,S,P,sigma,s):
    delta = dict.fromkeys(S,0)
    while S:
        w = S.pop()
        for v in P[w]:
            delta[v] += (1.0+delta[w])
        if w != s:
            betweenness[w] += sigma[w]*delta[w]
    return betweenness

See the paper Ulrik Brandes: On Variants of Shortest-Path Betweenness Centrality and their Generic Computation. Social Networks 30(2):136-145, 2008. http://www.inf.uni-konstanz.de/algo/publications/b-vspbc-08.pdf

The stress centrality algorithm is Algorithm 12.

FaCoffee

Based on the answer I have been given here, I tried to do exactly the same thing.

My attempt revolved around the use of the nx.all_shortest_paths(G,source,target) function, which produces a generator:

counts={}
for n in G.nodes(): counts[n]=0
for n in G.nodes():
    for j in G.nodes():
        if (n!=j):
            gener=nx.all_shortest_paths(G,source=n,target=j) #A generator
            print('From node '+str(n)+' to '+str(j))
            for p in gener:
                print(p) 
                for v in p: counts[v]+=1
            print('------')

I have tested this code with a NxN grid network of 100 nodes and it took me approximately 168 seconds to get the results. Now I am aware this is not the best answer as this code is not optimized, but I thought you might have wanted to know about it. Hopefully I can get some directions on how to improve my code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!