reaching.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. """Functions for computing reaching centrality of a node or a graph."""
  2. import networkx as nx
  3. from networkx.utils import pairwise
  4. __all__ = ["global_reaching_centrality", "local_reaching_centrality"]
  5. def _average_weight(G, path, weight=None):
  6. """Returns the average weight of an edge in a weighted path.
  7. Parameters
  8. ----------
  9. G : graph
  10. A networkx graph.
  11. path: list
  12. A list of vertices that define the path.
  13. weight : None or string, optional (default=None)
  14. If None, edge weights are ignored. Then the average weight of an edge
  15. is assumed to be the multiplicative inverse of the length of the path.
  16. Otherwise holds the name of the edge attribute used as weight.
  17. """
  18. path_length = len(path) - 1
  19. if path_length <= 0:
  20. return 0
  21. if weight is None:
  22. return 1 / path_length
  23. total_weight = sum(G.edges[i, j][weight] for i, j in pairwise(path))
  24. return total_weight / path_length
  25. def global_reaching_centrality(G, weight=None, normalized=True):
  26. """Returns the global reaching centrality of a directed graph.
  27. The *global reaching centrality* of a weighted directed graph is the
  28. average over all nodes of the difference between the local reaching
  29. centrality of the node and the greatest local reaching centrality of
  30. any node in the graph [1]_. For more information on the local
  31. reaching centrality, see :func:`local_reaching_centrality`.
  32. Informally, the local reaching centrality is the proportion of the
  33. graph that is reachable from the neighbors of the node.
  34. Parameters
  35. ----------
  36. G : DiGraph
  37. A networkx DiGraph.
  38. weight : None or string, optional (default=None)
  39. Attribute to use for edge weights. If ``None``, each edge weight
  40. is assumed to be one. A higher weight implies a stronger
  41. connection between nodes and a *shorter* path length.
  42. normalized : bool, optional (default=True)
  43. Whether to normalize the edge weights by the total sum of edge
  44. weights.
  45. Returns
  46. -------
  47. h : float
  48. The global reaching centrality of the graph.
  49. Examples
  50. --------
  51. >>> G = nx.DiGraph()
  52. >>> G.add_edge(1, 2)
  53. >>> G.add_edge(1, 3)
  54. >>> nx.global_reaching_centrality(G)
  55. 1.0
  56. >>> G.add_edge(3, 2)
  57. >>> nx.global_reaching_centrality(G)
  58. 0.75
  59. See also
  60. --------
  61. local_reaching_centrality
  62. References
  63. ----------
  64. .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
  65. "Hierarchy Measure for Complex Networks."
  66. *PLoS ONE* 7.3 (2012): e33799.
  67. https://doi.org/10.1371/journal.pone.0033799
  68. """
  69. if nx.is_negatively_weighted(G, weight=weight):
  70. raise nx.NetworkXError("edge weights must be positive")
  71. total_weight = G.size(weight=weight)
  72. if total_weight <= 0:
  73. raise nx.NetworkXError("Size of G must be positive")
  74. # If provided, weights must be interpreted as connection strength
  75. # (so higher weights are more likely to be chosen). However, the
  76. # shortest path algorithms in NetworkX assume the provided "weight"
  77. # is actually a distance (so edges with higher weight are less
  78. # likely to be chosen). Therefore we need to invert the weights when
  79. # computing shortest paths.
  80. #
  81. # If weight is None, we leave it as-is so that the shortest path
  82. # algorithm can use a faster, unweighted algorithm.
  83. if weight is not None:
  84. def as_distance(u, v, d):
  85. return total_weight / d.get(weight, 1)
  86. shortest_paths = nx.shortest_path(G, weight=as_distance)
  87. else:
  88. shortest_paths = nx.shortest_path(G)
  89. centrality = local_reaching_centrality
  90. # TODO This can be trivially parallelized.
  91. lrc = [
  92. centrality(G, node, paths=paths, weight=weight, normalized=normalized)
  93. for node, paths in shortest_paths.items()
  94. ]
  95. max_lrc = max(lrc)
  96. return sum(max_lrc - c for c in lrc) / (len(G) - 1)
  97. def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True):
  98. """Returns the local reaching centrality of a node in a directed
  99. graph.
  100. The *local reaching centrality* of a node in a directed graph is the
  101. proportion of other nodes reachable from that node [1]_.
  102. Parameters
  103. ----------
  104. G : DiGraph
  105. A NetworkX DiGraph.
  106. v : node
  107. A node in the directed graph `G`.
  108. paths : dictionary (default=None)
  109. If this is not `None` it must be a dictionary representation
  110. of single-source shortest paths, as computed by, for example,
  111. :func:`networkx.shortest_path` with source node `v`. Use this
  112. keyword argument if you intend to invoke this function many
  113. times but don't want the paths to be recomputed each time.
  114. weight : None or string, optional (default=None)
  115. Attribute to use for edge weights. If `None`, each edge weight
  116. is assumed to be one. A higher weight implies a stronger
  117. connection between nodes and a *shorter* path length.
  118. normalized : bool, optional (default=True)
  119. Whether to normalize the edge weights by the total sum of edge
  120. weights.
  121. Returns
  122. -------
  123. h : float
  124. The local reaching centrality of the node ``v`` in the graph
  125. ``G``.
  126. Examples
  127. --------
  128. >>> G = nx.DiGraph()
  129. >>> G.add_edges_from([(1, 2), (1, 3)])
  130. >>> nx.local_reaching_centrality(G, 3)
  131. 0.0
  132. >>> G.add_edge(3, 2)
  133. >>> nx.local_reaching_centrality(G, 3)
  134. 0.5
  135. See also
  136. --------
  137. global_reaching_centrality
  138. References
  139. ----------
  140. .. [1] Mones, Enys, Lilla Vicsek, and Tamás Vicsek.
  141. "Hierarchy Measure for Complex Networks."
  142. *PLoS ONE* 7.3 (2012): e33799.
  143. https://doi.org/10.1371/journal.pone.0033799
  144. """
  145. if paths is None:
  146. if nx.is_negatively_weighted(G, weight=weight):
  147. raise nx.NetworkXError("edge weights must be positive")
  148. total_weight = G.size(weight=weight)
  149. if total_weight <= 0:
  150. raise nx.NetworkXError("Size of G must be positive")
  151. if weight is not None:
  152. # Interpret weights as lengths.
  153. def as_distance(u, v, d):
  154. return total_weight / d.get(weight, 1)
  155. paths = nx.shortest_path(G, source=v, weight=as_distance)
  156. else:
  157. paths = nx.shortest_path(G, source=v)
  158. # If the graph is unweighted, simply return the proportion of nodes
  159. # reachable from the source node ``v``.
  160. if weight is None and G.is_directed():
  161. return (len(paths) - 1) / (len(G) - 1)
  162. if normalized and weight is not None:
  163. norm = G.size(weight=weight) / G.size()
  164. else:
  165. norm = 1
  166. # TODO This can be trivially parallelized.
  167. avgw = (_average_weight(G, path, weight=weight) for path in paths.values())
  168. sum_avg_weight = sum(avgw) / norm
  169. return sum_avg_weight / (len(G) - 1)