def closeness_centrality(G, nodes, normalized=True):
 closeness = {}
 path_length = nx.single_source_shortest_path_length
 top = set(nodes)
 bottom = (set(G) - top)
 n = float(len(top))
 m = float(len(bottom))
 for node in top:
  sp = dict(path_length(G, node))
  totsp = sum(sp.values())
  if ((totsp > 0.0) and (len(G) > 1)):
   closeness[node] = ((m + (2 * (n - 1))) / totsp)
   if normalized:
    s = ((len(sp) - 1.0) / (len(G) - 1))
    closeness[node] *= s
  else:
   closeness[n] = 0.0
 for node in bottom:
  sp = dict(path_length(G, node))
  totsp = sum(sp.values())
  if ((totsp > 0.0) and (len(G) > 1)):
   closeness[node] = ((n + (2 * (m - 1))) / totsp)
   if normalized:
    s = ((len(sp) - 1.0) / (len(G) - 1))
    closeness[node] *= s
  else:
   closeness[n] = 0.0
 return closeness

def closeness_centrality ( G , nodes , normalized = True ) : closeness = { } path_length = nx . single_source_shortest_path_length top = set ( nodes ) bottom = ( set ( G ) - top ) n = float ( len ( top ) ) m = float ( len ( bottom ) ) for node in top : sp = dict ( path_length ( G , node ) ) totsp = sum ( sp . values ( ) ) if ( ( totsp > 0.0 ) and ( len ( G ) > 1 ) ) : closeness [ node ] = ( ( m + ( 2 * ( n - 1 ) ) ) / totsp ) if normalized : s = ( ( len ( sp ) - 1.0 ) / ( len ( G ) - 1 ) ) closeness [ node ] *= s else : closeness [ n ] = 0.0 for node in bottom : sp = dict ( path_length ( G , node ) ) totsp = sum ( sp . values ( ) ) if ( ( totsp > 0.0 ) and ( len ( G ) > 1 ) ) : closeness [ node ] = ( ( n + ( 2 * ( m - 1 ) ) ) / totsp ) if normalized : s = ( ( len ( sp ) - 1.0 ) / ( len ( G ) - 1 ) ) closeness [ node ] *= s else : closeness [ n ] = 0.0 return closeness
compute closeness centrality for nodes .