我正在考虑顶点i的应力是i所属的所有顶点对之间的最短路径数。
我正在尝试使用 Networkx 来计算它,到目前为止我已经通过三种方式进行了计算。可读的、脏的和最脏的,但没有一个是快速的。实际上,我希望它比Networkx上的中介(源)更快。有没有更好的计算方法?提前感谢您的任何建议、回答或评论。下面看看我到目前为止做了什么:
Ps.:这是一个带有代码的馅饼,如果你想试一试,再次感谢。
这是所有版本的共同部分:
import networkx as nx
from collections import defaultdict
最脏的,振作起来:
def stress_centrality_dirtiest(g):
stress = defaultdict(int)
for a in nx.nodes_iter(g):
for b in nx.nodes_iter(g):
if a==b:
continue
# pred = nx.predecessor(G,b) # for unweighted graphs
pred, distance = nx.dijkstra_predecessor_and_distance(g,b) # for weighted graphs
if not pred.has_key(a):
return []
path = [[a,0]]
path_length = 1
index = 0
while index >= 0:
n,i = path[index]
if n == b:
for vertex in map(lambda x:x[0], path[:index+1])[1:-1]:
stress[vertex] += 1
if len(pred[n]) > i:
index += 1
if index == path_length:
path.append([pred[n][i],0])
path_length += 1
else:
path[index] = [pred[n][i],0]
else:
index -= 1
if index >= 0:
path[index][4] += 1
return stress
肮脏的
def stress_centrality_dirty(g):
stress = defaultdict(int)
paths = nx.all_pairs_dijkstra_path(g)
for item in paths.values():
for element in item.values():
if len(element) > 2:
for vertex in element[1:-1]:
stress[vertex] += 1
return stress
可读
def stress_centrality_readable(g):
stress = defaultdict(int)
paths = nx.all_pairs_dijkstra_path(g)
for source in nx.nodes_iter(g):
for end in nx.nodes_iter(g):
if source == end:
continue
path = paths[source][end]
if len(path) > 2: # path must contains at least 3 vertices source - another node - end
for vertex in path[1:-1]: # when counting the number of occurrencies, exclude source and end vertices
stress[vertex] += 1
return stress