summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDan Schult <dschult@colgate.edu>2015-10-03 00:11:54 -0400
committerDan Schult <dschult@colgate.edu>2015-10-03 00:11:54 -0400
commit76d040056bd935a95874058ed97b7d73eabca64a (patch)
treef95a284850562187d23e41327bfa0ab0b3439473
parent4faf981c68db60886dca1c49bfebf0fd511ce096 (diff)
parentfde3d8d078d7ca45bd7db50b5c89c8f5f923d786 (diff)
downloadnetworkx-76d040056bd935a95874058ed97b7d73eabca64a.tar.gz
Merge pull request #1790 from networkx/dschult-patch-3
Rewrite harmonic_centrality to better use iterator
-rw-r--r--networkx/algorithms/centrality/harmonic.py30
1 files changed, 11 insertions, 19 deletions
diff --git a/networkx/algorithms/centrality/harmonic.py b/networkx/algorithms/centrality/harmonic.py
index 76f692a3..62ba653b 100644
--- a/networkx/algorithms/centrality/harmonic.py
+++ b/networkx/algorithms/centrality/harmonic.py
@@ -52,27 +52,19 @@ def harmonic_centrality(G, distance=None):
References
----------
- .. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality." Internet Mathematics 10.3-4 (2014): 222-262.
+ .. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality."
+ Internet Mathematics 10.3-4 (2014): 222-262.
"""
-
+ if len(G) <= 1:
+ return {singleton: 0.0 for singleton in G.nodes()}
+
+ if G.is_directed():
+ G = G.reverse()
+
if distance is not None:
# use Dijkstra's algorithm with specified attribute as edge weight
- path_length = functools.partial(nx.all_pairs_dijkstra_path_length,
- weight=distance)
+ sp = nx.all_pairs_dijkstra_path_length(G, weight=distance)
else:
- path_length = nx.all_pairs_shortest_path_length
-
- nodes = G.nodes()
- harmonic_centrality = {}
-
- if len(G) <= 1:
- for singleton in nodes:
- harmonic_centrality[singleton] = 0.0
- return harmonic_centrality
-
- sp = path_length(G.reverse() if G.is_directed() else G)
- for node, dist_dict in sp:
- harmonic_centrality[node] = sum(
- [1/dist if dist > 0 else 0 for dist in dist_dict.values()])
+ sp = nx.all_pairs_shortest_path_length(G)
- return harmonic_centrality
+ return {n: sum(1/d if d > 0 else 0 for d in dd.values()) for n, dd in sp}