closeness.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. """
  2. Closeness centrality measures.
  3. """
  4. import functools
  5. import networkx as nx
  6. from networkx.exception import NetworkXError
  7. from networkx.utils.decorators import not_implemented_for
  8. __all__ = ["closeness_centrality", "incremental_closeness_centrality"]
  9. def closeness_centrality(G, u=None, distance=None, wf_improved=True):
  10. r"""Compute closeness centrality for nodes.
  11. Closeness centrality [1]_ of a node `u` is the reciprocal of the
  12. average shortest path distance to `u` over all `n-1` reachable nodes.
  13. .. math::
  14. C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
  15. where `d(v, u)` is the shortest-path distance between `v` and `u`,
  16. and `n-1` is the number of nodes reachable from `u`. Notice that the
  17. closeness distance function computes the incoming distance to `u`
  18. for directed graphs. To use outward distance, act on `G.reverse()`.
  19. Notice that higher values of closeness indicate higher centrality.
  20. Wasserman and Faust propose an improved formula for graphs with
  21. more than one connected component. The result is "a ratio of the
  22. fraction of actors in the group who are reachable, to the average
  23. distance" from the reachable actors [2]_. You might think this
  24. scale factor is inverted but it is not. As is, nodes from small
  25. components receive a smaller closeness value. Letting `N` denote
  26. the number of nodes in the graph,
  27. .. math::
  28. C_{WF}(u) = \frac{n-1}{N-1} \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
  29. Parameters
  30. ----------
  31. G : graph
  32. A NetworkX graph
  33. u : node, optional
  34. Return only the value for node u
  35. distance : edge attribute key, optional (default=None)
  36. Use the specified edge attribute as the edge distance in shortest
  37. path calculations. If `None` (the default) all edges have a distance of 1.
  38. Absent edge attributes are assigned a distance of 1. Note that no check
  39. is performed to ensure that edges have the provided attribute.
  40. wf_improved : bool, optional (default=True)
  41. If True, scale by the fraction of nodes reachable. This gives the
  42. Wasserman and Faust improved formula. For single component graphs
  43. it is the same as the original formula.
  44. Returns
  45. -------
  46. nodes : dictionary
  47. Dictionary of nodes with closeness centrality as the value.
  48. Examples
  49. --------
  50. >>> G = nx.Graph([(0, 1), (0, 2), (0, 3), (1, 2), (1, 3)])
  51. >>> nx.closeness_centrality(G)
  52. {0: 1.0, 1: 1.0, 2: 0.75, 3: 0.75}
  53. See Also
  54. --------
  55. betweenness_centrality, load_centrality, eigenvector_centrality,
  56. degree_centrality, incremental_closeness_centrality
  57. Notes
  58. -----
  59. The closeness centrality is normalized to `(n-1)/(|G|-1)` where
  60. `n` is the number of nodes in the connected part of graph
  61. containing the node. If the graph is not completely connected,
  62. this algorithm computes the closeness centrality for each
  63. connected part separately scaled by that parts size.
  64. If the 'distance' keyword is set to an edge attribute key then the
  65. shortest-path length will be computed using Dijkstra's algorithm with
  66. that edge attribute as the edge weight.
  67. The closeness centrality uses *inward* distance to a node, not outward.
  68. If you want to use outword distances apply the function to `G.reverse()`
  69. In NetworkX 2.2 and earlier a bug caused Dijkstra's algorithm to use the
  70. outward distance rather than the inward distance. If you use a 'distance'
  71. keyword and a DiGraph, your results will change between v2.2 and v2.3.
  72. References
  73. ----------
  74. .. [1] Linton C. Freeman: Centrality in networks: I.
  75. Conceptual clarification. Social Networks 1:215-239, 1979.
  76. https://doi.org/10.1016/0378-8733(78)90021-7
  77. .. [2] pg. 201 of Wasserman, S. and Faust, K.,
  78. Social Network Analysis: Methods and Applications, 1994,
  79. Cambridge University Press.
  80. """
  81. if G.is_directed():
  82. G = G.reverse() # create a reversed graph view
  83. if distance is not None:
  84. # use Dijkstra's algorithm with specified attribute as edge weight
  85. path_length = functools.partial(
  86. nx.single_source_dijkstra_path_length, weight=distance
  87. )
  88. else:
  89. path_length = nx.single_source_shortest_path_length
  90. if u is None:
  91. nodes = G.nodes
  92. else:
  93. nodes = [u]
  94. closeness_dict = {}
  95. for n in nodes:
  96. sp = path_length(G, n)
  97. totsp = sum(sp.values())
  98. len_G = len(G)
  99. _closeness_centrality = 0.0
  100. if totsp > 0.0 and len_G > 1:
  101. _closeness_centrality = (len(sp) - 1.0) / totsp
  102. # normalize to number of nodes-1 in connected part
  103. if wf_improved:
  104. s = (len(sp) - 1.0) / (len_G - 1)
  105. _closeness_centrality *= s
  106. closeness_dict[n] = _closeness_centrality
  107. if u is not None:
  108. return closeness_dict[u]
  109. return closeness_dict
  110. @not_implemented_for("directed")
  111. def incremental_closeness_centrality(
  112. G, edge, prev_cc=None, insertion=True, wf_improved=True
  113. ):
  114. r"""Incremental closeness centrality for nodes.
  115. Compute closeness centrality for nodes using level-based work filtering
  116. as described in Incremental Algorithms for Closeness Centrality by Sariyuce et al.
  117. Level-based work filtering detects unnecessary updates to the closeness
  118. centrality and filters them out.
  119. ---
  120. From "Incremental Algorithms for Closeness Centrality":
  121. Theorem 1: Let :math:`G = (V, E)` be a graph and u and v be two vertices in V
  122. such that there is no edge (u, v) in E. Let :math:`G' = (V, E \cup uv)`
  123. Then :math:`cc[s] = cc'[s]` if and only if :math:`\left|dG(s, u) - dG(s, v)\right| \leq 1`.
  124. Where :math:`dG(u, v)` denotes the length of the shortest path between
  125. two vertices u, v in a graph G, cc[s] is the closeness centrality for a
  126. vertex s in V, and cc'[s] is the closeness centrality for a
  127. vertex s in V, with the (u, v) edge added.
  128. ---
  129. We use Theorem 1 to filter out updates when adding or removing an edge.
  130. When adding an edge (u, v), we compute the shortest path lengths from all
  131. other nodes to u and to v before the node is added. When removing an edge,
  132. we compute the shortest path lengths after the edge is removed. Then we
  133. apply Theorem 1 to use previously computed closeness centrality for nodes
  134. where :math:`\left|dG(s, u) - dG(s, v)\right| \leq 1`. This works only for
  135. undirected, unweighted graphs; the distance argument is not supported.
  136. Closeness centrality [1]_ of a node `u` is the reciprocal of the
  137. sum of the shortest path distances from `u` to all `n-1` other nodes.
  138. Since the sum of distances depends on the number of nodes in the
  139. graph, closeness is normalized by the sum of minimum possible
  140. distances `n-1`.
  141. .. math::
  142. C(u) = \frac{n - 1}{\sum_{v=1}^{n-1} d(v, u)},
  143. where `d(v, u)` is the shortest-path distance between `v` and `u`,
  144. and `n` is the number of nodes in the graph.
  145. Notice that higher values of closeness indicate higher centrality.
  146. Parameters
  147. ----------
  148. G : graph
  149. A NetworkX graph
  150. edge : tuple
  151. The modified edge (u, v) in the graph.
  152. prev_cc : dictionary
  153. The previous closeness centrality for all nodes in the graph.
  154. insertion : bool, optional
  155. If True (default) the edge was inserted, otherwise it was deleted from the graph.
  156. wf_improved : bool, optional (default=True)
  157. If True, scale by the fraction of nodes reachable. This gives the
  158. Wasserman and Faust improved formula. For single component graphs
  159. it is the same as the original formula.
  160. Returns
  161. -------
  162. nodes : dictionary
  163. Dictionary of nodes with closeness centrality as the value.
  164. See Also
  165. --------
  166. betweenness_centrality, load_centrality, eigenvector_centrality,
  167. degree_centrality, closeness_centrality
  168. Notes
  169. -----
  170. The closeness centrality is normalized to `(n-1)/(|G|-1)` where
  171. `n` is the number of nodes in the connected part of graph
  172. containing the node. If the graph is not completely connected,
  173. this algorithm computes the closeness centrality for each
  174. connected part separately.
  175. References
  176. ----------
  177. .. [1] Freeman, L.C., 1979. Centrality in networks: I.
  178. Conceptual clarification. Social Networks 1, 215--239.
  179. https://doi.org/10.1016/0378-8733(78)90021-7
  180. .. [2] Sariyuce, A.E. ; Kaya, K. ; Saule, E. ; Catalyiirek, U.V. Incremental
  181. Algorithms for Closeness Centrality. 2013 IEEE International Conference on Big Data
  182. http://sariyuce.com/papers/bigdata13.pdf
  183. """
  184. if prev_cc is not None and set(prev_cc.keys()) != set(G.nodes()):
  185. raise NetworkXError("prev_cc and G do not have the same nodes")
  186. # Unpack edge
  187. (u, v) = edge
  188. path_length = nx.single_source_shortest_path_length
  189. if insertion:
  190. # For edge insertion, we want shortest paths before the edge is inserted
  191. du = path_length(G, u)
  192. dv = path_length(G, v)
  193. G.add_edge(u, v)
  194. else:
  195. G.remove_edge(u, v)
  196. # For edge removal, we want shortest paths after the edge is removed
  197. du = path_length(G, u)
  198. dv = path_length(G, v)
  199. if prev_cc is None:
  200. return nx.closeness_centrality(G)
  201. nodes = G.nodes()
  202. closeness_dict = {}
  203. for n in nodes:
  204. if n in du and n in dv and abs(du[n] - dv[n]) <= 1:
  205. closeness_dict[n] = prev_cc[n]
  206. else:
  207. sp = path_length(G, n)
  208. totsp = sum(sp.values())
  209. len_G = len(G)
  210. _closeness_centrality = 0.0
  211. if totsp > 0.0 and len_G > 1:
  212. _closeness_centrality = (len(sp) - 1.0) / totsp
  213. # normalize to number of nodes-1 in connected part
  214. if wf_improved:
  215. s = (len(sp) - 1.0) / (len_G - 1)
  216. _closeness_centrality *= s
  217. closeness_dict[n] = _closeness_centrality
  218. # Leave the graph as we found it
  219. if insertion:
  220. G.remove_edge(u, v)
  221. else:
  222. G.add_edge(u, v)
  223. return closeness_dict