closeness.py 10 KB

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