betweenness.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. """Betweenness centrality measures."""
  2. import math
  3. from collections import deque
  4. from heapq import heappop, heappush
  5. from itertools import count
  6. import networkx as nx
  7. from networkx.algorithms.shortest_paths.weighted import _weight_function
  8. from networkx.utils import py_random_state
  9. from networkx.utils.decorators import not_implemented_for
  10. __all__ = ["betweenness_centrality", "edge_betweenness_centrality"]
  11. @py_random_state("seed")
  12. @nx._dispatchable(edge_attrs="weight")
  13. def betweenness_centrality(
  14. G, k=None, normalized=True, weight=None, endpoints=False, seed=None
  15. ):
  16. r"""Compute the shortest-path betweenness centrality for nodes.
  17. Betweenness centrality of a node $v$ is the sum of the
  18. fraction of all-pairs shortest paths that pass through $v$.
  19. .. math::
  20. c_B(v) = \sum_{s, t \in V} \frac{\sigma(s, t | v)}{\sigma(s, t)}
  21. where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
  22. shortest $(s, t)$-paths, and $\sigma(s, t | v)$ is the number of
  23. those paths passing through some node $v$ other than $s$ and $t$.
  24. If $s = t$, $\sigma(s, t) = 1$, and if $v \in \{s, t\}$,
  25. $\sigma(s, t | v) = 0$ [2]_.
  26. The denominator $\sigma(s, t)$ is a normalization factor that can be
  27. turned off to get the raw path counts.
  28. Parameters
  29. ----------
  30. G : graph
  31. A NetworkX graph.
  32. k : int, optional (default=None)
  33. If `k` is not `None`, use `k` sampled nodes as sources for the considered paths.
  34. The resulting sampled counts are then inflated to approximate betweenness.
  35. Higher values of `k` give better approximation. Must have ``k <= len(G)``.
  36. normalized : bool, optional (default=True)
  37. If `True`, the betweenness values are rescaled by dividing by the number of
  38. possible $(s, t)$-pairs in the graph.
  39. weight : None or string, optional (default=None)
  40. If `None`, all edge weights are 1.
  41. Otherwise holds the name of the edge attribute used as weight.
  42. Weights are used to calculate weighted shortest paths, so they are
  43. interpreted as distances.
  44. endpoints : bool, optional (default=False)
  45. If `True`, include the endpoints $s$ and $t$ in the shortest path counts.
  46. This is taken into account when rescaling the values.
  47. seed : integer, random_state, or None (default)
  48. Indicator of random number generation state.
  49. See :ref:`Randomness<randomness>`.
  50. Note that this is only used if ``k is not None``.
  51. Returns
  52. -------
  53. nodes : dict
  54. Dictionary of nodes with betweenness centrality as the value.
  55. See Also
  56. --------
  57. betweenness_centrality_subset
  58. edge_betweenness_centrality
  59. load_centrality
  60. Notes
  61. -----
  62. The algorithm is from Ulrik Brandes [1]_.
  63. See [4]_ for the original first published version and [2]_ for details on
  64. algorithms for variations and related metrics.
  65. For approximate betweenness calculations, set `k` to the number of sampled
  66. nodes ("pivots") used as sources to estimate the betweenness values.
  67. The formula then sums over $s$ is in these pivots, instead of over all nodes.
  68. The resulting sum is then inflated to approximate the full sum.
  69. For a discussion of how to choose `k` for efficiency, see [3]_.
  70. For weighted graphs the edge weights must be greater than zero.
  71. Zero edge weights can produce an infinite number of equal length
  72. paths between pairs of nodes.
  73. Directed graphs and undirected graphs count paths differently.
  74. In directed graphs, each pair of source-target nodes is considered separately
  75. in each direction, as the shortest paths can differ by direction.
  76. However, in undirected graphs, each pair of nodes is considered only once,
  77. as the shortest paths are symmetric.
  78. This means the normalization factor to divide by is $N(N-1)$ for directed graphs
  79. and $N(N-1)/2$ for undirected graphs, where $N = n$ (the number of nodes)
  80. if endpoints are included and $N = n-1$ otherwise.
  81. This algorithm is not guaranteed to be correct if edge weights
  82. are floating point numbers. As a workaround you can use integer
  83. numbers by multiplying the relevant edge attributes by a convenient
  84. constant factor (e.g. 100) and converting to integers.
  85. References
  86. ----------
  87. .. [1] Ulrik Brandes:
  88. A Faster Algorithm for Betweenness Centrality.
  89. Journal of Mathematical Sociology 25(2):163--177, 2001.
  90. https://doi.org/10.1080/0022250X.2001.9990249
  91. .. [2] Ulrik Brandes:
  92. On Variants of Shortest-Path Betweenness
  93. Centrality and their Generic Computation.
  94. Social Networks 30(2):136--145, 2008.
  95. https://doi.org/10.1016/j.socnet.2007.11.001
  96. .. [3] Ulrik Brandes and Christian Pich:
  97. Centrality Estimation in Large Networks.
  98. International Journal of Bifurcation and Chaos 17(7):2303--2318, 2007.
  99. https://dx.doi.org/10.1142/S0218127407018403
  100. .. [4] Linton C. Freeman:
  101. A set of measures of centrality based on betweenness.
  102. Sociometry 40: 35--41, 1977
  103. https://doi.org/10.2307/3033543
  104. Examples
  105. --------
  106. Consider an undirected 3-path. Each pair of nodes has exactly one shortest
  107. path between them. Since the graph is undirected, only ordered pairs are counted.
  108. Of these (and when `endpoints` is `False`), none of the shortest paths pass
  109. through 0 and 2, and only the shortest path between 0 and 2 passes through 1.
  110. As such, the counts should be ``{0: 0, 1: 1, 2: 0}``.
  111. >>> G = nx.path_graph(3)
  112. >>> nx.betweenness_centrality(G, normalized=False, endpoints=False)
  113. {0: 0.0, 1: 1.0, 2: 0.0}
  114. If `endpoints` is `True`, we also need to count endpoints as being on the path:
  115. $\sigma(s, t | s) = \sigma(s, t | t) = \sigma(s, t)$.
  116. In our example, 0 is then part of two shortest paths (0 to 1 and 0 to 2);
  117. similarly, 2 is part of two shortest paths (0 to 2 and 1 to 2).
  118. 1 is part of all three shortest paths. This makes the new raw
  119. counts ``{0: 2, 1: 3, 2: 2}``.
  120. >>> nx.betweenness_centrality(G, normalized=False, endpoints=True)
  121. {0: 2.0, 1: 3.0, 2: 2.0}
  122. With normalization, the values are divided by the number of ordered $(s, t)$-pairs.
  123. If we are not counting endpoints, there are $n - 1$ possible choices for $s$
  124. (all except the node we are computing betweenness centrality for), which in turn
  125. leaves $n - 2$ possible choices for $t$ as $s \ne t$.
  126. The total number of ordered pairs when `endpoints` is `False` is $(n - 1)(n - 2)/2 = 1$.
  127. If `endpoints` is `True`, there are $n(n - 1)/2 = 3$ ordered $(s, t)$-pairs to divide by.
  128. >>> nx.betweenness_centrality(G, normalized=True, endpoints=False)
  129. {0: 0.0, 1: 1.0, 2: 0.0}
  130. >>> nx.betweenness_centrality(G, normalized=True, endpoints=True)
  131. {0: 0.6666666666666666, 1: 1.0, 2: 0.6666666666666666}
  132. If the graph is directed instead, we now need to consider $(s, t)$-pairs
  133. in both directions. Our example becomes a directed 3-path.
  134. Without counting endpoints, we only have one path through 1 (0 to 2).
  135. This means the raw counts are ``{0: 0, 1: 1, 2: 0}``.
  136. >>> DG = nx.path_graph(3, create_using=nx.DiGraph)
  137. >>> nx.betweenness_centrality(DG, normalized=False, endpoints=False)
  138. {0: 0.0, 1: 1.0, 2: 0.0}
  139. If we do include endpoints, the raw counts are ``{0: 2, 1: 3, 2: 2}``.
  140. >>> nx.betweenness_centrality(DG, normalized=False, endpoints=True)
  141. {0: 2.0, 1: 3.0, 2: 2.0}
  142. If we want to normalize directed betweenness centrality, the raw counts
  143. are normalized by the number of $(s, t)$-pairs. There are $n(n - 1)$
  144. possible paths with endpoints and $(n - 1)(n - 2)$ without endpoints.
  145. In our example, that's 6 with endpoints and 2 without endpoints.
  146. >>> nx.betweenness_centrality(DG, normalized=True, endpoints=True)
  147. {0: 0.3333333333333333, 1: 0.5, 2: 0.3333333333333333}
  148. >>> nx.betweenness_centrality(DG, normalized=True, endpoints=False)
  149. {0: 0.0, 1: 0.5, 2: 0.0}
  150. Computing the full betweenness centrality can be costly.
  151. This function can also be used to compute approximate betweenness centrality
  152. by setting `k`. This only determines the number of source nodes to sample;
  153. all nodes are targets.
  154. For simplicity, we only consider the case where endpoints are included in the counts.
  155. Since the partial sums only include `k` terms, instead of ``n``,
  156. we multiply them by ``n / k``, to approximate the full sum.
  157. As the sets of sources and targets are not the same anymore,
  158. paths have to be counted in a directed way. We thus count each as half a path.
  159. This ensures that the results approximate the standard betweenness for ``k == n``.
  160. For instance, in the undirected 3-path graph case, setting ``k = 2`` (with ``seed=42``)
  161. selects nodes 0 and 2 as sources.
  162. This means only shortest paths starting at these nodes are considered.
  163. The raw counts with endpoints are ``{0: 3, 1: 4, 2: 3}``. Accounting for the partial sum
  164. and applying the undirectedness half-path correction, we get
  165. >>> nx.betweenness_centrality(G, k=2, normalized=False, endpoints=True, seed=42)
  166. {0: 2.25, 1: 3.0, 2: 2.25}
  167. When normalizing, we instead want to divide by the total number of $(s, t)$-pairs.
  168. This is $k(n - 1)$ with endpoints.
  169. >>> nx.betweenness_centrality(G, k=2, normalized=True, endpoints=True, seed=42)
  170. {0: 0.75, 1: 1.0, 2: 0.75}
  171. """
  172. betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
  173. if k == len(G):
  174. # This is done for performance; the result is the same regardless.
  175. k = None
  176. if k is None:
  177. nodes = G
  178. else:
  179. nodes = seed.sample(list(G.nodes()), k)
  180. for s in nodes:
  181. # single source shortest paths
  182. if weight is None: # use BFS
  183. S, P, sigma, _ = _single_source_shortest_path_basic(G, s)
  184. else: # use Dijkstra's algorithm
  185. S, P, sigma, _ = _single_source_dijkstra_path_basic(G, s, weight)
  186. # accumulation
  187. if endpoints:
  188. betweenness, _ = _accumulate_endpoints(betweenness, S, P, sigma, s)
  189. else:
  190. betweenness, _ = _accumulate_basic(betweenness, S, P, sigma, s)
  191. # rescaling
  192. betweenness = _rescale(
  193. betweenness,
  194. len(G),
  195. normalized=normalized,
  196. directed=G.is_directed(),
  197. endpoints=endpoints,
  198. sampled_nodes=None if k is None else nodes,
  199. )
  200. return betweenness
  201. @py_random_state("seed")
  202. @nx._dispatchable(edge_attrs="weight")
  203. def edge_betweenness_centrality(G, k=None, normalized=True, weight=None, seed=None):
  204. r"""Compute betweenness centrality for edges.
  205. Betweenness centrality of an edge $e$ is the sum of the
  206. fraction of all-pairs shortest paths that pass through $e$.
  207. .. math::
  208. c_B(e) = \sum_{s, t \in V} \frac{\sigma(s, t | e)}{\sigma(s, t)}
  209. where $V$ is the set of nodes, $\sigma(s, t)$ is the number of
  210. shortest $(s, t)$-paths, and $\sigma(s, t | e)$ is the number of
  211. those paths passing through edge $e$ [1]_.
  212. The denominator $\sigma(s, t)$ is a normalization factor that can be
  213. turned off to get the raw path counts.
  214. Parameters
  215. ----------
  216. G : graph
  217. A NetworkX graph.
  218. k : int, optional (default=None)
  219. If `k` is not `None`, use `k` sampled nodes as sources for the considered paths.
  220. The resulting sampled counts are then inflated to approximate betweenness.
  221. Higher values of `k` give better approximation. Must have ``k <= len(G)``.
  222. normalized : bool, optional (default=True)
  223. If `True`, the betweenness values are rescaled by dividing by the number of
  224. possible $(s, t)$-pairs in the graph.
  225. weight : None or string, optional (default=None)
  226. If `None`, all edge weights are 1.
  227. Otherwise holds the name of the edge attribute used as weight.
  228. Weights are used to calculate weighted shortest paths, so they are
  229. interpreted as distances.
  230. seed : integer, random_state, or None (default)
  231. Indicator of random number generation state.
  232. See :ref:`Randomness<randomness>`.
  233. Note that this is only used if ``k is not None``.
  234. Returns
  235. -------
  236. edges : dict
  237. Dictionary of edges with betweenness centrality as the value.
  238. See Also
  239. --------
  240. betweenness_centrality
  241. edge_betweenness_centrality_subset
  242. edge_load
  243. Notes
  244. -----
  245. The algorithm is from Ulrik Brandes [1]_.
  246. For weighted graphs the edge weights must be greater than zero.
  247. Zero edge weights can produce an infinite number of equal length
  248. paths between pairs of nodes.
  249. References
  250. ----------
  251. .. [1] Ulrik Brandes: On Variants of Shortest-Path Betweenness
  252. Centrality and their Generic Computation.
  253. Social Networks 30(2):136--145, 2008.
  254. https://doi.org/10.1016/j.socnet.2007.11.001
  255. Examples
  256. --------
  257. Consider an undirected 3-path. Each pair of nodes has exactly one shortest
  258. path between them. Since the graph is undirected, only ordered pairs are counted.
  259. Each edge has two shortest paths passing through it.
  260. As such, the raw counts should be ``{(0, 1): 2, (1, 2): 2}``.
  261. >>> G = nx.path_graph(3)
  262. >>> nx.edge_betweenness_centrality(G, normalized=False)
  263. {(0, 1): 2.0, (1, 2): 2.0}
  264. With normalization, the values are divided by the number of ordered $(s, t)$-pairs,
  265. which is $n(n-1)/2$. For the 3-path, this is $3(3-1)/2 = 3$.
  266. >>> nx.edge_betweenness_centrality(G, normalized=True)
  267. {(0, 1): 0.6666666666666666, (1, 2): 0.6666666666666666}
  268. For a directed graph, all $(s, t)$-pairs are considered. The normalization factor
  269. is $n(n-1)$ to reflect this.
  270. >>> DG = nx.path_graph(3, create_using=nx.DiGraph)
  271. >>> nx.edge_betweenness_centrality(DG, normalized=False)
  272. {(0, 1): 2.0, (1, 2): 2.0}
  273. >>> nx.edge_betweenness_centrality(DG, normalized=True)
  274. {(0, 1): 0.3333333333333333, (1, 2): 0.3333333333333333}
  275. Computing the full edge betweenness centrality can be costly.
  276. This function can also be used to compute approximate edge betweenness centrality
  277. by setting `k`. This determines the number of source nodes to sample.
  278. Since the partial sums only include `k` terms, instead of ``n``,
  279. we multiply them by ``n / k``, to approximate the full sum.
  280. As the sets of sources and targets are not the same anymore,
  281. paths have to be counted in a directed way. We thus count each as half a path.
  282. This ensures that the results approximate the standard betweenness for ``k == n``.
  283. For instance, in the undirected 3-path graph case, setting ``k = 2`` (with ``seed=42``)
  284. selects nodes 0 and 2 as sources.
  285. This means only shortest paths starting at these nodes are considered.
  286. The raw counts are ``{(0, 1): 3, (1, 2): 3}``. Accounting for the partial sum
  287. and applying the undirectedness half-path correction, we get
  288. >>> nx.edge_betweenness_centrality(G, k=2, normalized=False, seed=42)
  289. {(0, 1): 2.25, (1, 2): 2.25}
  290. When normalizing, we instead want to divide by the total number of $(s, t)$-pairs.
  291. This is $k(n-1)$, which is $4$ in our case.
  292. >>> nx.edge_betweenness_centrality(G, k=2, normalized=True, seed=42)
  293. {(0, 1): 0.75, (1, 2): 0.75}
  294. """
  295. betweenness = dict.fromkeys(G, 0.0) # b[v]=0 for v in G
  296. # b[e]=0 for e in G.edges()
  297. betweenness.update(dict.fromkeys(G.edges(), 0.0))
  298. if k is None:
  299. nodes = G
  300. else:
  301. nodes = seed.sample(list(G.nodes()), k)
  302. for s in nodes:
  303. # single source shortest paths
  304. if weight is None: # use BFS
  305. S, P, sigma, _ = _single_source_shortest_path_basic(G, s)
  306. else: # use Dijkstra's algorithm
  307. S, P, sigma, _ = _single_source_dijkstra_path_basic(G, s, weight)
  308. # accumulation
  309. betweenness = _accumulate_edges(betweenness, S, P, sigma, s)
  310. # rescaling
  311. for n in G: # remove nodes to only return edges
  312. del betweenness[n]
  313. betweenness = _rescale(
  314. betweenness,
  315. len(G),
  316. normalized=normalized,
  317. directed=G.is_directed(),
  318. sampled_nodes=None if k is None else nodes,
  319. )
  320. if G.is_multigraph():
  321. betweenness = _add_edge_keys(G, betweenness, weight=weight)
  322. return betweenness
  323. # helpers for betweenness centrality
  324. def _single_source_shortest_path_basic(G, s):
  325. S = []
  326. P = {}
  327. for v in G:
  328. P[v] = []
  329. sigma = dict.fromkeys(G, 0.0) # sigma[v]=0 for v in G
  330. D = {}
  331. sigma[s] = 1.0
  332. D[s] = 0
  333. Q = deque([s])
  334. while Q: # use BFS to find shortest paths
  335. v = Q.popleft()
  336. S.append(v)
  337. Dv = D[v]
  338. sigmav = sigma[v]
  339. for w in G[v]:
  340. if w not in D:
  341. Q.append(w)
  342. D[w] = Dv + 1
  343. if D[w] == Dv + 1: # this is a shortest path, count paths
  344. sigma[w] += sigmav
  345. P[w].append(v) # predecessors
  346. return S, P, sigma, D
  347. def _single_source_dijkstra_path_basic(G, s, weight):
  348. weight = _weight_function(G, weight)
  349. # modified from Eppstein
  350. S = []
  351. P = {}
  352. for v in G:
  353. P[v] = []
  354. sigma = dict.fromkeys(G, 0.0) # sigma[v]=0 for v in G
  355. D = {}
  356. sigma[s] = 1.0
  357. seen = {s: 0}
  358. c = count()
  359. Q = [] # use Q as heap with (distance,node id) tuples
  360. heappush(Q, (0, next(c), s, s))
  361. while Q:
  362. (dist, _, pred, v) = heappop(Q)
  363. if v in D:
  364. continue # already searched this node.
  365. sigma[v] += sigma[pred] # count paths
  366. S.append(v)
  367. D[v] = dist
  368. for w, edgedata in G[v].items():
  369. vw_dist = dist + weight(v, w, edgedata)
  370. if w not in D and (w not in seen or vw_dist < seen[w]):
  371. seen[w] = vw_dist
  372. heappush(Q, (vw_dist, next(c), v, w))
  373. sigma[w] = 0.0
  374. P[w] = [v]
  375. elif vw_dist == seen[w]: # handle equal paths
  376. sigma[w] += sigma[v]
  377. P[w].append(v)
  378. return S, P, sigma, D
  379. def _accumulate_basic(betweenness, S, P, sigma, s):
  380. delta = dict.fromkeys(S, 0)
  381. while S:
  382. w = S.pop()
  383. coeff = (1 + delta[w]) / sigma[w]
  384. for v in P[w]:
  385. delta[v] += sigma[v] * coeff
  386. if w != s:
  387. betweenness[w] += delta[w]
  388. return betweenness, delta
  389. def _accumulate_endpoints(betweenness, S, P, sigma, s):
  390. betweenness[s] += len(S) - 1
  391. delta = dict.fromkeys(S, 0)
  392. while S:
  393. w = S.pop()
  394. coeff = (1 + delta[w]) / sigma[w]
  395. for v in P[w]:
  396. delta[v] += sigma[v] * coeff
  397. if w != s:
  398. betweenness[w] += delta[w] + 1
  399. return betweenness, delta
  400. def _accumulate_edges(betweenness, S, P, sigma, s):
  401. delta = dict.fromkeys(S, 0)
  402. while S:
  403. w = S.pop()
  404. coeff = (1 + delta[w]) / sigma[w]
  405. for v in P[w]:
  406. c = sigma[v] * coeff
  407. if (v, w) not in betweenness:
  408. betweenness[(w, v)] += c
  409. else:
  410. betweenness[(v, w)] += c
  411. delta[v] += c
  412. if w != s:
  413. betweenness[w] += delta[w]
  414. return betweenness
  415. def _rescale(
  416. betweenness, n, *, normalized, directed, endpoints=True, sampled_nodes=None
  417. ):
  418. # For edge betweenness, `endpoints` is always `True`.
  419. k = None if sampled_nodes is None else len(sampled_nodes)
  420. # N is used to count the number of valid (s, t) pairs where s != t that
  421. # could have a path pass through v. If endpoints is False, then v must
  422. # not be the target t, hence why we subtract by 1.
  423. N = n if endpoints else n - 1
  424. if N < 2:
  425. # No rescaling necessary: b=0 for all nodes
  426. return betweenness
  427. K_source = N if k is None else k
  428. if k is None or endpoints:
  429. # No sampling adjustment needed
  430. if normalized:
  431. # Divide by the number of valid (s, t) node pairs that could have
  432. # a path through v where s != t.
  433. scale = 1 / (K_source * (N - 1))
  434. else:
  435. # Scale to the full BC
  436. if not directed:
  437. # The non-normalized BC values are computed the same way for
  438. # directed and undirected graphs: shortest paths are computed and
  439. # counted for each *ordered* (s, t) pair. Undirected graphs should
  440. # only count valid *unordered* node pairs {s, t}; that is, (s, t)
  441. # and (t, s) should be counted only once. We correct for this here.
  442. correction = 2
  443. else:
  444. correction = 1
  445. scale = N / (K_source * correction)
  446. if scale != 1:
  447. for v in betweenness:
  448. betweenness[v] *= scale
  449. return betweenness
  450. # Sampling adjustment needed when excluding endpoints when using k. In this
  451. # case, we need to handle source nodes differently from non-source nodes,
  452. # because source nodes can't include themselves since endpoints are excluded.
  453. # Without this, k == n would be a special case that would violate the
  454. # assumption that node `v` is not one of the (s, t) node pairs.
  455. if normalized:
  456. # NaN for undefined 0/0; there is no data for source node when k=1
  457. scale_source = 1 / ((K_source - 1) * (N - 1)) if K_source > 1 else math.nan
  458. scale_nonsource = 1 / (K_source * (N - 1))
  459. else:
  460. correction = 1 if directed else 2
  461. scale_source = N / ((K_source - 1) * correction) if K_source > 1 else math.nan
  462. scale_nonsource = N / (K_source * correction)
  463. sampled_nodes = set(sampled_nodes)
  464. for v in betweenness:
  465. betweenness[v] *= scale_source if v in sampled_nodes else scale_nonsource
  466. return betweenness
  467. @not_implemented_for("graph")
  468. def _add_edge_keys(G, betweenness, weight=None):
  469. r"""Adds the corrected betweenness centrality (BC) values for multigraphs.
  470. Parameters
  471. ----------
  472. G : NetworkX graph.
  473. betweenness : dictionary
  474. Dictionary mapping adjacent node tuples to betweenness centrality values.
  475. weight : string or function
  476. See `_weight_function` for details. Defaults to `None`.
  477. Returns
  478. -------
  479. edges : dictionary
  480. The parameter `betweenness` including edges with keys and their
  481. betweenness centrality values.
  482. The BC value is divided among edges of equal weight.
  483. """
  484. _weight = _weight_function(G, weight)
  485. edge_bc = dict.fromkeys(G.edges, 0.0)
  486. for u, v in betweenness:
  487. d = G[u][v]
  488. wt = _weight(u, v, d)
  489. keys = [k for k in d if _weight(u, v, {k: d[k]}) == wt]
  490. bc = betweenness[(u, v)] / len(keys)
  491. for k in keys:
  492. edge_bc[(u, v, k)] = bc
  493. return edge_bc