vitality.py 2.2 KB

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