networkx强调有向图的中心性

时间:2017-05-19 20:09:13

标签: python-2.7 networkx

这个代码对于有向图是否正确?可以在不使用map()的情况下编写此代码吗? g是否表示包含节点的图表?如何在G=karate_club_graph()之后使用此功能并在G中输入此stress_centrality(G)

def stress_centrality(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

0 个答案:

没有答案