harmonic.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Functions for computing the harmonic centrality of a graph."""
  2. from functools import partial
  3. import networkx as nx
  4. __all__ = ["harmonic_centrality"]
  5. def harmonic_centrality(G, nbunch=None, distance=None, sources=None):
  6. r"""Compute harmonic centrality for nodes.
  7. Harmonic centrality [1]_ of a node `u` is the sum of the reciprocal
  8. of the shortest path distances from all other nodes to `u`
  9. .. math::
  10. C(u) = \sum_{v \neq u} \frac{1}{d(v, u)}
  11. where `d(v, u)` is the shortest-path distance between `v` and `u`.
  12. If `sources` is given as an argument, the returned harmonic centrality
  13. values are calculated as the sum of the reciprocals of the shortest
  14. path distances from the nodes specified in `sources` to `u` instead
  15. of from all nodes to `u`.
  16. Notice that higher values indicate higher centrality.
  17. Parameters
  18. ----------
  19. G : graph
  20. A NetworkX graph
  21. nbunch : container (default: all nodes in G)
  22. Container of nodes for which harmonic centrality values are calculated.
  23. sources : container (default: all nodes in G)
  24. Container of nodes `v` over which reciprocal distances are computed.
  25. Nodes not in `G` are silently ignored.
  26. distance : edge attribute key, optional (default=None)
  27. Use the specified edge attribute as the edge distance in shortest
  28. path calculations. If `None`, then each edge will have distance equal to 1.
  29. Returns
  30. -------
  31. nodes : dictionary
  32. Dictionary of nodes with harmonic centrality as the value.
  33. See Also
  34. --------
  35. betweenness_centrality, load_centrality, eigenvector_centrality,
  36. degree_centrality, closeness_centrality
  37. Notes
  38. -----
  39. If the 'distance' keyword is set to an edge attribute key then the
  40. shortest-path length will be computed using Dijkstra's algorithm with
  41. that edge attribute as the edge weight.
  42. References
  43. ----------
  44. .. [1] Boldi, Paolo, and Sebastiano Vigna. "Axioms for centrality."
  45. Internet Mathematics 10.3-4 (2014): 222-262.
  46. """
  47. nbunch = set(G.nbunch_iter(nbunch)) if nbunch is not None else set(G.nodes)
  48. sources = set(G.nbunch_iter(sources)) if sources is not None else G.nodes
  49. spl = partial(nx.shortest_path_length, G, weight=distance)
  50. centrality = {u: 0 for u in nbunch}
  51. for v in sources:
  52. dist = spl(v)
  53. for u in nbunch.intersection(dist):
  54. d = dist[u]
  55. if d == 0: # handle u == v and edges with 0 weight
  56. continue
  57. centrality[u] += 1 / d
  58. return centrality