vitality.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """
  2. Vitality measures.
  3. """
  4. from functools import partial
  5. import networkx as nx
  6. __all__ = ["closeness_vitality"]
  7. @nx._dispatchable(edge_attrs="weight")
  8. def closeness_vitality(G, node=None, weight=None, wiener_index=None):
  9. """Returns the closeness vitality for nodes in the graph.
  10. The *closeness vitality* of a node, defined in Section 3.6.2 of [1],
  11. is the change in the sum of distances between all node pairs when
  12. excluding that node.
  13. Parameters
  14. ----------
  15. G : NetworkX graph
  16. A strongly-connected graph.
  17. weight : string
  18. The name of the edge attribute used as weight. This is passed
  19. directly to the :func:`~networkx.wiener_index` function.
  20. node : object
  21. If specified, only the closeness vitality for this node will be
  22. returned. Otherwise, a dictionary mapping each node to its
  23. closeness vitality will be returned.
  24. Other parameters
  25. ----------------
  26. wiener_index : number
  27. If you have already computed the Wiener index of the graph
  28. `G`, you can provide that value here. Otherwise, it will be
  29. computed for you.
  30. Returns
  31. -------
  32. dictionary or float
  33. If `node` is None, this function returns a dictionary
  34. with nodes as keys and closeness vitality as the
  35. value. Otherwise, it returns only the closeness vitality for the
  36. specified `node`.
  37. The closeness vitality of a node may be negative infinity if
  38. removing that node would disconnect the graph.
  39. Examples
  40. --------
  41. >>> G = nx.cycle_graph(3)
  42. >>> nx.closeness_vitality(G)
  43. {0: 2.0, 1: 2.0, 2: 2.0}
  44. See Also
  45. --------
  46. closeness_centrality
  47. References
  48. ----------
  49. .. [1] Ulrik Brandes, Thomas Erlebach (eds.).
  50. *Network Analysis: Methodological Foundations*.
  51. Springer, 2005.
  52. <http://books.google.com/books?id=TTNhSm7HYrIC>
  53. """
  54. if wiener_index is None:
  55. wiener_index = nx.wiener_index(G, weight=weight)
  56. if node is not None:
  57. after = nx.wiener_index(G.subgraph(set(G) - {node}), weight=weight)
  58. return wiener_index - after
  59. vitality = partial(closeness_vitality, G, weight=weight, wiener_index=wiener_index)
  60. return {v: vitality(node=v) for v in G}